Merge branch 'continuedev:main' into init-tool-policy-in-tools-definitions
This commit is contained in:
commit
ed794ec6ae
118 changed files with 3523 additions and 1038 deletions
6
.continue/rules/typescript-enum-usage.md
Normal file
6
.continue/rules/typescript-enum-usage.md
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
---
|
||||
globs: "**/*.{ts,tsx}"
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
Use enums instead of simple string unions when possible in TypeScript code
|
||||
4
.github/pull_request_template.md
vendored
4
.github/pull_request_template.md
vendored
|
|
@ -8,9 +8,9 @@
|
|||
- [] The relevant docs, if any, have been updated or created
|
||||
- [] The relevant tests, if any, have been updated or created
|
||||
|
||||
## Screenshots
|
||||
## Screen recording or screenshot
|
||||
|
||||
[ For visual changes, include screenshots. Screen recordings are particularly helpful, and appreciated! ]
|
||||
[ When applicable, please include a short screen recording or screenshot - this makes it much easier for us as contributors to review and understand your changes. See [this PR](https://github.com/continuedev/continue/pull/6455) as a good example. ]
|
||||
|
||||
## Tests
|
||||
|
||||
|
|
|
|||
|
|
@ -192,6 +192,7 @@ To keep the Continue codebase clean and maintainable, we expect the following fr
|
|||
- Keep changes focused. Multiple unrelated fixes should be opened as separate PRs
|
||||
- Write or update tests for new functionality
|
||||
- Update relevant documentation in the `docs` folder
|
||||
- **For new features**: Include a short screen recording or screenshot demonstrating the new functionality. This makes it much easier for us as contributors to review and understand your changes. See [this PR](https://github.com/continuedev/continue/pull/6455) as a good example
|
||||
- Open a PR against the `main` branch. Make sure to fill in the PR template
|
||||
|
||||
### Formatting
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import { BracketMatchingService } from "./filtering/BracketMatchingService.js";
|
|||
import { CompletionStreamer } from "./generation/CompletionStreamer.js";
|
||||
import { postprocessCompletion } from "./postprocessing/index.js";
|
||||
import { shouldPrefilter } from "./prefiltering/index.js";
|
||||
import { getAllSnippets } from "./snippets/index.js";
|
||||
import { getAllSnippetsWithoutRace } from "./snippets/index.js";
|
||||
import { renderPrompt } from "./templating/index.js";
|
||||
import { GetLspDefinitionsFunction } from "./types.js";
|
||||
import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js";
|
||||
|
|
@ -121,6 +121,12 @@ export class CompletionProvider {
|
|||
...config?.tabAutocompleteOptions,
|
||||
...llm.autocompleteOptions,
|
||||
};
|
||||
|
||||
// Enable static contextualization if defined.
|
||||
if (config?.experimental?.enableStaticContextualization) {
|
||||
options.experimental_enableStaticContextualization = true;
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
|
|
@ -171,7 +177,7 @@ export class CompletionProvider {
|
|||
}
|
||||
|
||||
const [snippetPayload, workspaceDirs] = await Promise.all([
|
||||
getAllSnippets({
|
||||
getAllSnippetsWithoutRace({
|
||||
helper,
|
||||
ide: this.ide,
|
||||
getDefinitionsFromLsp: this.getDefinitionsFromLsp,
|
||||
|
|
@ -258,6 +264,10 @@ export class CompletionProvider {
|
|||
...helper.options,
|
||||
};
|
||||
|
||||
if (options.experimental_enableStaticContextualization) {
|
||||
outcome.enabledStaticContextualization = true;
|
||||
}
|
||||
|
||||
//////////
|
||||
|
||||
// Save to cache
|
||||
|
|
|
|||
|
|
@ -2,16 +2,19 @@ import { IDE } from "../..";
|
|||
import {
|
||||
AutocompleteCodeSnippet,
|
||||
AutocompleteSnippetType,
|
||||
AutocompleteStaticSnippet,
|
||||
} from "../snippets/types";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
|
||||
import { ImportDefinitionsService } from "./ImportDefinitionsService";
|
||||
import { getSymbolsForSnippet } from "./ranking";
|
||||
import { RootPathContextService } from "./root-path-context/RootPathContextService";
|
||||
import { StaticContextService } from "./static-context/StaticContextService";
|
||||
|
||||
export class ContextRetrievalService {
|
||||
private importDefinitionsService: ImportDefinitionsService;
|
||||
private rootPathContextService: RootPathContextService;
|
||||
private staticContextService: StaticContextService;
|
||||
|
||||
constructor(private readonly ide: IDE) {
|
||||
this.importDefinitionsService = new ImportDefinitionsService(this.ide);
|
||||
|
|
@ -19,6 +22,7 @@ export class ContextRetrievalService {
|
|||
this.importDefinitionsService,
|
||||
this.ide,
|
||||
);
|
||||
this.staticContextService = new StaticContextService(this.ide);
|
||||
}
|
||||
|
||||
public async getSnippetsFromImportDefinitions(
|
||||
|
|
@ -71,6 +75,12 @@ export class ContextRetrievalService {
|
|||
);
|
||||
}
|
||||
|
||||
public async getStaticContextSnippets(
|
||||
helper: HelperVars,
|
||||
): Promise<AutocompleteStaticSnippet[]> {
|
||||
return this.staticContextService.getContext(helper);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the import definitions cache for a file.
|
||||
* This is normally done automatically when the active text editor changes,
|
||||
|
|
|
|||
888
core/autocomplete/context/static-context/StaticContextService.ts
Normal file
888
core/autocomplete/context/static-context/StaticContextService.ts
Normal file
|
|
@ -0,0 +1,888 @@
|
|||
import * as fs from "fs/promises";
|
||||
import path from "path";
|
||||
import { pathToFileURL } from "url";
|
||||
import Parser from "web-tree-sitter";
|
||||
import { IDE, Position } from "../../..";
|
||||
import { localPathOrUriToPath } from "../../../util/pathToUri";
|
||||
import { getFullLanguageName, getQueryForFile } from "../../../util/treeSitter";
|
||||
import {
|
||||
AutocompleteSnippetType,
|
||||
AutocompleteStaticSnippet,
|
||||
} from "../../snippets/types";
|
||||
import { getAst } from "../../util/ast";
|
||||
import { HelperVars } from "../../util/HelperVars";
|
||||
import {
|
||||
extractFunctionTypeFromDecl,
|
||||
extractTopLevelDecls,
|
||||
findEnclosingTypeDeclaration,
|
||||
unwrapToBaseType,
|
||||
} from "./tree-sitter-utils";
|
||||
import {
|
||||
HoleContext,
|
||||
RelevantHeaders,
|
||||
RelevantTypes,
|
||||
StaticContext,
|
||||
TypeSpanAndSourceFile,
|
||||
TypeSpanAndSourceFileAndAst,
|
||||
} from "./types";
|
||||
|
||||
export class StaticContextService {
|
||||
private readonly ide: IDE;
|
||||
|
||||
constructor(ide: IDE) {
|
||||
this.ide = ide;
|
||||
}
|
||||
|
||||
public logAutocompleteStaticSnippet(
|
||||
ctx: StaticContext,
|
||||
label = "Static Snippet",
|
||||
) {
|
||||
console.log(`=== ${label} ===`);
|
||||
console.log("Hole Type:", ctx.holeType);
|
||||
|
||||
console.log(`\nRelevant Types (${ctx.relevantTypes.size} files):`);
|
||||
ctx.relevantTypes.forEach((types, filepath) => {
|
||||
console.log(` 📁 ${filepath}`);
|
||||
types.forEach((type) => console.log(` • ${type}`));
|
||||
});
|
||||
|
||||
console.log(`\nRelevant Headers (${ctx.relevantHeaders.size} files):`);
|
||||
ctx.relevantHeaders.forEach((headers, filepath) => {
|
||||
console.log(` 📁 ${filepath}`);
|
||||
headers.forEach((header) => console.log(` • ${header}`));
|
||||
});
|
||||
}
|
||||
|
||||
public static formatAutocompleteStaticSnippet(ctx: StaticContext): string {
|
||||
let output = `AutocompleteStaticSnippet:\n`;
|
||||
output += ` holeType: ${ctx.holeType}\n`;
|
||||
|
||||
output += ` relevantTypes:\n`;
|
||||
if (ctx.relevantTypes.size === 0) {
|
||||
output += ` (none)\n`;
|
||||
} else {
|
||||
ctx.relevantTypes.forEach((types, filepath) => {
|
||||
output += ` ${filepath}: [${types.join(", ")}]\n`;
|
||||
});
|
||||
}
|
||||
|
||||
output += ` relevantHeaders:\n`;
|
||||
if (ctx.relevantHeaders.size === 0) {
|
||||
output += ` (none)\n`;
|
||||
} else {
|
||||
ctx.relevantHeaders.forEach((headers, filepath) => {
|
||||
output += ` ${filepath}: [${headers.join(", ")}]\n`;
|
||||
});
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
public async getContext(
|
||||
helper: HelperVars,
|
||||
): Promise<AutocompleteStaticSnippet[]> {
|
||||
const start = Date.now();
|
||||
const tsFiles = await this.getTypeScriptFilesFromWorkspaces(
|
||||
helper.workspaceUris,
|
||||
);
|
||||
// Get the three contexts holeContext, relevantTypes, relevantHeaders.
|
||||
const holeContext = await this.getHoleContext(
|
||||
helper.fileContents,
|
||||
helper.filepath,
|
||||
helper.pos,
|
||||
);
|
||||
|
||||
const relevantTypes = await this.extractRelevantTypes(
|
||||
holeContext.fullHoverResult,
|
||||
holeContext.functionName,
|
||||
holeContext.range.start.line,
|
||||
holeContext.source,
|
||||
new Map<string, string>(),
|
||||
);
|
||||
|
||||
// if (this.language === "typescript") {
|
||||
// repo = getAllTSFiles(this.repoPath);
|
||||
// } else if (this.language === "ocaml") {
|
||||
// repo = getAllOCamlFiles(this.repoPath);
|
||||
// }
|
||||
//
|
||||
|
||||
const relevantHeaders = await this.extractRelevantHeaders(
|
||||
tsFiles,
|
||||
relevantTypes,
|
||||
holeContext.functionTypeSpan,
|
||||
helper.pos,
|
||||
holeContext.returnTypeIsAny,
|
||||
);
|
||||
|
||||
const relevantTypesToReturn: Map<string, string[]> = new Map<
|
||||
string,
|
||||
string[]
|
||||
>();
|
||||
relevantTypes.forEach(({ typeSpan: v, sourceFile: src }, _) => {
|
||||
if (relevantTypesToReturn.has(src)) {
|
||||
const updated = relevantTypesToReturn.get(src)!;
|
||||
updated.push(v);
|
||||
relevantTypesToReturn.set(src, updated);
|
||||
} else {
|
||||
relevantTypesToReturn.set(src, [v]);
|
||||
}
|
||||
});
|
||||
|
||||
const relevantHeadersToReturn: Map<string, string[]> = new Map<
|
||||
string,
|
||||
string[]
|
||||
>();
|
||||
relevantHeaders.forEach(({ typeSpan: v, sourceFile: src }) => {
|
||||
if (relevantHeadersToReturn.has(src)) {
|
||||
const updated = relevantHeadersToReturn.get(src)!;
|
||||
if (!updated.includes(v)) {
|
||||
updated.push(v);
|
||||
}
|
||||
relevantHeadersToReturn.set(src, updated);
|
||||
} else {
|
||||
relevantHeadersToReturn.set(src, [v]);
|
||||
}
|
||||
});
|
||||
|
||||
const ctx = {
|
||||
holeType: holeContext.functionTypeSpan,
|
||||
relevantTypes: relevantTypesToReturn,
|
||||
relevantHeaders: relevantHeadersToReturn,
|
||||
};
|
||||
const end = Date.now();
|
||||
|
||||
this.logAutocompleteStaticSnippet(ctx);
|
||||
|
||||
// console.log(end - start);
|
||||
|
||||
const snippets: AutocompleteStaticSnippet[] = [];
|
||||
|
||||
snippets.push({
|
||||
type: AutocompleteSnippetType.Static,
|
||||
filepath: pathToFileURL(path.resolve(holeContext.source)).toString(),
|
||||
content: holeContext.fullHoverResult,
|
||||
});
|
||||
|
||||
for (const [filepath, typs] of ctx.relevantTypes.entries()) {
|
||||
snippets.push({
|
||||
type: AutocompleteSnippetType.Static,
|
||||
filepath: pathToFileURL(path.resolve(filepath)).toString(),
|
||||
content: typs.join("\n"),
|
||||
});
|
||||
}
|
||||
|
||||
for (const [filepath, headers] of ctx.relevantHeaders.entries()) {
|
||||
snippets.push({
|
||||
type: AutocompleteSnippetType.Static,
|
||||
filepath: pathToFileURL(path.resolve(filepath)).toString(),
|
||||
content: headers.join("\n"),
|
||||
});
|
||||
}
|
||||
|
||||
return snippets;
|
||||
}
|
||||
|
||||
private async getHoleContext(
|
||||
sketchFileContent: string,
|
||||
sketchFilePath: string,
|
||||
cursorPosition: Position,
|
||||
): Promise<HoleContext> {
|
||||
// We need to inject the hole @ to trigger a treesitter error node.
|
||||
sketchFilePath = localPathOrUriToPath(sketchFilePath);
|
||||
// const sketchFileContent = await fs.readFile(sketchFilePath, "utf8");
|
||||
const injectedContent = this.insertAtPosition(
|
||||
sketchFileContent,
|
||||
cursorPosition,
|
||||
"@;",
|
||||
);
|
||||
|
||||
// The hole's position is cursorPosition.
|
||||
|
||||
// Use treesitter to parse.
|
||||
const ast = await getAst(sketchFilePath, injectedContent);
|
||||
if (!ast) {
|
||||
throw new Error("failed to get ast");
|
||||
}
|
||||
const language = getFullLanguageName(sketchFilePath);
|
||||
const query = await getQueryForFile(
|
||||
sketchFilePath,
|
||||
`static-context-queries/hole-queries/${language}.scm`,
|
||||
);
|
||||
if (!query) {
|
||||
throw new Error(
|
||||
`getHoleContext: failed to get query for file ${sketchFilePath} and language ${language}`,
|
||||
);
|
||||
}
|
||||
|
||||
const captures = query.captures(ast.rootNode);
|
||||
const res: HoleContext = {
|
||||
fullHoverResult: "",
|
||||
functionName: "",
|
||||
functionTypeSpan: "",
|
||||
returnTypeIsAny: false,
|
||||
range: {
|
||||
start: { line: 0, character: 0 },
|
||||
end: { line: 0, character: 0 },
|
||||
},
|
||||
source: `file://${sketchFilePath}`,
|
||||
};
|
||||
let paramsTypes = "";
|
||||
for (const c of captures) {
|
||||
const { name, node } = c;
|
||||
// console.log(`${name} →`, node.text, node.startPosition, node.endPosition);
|
||||
|
||||
switch (name) {
|
||||
case "function.decl": {
|
||||
res.fullHoverResult = node.text;
|
||||
break;
|
||||
}
|
||||
case "function.name": {
|
||||
res.functionName = node.text;
|
||||
break;
|
||||
}
|
||||
case "function.params": {
|
||||
paramsTypes = node.text;
|
||||
res.range = {
|
||||
start: {
|
||||
line: node.startPosition.row,
|
||||
character: node.startPosition.column,
|
||||
},
|
||||
end: {
|
||||
line: node.endPosition.row,
|
||||
character: node.endPosition.column,
|
||||
},
|
||||
};
|
||||
break;
|
||||
}
|
||||
case "function.type": {
|
||||
res.functionTypeSpan = node.text;
|
||||
res.range = {
|
||||
start: {
|
||||
line: node.startPosition.row,
|
||||
character: node.startPosition.column,
|
||||
},
|
||||
end: {
|
||||
line: node.endPosition.row,
|
||||
character: node.endPosition.column,
|
||||
},
|
||||
};
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (res.functionTypeSpan === "") {
|
||||
res.functionTypeSpan = `${paramsTypes} => any`;
|
||||
res.returnTypeIsAny = true;
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
private async extractRelevantTypes(
|
||||
declText: string,
|
||||
typeName: string,
|
||||
startLine: number,
|
||||
currentFile: string,
|
||||
foundContents: Map<string, string>, // uri -> contents
|
||||
): Promise<RelevantTypes> {
|
||||
const foundSoFar = new Map<string, TypeSpanAndSourceFileAndAst>(); // identifier -> [full hover result, source]
|
||||
|
||||
await this.extractRelevantTypesHelper(
|
||||
declText,
|
||||
typeName,
|
||||
startLine,
|
||||
foundSoFar,
|
||||
currentFile,
|
||||
foundContents,
|
||||
);
|
||||
|
||||
return foundSoFar;
|
||||
}
|
||||
|
||||
private async extractRelevantTypesHelper(
|
||||
declText: string,
|
||||
typeName: string,
|
||||
startLine: number,
|
||||
foundSoFar: Map<string, TypeSpanAndSourceFileAndAst>, // identifier -> [full hover result, source]
|
||||
currentFile: string,
|
||||
foundContents: Map<string, string>, // uri -> contents
|
||||
) {
|
||||
if (!foundSoFar.has(typeName)) {
|
||||
const ast = await getAst(currentFile, declText);
|
||||
if (!ast) {
|
||||
throw new Error(`failed to get ast for file ${currentFile}`);
|
||||
}
|
||||
foundSoFar.set(typeName, {
|
||||
typeSpan: declText,
|
||||
sourceFile: currentFile.slice(7),
|
||||
ast: ast,
|
||||
});
|
||||
|
||||
const language = getFullLanguageName(currentFile);
|
||||
const query = await getQueryForFile(
|
||||
currentFile,
|
||||
`static-context-queries/relevant-types-queries/${language}-extract-identifiers.scm`,
|
||||
);
|
||||
if (!query) {
|
||||
throw new Error(
|
||||
`failed to get query for file ${currentFile} and language ${language}`,
|
||||
);
|
||||
}
|
||||
|
||||
const identifiers = query.captures(ast.rootNode);
|
||||
|
||||
for (const { name, node } of identifiers) {
|
||||
if (foundSoFar.has(node.text)) continue;
|
||||
|
||||
try {
|
||||
const typeDefinitionResult = await this.ide.gotoTypeDefinition({
|
||||
filepath: currentFile,
|
||||
position: {
|
||||
character: node.startPosition.column,
|
||||
line: startLine + node.startPosition.row,
|
||||
},
|
||||
});
|
||||
|
||||
if (typeDefinitionResult.length > 0) {
|
||||
const tdLocation = typeDefinitionResult[0];
|
||||
|
||||
let content = "";
|
||||
|
||||
if (foundContents.has(tdLocation.filepath)) {
|
||||
content = foundContents.get(tdLocation.filepath)!;
|
||||
} else {
|
||||
content = await fs.readFile(
|
||||
localPathOrUriToPath(tdLocation.filepath),
|
||||
"utf8",
|
||||
);
|
||||
foundContents.set(tdLocation.filepath, content);
|
||||
}
|
||||
|
||||
const ast = await getAst(tdLocation.filepath, content);
|
||||
if (!ast) {
|
||||
throw new Error(
|
||||
`failed to get ast for file ${tdLocation.filepath}`,
|
||||
);
|
||||
}
|
||||
const decl = findEnclosingTypeDeclaration(
|
||||
content,
|
||||
tdLocation.range.start.line,
|
||||
tdLocation.range.start.character,
|
||||
ast,
|
||||
);
|
||||
if (!decl) {
|
||||
// throw new Error(`failed to get decl for file ${tdLocation.uri}`);
|
||||
console.error(
|
||||
`failed to get decl for file ${tdLocation.filepath}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (decl) {
|
||||
await this.extractRelevantTypesHelper(
|
||||
decl.fullText,
|
||||
node.text,
|
||||
tdLocation.range.start.line,
|
||||
foundSoFar,
|
||||
tdLocation.filepath,
|
||||
foundContents,
|
||||
);
|
||||
} else {
|
||||
// console.log("decl not found");
|
||||
}
|
||||
} else {
|
||||
// console.log("td not found");
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async extractRelevantHeaders(
|
||||
sources: string[],
|
||||
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
|
||||
holeType: string,
|
||||
cursorPosition: Position,
|
||||
returnTypeIsAny: boolean,
|
||||
): Promise<RelevantHeaders> {
|
||||
const relevantContext = new Set<TypeSpanAndSourceFile>();
|
||||
if (returnTypeIsAny) return relevantContext;
|
||||
// NOTE: This is necessary because TypeScript sucks.
|
||||
// There is no way to compare objects by value,
|
||||
// so sets of objects starts to accumulate tons of duplicates.
|
||||
const relevantContextMap = new Map<string, TypeSpanAndSourceFile>();
|
||||
const foundNormalForms = new Map<string, string>();
|
||||
|
||||
const targetTypes = await this.generateTargetTypes(relevantTypes, holeType);
|
||||
|
||||
for (const source of sources) {
|
||||
const topLevelDecls = await extractTopLevelDecls(source);
|
||||
for (const tld of topLevelDecls) {
|
||||
// pattern 0 is let/const, 1 is var, 2 is fun
|
||||
// if (!seenDecls.has(JSON.stringify()) {
|
||||
const originalDeclText =
|
||||
tld.pattern === 2
|
||||
? tld.captures.find((d) => d.name === "top.fn.decl")!.node.text
|
||||
: tld.captures.find((d) => d.name === "top.var.decl")!.node.text;
|
||||
|
||||
if (tld.pattern === 2) {
|
||||
// build a type span
|
||||
// TODO: this fails sometimes with Cannot read properties of undefined (reading 'text')
|
||||
// most likely due to my scm query and how I'm not attaching param name along with param type
|
||||
let funcType = "";
|
||||
try {
|
||||
funcType = extractFunctionTypeFromDecl(tld);
|
||||
} catch (err) {
|
||||
// Most likely is the case that there is no explicit return type annotation.
|
||||
const sigHelp = await this.ide.getSignatureHelp({
|
||||
filepath: source,
|
||||
position: cursorPosition,
|
||||
});
|
||||
if (!sigHelp) continue;
|
||||
funcType = sigHelp.signatures[0].label;
|
||||
|
||||
// TODO: This only works for TypeScript.
|
||||
function convertToArrowType(signature: string): string {
|
||||
// Handle various function declaration formats.
|
||||
const patterns = [
|
||||
// Standard: functionName(params): returnType.
|
||||
/^(\w+)\s*\((.*?)\)\s*:\s*(.+)$/,
|
||||
// With generics: functionName<T>(params): returnType.
|
||||
/^(\w+)\s*<[^>]*>\s*\((.*?)\)\s*:\s*(.+)$/,
|
||||
// With modifiers: export function functionName(params): returnType.
|
||||
/^(?:export\s+)?(?:function\s+)?(\w+)\s*\((.*?)\)\s*:\s*(.+)$/,
|
||||
];
|
||||
|
||||
for (const pattern of patterns) {
|
||||
const match = signature.match(pattern);
|
||||
if (match) {
|
||||
const [, , parameters, returnType] = match;
|
||||
return `(${parameters}) => ${returnType}`;
|
||||
}
|
||||
}
|
||||
|
||||
return signature;
|
||||
}
|
||||
|
||||
funcType = convertToArrowType(funcType);
|
||||
}
|
||||
const wrapped = `type __TMP = ${funcType};`;
|
||||
|
||||
const ast = await getAst("file.ts", wrapped);
|
||||
if (!ast) {
|
||||
throw new Error(`failed to generate ast for ${wrapped}`);
|
||||
}
|
||||
|
||||
// console.log(ast.rootNode);
|
||||
const alias = ast.rootNode.namedChild(0);
|
||||
// console.log(alias);
|
||||
if (!alias || alias.type !== "type_alias_declaration") {
|
||||
throw new Error(
|
||||
"extractRelevantHeaders: Failed to parse type alias",
|
||||
);
|
||||
}
|
||||
|
||||
const valueNode = alias.childForFieldName("value");
|
||||
if (!valueNode) throw new Error("No type value found");
|
||||
|
||||
const baseNode = unwrapToBaseType(valueNode);
|
||||
|
||||
await this.extractRelevantHeadersHelper(
|
||||
originalDeclText,
|
||||
baseNode,
|
||||
targetTypes,
|
||||
relevantTypes,
|
||||
relevantContext,
|
||||
relevantContextMap,
|
||||
foundNormalForms,
|
||||
source,
|
||||
);
|
||||
} else {
|
||||
const varTypNode = tld.captures.find(
|
||||
(d) => d.name === "top.var.type",
|
||||
)!.node;
|
||||
await this.extractRelevantHeadersHelper(
|
||||
originalDeclText,
|
||||
varTypNode,
|
||||
targetTypes,
|
||||
relevantTypes,
|
||||
relevantContext,
|
||||
relevantContextMap,
|
||||
foundNormalForms,
|
||||
source,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const v of relevantContextMap.values()) {
|
||||
relevantContext.add(v);
|
||||
}
|
||||
|
||||
return relevantContext;
|
||||
}
|
||||
|
||||
private async extractRelevantHeadersHelper(
|
||||
originalDeclText: string,
|
||||
node: Parser.SyntaxNode,
|
||||
targetTypes: Set<Parser.SyntaxNode>,
|
||||
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
|
||||
relevantContext: Set<TypeSpanAndSourceFile>,
|
||||
relevantContextMap: Map<string, TypeSpanAndSourceFile>,
|
||||
foundNormalForms: Map<string, string>,
|
||||
source: string,
|
||||
) {
|
||||
for (const typ of targetTypes) {
|
||||
if (
|
||||
await this.isTypeEquivalent(node, typ, relevantTypes, foundNormalForms)
|
||||
) {
|
||||
const ctx = { typeSpan: originalDeclText, sourceFile: source };
|
||||
relevantContextMap.set(JSON.stringify(ctx), ctx);
|
||||
}
|
||||
|
||||
if (node.type === "function_type") {
|
||||
const retTypeNode = node.namedChildren.find(
|
||||
(c) => c && c.type === "return_type",
|
||||
);
|
||||
if (retTypeNode) {
|
||||
await this.extractRelevantHeadersHelper(
|
||||
originalDeclText,
|
||||
retTypeNode,
|
||||
targetTypes,
|
||||
relevantTypes,
|
||||
relevantContext,
|
||||
relevantContextMap,
|
||||
foundNormalForms,
|
||||
source,
|
||||
);
|
||||
}
|
||||
} else if (node.type === "tuple_type") {
|
||||
for (const c of node.namedChildren) {
|
||||
await this.extractRelevantHeadersHelper(
|
||||
originalDeclText,
|
||||
c!,
|
||||
targetTypes,
|
||||
relevantTypes,
|
||||
relevantContext,
|
||||
relevantContextMap,
|
||||
foundNormalForms,
|
||||
source,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async generateTargetTypes(
|
||||
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
|
||||
holeType: string,
|
||||
) {
|
||||
const targetTypes = new Set<Parser.SyntaxNode>();
|
||||
// const ast = relevantTypes.get(holeIdentifier)!.ast;
|
||||
const ast = await getAst("file.ts", `type T = ${holeType};`);
|
||||
if (!ast) {
|
||||
throw new Error(`failed to generate ast for ${holeType}`);
|
||||
}
|
||||
|
||||
const alias = ast.rootNode.namedChild(0);
|
||||
if (!alias || alias.type !== "type_alias_declaration") {
|
||||
throw new Error("generateTargetTypes: Failed to parse type alias");
|
||||
}
|
||||
|
||||
const valueNode = alias.childForFieldName("value");
|
||||
if (!valueNode) throw new Error("No type value found");
|
||||
|
||||
const baseNode = unwrapToBaseType(valueNode);
|
||||
targetTypes.add(baseNode);
|
||||
await this.generateTargetTypesHelper(
|
||||
relevantTypes,
|
||||
holeType,
|
||||
targetTypes,
|
||||
baseNode,
|
||||
);
|
||||
|
||||
return targetTypes;
|
||||
}
|
||||
|
||||
private async generateTargetTypesHelper(
|
||||
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
|
||||
currType: string,
|
||||
targetTypes: Set<Parser.SyntaxNode>,
|
||||
node: Parser.SyntaxNode | null,
|
||||
): Promise<void> {
|
||||
if (!node) return;
|
||||
|
||||
if (node.type === "function_type") {
|
||||
const returnType = node.childForFieldName("return_type");
|
||||
if (returnType) {
|
||||
targetTypes.add(returnType);
|
||||
await this.generateTargetTypesHelper(
|
||||
relevantTypes,
|
||||
currType,
|
||||
targetTypes,
|
||||
returnType,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (node.type === "tuple_type") {
|
||||
for (const child of node.namedChildren) {
|
||||
if (child) {
|
||||
targetTypes.add(child);
|
||||
await this.generateTargetTypesHelper(
|
||||
relevantTypes,
|
||||
currType,
|
||||
targetTypes,
|
||||
child,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (relevantTypes.has(node.text)) {
|
||||
// const ast = relevantTypes.get(node.text)!.ast;
|
||||
const typeSpan = relevantTypes.get(node.text)?.typeSpan;
|
||||
|
||||
// const ast = await getAst("file.ts", `type T = ${typeSpan}`);
|
||||
const ast = await getAst("file.ts", typeSpan!);
|
||||
if (!ast) {
|
||||
throw new Error(`failed to generate ast for ${typeSpan}`);
|
||||
}
|
||||
|
||||
const alias = ast.rootNode.namedChild(0);
|
||||
if (!alias || alias.type !== "type_alias_declaration") {
|
||||
console.error("generateTargetTypesHelper: Failed to parse type alias");
|
||||
return;
|
||||
// throw new Error(
|
||||
// "generateTargetTypesHelper: Failed to parse type alias",
|
||||
// );
|
||||
}
|
||||
|
||||
const valueNode = alias.childForFieldName("value");
|
||||
if (!valueNode) throw new Error("No type value found");
|
||||
|
||||
const baseNode = unwrapToBaseType(valueNode);
|
||||
await this.generateTargetTypesHelper(
|
||||
relevantTypes,
|
||||
currType,
|
||||
targetTypes,
|
||||
baseNode,
|
||||
);
|
||||
}
|
||||
|
||||
// if (node.type === "type_identifier" || node.type === "predefined_type") {
|
||||
// return [node.text];
|
||||
// }
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
private async isTypeEquivalent(
|
||||
node: Parser.SyntaxNode,
|
||||
typ: Parser.SyntaxNode,
|
||||
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
|
||||
foundNormalForms: Map<string, string>,
|
||||
): Promise<boolean> {
|
||||
if (!node || !typ) {
|
||||
return false;
|
||||
}
|
||||
let normT1 = "";
|
||||
let normT2 = "";
|
||||
if (foundNormalForms.has(node.text)) {
|
||||
// console.log("found t1", true)
|
||||
normT1 = foundNormalForms.get(node.text)!;
|
||||
} else {
|
||||
// console.log("not found t1", false)
|
||||
normT1 = await this.normalize(node, relevantTypes);
|
||||
foundNormalForms.set(node.text, normT1);
|
||||
}
|
||||
if (foundNormalForms.has(typ.text)) {
|
||||
// console.log("found t2", true)
|
||||
normT2 = foundNormalForms.get(typ.text)!;
|
||||
} else {
|
||||
// console.log("not found t2", false)
|
||||
normT2 = await this.normalize(typ, relevantTypes);
|
||||
foundNormalForms.set(typ.text, normT2);
|
||||
}
|
||||
// const normT1 = foundNormalForms.has(t1) ? foundNormalForms.get(t1) : this.normalize2(t1, relevantTypes);
|
||||
// const normT2 = foundNormalForms.has(t2) ? foundNormalForms.get(t2) : this.normalize2(t2, relevantTypes);
|
||||
// console.log(`normal forms: ${normT1} {}{} ${normT2}`)
|
||||
return normT1 === normT2;
|
||||
}
|
||||
|
||||
private async normalize(
|
||||
node: Parser.SyntaxNode,
|
||||
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
|
||||
): Promise<string> {
|
||||
if (!node) return "";
|
||||
|
||||
switch (node.type) {
|
||||
case "function_type": {
|
||||
const params = node.child(0); // formal_parameters
|
||||
const returnType =
|
||||
node.childForFieldName("type") || node.namedChildren[1]; // function_type → parameters, =>, return
|
||||
|
||||
const paramTypes =
|
||||
params?.namedChildren
|
||||
.map((param) =>
|
||||
this.normalize(
|
||||
param!.childForFieldName("type")! ||
|
||||
param!.namedChildren.at(-1),
|
||||
relevantTypes,
|
||||
),
|
||||
)
|
||||
.join(", ") || "";
|
||||
|
||||
const ret = this.normalize(returnType!, relevantTypes);
|
||||
return `(${paramTypes}) => ${ret}`;
|
||||
}
|
||||
|
||||
case "tuple_type": {
|
||||
const elements = node.namedChildren.map((c) =>
|
||||
this.normalize(c!, relevantTypes),
|
||||
);
|
||||
return `[${elements.join(", ")}]`;
|
||||
}
|
||||
|
||||
case "union_type": {
|
||||
const parts = node.namedChildren.map((c) =>
|
||||
this.normalize(c!, relevantTypes),
|
||||
);
|
||||
return parts.join(" | ");
|
||||
}
|
||||
|
||||
case "type_identifier": {
|
||||
const alias = relevantTypes.get(node.text);
|
||||
if (!alias) return node.text;
|
||||
|
||||
// Parse the alias's type span
|
||||
const wrapped = `type __TMP = ${alias};`;
|
||||
const tree = await getAst("file.ts", wrapped);
|
||||
const valueNode = tree!.rootNode
|
||||
.descendantsOfType("type_alias_declaration")[0]
|
||||
?.childForFieldName("value");
|
||||
|
||||
return this.normalize(valueNode!, relevantTypes);
|
||||
}
|
||||
|
||||
case "predefined_type":
|
||||
case "number":
|
||||
case "string":
|
||||
return node.text;
|
||||
|
||||
default:
|
||||
// Fallback for types like array, etc.
|
||||
return node.text;
|
||||
}
|
||||
}
|
||||
|
||||
private insertAtPosition = (
|
||||
contents: string,
|
||||
cursorPosition: { line: number; character: number },
|
||||
insertText: string,
|
||||
): string => {
|
||||
const lines = contents.split(/\r?\n/); // Handle both LF and CRLF line endings
|
||||
const { line, character } = cursorPosition;
|
||||
|
||||
if (line < 0 || line >= lines.length) {
|
||||
throw new Error("Invalid line number");
|
||||
}
|
||||
|
||||
const targetLine = lines[line];
|
||||
if (character < 0 || character > targetLine.length) {
|
||||
throw new Error("Invalid character index");
|
||||
}
|
||||
|
||||
// Insert the text
|
||||
lines[line] =
|
||||
targetLine.slice(0, character) + insertText + targetLine.slice(character);
|
||||
|
||||
return lines.join("\n"); // Reconstruct the file
|
||||
};
|
||||
|
||||
private async getTypeScriptFilesFromWorkspaces(
|
||||
workspaceUris: string[],
|
||||
): Promise<string[]> {
|
||||
const tsExtensions = [".ts"];
|
||||
const allTsFiles: string[] = [];
|
||||
|
||||
for (const workspaceUri of workspaceUris) {
|
||||
try {
|
||||
// Convert URI to file path
|
||||
const folderPath = workspaceUri.startsWith("file://")
|
||||
? new URL(workspaceUri).pathname
|
||||
: workspaceUri;
|
||||
|
||||
const tsFiles = await this.scanDirectoryForTypeScriptFiles(
|
||||
folderPath,
|
||||
tsExtensions,
|
||||
);
|
||||
allTsFiles.push(...tsFiles);
|
||||
} catch (error) {
|
||||
console.error(`Error scanning workspace ${workspaceUri}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
return allTsFiles;
|
||||
}
|
||||
|
||||
private async scanDirectoryForTypeScriptFiles(
|
||||
dirPath: string,
|
||||
tsExtensions: string[],
|
||||
): Promise<string[]> {
|
||||
const tsFiles: string[] = [];
|
||||
|
||||
const shouldSkipDirectory = (dirName: string): boolean => {
|
||||
const skipDirs = [
|
||||
"node_modules",
|
||||
".git",
|
||||
".vscode",
|
||||
"dist",
|
||||
"build",
|
||||
"out",
|
||||
".next",
|
||||
"coverage",
|
||||
".nyc_output",
|
||||
"tmp",
|
||||
"temp",
|
||||
".cache",
|
||||
];
|
||||
|
||||
return skipDirs.includes(dirName) || dirName.startsWith(".");
|
||||
};
|
||||
|
||||
async function scanRecursively(currentPath: string): Promise<void> {
|
||||
try {
|
||||
const entries = await fs.readdir(currentPath, {
|
||||
withFileTypes: true,
|
||||
});
|
||||
|
||||
for (const entry of entries) {
|
||||
const fullPath = localPathOrUriToPath(
|
||||
path.join(currentPath, entry.name),
|
||||
);
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
// Skip common directories that typically don't contain source files
|
||||
if (!shouldSkipDirectory(entry.name)) {
|
||||
await scanRecursively(fullPath);
|
||||
}
|
||||
} else if (entry.isFile()) {
|
||||
const extension = path.extname(entry.name).toLowerCase();
|
||||
if (tsExtensions.includes(extension)) {
|
||||
tsFiles.push(fullPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Error reading directory ${currentPath}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
await scanRecursively(dirPath);
|
||||
return tsFiles;
|
||||
}
|
||||
}
|
||||
222
core/autocomplete/context/static-context/tree-sitter-utils.ts
Normal file
222
core/autocomplete/context/static-context/tree-sitter-utils.ts
Normal file
|
|
@ -0,0 +1,222 @@
|
|||
import * as fs from "fs/promises";
|
||||
import Parser from "web-tree-sitter";
|
||||
import { getFullLanguageName, getQueryForFile } from "../../../util/treeSitter";
|
||||
import { getAst } from "../../util/ast";
|
||||
|
||||
export interface TypeDeclarationResult {
|
||||
name: string;
|
||||
fullText: string;
|
||||
startLine: number;
|
||||
startColumn: number;
|
||||
endLine: number;
|
||||
endColumn: number;
|
||||
kind: string;
|
||||
}
|
||||
|
||||
export function findEnclosingTypeDeclaration(
|
||||
sourceCode: string,
|
||||
cursorLine: number,
|
||||
cursorColumn: number,
|
||||
ast: Parser.Tree,
|
||||
): TypeDeclarationResult | null {
|
||||
const point = { row: cursorLine, column: cursorColumn };
|
||||
let node = ast.rootNode.descendantForPosition(point);
|
||||
|
||||
while (
|
||||
node &&
|
||||
![
|
||||
"type_alias_declaration",
|
||||
"interface_declaration",
|
||||
"enum_declaration",
|
||||
].includes(node.type)
|
||||
) {
|
||||
if (!node.parent) return null;
|
||||
node = node.parent;
|
||||
}
|
||||
|
||||
if (!node) return null;
|
||||
|
||||
const nameNode = node.childForFieldName("name");
|
||||
const name = nameNode?.text ?? "<anonymous>";
|
||||
const fullText = sourceCode.slice(node.startIndex, node.endIndex);
|
||||
|
||||
return {
|
||||
name,
|
||||
fullText,
|
||||
startLine: node.startPosition.row,
|
||||
startColumn: node.startPosition.column,
|
||||
endLine: node.endPosition.row,
|
||||
endColumn: node.endPosition.column,
|
||||
kind: node.type,
|
||||
};
|
||||
}
|
||||
|
||||
export async function extractTopLevelDecls(
|
||||
currentFile: string,
|
||||
givenParser?: Parser,
|
||||
) {
|
||||
const ast = await getAst(currentFile, await fs.readFile(currentFile, "utf8"));
|
||||
if (!ast) {
|
||||
throw new Error(`failed to get ast for file ${currentFile}`);
|
||||
}
|
||||
let language;
|
||||
if (givenParser) {
|
||||
language = givenParser.getLanguage();
|
||||
} else {
|
||||
language = getFullLanguageName(currentFile);
|
||||
}
|
||||
|
||||
const query = await getQueryForFile(
|
||||
currentFile,
|
||||
`static-context-queries/relevant-headers-queries/${language}-get-toplevel-headers.scm`,
|
||||
);
|
||||
if (!query) {
|
||||
throw new Error(
|
||||
`failed to get query for file ${currentFile} and language ${language}`,
|
||||
);
|
||||
}
|
||||
return query.matches(ast.rootNode);
|
||||
}
|
||||
|
||||
export async function extractTopLevelDeclsWithFormatting(
|
||||
currentFile: string,
|
||||
givenParser?: Parser,
|
||||
) {
|
||||
const ast = await getAst(currentFile, await fs.readFile(currentFile, "utf8"));
|
||||
if (!ast) {
|
||||
throw new Error(`failed to get ast for file ${currentFile}`);
|
||||
}
|
||||
let language;
|
||||
if (givenParser) {
|
||||
language = givenParser.getLanguage();
|
||||
} else {
|
||||
language = getFullLanguageName(currentFile);
|
||||
}
|
||||
|
||||
const query = await getQueryForFile(
|
||||
currentFile,
|
||||
`static-context-queries/relevant-headers-queries/${language}-get-toplevel-headers.scm`,
|
||||
);
|
||||
if (!query) {
|
||||
throw new Error(
|
||||
`failed to get query for file ${currentFile} and language ${language}`,
|
||||
);
|
||||
}
|
||||
const matches = query.matches(ast.rootNode);
|
||||
|
||||
const results = [];
|
||||
|
||||
for (const match of matches) {
|
||||
const item: {
|
||||
declaration: string;
|
||||
nodeType: string;
|
||||
name: string;
|
||||
declaredType: string;
|
||||
returnType?: string;
|
||||
} = {
|
||||
declaration: "",
|
||||
nodeType: "",
|
||||
name: "",
|
||||
declaredType: "",
|
||||
};
|
||||
|
||||
for (const { name, node } of match.captures) {
|
||||
if (name === "top.var.decl") {
|
||||
item.nodeType = "variable";
|
||||
item.declaration = node.text;
|
||||
|
||||
// Attempt to get the declared type (e.g., const x: string = ...)
|
||||
const typeNode = node.descendantsOfType("type_annotation")[0];
|
||||
if (typeNode) {
|
||||
item.declaredType = typeNode.text.replace(/^:\s*/, "");
|
||||
}
|
||||
} else if (name === "top.var.name" || name === "top.fn.name") {
|
||||
item.name = node.text;
|
||||
} else if (name === "top.fn.decl") {
|
||||
item.nodeType = "function";
|
||||
item.declaration = node.text;
|
||||
|
||||
// Get the return type (e.g., function foo(): string)
|
||||
const returnTypeNode = node.childForFieldName("return_type");
|
||||
if (returnTypeNode) {
|
||||
item.returnType = returnTypeNode.text.replace(/^:\s*/, "");
|
||||
}
|
||||
|
||||
// Get declaredType if needed (TypeScript style)
|
||||
const nameNode = node.childForFieldName("name");
|
||||
if (nameNode && nameNode.nextSibling?.type === "type_annotation") {
|
||||
item.declaredType = nameNode.nextSibling.text.replace(/^:\s*/, "");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (item.name && item.declaration) {
|
||||
results.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
export function extractFunctionTypeFromDecl(match: Parser.QueryMatch): string {
|
||||
let paramsNode: Parser.SyntaxNode | undefined = undefined;
|
||||
let returnNode: Parser.SyntaxNode | undefined = undefined;
|
||||
|
||||
for (const capture of match.captures) {
|
||||
if (capture.name === "top.fn.param.type") {
|
||||
paramsNode = capture.node;
|
||||
} else if (capture.name === "top.fn.type") {
|
||||
returnNode = capture.node;
|
||||
}
|
||||
}
|
||||
|
||||
if (!paramsNode) {
|
||||
console.error(
|
||||
`extractFunctionTypeFromDecl: paramsNode ${paramsNode} not found`,
|
||||
);
|
||||
throw new Error(
|
||||
`extractFunctionTypeFromDecl: paramsNode ${paramsNode} not found`,
|
||||
);
|
||||
}
|
||||
|
||||
if (!returnNode) {
|
||||
console.error(
|
||||
`extractFunctionTypeFromDecl: returnNode ${returnNode} not found`,
|
||||
);
|
||||
throw new Error(
|
||||
`extractFunctionTypeFromDecl: returnNode ${returnNode} not found`,
|
||||
);
|
||||
}
|
||||
|
||||
return `(${paramsNode!.text}) => ${returnNode!.text}`;
|
||||
}
|
||||
|
||||
export function unwrapToBaseType(node: Parser.SyntaxNode): Parser.SyntaxNode {
|
||||
if (
|
||||
[
|
||||
"function_type",
|
||||
"tuple_type",
|
||||
"type_identifier",
|
||||
"predefined_type",
|
||||
].includes(node.type)
|
||||
) {
|
||||
return node;
|
||||
}
|
||||
|
||||
for (const child of node.namedChildren) {
|
||||
const unwrapped = unwrapToBaseType(child!);
|
||||
if (
|
||||
unwrapped !== child ||
|
||||
[
|
||||
"function_type",
|
||||
"tuple_type",
|
||||
"type_identifier",
|
||||
"predefined_type",
|
||||
].includes(unwrapped.type)
|
||||
) {
|
||||
return unwrapped;
|
||||
}
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
33
core/autocomplete/context/static-context/types.ts
Normal file
33
core/autocomplete/context/static-context/types.ts
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
import { Tree } from "web-tree-sitter";
|
||||
import { Range } from "../../..";
|
||||
|
||||
export interface TypeSpanAndSourceFile {
|
||||
typeSpan: string;
|
||||
sourceFile: string;
|
||||
}
|
||||
|
||||
export interface TypeSpanAndSourceFileAndAst extends TypeSpanAndSourceFile {
|
||||
ast: Tree;
|
||||
}
|
||||
|
||||
export interface HoleContext {
|
||||
fullHoverResult: string;
|
||||
functionName: string;
|
||||
functionTypeSpan: string;
|
||||
returnTypeIsAny: boolean;
|
||||
range: Range;
|
||||
source: string;
|
||||
}
|
||||
|
||||
export type RelevantTypes = Map<string, TypeSpanAndSourceFileAndAst>;
|
||||
export type RelevantHeaders = Set<TypeSpanAndSourceFile>;
|
||||
|
||||
export type Filepath = string;
|
||||
export type RelevantType = string;
|
||||
export type RelevantHeader = string;
|
||||
|
||||
export interface StaticContext {
|
||||
holeType: string;
|
||||
relevantTypes: Map<Filepath, RelevantType[]>;
|
||||
relevantHeaders: Map<Filepath, RelevantHeader[]>;
|
||||
}
|
||||
|
|
@ -11,6 +11,7 @@ import {
|
|||
AutocompleteCodeSnippet,
|
||||
AutocompleteDiffSnippet,
|
||||
AutocompleteSnippetType,
|
||||
AutocompleteStaticSnippet,
|
||||
} from "./types";
|
||||
|
||||
const IDE_SNIPPETS_ENABLED = false; // ideSnippets is not used, so it's temporarily disabled
|
||||
|
|
@ -24,6 +25,7 @@ export interface SnippetPayload {
|
|||
diffSnippets: AutocompleteDiffSnippet[];
|
||||
clipboardSnippets: AutocompleteClipboardSnippet[];
|
||||
recentlyOpenedFileSnippets: AutocompleteCodeSnippet[];
|
||||
staticSnippet: AutocompleteStaticSnippet[];
|
||||
}
|
||||
|
||||
function racePromise<T>(promise: Promise<T[]>, timeout = 100): Promise<T[]> {
|
||||
|
|
@ -185,6 +187,7 @@ export const getAllSnippets = async ({
|
|||
diffSnippets,
|
||||
clipboardSnippets,
|
||||
recentlyOpenedFileSnippets,
|
||||
staticSnippet,
|
||||
] = await Promise.all([
|
||||
racePromise(contextRetrievalService.getRootPathSnippets(helper)),
|
||||
racePromise(
|
||||
|
|
@ -196,6 +199,9 @@ export const getAllSnippets = async ({
|
|||
[], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882,
|
||||
racePromise(getClipboardSnippets(ide)),
|
||||
racePromise(getSnippetsFromRecentlyOpenedFiles(helper, ide)), // giving this one a little more time to complete
|
||||
helper.options.experimental_enableStaticContextualization
|
||||
? racePromise(contextRetrievalService.getStaticContextSnippets(helper))
|
||||
: [],
|
||||
]);
|
||||
|
||||
return {
|
||||
|
|
@ -207,6 +213,7 @@ export const getAllSnippets = async ({
|
|||
clipboardSnippets,
|
||||
recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges,
|
||||
recentlyOpenedFileSnippets,
|
||||
staticSnippet,
|
||||
};
|
||||
};
|
||||
|
||||
|
|
@ -231,6 +238,7 @@ export const getAllSnippetsWithoutRace = async ({
|
|||
diffSnippets,
|
||||
clipboardSnippets,
|
||||
recentlyOpenedFileSnippets,
|
||||
staticSnippet,
|
||||
] = await Promise.all([
|
||||
contextRetrievalService.getRootPathSnippets(helper),
|
||||
contextRetrievalService.getSnippetsFromImportDefinitions(helper),
|
||||
|
|
@ -240,6 +248,9 @@ export const getAllSnippetsWithoutRace = async ({
|
|||
[], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882,
|
||||
getClipboardSnippets(ide),
|
||||
getSnippetsFromRecentlyOpenedFiles(helper, ide),
|
||||
helper.options.experimental_enableStaticContextualization
|
||||
? contextRetrievalService.getStaticContextSnippets(helper)
|
||||
: [],
|
||||
]);
|
||||
|
||||
return {
|
||||
|
|
@ -251,5 +262,6 @@ export const getAllSnippetsWithoutRace = async ({
|
|||
clipboardSnippets,
|
||||
recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges,
|
||||
recentlyOpenedFileSnippets,
|
||||
staticSnippet,
|
||||
};
|
||||
};
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ export enum AutocompleteSnippetType {
|
|||
Code = "code",
|
||||
Diff = "diff",
|
||||
Clipboard = "clipboard",
|
||||
Static = "static",
|
||||
}
|
||||
|
||||
interface BaseAutocompleteSnippet {
|
||||
|
|
@ -23,7 +24,13 @@ export interface AutocompleteClipboardSnippet extends BaseAutocompleteSnippet {
|
|||
copiedAt: string;
|
||||
}
|
||||
|
||||
export interface AutocompleteStaticSnippet extends BaseAutocompleteSnippet {
|
||||
type: AutocompleteSnippetType.Static;
|
||||
filepath: string;
|
||||
}
|
||||
|
||||
export type AutocompleteSnippet =
|
||||
| AutocompleteCodeSnippet
|
||||
| AutocompleteDiffSnippet
|
||||
| AutocompleteClipboardSnippet;
|
||||
| AutocompleteClipboardSnippet
|
||||
| AutocompleteStaticSnippet;
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import {
|
|||
AutocompleteCodeSnippet,
|
||||
AutocompleteSnippet,
|
||||
AutocompleteSnippetType,
|
||||
AutocompleteStaticSnippet,
|
||||
} from "../snippets/types";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
import { formatOpenedFilesContext } from "./formatOpenedFilesContext";
|
||||
|
|
@ -32,9 +33,9 @@ const shuffleArray = <T>(array: T[]): T[] => {
|
|||
};
|
||||
|
||||
function filterSnippetsAlreadyInCaretWindow(
|
||||
snippets: AutocompleteCodeSnippet[],
|
||||
snippets: (AutocompleteCodeSnippet | AutocompleteStaticSnippet)[],
|
||||
caretWindow: string,
|
||||
): AutocompleteCodeSnippet[] {
|
||||
): (AutocompleteCodeSnippet | AutocompleteStaticSnippet)[] {
|
||||
return snippets.filter(
|
||||
(s) => s.content.trim() !== "" && !caretWindow.includes(s.content.trim()),
|
||||
);
|
||||
|
|
@ -52,7 +53,11 @@ export const getSnippets = (
|
|||
recentlyOpenedFiles: payload.recentlyOpenedFileSnippets,
|
||||
base: shuffleArray(
|
||||
filterSnippetsAlreadyInCaretWindow(
|
||||
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
|
||||
[
|
||||
...payload.rootPathSnippets,
|
||||
...payload.importDefinitionSnippets,
|
||||
...payload.staticSnippet,
|
||||
],
|
||||
helper.prunedCaretWindow,
|
||||
),
|
||||
),
|
||||
|
|
@ -107,7 +112,11 @@ export const getSnippets = (
|
|||
defaultPriority: 99, // make sure it's the last one to be processed, but still possible to override
|
||||
snippets: shuffleArray(
|
||||
filterSnippetsAlreadyInCaretWindow(
|
||||
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
|
||||
[
|
||||
...payload.rootPathSnippets,
|
||||
...payload.importDefinitionSnippets,
|
||||
...payload.staticSnippet,
|
||||
],
|
||||
helper.prunedCaretWindow,
|
||||
),
|
||||
),
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import {
|
|||
AutocompleteDiffSnippet,
|
||||
AutocompleteSnippet,
|
||||
AutocompleteSnippetType,
|
||||
AutocompleteStaticSnippet,
|
||||
} from "../snippets/types";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
|
||||
|
|
@ -51,6 +52,12 @@ const formatDiffSnippet = (
|
|||
return snippet;
|
||||
};
|
||||
|
||||
const formatStaticSnippet = (
|
||||
snippet: AutocompleteStaticSnippet,
|
||||
): AutocompleteStaticSnippet => {
|
||||
return snippet;
|
||||
};
|
||||
|
||||
const commentifySnippet = (
|
||||
helper: HelperVars,
|
||||
snippet: AutocompleteSnippet,
|
||||
|
|
@ -81,6 +88,8 @@ export const formatSnippets = (
|
|||
return formatDiffSnippet(snippet);
|
||||
case AutocompleteSnippetType.Clipboard:
|
||||
return formatClipboardSnippet(snippet, workspaceDirs);
|
||||
case AutocompleteSnippetType.Static:
|
||||
return formatStaticSnippet(snippet);
|
||||
}
|
||||
})
|
||||
.map((item) => {
|
||||
|
|
|
|||
|
|
@ -105,24 +105,27 @@ export class AutocompleteLoggingService {
|
|||
});
|
||||
|
||||
const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome;
|
||||
void Telemetry.capture(
|
||||
"autocomplete",
|
||||
{
|
||||
accepted: restOfOutcome.accepted,
|
||||
cacheHit: restOfOutcome.cacheHit,
|
||||
completionId: restOfOutcome.completionId,
|
||||
completionOptions: restOfOutcome.completionOptions,
|
||||
debounceDelay: restOfOutcome.debounceDelay,
|
||||
fileExtension: getUriFileExtension(restOfOutcome.filepath),
|
||||
maxPromptTokens: restOfOutcome.maxPromptTokens,
|
||||
modelName: restOfOutcome.modelName,
|
||||
modelProvider: restOfOutcome.modelProvider,
|
||||
multilineCompletions: restOfOutcome.multilineCompletions,
|
||||
time: restOfOutcome.time,
|
||||
useRecentlyEdited: restOfOutcome.useRecentlyEdited,
|
||||
numLines: restOfOutcome.numLines,
|
||||
},
|
||||
true,
|
||||
);
|
||||
const toLog = {
|
||||
accepted: restOfOutcome.accepted,
|
||||
cacheHit: restOfOutcome.cacheHit,
|
||||
completionId: restOfOutcome.completionId,
|
||||
completionOptions: restOfOutcome.completionOptions,
|
||||
debounceDelay: restOfOutcome.debounceDelay,
|
||||
fileExtension: getUriFileExtension(restOfOutcome.filepath),
|
||||
maxPromptTokens: restOfOutcome.maxPromptTokens,
|
||||
modelName: restOfOutcome.modelName,
|
||||
modelProvider: restOfOutcome.modelProvider,
|
||||
multilineCompletions: restOfOutcome.multilineCompletions,
|
||||
time: restOfOutcome.time,
|
||||
useRecentlyEdited: restOfOutcome.useRecentlyEdited,
|
||||
numLines: restOfOutcome.numLines,
|
||||
};
|
||||
|
||||
outcome.enabledStaticContextualization
|
||||
? void Telemetry.capture("autocomplete", {
|
||||
...toLog,
|
||||
enabledStaticContextualization: true,
|
||||
})
|
||||
: void Telemetry.capture("autocomplete", toLog);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -42,4 +42,5 @@ export interface AutocompleteOutcome extends TabAutocompleteOptions {
|
|||
completionId: string;
|
||||
uniqueId: string;
|
||||
timestamp: string;
|
||||
enabledStaticContextualization?: boolean;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,5 +11,6 @@ export function convertCustomCommandToSlashCommand(
|
|||
description: customCommand.description ?? "",
|
||||
prompt: customCommand.prompt,
|
||||
source: "json-custom-command",
|
||||
promptFile: customCommand.sourceFile, // TODO refactor promptFile to align with sourceFile
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,5 +9,6 @@ export function convertPromptBlockToSlashCommand(
|
|||
description: prompt.description ?? "",
|
||||
prompt: prompt.prompt,
|
||||
source: "yaml-prompt-block",
|
||||
promptFile: prompt.sourceFile, // Align with the sourceFile property
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -522,7 +522,10 @@ export class ConfigHandler {
|
|||
return config;
|
||||
}
|
||||
|
||||
async openConfigProfile(profileId?: string) {
|
||||
async openConfigProfile(
|
||||
profileId?: string,
|
||||
element?: { sourceFile?: string },
|
||||
) {
|
||||
let openProfileId = profileId || this.currentProfile?.profileDescription.id;
|
||||
if (!openProfileId) {
|
||||
return;
|
||||
|
|
@ -530,8 +533,10 @@ export class ConfigHandler {
|
|||
const profile = this.currentOrg.profiles.find(
|
||||
(p) => p.profileDescription.id === openProfileId,
|
||||
);
|
||||
|
||||
if (profile?.profileDescription.profileType === "local") {
|
||||
await this.ide.openFile(profile.profileDescription.uri);
|
||||
const configFile = element?.sourceFile ?? profile.profileDescription.uri;
|
||||
await this.ide.openFile(configFile);
|
||||
} else {
|
||||
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
|
||||
await this.ide.openUrl(`${env.APP_URL}${openProfileId}`);
|
||||
|
|
|
|||
|
|
@ -652,6 +652,7 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
|
|||
configurationStatus: llm.getConfigurationStatus(),
|
||||
apiKeyLocation: llm.apiKeyLocation,
|
||||
envSecretLocations: llm.envSecretLocations,
|
||||
sourceFile: llm.sourceFile,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ export const sharedConfigSchema = z
|
|||
optInNextEditFeature: z.boolean(),
|
||||
enableExperimentalTools: z.boolean(),
|
||||
codebaseToolCallingOnly: z.boolean(),
|
||||
enableStaticContextualization: z.boolean(),
|
||||
|
||||
// `ui` in `ContinueConfig`
|
||||
showSessionTabs: z.boolean(),
|
||||
|
|
@ -188,6 +189,10 @@ export function modifyAnyConfigWithSharedConfig<
|
|||
configCopy.experimental.codebaseToolCallingOnly =
|
||||
sharedConfig.codebaseToolCallingOnly;
|
||||
}
|
||||
if (sharedConfig.enableStaticContextualization !== undefined) {
|
||||
configCopy.experimental.enableStaticContextualization =
|
||||
sharedConfig.enableStaticContextualization;
|
||||
}
|
||||
|
||||
return configCopy;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -56,6 +56,7 @@ function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
|
|||
rule: rule.rule,
|
||||
globs: rule.globs,
|
||||
name: rule.name,
|
||||
ruleFile: rule.sourceFile,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -235,8 +236,8 @@ async function configYamlToContinueConfig(options: {
|
|||
startUrl: doc.startUrl,
|
||||
rootUrl: doc.rootUrl,
|
||||
faviconUrl: doc.faviconUrl,
|
||||
maxDepth: doc.maxDepth,
|
||||
useLocalCrawling: doc.useLocalCrawling,
|
||||
sourceFile: doc.sourceFile,
|
||||
}));
|
||||
|
||||
config.mcpServers?.forEach((mcpServer) => {
|
||||
|
|
@ -429,6 +430,7 @@ async function configYamlToContinueConfig(options: {
|
|||
(config.mcpServers ?? []).map((server) => ({
|
||||
id: server.name,
|
||||
name: server.name,
|
||||
sourceFile: server.sourceFile,
|
||||
transport: {
|
||||
type: "stdio",
|
||||
args: [],
|
||||
|
|
|
|||
|
|
@ -349,7 +349,10 @@ export class Core {
|
|||
});
|
||||
|
||||
on("config/openProfile", async (msg) => {
|
||||
await this.configHandler.openConfigProfile(msg.data.profileId);
|
||||
await this.configHandler.openConfigProfile(
|
||||
msg.data.profileId,
|
||||
msg.data?.element,
|
||||
);
|
||||
});
|
||||
|
||||
on("config/reload", async (msg) => {
|
||||
|
|
|
|||
78
core/index.d.ts
vendored
78
core/index.d.ts
vendored
|
|
@ -237,6 +237,7 @@ export interface SiteIndexingConfig {
|
|||
maxDepth?: number;
|
||||
faviconUrl?: string;
|
||||
useLocalCrawling?: boolean;
|
||||
sourceFile?: string;
|
||||
}
|
||||
|
||||
export interface DocsIndexingDetails {
|
||||
|
|
@ -660,6 +661,8 @@ export interface LLMOptions {
|
|||
deploymentId?: string;
|
||||
|
||||
env?: Record<string, string | number | boolean>;
|
||||
|
||||
sourceFile?: string;
|
||||
}
|
||||
|
||||
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
|
||||
|
|
@ -871,6 +874,8 @@ export interface IDE {
|
|||
|
||||
// LSP
|
||||
gotoDefinition(location: Location): Promise<RangeInFile[]>;
|
||||
gotoTypeDefinition(location: Location): Promise<RangeInFile[]>; // TODO: add to jetbrains
|
||||
getSignatureHelp(location: Location): Promise<SignatureHelp | null>; // TODO: add to jetbrains
|
||||
|
||||
// Callbacks
|
||||
onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void;
|
||||
|
|
@ -1035,6 +1040,7 @@ export interface CustomCommand {
|
|||
name: string;
|
||||
prompt: string;
|
||||
description?: string;
|
||||
sourceFile?: string;
|
||||
}
|
||||
|
||||
export interface Prediction {
|
||||
|
|
@ -1158,6 +1164,8 @@ export interface ModelDescription {
|
|||
capabilities?: ModelCapability;
|
||||
roles?: ModelRole[];
|
||||
configurationStatus?: LLMConfigurationStatuses;
|
||||
|
||||
sourceFile?: string;
|
||||
}
|
||||
|
||||
export interface JSONEmbedOptions {
|
||||
|
|
@ -1215,6 +1223,7 @@ export interface TabAutocompleteOptions {
|
|||
experimental_includeRecentlyVisitedRanges: boolean | number;
|
||||
experimental_includeRecentlyEditedRanges: boolean | number;
|
||||
experimental_includeDiff: boolean | number;
|
||||
experimental_enableStaticContextualization: boolean;
|
||||
}
|
||||
|
||||
export interface StdioOptions {
|
||||
|
|
@ -1312,6 +1321,7 @@ export interface MCPServerStatus extends MCPOptions {
|
|||
tools: MCPTool[];
|
||||
resources: MCPResource[];
|
||||
resourceTemplates: MCPResourceTemplate[];
|
||||
sourceFile?: string;
|
||||
}
|
||||
|
||||
export interface ContinueUIConfig {
|
||||
|
|
@ -1414,6 +1424,68 @@ export interface RangeInFileWithNextEditInfo {
|
|||
|
||||
export type SetCodeToEditPayload = RangeInFileWithContents | FileWithContents;
|
||||
|
||||
/**
|
||||
* Signature help represents the signature of something
|
||||
* callable. There can be multiple signatures but only one
|
||||
* active and only one active parameter.
|
||||
*/
|
||||
export class SignatureHelp {
|
||||
/**
|
||||
* One or more signatures.
|
||||
*/
|
||||
signatures: SignatureInformation[];
|
||||
|
||||
/**
|
||||
* The active signature.
|
||||
*/
|
||||
activeSignature: number;
|
||||
|
||||
/**
|
||||
* The active parameter of the active signature.
|
||||
*/
|
||||
activeParameter: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents the signature of something callable. A signature
|
||||
* can have a label, like a function-name, a doc-comment, and
|
||||
* a set of parameters.
|
||||
*/
|
||||
export class SignatureInformation {
|
||||
/**
|
||||
* The label of this signature. Will be shown in
|
||||
* the UI.
|
||||
*/
|
||||
label: string;
|
||||
|
||||
/**
|
||||
* The parameters of this signature.
|
||||
*/
|
||||
parameters: ParameterInformation[];
|
||||
|
||||
/**
|
||||
* The index of the active parameter.
|
||||
*
|
||||
* If provided, this is used in place of {@linkcode SignatureHelp.activeParameter}.
|
||||
*/
|
||||
activeParameter?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a parameter of a callable-signature. A parameter can
|
||||
* have a label and a doc-comment.
|
||||
*/
|
||||
export class ParameterInformation {
|
||||
/**
|
||||
* The label of this signature.
|
||||
*
|
||||
* Either a string or inclusive start and exclusive end offsets within its containing
|
||||
* {@link SignatureInformation.label signature label}. *Note*: A label of type string must be
|
||||
* a substring of its containing signature information's {@link SignatureInformation.label label}.
|
||||
*/
|
||||
label: string | [number, number];
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
|
|
@ -1484,6 +1556,12 @@ export interface ExperimentalConfig {
|
|||
* instead of embeddings, FTS, recently edited files, etc.
|
||||
*/
|
||||
codebaseToolCallingOnly?: boolean;
|
||||
|
||||
/**
|
||||
* If enabled, static contextualization will be used to
|
||||
* gather context for the model where necessary.
|
||||
*/
|
||||
enableStaticContextualization?: boolean;
|
||||
}
|
||||
|
||||
export interface AnalyticsConfig {
|
||||
|
|
|
|||
|
|
@ -187,6 +187,9 @@ export abstract class BaseLLM implements ILLM {
|
|||
maxEmbeddingChunkSize: number;
|
||||
maxEmbeddingBatchSize: number;
|
||||
|
||||
//URI to local block defining this LLM
|
||||
sourceFile?: string;
|
||||
|
||||
private _llmOptions: LLMOptions;
|
||||
|
||||
protected openaiAdapter?: BaseLlmApi;
|
||||
|
|
@ -290,6 +293,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
this.embeddingId = `${this.constructor.name}::${this.model}::${this.maxEmbeddingChunkSize}`;
|
||||
|
||||
this.autocompleteOptions = options.autocompleteOptions;
|
||||
this.sourceFile = options.sourceFile;
|
||||
}
|
||||
|
||||
getConfigurationStatus() {
|
||||
|
|
|
|||
|
|
@ -102,7 +102,10 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
),
|
||||
void,
|
||||
];
|
||||
"config/openProfile": [{ profileId: string | undefined }, void];
|
||||
"config/openProfile": [
|
||||
{ profileId: string | undefined; element?: { sourceFile?: string } },
|
||||
void,
|
||||
];
|
||||
"config/updateSharedConfig": [SharedConfigSchema, SharedConfigSchema];
|
||||
"config/updateSelectedModel": [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import type {
|
|||
Problem,
|
||||
Range,
|
||||
RangeInFile,
|
||||
SignatureHelp,
|
||||
TerminalOptions,
|
||||
Thread,
|
||||
} from "../";
|
||||
|
|
@ -82,6 +83,8 @@ export type ToIdeFromWebviewOrCoreProtocol = {
|
|||
getFileStats: [{ files: string[] }, FileStatsMap];
|
||||
|
||||
gotoDefinition: [{ location: Location }, RangeInFile[]];
|
||||
gotoTypeDefinition: [{ location: Location }, RangeInFile[]];
|
||||
getSignatureHelp: [{ location: Location }, SignatureHelp | null];
|
||||
|
||||
getControlPlaneSessionInfo: [
|
||||
{ silent: boolean; useOnboarding: boolean },
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ import type {
|
|||
Problem,
|
||||
Range,
|
||||
RangeInFile,
|
||||
SignatureHelp,
|
||||
TerminalOptions,
|
||||
Thread,
|
||||
} from "../..";
|
||||
|
|
@ -45,6 +46,14 @@ export class MessageIde implements IDE {
|
|||
return this.request("gotoDefinition", { location });
|
||||
}
|
||||
|
||||
async gotoTypeDefinition(location: Location): Promise<RangeInFile[]> {
|
||||
return this.request("gotoTypeDefinition", { location });
|
||||
}
|
||||
|
||||
async getSignatureHelp(location: Location): Promise<SignatureHelp | null> {
|
||||
return this.request("getSignatureHelp", { location });
|
||||
}
|
||||
|
||||
onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void {
|
||||
this.on("didChangeActiveTextEditor", (data) => callback(data.filepath));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ export const createRuleBlock: Tool = {
|
|||
'Creates a "rule" that can be referenced in future conversations. This should be used whenever you want to establish code standards / preferences that should be applied consistently, or when you want to avoid making a mistake again. To modify existing rules, use the edit tool instead.\n\nRule Types:\n- Always: Include only "rule" (always included in model context)\n- Auto Attached: Include "rule", "globs", and/or "regex" (included when files match patterns)\n- Agent Requested: Include "rule" and "description" (AI decides when to apply based on description)\n- Manual: Include only "rule" (only included when explicitly mentioned using @ruleName)',
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["name", "rule", "description"],
|
||||
required: ["name", "rule"],
|
||||
properties: {
|
||||
name: {
|
||||
type: "string",
|
||||
|
|
|
|||
|
|
@ -16,12 +16,11 @@ export const lsTool: Tool = {
|
|||
description: "List files and folders in a given directory",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["dirPath", "recursive"],
|
||||
properties: {
|
||||
dirPath: {
|
||||
type: "string",
|
||||
description:
|
||||
"The directory path relative to the root of the project. Always use forward slash paths like '/'. rather than e.g. '.'",
|
||||
"The directory path relative to the root of the project. Use forward slash paths like '/'. rather than e.g. '.'",
|
||||
},
|
||||
recursive: {
|
||||
type: "boolean",
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ export function getPreferredShell(): string {
|
|||
}
|
||||
}
|
||||
|
||||
export const PLATFORM_INFO = `Choose terminal commands and scripts optimized for ${os.platform} and ${os.arch} and shell ${getPreferredShell()}.`;
|
||||
export const PLATFORM_INFO = `Choose terminal commands and scripts optimized for ${os.platform()} and ${os.arch()} and shell ${getPreferredShell()}.`;
|
||||
|
||||
export const runTerminalCommandTool: Tool = {
|
||||
type: "function",
|
||||
|
|
|
|||
|
|
@ -1,22 +1,15 @@
|
|||
import { ToolImpl } from ".";
|
||||
import { RangeInFile } from "../..";
|
||||
import { retrieveContextItemsFromEmbeddings } from "../../context/retrieval/retrieval";
|
||||
import { getStringArg } from "../parseArgs";
|
||||
|
||||
export const codebaseToolImpl: ToolImpl = async (args, extras) => {
|
||||
if (!args.query || args.query.trim() === "") {
|
||||
return [
|
||||
{
|
||||
name: "Error",
|
||||
description: "Codebase search error",
|
||||
content: "Query parameter is required and cannot be empty.",
|
||||
},
|
||||
];
|
||||
}
|
||||
const query = getStringArg(args, "query");
|
||||
|
||||
try {
|
||||
const contextExtras = {
|
||||
config: extras.config,
|
||||
fullInput: args.query,
|
||||
fullInput: query,
|
||||
embeddingsProvider: extras.config.selectedModelByRole.embed,
|
||||
reranker: extras.config.selectedModelByRole.rerank,
|
||||
llm: extras.llm,
|
||||
|
|
@ -39,7 +32,7 @@ export const codebaseToolImpl: ToolImpl = async (args, extras) => {
|
|||
{
|
||||
name: "No Results",
|
||||
description: "Codebase search",
|
||||
content: `No relevant code found for query: "${args.query}". This could mean:
|
||||
content: `No relevant code found for query: "${query}". This could mean:
|
||||
- The codebase hasn't been indexed yet
|
||||
- No code matches the search criteria
|
||||
- Embeddings provider is not configured
|
||||
|
|
|
|||
|
|
@ -2,20 +2,24 @@ import { inferResolvedUriFromRelativePath } from "../../util/ideUtils";
|
|||
|
||||
import { ToolImpl } from ".";
|
||||
import { getCleanUriPath, getUriPathBasename } from "../../util/uri";
|
||||
import { getStringArg } from "../parseArgs";
|
||||
|
||||
export const createNewFileImpl: ToolImpl = async (args, extras) => {
|
||||
const filepath = getStringArg(args, "filepath");
|
||||
const contents = getStringArg(args, "contents", true);
|
||||
|
||||
const resolvedFileUri = await inferResolvedUriFromRelativePath(
|
||||
args.filepath,
|
||||
filepath,
|
||||
extras.ide,
|
||||
);
|
||||
if (resolvedFileUri) {
|
||||
const exists = await extras.ide.fileExists(resolvedFileUri);
|
||||
if (exists) {
|
||||
throw new Error(
|
||||
`File ${args.filepath} already exists. Use the edit tool to edit this file`,
|
||||
`File ${filepath} already exists. Use the edit tool to edit this file`,
|
||||
);
|
||||
}
|
||||
await extras.ide.writeFile(resolvedFileUri, args.contents);
|
||||
await extras.ide.writeFile(resolvedFileUri, contents);
|
||||
await extras.ide.openFile(resolvedFileUri);
|
||||
await extras.ide.saveFile(resolvedFileUri);
|
||||
if (extras.codeBaseIndexer) {
|
||||
|
|
|
|||
|
|
@ -2,6 +2,11 @@ import { createRuleMarkdown } from "@continuedev/config-yaml";
|
|||
import { ToolImpl } from ".";
|
||||
import { RuleWithSource } from "../..";
|
||||
import { createRuleFilePath } from "../../config/markdown/utils";
|
||||
import {
|
||||
getBooleanArg,
|
||||
getOptionalStringArg,
|
||||
getStringArg,
|
||||
} from "../parseArgs";
|
||||
|
||||
export type CreateRuleBlockArgs = Pick<
|
||||
Required<RuleWithSource>,
|
||||
|
|
@ -9,11 +14,21 @@ export type CreateRuleBlockArgs = Pick<
|
|||
> &
|
||||
Pick<RuleWithSource, "globs" | "regex" | "description" | "alwaysApply">;
|
||||
|
||||
export const createRuleBlockImpl: ToolImpl = async (
|
||||
{ name, rule, ...otherArgs }: CreateRuleBlockArgs,
|
||||
extras,
|
||||
) => {
|
||||
const fileContent = createRuleMarkdown(name, rule, otherArgs);
|
||||
export const createRuleBlockImpl: ToolImpl = async (args, extras) => {
|
||||
const name = getStringArg(args, "name");
|
||||
const rule = getStringArg(args, "rule");
|
||||
|
||||
const description = getOptionalStringArg(args, "description");
|
||||
const regex = getOptionalStringArg(args, "regex");
|
||||
const globs = getOptionalStringArg(args, "globs");
|
||||
const alwaysApply = getBooleanArg(args, "alwaysApply", false);
|
||||
|
||||
const fileContent = createRuleMarkdown(name, rule, {
|
||||
alwaysApply,
|
||||
description,
|
||||
globs,
|
||||
regex,
|
||||
});
|
||||
|
||||
const [localContinueDir] = await extras.ide.getWorkspaceDirs();
|
||||
const ruleFilePath = createRuleFilePath(localContinueDir, name);
|
||||
|
|
@ -24,7 +39,7 @@ export const createRuleBlockImpl: ToolImpl = async (
|
|||
return [
|
||||
{
|
||||
name: "New Rule Block",
|
||||
description: otherArgs.description || "",
|
||||
description: description || "",
|
||||
uri: {
|
||||
type: "file",
|
||||
value: ruleFilePath,
|
||||
|
|
|
|||
|
|
@ -1,10 +1,13 @@
|
|||
import { ToolImpl } from ".";
|
||||
import { getUrlContextItems } from "../../context/providers/URLContextProvider";
|
||||
import { getStringArg } from "../parseArgs";
|
||||
|
||||
const DEFAULT_FETCH_URL_CHAR_LIMIT = 20000;
|
||||
|
||||
export const fetchUrlContentImpl: ToolImpl = async (args, extras) => {
|
||||
const contextItems = await getUrlContextItems(args.url, extras.fetch);
|
||||
const url = getStringArg(args, "url");
|
||||
|
||||
const contextItems = await getUrlContextItems(url, extras.fetch);
|
||||
|
||||
// Track truncated content
|
||||
const truncatedUrls: string[] = [];
|
||||
|
|
@ -12,7 +15,7 @@ export const fetchUrlContentImpl: ToolImpl = async (args, extras) => {
|
|||
// Check and truncate each context item
|
||||
const processedItems = contextItems.map((item) => {
|
||||
if (item.content.length > DEFAULT_FETCH_URL_CHAR_LIMIT) {
|
||||
truncatedUrls.push(args.url);
|
||||
truncatedUrls.push(url);
|
||||
return {
|
||||
...item,
|
||||
content: item.content.substring(0, DEFAULT_FETCH_URL_CHAR_LIMIT),
|
||||
|
|
|
|||
|
|
@ -1,10 +1,13 @@
|
|||
import { ToolImpl } from ".";
|
||||
import { ContextItem } from "../..";
|
||||
import { getStringArg } from "../parseArgs";
|
||||
|
||||
const MAX_AGENT_GLOB_RESULTS = 100;
|
||||
|
||||
export const fileGlobSearchImpl: ToolImpl = async (args, extras) => {
|
||||
const pattern = getStringArg(args, "pattern");
|
||||
const results = await extras.ide.getFileResults(
|
||||
args.pattern,
|
||||
pattern,
|
||||
MAX_AGENT_GLOB_RESULTS,
|
||||
);
|
||||
const contextItems: ContextItem[] = [
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { ToolImpl } from ".";
|
||||
import { ContextItem } from "../..";
|
||||
import { formatGrepSearchResults } from "../../util/grepSearch";
|
||||
import { getStringArg } from "../parseArgs";
|
||||
|
||||
const DEFAULT_GREP_SEARCH_RESULTS_LIMIT = 100;
|
||||
const DEFAULT_GREP_SEARCH_CHAR_LIMIT = 5000; // ~1000 tokens, will keep truncation simply for now
|
||||
|
|
@ -41,8 +42,10 @@ function splitGrepResultsByFile(content: string): ContextItem[] {
|
|||
}
|
||||
|
||||
export const grepSearchImpl: ToolImpl = async (args, extras) => {
|
||||
const query = getStringArg(args, "query");
|
||||
|
||||
const results = await extras.ide.getSearchResults(
|
||||
args.query,
|
||||
query,
|
||||
DEFAULT_GREP_SEARCH_RESULTS_LIMIT,
|
||||
);
|
||||
const { formatted, numResults, truncated } = formatGrepSearchResults(
|
||||
|
|
@ -63,7 +66,7 @@ export const grepSearchImpl: ToolImpl = async (args, extras) => {
|
|||
|
||||
let contextItems: ContextItem[] = [];
|
||||
|
||||
const splitByFile: boolean = args.splitByFile || false;
|
||||
const splitByFile: boolean = args?.splitByFile || false;
|
||||
if (splitByFile) {
|
||||
contextItems = splitGrepResultsByFile(formatted);
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -2,28 +2,28 @@ import { resolveRelativePathInDir } from "../../util/ideUtils";
|
|||
import { getUriPathBasename } from "../../util/uri";
|
||||
|
||||
import { ToolImpl } from ".";
|
||||
import { getStringArg } from "../parseArgs";
|
||||
import { throwIfFileExceedsHalfOfContext } from "./readFileLimit";
|
||||
|
||||
export const readFileImpl: ToolImpl = async (args, extras) => {
|
||||
const firstUriMatch = await resolveRelativePathInDir(
|
||||
args.filepath,
|
||||
extras.ide,
|
||||
);
|
||||
const filepath = getStringArg(args, "filepath");
|
||||
|
||||
const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide);
|
||||
if (!firstUriMatch) {
|
||||
throw new Error(`Could not find file ${args.filepath}`);
|
||||
throw new Error(`Could not find file ${filepath}`);
|
||||
}
|
||||
const content = await extras.ide.readFile(firstUriMatch);
|
||||
|
||||
await throwIfFileExceedsHalfOfContext(
|
||||
args.filepath,
|
||||
filepath,
|
||||
content,
|
||||
extras.config.selectedModelByRole.chat,
|
||||
);
|
||||
|
||||
return [
|
||||
{
|
||||
name: getUriPathBasename(args.filepath),
|
||||
description: args.filepath,
|
||||
name: getUriPathBasename(firstUriMatch),
|
||||
description: filepath,
|
||||
content,
|
||||
uri: {
|
||||
type: "file",
|
||||
|
|
|
|||
|
|
@ -1,13 +1,14 @@
|
|||
import { ToolImpl } from ".";
|
||||
import { getStringArg } from "../parseArgs";
|
||||
|
||||
export const requestRuleImpl: ToolImpl = async (args, extras) => {
|
||||
const name = getStringArg(args, "name");
|
||||
|
||||
// Find the rule by name in the config
|
||||
const rule = extras.config.rules.find((r) => r.name === args.name);
|
||||
const rule = extras.config.rules.find((r) => r.name === name);
|
||||
|
||||
if (!rule || !rule.ruleFile) {
|
||||
throw new Error(
|
||||
`Rule with name "${args.name}" not found or has no file path`,
|
||||
);
|
||||
throw new Error(`Rule with name "${name}" not found or has no file path`);
|
||||
}
|
||||
|
||||
return [
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ import {
|
|||
isProcessBackgrounded,
|
||||
removeBackgroundedProcess,
|
||||
} from "../../util/processTerminalBackgroundStates";
|
||||
import { getBooleanArg, getStringArg } from "../parseArgs";
|
||||
|
||||
const asyncExec = util.promisify(childProcess.exec);
|
||||
|
||||
|
|
@ -50,8 +51,11 @@ const ENABLED_FOR_REMOTES = [
|
|||
];
|
||||
|
||||
export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
||||
const command = getStringArg(args, "command");
|
||||
// Default to waiting for completion if not specified
|
||||
const waitForCompletion = args.waitForCompletion !== false;
|
||||
const waitForCompletion =
|
||||
getBooleanArg(args, "waitForCompletion", false) ?? true;
|
||||
|
||||
const ideInfo = await extras.ide.getIdeInfo();
|
||||
const toolCallId = extras.toolCallId || "";
|
||||
|
||||
|
|
@ -84,7 +88,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
}
|
||||
|
||||
// Use spawn with color environment
|
||||
const childProc = childProcess.spawn(args.command, {
|
||||
const childProc = childProcess.spawn(command, {
|
||||
cwd,
|
||||
shell: true,
|
||||
env: getColorEnv(), // Add enhanced environment for colors
|
||||
|
|
@ -229,7 +233,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
// Standard execution, waiting for completion
|
||||
try {
|
||||
// Use color environment for exec as well
|
||||
const output = await asyncExec(args.command, {
|
||||
const output = await asyncExec(command, {
|
||||
cwd,
|
||||
env: getColorEnv(),
|
||||
});
|
||||
|
|
@ -258,7 +262,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
// but don't attach any listeners other than error
|
||||
try {
|
||||
// Use spawn with color environment
|
||||
const childProc = childProcess.spawn(args.command, {
|
||||
const childProc = childProcess.spawn(command, {
|
||||
cwd,
|
||||
shell: true,
|
||||
env: getColorEnv(), // Add color environment
|
||||
|
|
@ -309,7 +313,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
|
||||
// For remote environments, just run the command
|
||||
// Note: waitForCompletion is not supported in remote environments yet
|
||||
await extras.ide.runCommand(args.command);
|
||||
await extras.ide.runCommand(command);
|
||||
return [
|
||||
{
|
||||
name: "Terminal",
|
||||
|
|
|
|||
|
|
@ -1,10 +1,13 @@
|
|||
import { ToolImpl } from ".";
|
||||
import { fetchSearchResults } from "../../context/providers/WebContextProvider";
|
||||
import { getStringArg } from "../parseArgs";
|
||||
|
||||
const DEFAULT_WEB_SEARCH_CHAR_LIMIT = 8000;
|
||||
|
||||
export const searchWebImpl: ToolImpl = async (args, extras) => {
|
||||
const webResults = await fetchSearchResults(args.query, 5, extras.fetch);
|
||||
const query = getStringArg(args, "query");
|
||||
|
||||
const webResults = await fetchSearchResults(query, 5, extras.fetch);
|
||||
|
||||
// Track truncated results
|
||||
const truncatedResults: string[] = [];
|
||||
|
|
|
|||
|
|
@ -2,9 +2,11 @@ import generateRepoMap from "../../util/generateRepoMap";
|
|||
import { resolveRelativePathInDir } from "../../util/ideUtils";
|
||||
|
||||
import { ToolImpl } from ".";
|
||||
import { getStringArg } from "../parseArgs";
|
||||
|
||||
export const viewSubdirectoryImpl: ToolImpl = async (args: any, extras) => {
|
||||
const { directory_path } = args;
|
||||
const directory_path = getStringArg(args, "directory_path");
|
||||
|
||||
const uri = await resolveRelativePathInDir(directory_path, extras.ide);
|
||||
|
||||
if (!uri) {
|
||||
|
|
|
|||
|
|
@ -12,3 +12,52 @@ export function safeParseToolCallArgs(
|
|||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export function getStringArg(
|
||||
args: any,
|
||||
argName: string,
|
||||
allowEmpty = false,
|
||||
): string {
|
||||
if (!args || !(argName in args) || typeof args[argName] !== "string") {
|
||||
throw new Error(
|
||||
`\`${argName}\` argument is required${allowEmpty ? "" : " and must not be empty"}. (type string)`,
|
||||
);
|
||||
}
|
||||
if (!allowEmpty && !args[argName].trim()) {
|
||||
throw new Error(`Argument ${argName} must not be empty`);
|
||||
}
|
||||
return args[argName];
|
||||
}
|
||||
|
||||
export function getOptionalStringArg(
|
||||
args: any,
|
||||
argName: string,
|
||||
allowEmpty = false,
|
||||
) {
|
||||
if (typeof args?.[argName] === "undefined") {
|
||||
return undefined;
|
||||
}
|
||||
return getStringArg(args, argName, allowEmpty);
|
||||
}
|
||||
|
||||
export function getBooleanArg(args: any, argName: string, required = false) {
|
||||
if (!args || !(argName in args)) {
|
||||
if (required) {
|
||||
throw new Error(`Argument \`${argName}\` is required (type boolean)`);
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
if (typeof args[argName] === "string") {
|
||||
if (args[argName].toLowerCase() === "false") {
|
||||
return false;
|
||||
}
|
||||
if (args[argName].toLowerCase() === "true") {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (typeof args[argName] !== "boolean") {
|
||||
throw new Error(`Argument \`${argName}\` must be a boolean true or false`);
|
||||
}
|
||||
return args[argName];
|
||||
}
|
||||
|
|
|
|||
248
core/tools/parseArgs.vitest.ts
Normal file
248
core/tools/parseArgs.vitest.ts
Normal file
|
|
@ -0,0 +1,248 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import { ToolCallDelta } from "..";
|
||||
import {
|
||||
getBooleanArg,
|
||||
getOptionalStringArg,
|
||||
getStringArg,
|
||||
safeParseToolCallArgs,
|
||||
} from "./parseArgs";
|
||||
|
||||
describe("safeParseToolCallArgs", () => {
|
||||
it("should parse valid JSON arguments", () => {
|
||||
const toolCall: ToolCallDelta = {
|
||||
id: "1",
|
||||
function: {
|
||||
name: "testFunction",
|
||||
arguments: '{"name": "test", "value": 123}',
|
||||
},
|
||||
};
|
||||
|
||||
const result = safeParseToolCallArgs(toolCall);
|
||||
expect(result).toEqual({ name: "test", value: 123 });
|
||||
});
|
||||
|
||||
it("should parse valid JSON arguments with whitespace", () => {
|
||||
const toolCall: ToolCallDelta = {
|
||||
id: "1",
|
||||
function: {
|
||||
name: "testFunction",
|
||||
arguments: ' {"name": "test", "value": 123} ',
|
||||
},
|
||||
};
|
||||
|
||||
const result = safeParseToolCallArgs(toolCall);
|
||||
expect(result).toEqual({ name: "test", value: 123 });
|
||||
});
|
||||
|
||||
it("should return empty object for invalid JSON", () => {
|
||||
const toolCall: ToolCallDelta = {
|
||||
id: "1",
|
||||
function: {
|
||||
name: "testFunction",
|
||||
arguments: '{"name": "test", value: 123', // Invalid JSON
|
||||
},
|
||||
};
|
||||
|
||||
const result = safeParseToolCallArgs(toolCall);
|
||||
expect(result).toEqual({});
|
||||
});
|
||||
|
||||
it("should return empty object when arguments is empty", () => {
|
||||
const toolCall: ToolCallDelta = {
|
||||
id: "1",
|
||||
function: {
|
||||
name: "testFunction",
|
||||
arguments: "",
|
||||
},
|
||||
};
|
||||
|
||||
const result = safeParseToolCallArgs(toolCall);
|
||||
expect(result).toEqual({});
|
||||
});
|
||||
|
||||
it("should return empty object when arguments is null or undefined", () => {
|
||||
const toolCall1: ToolCallDelta = {
|
||||
id: "1",
|
||||
function: {
|
||||
name: "testFunction",
|
||||
arguments: null as any,
|
||||
},
|
||||
};
|
||||
|
||||
const toolCall2: ToolCallDelta = {
|
||||
id: "1",
|
||||
function: {
|
||||
name: "testFunction",
|
||||
arguments: undefined,
|
||||
},
|
||||
};
|
||||
|
||||
expect(safeParseToolCallArgs(toolCall1)).toEqual({});
|
||||
expect(safeParseToolCallArgs(toolCall2)).toEqual({});
|
||||
});
|
||||
|
||||
it("should handle case when function is undefined", () => {
|
||||
const toolCall: ToolCallDelta = {
|
||||
id: "1",
|
||||
function: undefined,
|
||||
};
|
||||
|
||||
const result = safeParseToolCallArgs(toolCall);
|
||||
expect(result).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe("getStringArg", () => {
|
||||
it("should return string argument when valid", () => {
|
||||
const args = { name: "test" };
|
||||
const result = getStringArg(args, "name");
|
||||
expect(result).toBe("test");
|
||||
});
|
||||
|
||||
it("should throw error when argument is missing", () => {
|
||||
const args = { otherArg: "test" };
|
||||
expect(() => getStringArg(args, "name")).toThrowError(
|
||||
"`name` argument is required and must not be empty. (type string)",
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error when argument is not a string", () => {
|
||||
const args = { name: 123 };
|
||||
expect(() => getStringArg(args, "name")).toThrowError(
|
||||
"`name` argument is required and must not be empty. (type string)",
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error when argument is empty and empty not allowed", () => {
|
||||
const args = { name: "" };
|
||||
expect(() => getStringArg(args, "name")).toThrowError(
|
||||
"Argument name must not be empty",
|
||||
);
|
||||
|
||||
const argsWithSpace = { name: " " };
|
||||
expect(() => getStringArg(argsWithSpace, "name")).toThrowError(
|
||||
"Argument name must not be empty",
|
||||
);
|
||||
});
|
||||
|
||||
it("should accept empty string when allowEmpty is true", () => {
|
||||
const args = { name: "" };
|
||||
const result = getStringArg(args, "name", true);
|
||||
expect(result).toBe("");
|
||||
|
||||
const argsWithSpace = { name: " " };
|
||||
const resultWithSpace = getStringArg(argsWithSpace, "name", true);
|
||||
expect(resultWithSpace).toBe(" ");
|
||||
});
|
||||
|
||||
it("should handle null or undefined args", () => {
|
||||
expect(() => getStringArg(null, "name")).toThrowError(
|
||||
"`name` argument is required and must not be empty. (type string)",
|
||||
);
|
||||
expect(() => getStringArg(undefined, "name")).toThrowError(
|
||||
"`name` argument is required and must not be empty. (type string)",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getOptionalStringArg", () => {
|
||||
it("should return undefined when argument is not provided", () => {
|
||||
const args = { otherArg: "test" };
|
||||
const result = getOptionalStringArg(args, "name");
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should return string argument when valid", () => {
|
||||
const args = { name: "test" };
|
||||
const result = getOptionalStringArg(args, "name");
|
||||
expect(result).toBe("test");
|
||||
});
|
||||
|
||||
it("should throw error when argument is not a string", () => {
|
||||
const args = { name: 123 };
|
||||
expect(() => getOptionalStringArg(args, "name")).toThrowError(
|
||||
"`name` argument is required and must not be empty. (type string)",
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error when argument is empty and empty not allowed", () => {
|
||||
const args = { name: "" };
|
||||
expect(() => getOptionalStringArg(args, "name")).toThrowError(
|
||||
"Argument name must not be empty",
|
||||
);
|
||||
});
|
||||
|
||||
it("should accept empty string when allowEmpty is true", () => {
|
||||
const args = { name: "" };
|
||||
const result = getOptionalStringArg(args, "name", true);
|
||||
expect(result).toBe("");
|
||||
});
|
||||
|
||||
it("should handle null or undefined args", () => {
|
||||
expect(getOptionalStringArg(null, "name")).toBeUndefined();
|
||||
expect(getOptionalStringArg(undefined, "name")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("getBooleanArg", () => {
|
||||
it("should return boolean argument when valid", () => {
|
||||
const argsTrue = { flag: true };
|
||||
const argsFalse = { flag: false };
|
||||
|
||||
expect(getBooleanArg(argsTrue, "flag")).toBe(true);
|
||||
expect(getBooleanArg(argsFalse, "flag")).toBe(false);
|
||||
});
|
||||
|
||||
it("should return undefined when argument is not provided and not required", () => {
|
||||
const args = { otherArg: true };
|
||||
const result = getBooleanArg(args, "flag");
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should throw error when argument is not provided and required", () => {
|
||||
const args = { otherArg: true };
|
||||
expect(() => getBooleanArg(args, "flag", true)).toThrowError(
|
||||
"Argument `flag` is required (type boolean)",
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle string "true" and "false" values', () => {
|
||||
const argsStringTrue = { flag: "true" };
|
||||
const argsStringFalse = { flag: "false" };
|
||||
const argsStringTrueUppercase = { flag: "TRUE" };
|
||||
const argsStringFalseUppercase = { flag: "FALSE" };
|
||||
|
||||
expect(getBooleanArg(argsStringTrue, "flag")).toBe(true);
|
||||
expect(getBooleanArg(argsStringFalse, "flag")).toBe(false);
|
||||
expect(getBooleanArg(argsStringTrueUppercase, "flag")).toBe(true);
|
||||
expect(getBooleanArg(argsStringFalseUppercase, "flag")).toBe(false);
|
||||
});
|
||||
|
||||
it("should throw error when argument is not a boolean or valid boolean string", () => {
|
||||
const argsNumber = { flag: 1 };
|
||||
const argsInvalidString = { flag: "yes" };
|
||||
const argsObject = { flag: {} };
|
||||
|
||||
expect(() => getBooleanArg(argsNumber, "flag")).toThrowError(
|
||||
"Argument `flag` must be a boolean true or false",
|
||||
);
|
||||
expect(() => getBooleanArg(argsInvalidString, "flag")).toThrowError(
|
||||
"Argument `flag` must be a boolean true or false",
|
||||
);
|
||||
expect(() => getBooleanArg(argsObject, "flag")).toThrowError(
|
||||
"Argument `flag` must be a boolean true or false",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle null or undefined args", () => {
|
||||
expect(getBooleanArg(null, "flag")).toBeUndefined();
|
||||
expect(getBooleanArg(undefined, "flag")).toBeUndefined();
|
||||
|
||||
expect(() => getBooleanArg(null, "flag", true)).toThrowError(
|
||||
"Argument `flag` is required (type boolean)",
|
||||
);
|
||||
expect(() => getBooleanArg(undefined, "flag", true)).toThrowError(
|
||||
"Argument `flag` is required (type boolean)",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -13,6 +13,7 @@ import {
|
|||
Problem,
|
||||
Range,
|
||||
RangeInFile,
|
||||
SignatureHelp,
|
||||
TerminalOptions,
|
||||
Thread,
|
||||
ToastType,
|
||||
|
|
@ -44,6 +45,14 @@ class FileSystemIde implements IDE {
|
|||
return Promise.resolve([]);
|
||||
}
|
||||
|
||||
gotoTypeDefinition(location: Location): Promise<RangeInFile[]> {
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
|
||||
getSignatureHelp(location: Location): Promise<SignatureHelp | null> {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
|
||||
onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void {
|
||||
return;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = {
|
|||
experimental_includeRecentlyVisitedRanges: true,
|
||||
experimental_includeRecentlyEditedRanges: true,
|
||||
experimental_includeDiff: true,
|
||||
experimental_enableStaticContextualization: false,
|
||||
};
|
||||
|
||||
export const COUNT_COMPLETION_REJECTED_AFTER = 10_000;
|
||||
|
|
|
|||
|
|
@ -94,4 +94,4 @@ If you need to force a refresh of the index, reload the VS Code window with <kbd
|
|||
|
||||
## Repository map
|
||||
|
||||
Models in the Claude 3, Llama 3.1/3.2, Gemini 1.5, and GPT-4o families will automatically use a [repository map](../custom-providers.mdx#repository-map) during codebase retrieval, which allows the model to understand the structure of your codebase and use it to answer questions. Currently, the repository map only contains the filepaths in the codebase.
|
||||
Models in the Claude 3, Llama 3.1/3.2, Gemini 1.5, and GPT-4o families will automatically use a [repository map](../custom-providers#repository-map) during codebase retrieval, which allows the model to understand the structure of your codebase and use it to answer questions. Currently, the repository map only contains the filepaths in the codebase.
|
||||
|
|
|
|||
|
|
@ -54,7 +54,7 @@ The `@Docs` context provider works by
|
|||
|
||||
### Hub `docs` Blocks
|
||||
|
||||
@Docs uses [`docs` blocks](../../hub/blocks/block-types.md#docs) in Assistants from the hub. Visit the hub to [explore `docs` blocks](https://hub.continue.dev/explore/docs) or [create your own](https://hub.continue.dev/new?type=block&blockType=docs).
|
||||
@Docs uses [`docs` blocks](../../hub/blocks/block-types#docs) in Assistants from the hub. Visit the hub to [explore `docs` blocks](https://hub.continue.dev/explore/docs) or [create your own](https://hub.continue.dev/new?type=block&blockType=docs).
|
||||
|
||||
### Through the `@Docs` Context Provider
|
||||
|
||||
|
|
@ -354,7 +354,6 @@ The following configuration example includes:
|
|||
- title: My Private Docs
|
||||
startUrl: http://10.2.1.2/docs
|
||||
faviconUrl: http://10.2.1.2/docs/assets/favicon.ico
|
||||
maxDepth: 4
|
||||
useLocalCrawling: true
|
||||
```
|
||||
</Tab>
|
||||
|
|
|
|||
|
|
@ -143,7 +143,10 @@ Reference the contents of all of your open files. Set `onlyPinned` to `true` to
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: open params: onlyPinned: true
|
||||
context:
|
||||
- provider: open
|
||||
params:
|
||||
onlyPinned: true
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -164,7 +167,10 @@ Optionally, set `n` to limit the number of results returned (default 6).
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: web params: n: 5
|
||||
context:
|
||||
- provider: web
|
||||
params:
|
||||
n: 5
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -183,7 +189,8 @@ Reference the most relevant snippets from your codebase.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: codebase
|
||||
context:
|
||||
- provider: codebase
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -223,7 +230,10 @@ Reference the results of codebase search, just like the results you would get fr
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: search params: maxResults: 100 # optional, defaults to 200
|
||||
context:
|
||||
- provider: search
|
||||
params:
|
||||
maxResults: 100 # optional, defaults to 200
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -244,7 +254,8 @@ Reference the markdown converted contents of a given URL.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: url
|
||||
context:
|
||||
- provider: url
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -263,7 +274,8 @@ Reference recent clipboard items
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: clipboard
|
||||
context:
|
||||
- provider: clipboard
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -282,7 +294,8 @@ Reference the structure of your current workspace.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: tree
|
||||
context:
|
||||
- provider: tree
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -301,7 +314,8 @@ Get Problems from the current file.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: problems
|
||||
context:
|
||||
- provider: problems
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -320,7 +334,10 @@ Reference the contents of the local variables in the debugger. Currently only av
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: debugger params: stackDepth: 3
|
||||
context:
|
||||
- provider: debugger
|
||||
params:
|
||||
stackDepth: 3
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -343,7 +360,10 @@ Reference the outline of your codebase. By default, signatures are included alon
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: repo-map params: includeSignatures: false # default true
|
||||
context:
|
||||
- provider: repo-map
|
||||
params:
|
||||
includeSignatures: false # default true
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -368,7 +388,8 @@ Reference the architecture and platform of your current operating system.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: os
|
||||
context:
|
||||
- provider: os
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -387,7 +408,13 @@ The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a
|
|||
config.yaml
|
||||
|
||||
```
|
||||
mcpServers: - name: My MCP Server command: uvx args: - mcp-server-sqlite - --db-path - /Users/NAME/test.db
|
||||
mcpServers:
|
||||
- name: My MCP Server
|
||||
command: uvx
|
||||
args:
|
||||
- mcp-server-sqlite
|
||||
- --db-path
|
||||
- /Users/NAME/test.db
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -420,7 +447,13 @@ Reference the conversation in a GitHub issue.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: issue params: repos: - owner: continuedev repo: continue githubToken: ghp_xxx
|
||||
context:
|
||||
- provider: issue
|
||||
params:
|
||||
repos:
|
||||
- owner: continuedev
|
||||
repo: continue
|
||||
githubToken: ghp_xxx
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -451,7 +484,29 @@ Reference table schemas from Sqlite, Postgres, MSSQL, and MySQL databases.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: database params: connections: - name: examplePostgres connection_type: postgres connection: user: username host: localhost database: exampleDB password: yourPassword port: 5432 - name: exampleMssql connection_type: mssql connection: user: username server: localhost database: exampleDB password: yourPassword - name: exampleSqlite connection_type: sqlite connection: filename: /path/to/your/sqlite/database.db
|
||||
context:
|
||||
- provider: database
|
||||
params:
|
||||
connections:
|
||||
- name: examplePostgres
|
||||
connection_type: postgres
|
||||
connection:
|
||||
user: username
|
||||
host: localhost
|
||||
database: exampleDB
|
||||
password: yourPassword
|
||||
port: 5432
|
||||
- name: exampleMssql
|
||||
connection_type: mssql
|
||||
connection:
|
||||
user: username
|
||||
server: localhost
|
||||
database: exampleDB
|
||||
password: yourPassword
|
||||
- name: exampleSqlite
|
||||
connection_type: sqlite
|
||||
connection:
|
||||
filename: /path/to/your/sqlite/database.db
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -514,7 +569,16 @@ Reference the schema of a table, and some sample rows
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: postgres params: host: localhost port: 5436 user: myuser password: catsarecool database: animals schema: public sampleRows: 3
|
||||
context:
|
||||
- provider: postgres
|
||||
params:
|
||||
host: localhost
|
||||
port: 5436
|
||||
user: myuser
|
||||
password: catsarecool
|
||||
database: animals
|
||||
schema: public
|
||||
sampleRows: 3
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -554,7 +618,10 @@ Reference the results of a Google search.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: google params: serperApiKey: <YOUR_SERPER.DEV_API_KEY>
|
||||
context:
|
||||
- provider: google
|
||||
params:
|
||||
serperApiKey: <YOUR_SERPER.DEV_API_KEY>
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -584,7 +651,10 @@ Reference an open MR for this branch on GitLab.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: gitlab-mr params: token: "..."
|
||||
context:
|
||||
- provider: gitlab-mr
|
||||
params:
|
||||
token: "..."
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -605,7 +675,11 @@ You can specify the domain to communicate with by setting the `domain` parameter
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: gitlab-mr params: token: "..." domain: "gitlab.example.com"
|
||||
context:
|
||||
- provider: gitlab-mr
|
||||
params:
|
||||
token: "..."
|
||||
domain: "gitlab.example.com"
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -635,7 +709,11 @@ Reference the conversation in a Jira issue.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: jira params: domain: company.atlassian.net token: ATATT...
|
||||
context:
|
||||
- provider: jira
|
||||
params:
|
||||
domain: company.atlassian.net
|
||||
token: ATATT...
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -663,7 +741,10 @@ This context provider supports both Jira API version 2 and 3. It will use versio
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: jira params: apiVersion: "2"
|
||||
context:
|
||||
- provider: jira
|
||||
params:
|
||||
apiVersion: "2"
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -696,7 +777,16 @@ Reference the messages in a Discord channel.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: discord params: discordKey: "bot token" guildId: "1234567890" channels: - id: "123456" name: "example-channel" - id: "678901" name: "example-channel-2"
|
||||
context:
|
||||
- provider: discord
|
||||
params:
|
||||
discordKey: "bot token"
|
||||
guildId: "1234567890"
|
||||
channels:
|
||||
- id: "123456"
|
||||
name: "example-channel"
|
||||
- id: "678901"
|
||||
name: "example-channel-2"
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -731,7 +821,10 @@ The HttpContextProvider makes a POST request to the url passed in the configurat
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: http params: url: "https://api.example.com/v1/users"
|
||||
context:
|
||||
- provider: http
|
||||
params:
|
||||
url: "https://api.example.com/v1/users"
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -770,7 +863,11 @@ Reference specific git commit metadata and diff or all of the recent commits.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: commit params: Depth: 50 LastXCommitsDepth: 10
|
||||
context:
|
||||
- provider: commit
|
||||
params:
|
||||
Depth: 50
|
||||
LastXCommitsDepth: 10
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -795,7 +892,11 @@ Query a [Greptile](https://www.greptile.com/) index of the current repo/branch.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: greptile params: greptileToken: "..." githubToken: "..."
|
||||
context:
|
||||
- provider: greptile
|
||||
params:
|
||||
greptileToken: "..."
|
||||
githubToken: "..."
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ Slash commands can be combined with additional instructions, including [context
|
|||
|
||||
### Assistant prompt blocks
|
||||
|
||||
The easiest way to add a slash command is by adding [`prompt` blocks](../../hub/blocks/block-types.md#prompts) to your assistant, which show up as slash commands in [Chat](../../features/chat/how-it-works.mdx).
|
||||
The easiest way to add a slash command is by adding [`prompt` blocks](../../hub/blocks/block-types#prompts) to your assistant, which show up as slash commands in [Chat](../../features/chat/how-it-works.mdx).
|
||||
|
||||
### Prompt files
|
||||
|
||||
|
|
|
|||
|
|
@ -48,7 +48,13 @@ We recommend configuring **GPT-4o** as your chat model.
|
|||
|
||||
## Autocomplete model
|
||||
|
||||
We recommend configuring **Codestral** as your autocomplete model. If you use Azure AI Foundry to deploy Codestral:
|
||||
We recommend configuring **Codestral** as your autocomplete model.
|
||||
|
||||
<Info>
|
||||
**Note:** Azure AI Foundry does not provide the FIM (Fill-in-Middle) endpoint required for autocomplete functionality. To use Codestral for autocomplete, deploy it through **Azure Machine Learning Studio** instead, which provides the necessary `/v1/fim/completions` endpoint.
|
||||
</Info>
|
||||
|
||||
If you use Azure Machine Learning Studio to deploy Codestral:
|
||||
|
||||
<Tabs>
|
||||
<Tab title="YAML">
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ You can add `embed` to a model's `roles` to specify that it can be used to embed
|
|||
|
||||
If you have the ability to use any model, we recommend `voyage-code-3`, which is listed below along with the rest of the options for embeddings models.
|
||||
|
||||
If you want to generate embeddings locally, we recommend using `nomic-embed-text` with [Ollama](../model-providers/top-level/ollama.mdx#embeddings-model).
|
||||
If you want to generate embeddings locally, we recommend using `nomic-embed-text` with [Ollama](../model-providers/top-level/ollama#embeddings-model).
|
||||
|
||||
### Voyage AI
|
||||
|
||||
|
|
@ -57,7 +57,7 @@ After obtaining an API key from [here](https://www.voyageai.com/), you can confi
|
|||
|
||||
### Ollama
|
||||
|
||||
See [here](../model-providers/top-level/ollama.mdx#embeddings-model) for instructions on how to use Ollama for embeddings.
|
||||
See [here](../model-providers/top-level/ollama#embeddings-model) for instructions on how to use Ollama for embeddings.
|
||||
|
||||
### Transformers.js (currently VS Code only)
|
||||
|
||||
|
|
@ -118,36 +118,36 @@ See [here](../model-providers/top-level/ollama.mdx#embeddings-model) for instruc
|
|||
|
||||
### OpenAI
|
||||
|
||||
See [here](../model-providers/top-level/openai.mdx#embeddings-model) for instructions on how to use OpenAI for embeddings.
|
||||
See [here](../model-providers/top-level/openai#embeddings-model) for instructions on how to use OpenAI for embeddings.
|
||||
|
||||
### Cohere
|
||||
|
||||
See [here](../model-providers/more/cohere.mdx#embeddings-model) for instructions on how to use Cohere for embeddings.
|
||||
See [here](../model-providers/more/cohere#embeddings-model) for instructions on how to use Cohere for embeddings.
|
||||
|
||||
### Gemini
|
||||
|
||||
See [here](../model-providers/top-level/gemini.mdx#embeddings-model) for instructions on how to use Gemini for embeddings.
|
||||
See [here](../model-providers/top-level/gemini#embeddings-model) for instructions on how to use Gemini for embeddings.
|
||||
|
||||
### Vertex
|
||||
|
||||
See [here](../model-providers/top-level/vertexai.mdx#embeddings-model) for instructions on how to use Vertex for embeddings.
|
||||
See [here](../model-providers/top-level/vertexai#embeddings-model) for instructions on how to use Vertex for embeddings.
|
||||
|
||||
### Mistral
|
||||
|
||||
See [here](../model-providers/top-level/mistral.mdx#embeddings-model) for instructions on how to use Mistral for embeddings.
|
||||
See [here](../model-providers/top-level/mistral#embeddings-model) for instructions on how to use Mistral for embeddings.
|
||||
|
||||
### NVIDIA
|
||||
|
||||
See [here](../model-providers/more/nvidia.mdx#embeddings-model) for instructions on how to use NVIDIA for embeddings.
|
||||
See [here](../model-providers/more/nvidia#embeddings-model) for instructions on how to use NVIDIA for embeddings.
|
||||
|
||||
### Bedrock
|
||||
|
||||
See [here](../model-providers/top-level/bedrock.mdx#embeddings-model) for instructions on how to use Bedrock for embeddings.
|
||||
See [here](../model-providers/top-level/bedrock#embeddings-model) for instructions on how to use Bedrock for embeddings.
|
||||
|
||||
### WatsonX
|
||||
|
||||
See [here](../model-providers/more/watsonx.mdx#embeddings-model) for instructions on how to use WatsonX for embeddings.
|
||||
See [here](../model-providers/more/watsonx#embeddings-model) for instructions on how to use WatsonX for embeddings.
|
||||
|
||||
### LMStudio
|
||||
|
||||
See [here](../model-providers/more/lmstudio.mdx#embeddings-model) for instructions on how to use LMStudio for embeddings.
|
||||
See [here](../model-providers/more/lmstudio#embeddings-model) for instructions on how to use LMStudio for embeddings.
|
||||
|
|
|
|||
|
|
@ -65,6 +65,7 @@
|
|||
"pages": [
|
||||
"features/agent/quick-start",
|
||||
"features/agent/how-it-works",
|
||||
"features/agent/plan-mode",
|
||||
"features/agent/model-setup",
|
||||
"features/agent/how-to-customize",
|
||||
"features/agent/context-selection"
|
||||
|
|
|
|||
|
|
@ -17,22 +17,37 @@ The following handshake describes how Agent uses tools:
|
|||
6. The model responds, potentially with another tool call and step 2 begins again
|
||||
|
||||
<Info>
|
||||
In [Chat mode](/features/chat/quick-start), tools are **not** included in the
|
||||
request to the model.
|
||||
Tool availability varies by mode:
|
||||
- **Chat mode**: No tools included
|
||||
- **Plan mode**: Only read-only tools included
|
||||
- **Agent mode**: All tools included
|
||||
</Info>
|
||||
|
||||
## Built-in tools
|
||||
|
||||
Continue includes several built-in tools which provide the model access to IDE functionality:
|
||||
Continue includes several built-in tools which provide the model access to IDE functionality.
|
||||
|
||||
- **Read file** (`read_file`): read the contents of a file within the project
|
||||
- **Read currently open file** (`read_currently_open_file`): read the contents of the currently open file
|
||||
- **Create new file** (`create_new_file`): Create a new file within the project, with path and contents specified by the model
|
||||
- **Exact search** (`exact_search`): perform a `ripgrep` search within the project
|
||||
- **Glob search** (`file_glob_search`): perform a glob search on files in the project. Currently limits to 100 output and warns the Agent if limit reached.
|
||||
- **Run terminal command** (`run_terminal_command`): run a terminal command from the workspace root
|
||||
- **Search web** (`search_web`): Perform a web search to get top results
|
||||
- **View diff** (`view_diff`): View the current working git diff
|
||||
- **View repo map** (`view_repo_map`): request a copy of the repository map—same as the [Repo Map Context Provider](/customize/custom-providers#repository-map)
|
||||
- **View subdirectory** (`view_subdirectory`): request a copy of a repo map for a specific directory within the project
|
||||
- **Create Rule Block** (`create_rule_block`): creates a new rule block in `.continue/rules` based on the contents of the conversation
|
||||
### Plan mode tools (read-only)
|
||||
|
||||
In Plan mode, only these read-only tools are available:
|
||||
- **Read file** (`read_file`)
|
||||
- **Read currently open file** (`read_currently_open_file`)
|
||||
- **List directory** (`ls`)
|
||||
- **Glob search** (`glob_search`)
|
||||
- **Grep search** (`grep_search`)
|
||||
- **Fetch URL content** (`fetch_url_content`)
|
||||
- **Search web** (`search_web`)
|
||||
- **View diff** (`view_diff`)
|
||||
- **View repo map** (`view_repo_map`)
|
||||
- **View subdirectory** (`view_subdirectory`)
|
||||
- **Codebase tool** (`codebase_tool`)
|
||||
|
||||
### Agent mode tools (all tools)
|
||||
|
||||
In Agent mode, all tools are available including the read-only tools above plus:
|
||||
|
||||
- **Create new file** (`create_new_file`): Create a new file within the project
|
||||
- **Edit file** (`edit_file`): Make changes to existing files
|
||||
- **Run terminal command** (`run_terminal_command`): Run commands from the workspace root
|
||||
- **Create Rule Block** (`create_rule_block`): Create a new rule block in `.continue/rules`
|
||||
- All other write/execute tools for modifying the codebase
|
||||
|
|
|
|||
49
docs/features/agent/plan-mode.mdx
Normal file
49
docs/features/agent/plan-mode.mdx
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
---
|
||||
title: "Plan Mode"
|
||||
description: "Explore and understand code safely with read-only tools"
|
||||
---
|
||||
|
||||
## What is Plan mode?
|
||||
|
||||
Plan mode is a restricted environment that provides read-only access to your codebase. It's designed for safe exploration, understanding code, and planning changes without making any modifications.
|
||||
|
||||

|
||||
|
||||
### Key features
|
||||
|
||||
- **Read-only tools**: Access files, search, and analyze without risk
|
||||
- **Safe exploration**: Perfect for understanding unfamiliar codebases
|
||||
- **Planning focus**: Develop implementation strategies before execution
|
||||
- **MCP support**: Works with all MCP tools alongside built-in read-only tools
|
||||
|
||||
### How it works
|
||||
|
||||
Plan mode filters the available tools to only include read-only operations. This means you can:
|
||||
- Read any file in your project
|
||||
- Search through code with grep and glob patterns
|
||||
- View repository structure and diffs
|
||||
- Fetch web content for additional context
|
||||
- Use all MCP tools
|
||||
|
||||
But you cannot:
|
||||
- Create, edit, or delete files
|
||||
- Run terminal commands
|
||||
- Make any system changes
|
||||
|
||||
### Getting started
|
||||
|
||||
Select "Plan" from the mode selector below the chat input, or use `Cmd/Ctrl + .` to cycle through modes.
|
||||
|
||||

|
||||
|
||||
For detailed information about tools and usage, see the [Agent documentation](/features/agent/how-it-works), which covers both Agent and Plan modes.
|
||||
|
||||
### Common workflow
|
||||
|
||||
1. **Start in Plan mode** to explore and understand
|
||||
2. **Develop your approach** with the model's help
|
||||
3. **Switch to Agent mode** when ready to implement
|
||||
|
||||
<Tip>
|
||||
Plan mode shares the same interface and context features as Chat and Agent modes. You can use `@` context providers and highlight code just like in other modes.
|
||||
</Tip>
|
||||
|
|
@ -6,18 +6,39 @@ title: "Quick Start"
|
|||
|
||||
Agent equips the Chat model with the tools needed to handle a wide range of coding tasks, allowing the model to make decisions and save you the work of manually finding context and performing actions.
|
||||
|
||||
### When to use each mode
|
||||
|
||||
- **Plan mode**: Use when you want to explore code, understand systems, or plan changes without making modifications. Perfect for:
|
||||
- Understanding unfamiliar codebases
|
||||
- Planning complex refactors
|
||||
- Debugging and investigation
|
||||
- Creating implementation strategies
|
||||
|
||||
- **Agent mode**: Use when you're ready to make changes. Ideal for:
|
||||
- Implementing features
|
||||
- Fixing bugs
|
||||
- Running tests and commands
|
||||
- Executing plans developed in Plan mode
|
||||
|
||||
### Use Agent
|
||||
|
||||
You can switch to `Agent` in the mode selector below the chat input box.
|
||||
You can switch to `Agent` in the mode selector below the chat input box. The mode selector offers three options:
|
||||
- **Chat**: No tools available, pure conversation
|
||||
- **Plan**: Read-only tools for safe exploration and planning
|
||||
- **Agent**: All tools available for making changes
|
||||
|
||||

|
||||
|
||||
<Info>
|
||||
If Agent is disabled with a `Not Supported` message, the selected model or
|
||||
If Agent or Plan is disabled with a `Not Supported` message, the selected model or
|
||||
provider doesn't support tools, or Continue doesn't yet support tools with it.
|
||||
See [Model Blocks](/customization/models) for more information.
|
||||
</Info>
|
||||
|
||||
<Tip>
|
||||
Use the keyboard shortcut `Cmd/Ctrl + .` to quickly cycle between modes.
|
||||
</Tip>
|
||||
|
||||
### Chat with Agent
|
||||
|
||||
Agent lives within the same interface as [Chat](/features/chat/how-it-works), so the same [input](/features/chat/quick-start#1-start-a-conversation) is used to send messages and you can still use the same manual methods of providing context, such as [`@` context providers](/features/chat/quick-start#3-use--for-additional-context) or adding [highlighted code from the editor](/features/chat/quick-start#2-include-code-context).
|
||||
|
|
|
|||
|
|
@ -25,6 +25,13 @@ These models have varying tool calling and reasoning capabilities.
|
|||
3. Add `GEMINI_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
|
||||
4. Click `Reload config` in the assistant selector in the Continue IDE extension
|
||||
|
||||
[Kimi K2](hub.continue.dev/togetherai/kimi-k2-instruct) from Moonshot AI
|
||||
|
||||
1. Get your API key from [Together AI](https://api.together.ai)
|
||||
2. Add [Kimi K2](hub.continue.dev/togetherai/kimi-k2-instruct) to your assistant on Continue Hub
|
||||
3. Add `TOGETHER_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
|
||||
4. Click `Reload config` in the assistant selector in the Continue IDE extension
|
||||
|
||||
[o3](https://hub.continue.dev/openai/o3) from OpenAI
|
||||
|
||||
1. Get your API key from [OpenAI](https://platform.openai.com)
|
||||
|
|
@ -46,10 +53,10 @@ These models have varying tool calling and reasoning capabilities.
|
|||
3. Add `MISTRAL_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
|
||||
4. Click `Reload config` in the assistant selector in the Continue IDE extension
|
||||
|
||||
[Kimi K2](hub.continue.dev/togetherai/kimi-k2-instruct) from Moonshot AI
|
||||
[DeepSeek-V3](https://hub.continue.dev/togetherai/deepseek-v3) from DeepSeek
|
||||
|
||||
1. Get your API key from [TogetherAI](https://api.together.ai)
|
||||
2. Add [Kimi K2](hub.continue.dev/togetherai/kimi-k2-instruct) to your assistant on Continue Hub
|
||||
1. Get your API key from [Together AI](https://api.together.ai)
|
||||
2. Add [DeepSeek-V3](https://hub.continue.dev/togetherai/deepseek-v3) to your assistant on Continue Hub
|
||||
3. Add `TOGETHER_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets)
|
||||
4. Click `Reload config` in the assistant selector in the Continue IDE extension
|
||||
|
||||
|
|
@ -59,6 +66,18 @@ These models can be run on your computer if you have enough VRAM.
|
|||
|
||||
Their limited tool calling and reasoning capabilities will make it challenging to use Agent mode.
|
||||
|
||||
[Qwen2.5-Coder 32B](https://hub.continue.dev/ollama/qwen2.5-coder-32b)
|
||||
|
||||
1. Add [Qwen2.5-Coder 32B](https://hub.continue.dev/ollama/qwen2.5-coder-32b) to your assistant on Continue Hub
|
||||
2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide)
|
||||
3. Click `Reload config` in the assistant selector in the Continue IDE extension
|
||||
|
||||
[Devstral Small 27B](https://hub.continue.dev/ollama/devstral)
|
||||
|
||||
1. Add [Devstral Small](https://hub.continue.dev/ollama/devstral) to your assistant on Continue Hub
|
||||
2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide)
|
||||
3. Click `Reload config` in the assistant selector in the Continue IDE extension
|
||||
|
||||
[Qwen2.5-Coder 7B](https://hub.continue.dev/ollama/qwen2.5-coder-7b) from Qwen
|
||||
|
||||
1. Add [Qwen2.5-Coder 7B](https://hub.continue.dev/ollama/qwen2.5-coder-7b) to your assistant on Continue Hub
|
||||
|
|
@ -71,10 +90,4 @@ Their limited tool calling and reasoning capabilities will make it challenging t
|
|||
2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide)
|
||||
3. Click `Reload config` in the assistant selector in the Continue IDE extension
|
||||
|
||||
[Llama 3.1 8B](https://hub.continue.dev/ollama/llama3.1-8b) from Meta
|
||||
|
||||
1. Add [Llama 3.1 8B](https://hub.continue.dev/ollama/llama3.1-8b) to your assistant on Continue Hub
|
||||
2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide)
|
||||
3. Click `Reload config` in the assistant selector in the Continue IDE extension
|
||||
|
||||
For more detailed setup instructions, see [here](/getting-started/install#setup-your-first-model)
|
||||
|
|
|
|||
|
|
@ -4,8 +4,4 @@ The input you provide is included in the prompt.
|
|||
|
||||
## Code to Edit
|
||||
|
||||
The **entire contents** of each file (the current file for Jetbrains inline Edit, the `Code to Edit` item for VS Code Edit mode) are included in the prompt for context. The model will only attempt to edit the highlighted/specified ranges.
|
||||
|
||||
## Context Providers
|
||||
|
||||
In VS Code Edit mode, you can use `@` to add context using [Context Providers](/customize/custom-providers), similar to [Chat](/features/chat/context-selection). Some context providers may be disabled in Edit mode.
|
||||
The **entire contents** of the current file are included in the prompt for context. The model will only attempt to edit the highlighted/specified ranges.
|
||||
|
|
|
|||
|
|
@ -6,4 +6,6 @@ You can configure particular models from your Assistant to be used for Edit and
|
|||
2. Click the cube icon to expand the "Models" section
|
||||
3. Use the dropdowns to select models for Edit and Apply
|
||||
|
||||

|
||||
|
||||
Learn more about the [Edit role](/customize/model-roles/edit) and [Apply role](/customize/model-roles/apply).
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ Edit is recommended for small, targeted changes, such as
|
|||
|
||||
## Highlight code and activate
|
||||
|
||||
Highlight the block of code you would like to modify and press `cmd/ctrl` + `i` to active Edit mode. You can also enter Edit mode by pressing `cmd/ctrl` + `i` with no code highlighted, which will default to editing the current file.
|
||||
Highlight the block of code you would like to modify and press `Cmd+I` (Mac) or `Ctrl+I` (Windows/Linux) to activate Edit mode. You can also press `Cmd/Ctrl+I` with no code highlighted, which will default to inserting code at the current cursor location.
|
||||
|
||||
## Describe code changes
|
||||
|
||||
|
|
@ -24,23 +24,12 @@ Describe the changes you would like the model to make to your highlighted code.
|
|||
|
||||
Proposed changes appear as inline diffs within your highlighted text.
|
||||
|
||||
You can navigate through each proposed change, accepting or rejecting them using `cmd/ctrl` + `opt` + `y` (to accept) or `cmd/ctrl` + `opt` + `n` (to reject).
|
||||
You can navigate through each proposed change, accepting or rejecting them using `Cmd+Opt+Y` (Mac) or `Ctrl+Alt+Y` (Windows/Linux) to accept, or `Cmd+Opt+N` (Mac) or `Ctrl+Alt+N` (Windows/Linux) to reject.
|
||||
|
||||
You can also accept or reject all changes at once using `cmd/ctrl` + `shift` + `enter` (to accept) or `cmd/ctrl` + `shift` + `delete/backspace` (to reject).
|
||||
You can also accept or reject all changes at once using `Cmd+Shift+Enter` (Mac) or `Ctrl+Shift+Enter` (Windows/Linux) to accept, or `Cmd+Shift+Delete` (Mac) or `Ctrl+Shift+Backspace` (Windows/Linux) to reject.
|
||||
|
||||
If you want to request a new suggestion for the same highlighted code section, you can use `cmd/ctrl` + `i` to re-prompt the model.
|
||||
If you want to request a new suggestion for the same highlighted code section, you can use `Cmd+I` (Mac) or `Ctrl+I` (Windows/Linux) to re-prompt the model.
|
||||
|
||||
## VS Code
|
||||
|
||||
In VS Code, Edit is implemented in the extension sidebar with a similar interface to [Chat](/features/chat/how-it-works), and you can also enter Edit mode by using the Mode Selector below the main Chat input to select `Edit`.
|
||||
|
||||

|
||||
|
||||
You can also reject and accept diffs using the `Reject All` and `Accept All` buttons that show up in the Chat when diffs are present (see examples below).
|
||||
|
||||
### Adding Code to Edit
|
||||
|
||||
Along with adding highlighted code, you can also manually add files to edit using the `Add file` combobox or by clicking the dropdown and selecting `Add all open files` to add all files that are currently open in the editor.
|
||||
|
||||
## Jetbrains
|
||||
|
||||
|
|
|
|||
112
docs/features/plan/how-it-works.mdx
Normal file
112
docs/features/plan/how-it-works.mdx
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
---
|
||||
title: "How Plan Works"
|
||||
description: "Plan mode provides a restricted environment with read-only tools, enabling safe exploration and planning without making changes to your codebase."
|
||||
---
|
||||
|
||||
## Understanding Plan mode
|
||||
|
||||
Plan mode is designed to help you understand code and construct plans before making changes. It sits between Chat mode (no tools) and Agent mode (all tools), providing a middle ground where you can explore and analyze without risk.
|
||||
|
||||
### The key difference: Read-only tools
|
||||
|
||||
While Agent mode has access to all tools including those that modify files, Plan mode restricts access to only read-only tools. This ensures that:
|
||||
|
||||
- No files are created, modified, or deleted
|
||||
- No commands are executed that could change system state
|
||||
- All exploration is safe and non-destructive
|
||||
- You can confidently investigate without unintended consequences
|
||||
|
||||
## How Plan mode works
|
||||
|
||||
When you select Plan mode:
|
||||
|
||||
1. Continue sends a special system message instructing the model to focus on understanding and planning
|
||||
2. The tool list is filtered to include only read-only tools
|
||||
3. The model can use these tools to explore and analyze your codebase
|
||||
4. When you're ready to implement changes, you switch to Agent mode
|
||||
|
||||
### Available tools in Plan mode
|
||||
|
||||
Plan mode includes these read-only built-in tools:
|
||||
|
||||
- **Read file** (`read_file`): Read the contents of any file in the project
|
||||
- **Read currently open file** (`read_currently_open_file`): Read the contents of the currently open file
|
||||
- **List directory** (`ls`): List files and directories
|
||||
- **Glob search** (`glob_search`): Search for files matching a pattern
|
||||
- **Grep search** (`grep_search`): Search file contents using regex patterns
|
||||
- **Fetch URL content** (`fetch_url_content`): Retrieve content from web URLs
|
||||
- **Search web** (`search_web`): Perform web searches for additional context
|
||||
- **View diff** (`view_diff`): View the current git diff
|
||||
- **View repo map** (`view_repo_map`): Get an overview of the repository structure
|
||||
- **View subdirectory** (`view_subdirectory`): Get a detailed view of a specific directory
|
||||
- **Codebase tool** (`codebase_tool`): Advanced codebase analysis capabilities
|
||||
|
||||
### MCP tools support
|
||||
|
||||
In addition to built-in read-only tools, Plan mode also supports all MCP (Model Context Protocol) tools. This allows integration with external services that provide additional context or analysis capabilities without modifying your local environment.
|
||||
|
||||
<Info>
|
||||
While Plan mode restricts built-in tools to read-only operations, MCP tools are not filtered by Continue. Some MCP tools may have write capabilities that could modify your system or external services. Always verify what actions your MCP tools can perform before using them in Plan mode.
|
||||
</Info>
|
||||
|
||||
## The planning workflow
|
||||
|
||||
A typical Plan mode workflow follows these steps:
|
||||
|
||||
1. **Exploration**: Use read-only tools to understand the current state
|
||||
2. **Analysis**: Identify what needs to change and potential impacts
|
||||
3. **Planning**: Develop a detailed plan for implementation
|
||||
4. **Verification**: Review the plan and ensure it addresses all requirements
|
||||
5. **Execution**: Switch to Agent mode to implement the plan
|
||||
|
||||
### Example: Planning a refactor
|
||||
|
||||
```
|
||||
User: Help me plan a refactor to extract the authentication logic into a separate module
|
||||
|
||||
Plan mode:
|
||||
1. Reads relevant files to understand current structure
|
||||
2. Analyzes dependencies and usage patterns
|
||||
3. Identifies all places that need updates
|
||||
4. Creates a step-by-step refactoring plan
|
||||
5. Suggests: "Switch to Agent mode to implement this plan"
|
||||
```
|
||||
|
||||
## System message and behavior
|
||||
|
||||
Plan mode uses a dedicated system message that:
|
||||
|
||||
- Instructs the model to focus on understanding and planning
|
||||
- Emphasizes using only read-only tools
|
||||
- Reminds the model to suggest switching to Agent mode for implementation
|
||||
- Encourages thorough analysis before suggesting changes
|
||||
|
||||
<Info>
|
||||
The system message can be customized per model. See [How to
|
||||
Customize](/features/plan/how-to-customize) for details or see it [directly in
|
||||
the
|
||||
code](https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts).
|
||||
</Info>
|
||||
|
||||
## When to use Plan mode vs other modes
|
||||
|
||||
### Use Plan mode when:
|
||||
|
||||
- Exploring unfamiliar codebases
|
||||
- Planning complex refactors or features
|
||||
- Debugging and understanding issues
|
||||
- Reviewing code architecture
|
||||
- Creating implementation strategies
|
||||
|
||||
### Use Chat mode when:
|
||||
|
||||
- Having discussions without needing file access
|
||||
- Asking general programming questions
|
||||
- Getting explanations without exploring code
|
||||
|
||||
### Use Agent mode when:
|
||||
|
||||
- Ready to implement changes
|
||||
- Need to create or modify files
|
||||
- Want to run commands or tests
|
||||
- Implementing a plan developed in Plan mode
|
||||
60
docs/features/plan/quick-start.mdx
Normal file
60
docs/features/plan/quick-start.mdx
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
---
|
||||
title: "Quick Start"
|
||||
---
|
||||
|
||||
## How to use it
|
||||
|
||||
Plan mode provides a safe environment for understanding and constructing plans without making changes. It equips the Chat model with read-only tools, allowing you to explore, analyze, and plan modifications before executing them.
|
||||
|
||||
### Use Plan
|
||||
|
||||
You can switch to `Plan` in the mode selector below the chat input box.
|
||||
|
||||

|
||||
|
||||
<Info>
|
||||
If Plan is disabled with a `Not Supported` message, the selected model or
|
||||
provider doesn't support tools. See [Model Setup](/features/plan/model-setup)
|
||||
for more information.
|
||||
</Info>
|
||||
|
||||
### Chat with Plan
|
||||
|
||||
Plan mode lives within the same interface as [Chat](/features/chat/how-it-works) and [Agent](/features/agent/how-it-works), so the same [input](/features/chat/quick-start#1-start-a-conversation) is used to send messages and you can still use the same manual methods of providing context, such as [`@` context providers](/features/chat/quick-start#3-use--for-additional-context) or adding [highlighted code from the editor](/features/chat/quick-start#2-include-code-context).
|
||||
|
||||
#### What makes Plan different
|
||||
|
||||
Unlike Agent mode, Plan mode:
|
||||
- Only uses read-only tools (file reading, searching, analysis)
|
||||
- Cannot modify, create, or delete files
|
||||
- Focuses on understanding and planning rather than execution
|
||||
- Provides a safe environment for exploration
|
||||
|
||||
### Common use cases
|
||||
|
||||
Plan mode is ideal for:
|
||||
- **Code exploration**: Understanding how a codebase works
|
||||
- **Planning refactors**: Analyzing impact before making changes
|
||||
- **Debugging**: Investigating issues without modifying code
|
||||
- **Architecture review**: Understanding system design and dependencies
|
||||
- **Pre-implementation planning**: Thinking through changes before executing
|
||||
|
||||
### Example workflow
|
||||
|
||||
1. **Start in Plan mode** to explore and understand the task
|
||||
2. **Develop a plan** with the model's help
|
||||
3. **Switch to Agent mode** when ready to implement changes
|
||||
|
||||
For example, you might say:
|
||||
|
||||
> Help me understand how the authentication system works and plan improvements to add OAuth support
|
||||
|
||||
Plan mode will analyze the existing code, understand the current implementation, and help you create a detailed plan—all without making any changes.
|
||||
|
||||
## Switching to execution
|
||||
|
||||
When you're ready to implement your plan, simply switch to Agent mode using the mode selector or keyboard shortcut (`Cmd/Ctrl + .`). The conversation context carries over, so Agent mode can immediately start implementing the plan you developed.
|
||||
|
||||
<Tip>
|
||||
Use the keyboard shortcut `Cmd/Ctrl + .` to quickly cycle between Chat, Plan, and Agent modes.
|
||||
</Tip>
|
||||
|
|
@ -27,7 +27,7 @@ description: "To quickly understand what you can do with Continue, check out eac
|
|||
<Tab title="Edit">
|
||||
[Edit](/features/edit/quick-start) is a convenient way to modify code without leaving your current file
|
||||
|
||||

|
||||

|
||||
|
||||
<Info>
|
||||
Learn more about [Edit](/features/edit/quick-start)
|
||||
|
|
@ -43,4 +43,14 @@ description: "To quickly understand what you can do with Continue, check out eac
|
|||
Learn more about [Agent](/features/agent/quick-start)
|
||||
</Info>
|
||||
</Tab>
|
||||
|
||||
<Tab title="Plan">
|
||||
[Plan](/features/agent/plan-mode) provides a safe environment with read-only tools for exploring code and planning changes
|
||||
|
||||

|
||||
|
||||
<Info>
|
||||
Learn more about [Plan](/features/agent/plan-mode)
|
||||
</Info>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
|
|
|||
|
|
@ -79,7 +79,13 @@ After you've set up your server, you can configure Continue to use it by adding
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: http params: url: https://myserver.com/retrieve name: http description: Custom HTTP Context Provider displayTitle: My Custom Context
|
||||
context:
|
||||
- provider: http
|
||||
params:
|
||||
url: https://myserver.com/retrieve
|
||||
name: http
|
||||
description: Custom HTTP Context Provider
|
||||
displayTitle: My Custom Context
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
|
|||
|
|
@ -25,7 +25,11 @@ Basic authentication can be done with any provider using the `apiKey` field:
|
|||
config.yaml
|
||||
|
||||
```
|
||||
models: - name: Ollama provider: ollama model: llama2-7b apiKey: <YOUR_CUSTOM_OLLAMA_SERVER_API_KEY>
|
||||
models:
|
||||
- name: Ollama
|
||||
provider: ollama
|
||||
model: llama2-7b
|
||||
apiKey: <YOUR_CUSTOM_OLLAMA_SERVER_API_KEY>
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -53,7 +57,13 @@ If you need to send custom headers for authentication, you may use the `requestO
|
|||
config.yaml
|
||||
|
||||
```
|
||||
models: - name: Ollama provider: ollama model: llama2-7b requestOptions: headers: X-Auth-Token: xxx
|
||||
models:
|
||||
- name: Ollama
|
||||
provider: ollama
|
||||
model: llama2-7b
|
||||
requestOptions:
|
||||
headers:
|
||||
X-Auth-Token: xxx
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -79,7 +89,15 @@ Similarly if your model requires a Certificate for authentication, you may use t
|
|||
config.yaml
|
||||
|
||||
```
|
||||
models: - name: Ollama provider: ollama model: llama2-7b requestOptions: clientCertificate: cert: C:\tempollama.pem key: C:\tempollama.key passphrase: c0nt!nu3
|
||||
models:
|
||||
- name: Ollama
|
||||
provider: ollama
|
||||
model: llama2-7b
|
||||
requestOptions:
|
||||
clientCertificate:
|
||||
cert: C:\tempollama.pem
|
||||
key: C:\tempollama.key
|
||||
passphrase: c0nt!nu3
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
|
|||
|
|
@ -21,7 +21,10 @@ Ollama is the fastest way to get up and running with local language models. We r
|
|||
config.yaml
|
||||
|
||||
```
|
||||
models: - name: Llama 3.1 8b provider: ollama model: llama3.1-8b
|
||||
models:
|
||||
- name: Llama 3.1 8b
|
||||
provider: ollama
|
||||
model: llama3.1-8b
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -53,7 +56,11 @@ Groq provides the fastest available inference for open-source language models, i
|
|||
config.yaml
|
||||
|
||||
```
|
||||
models: - name: Llama 3.3 70b Versatile provider: groq model: llama-3.3-70b-versatile apiKey: <YOUR_GROQ_API_KEY>
|
||||
models:
|
||||
- name: Llama 3.3 70b Versatile
|
||||
provider: groq
|
||||
model: llama-3.3-70b-versatile
|
||||
apiKey: <YOUR_GROQ_API_KEY>
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -85,7 +92,11 @@ Together AI provides fast and reliable inference of open-source models. You'll b
|
|||
config.yaml
|
||||
|
||||
```
|
||||
models: - name: Llama 3.1 405b provider: together model: llama3.1-405b apiKey: <YOUR_TOGETHER_API_KEY>
|
||||
models:
|
||||
- name: Llama 3.1 405b
|
||||
provider: together
|
||||
model: llama3.1-405b
|
||||
apiKey: <YOUR_TOGETHER_API_KEY>
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -116,7 +127,11 @@ Replicate makes it easy to host and run open-source AI with an API.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
models: - name: Llama 3.1 405b provider: replicate model: llama3.1-405b apiKey: <YOUR_REPLICATE_API_KEY>
|
||||
models:
|
||||
- name: Llama 3.1 405b
|
||||
provider: replicate
|
||||
model: llama3.1-405b
|
||||
apiKey: <YOUR_REPLICATE_API_KEY>
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -148,7 +163,11 @@ SambaNova Cloud provides world record Llama3.1 70B/405B serving.
|
|||
config.yaml
|
||||
|
||||
```
|
||||
models: - name: SambaNova Llama 3.1 405B provider: sambanova model: llama3.1-405b apiKey: <YOUR_SAMBA_API_KEY>
|
||||
models:
|
||||
- name: SambaNova Llama 3.1 405B
|
||||
provider: sambanova
|
||||
model: llama3.1-405b
|
||||
apiKey: <YOUR_SAMBA_API_KEY>
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
@ -180,7 +199,11 @@ Cerebras Inference uses specialized silicon to provides fast inference for the L
|
|||
config.yaml
|
||||
|
||||
```
|
||||
models: - name: Cerebras Llama 3.1 70B provider: cerebras model: llama3.1-70b apiKey: <YOUR_CEREBRAS_API_KEY>
|
||||
models:
|
||||
- name: Cerebras Llama 3.1 70B
|
||||
provider: cerebras
|
||||
model: llama3.1-70b
|
||||
apiKey: <YOUR_CEREBRAS_API_KEY>
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
|
|||
|
|
@ -19,7 +19,14 @@ Before getting started, ensure your system meets these requirements:
|
|||
Choose the installation method for your operating system:
|
||||
|
||||
```
|
||||
# macOSbrew install ollama# Linuxcurl -fsSL https://ollama.ai/install.sh | sh# Windows# Download from ollama.ai
|
||||
# macOS
|
||||
brew install ollama
|
||||
|
||||
# Linux
|
||||
curl -fsSL https://ollama.ai/install.sh | sh
|
||||
|
||||
# Windows
|
||||
# Download from ollama.ai
|
||||
```
|
||||
|
||||
### Step 2: Download Models
|
||||
|
|
@ -27,7 +34,10 @@ Choose the installation method for your operating system:
|
|||
After installing Ollama, download the models you want to use. Here are some popular options:
|
||||
|
||||
```
|
||||
# Popular models for developmentollama pull llama2ollama pull codellamaollama pull mistral
|
||||
# Popular models for development
|
||||
ollama pull llama2
|
||||
ollama pull codellama
|
||||
ollama pull mistral
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
|
|
|||
|
|
@ -18,7 +18,15 @@ title: "How to Set Up Codestral"
|
|||
config.yaml
|
||||
|
||||
```
|
||||
models: - name: Codestral provider: mistral model: codestral-latest apiKey: <YOUR_CODESTRAL_API_KEY> apiBase: https://codestral.mistral.ai/v1 roles: - chat - autocomplete
|
||||
models:
|
||||
- name: Codestral
|
||||
provider: mistral
|
||||
model: codestral-latest
|
||||
apiKey: <YOUR_CODESTRAL_API_KEY>
|
||||
apiBase: https://codestral.mistral.ai/v1
|
||||
roles:
|
||||
- chat
|
||||
- autocomplete
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
|
|||
BIN
docs/images/edit-model.png
Normal file
BIN
docs/images/edit-model.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 127 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 6 MiB After Width: | Height: | Size: 3.6 MiB |
BIN
docs/images/plan-mode-compressed.gif
Normal file
BIN
docs/images/plan-mode-compressed.gif
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 25 MiB |
BIN
docs/images/plan-mode-selector.png
Normal file
BIN
docs/images/plan-mode-selector.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 69 KiB |
BIN
docs/images/plan-mode.gif
Normal file
BIN
docs/images/plan-mode.gif
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 9 MiB |
|
|
@ -61,7 +61,7 @@ Blocks:
|
|||
- `.continue/models` - for models
|
||||
- `.continue/prompts` - for prompts
|
||||
- `.continue/context` - for context providers
|
||||
- `.continue/docs` - for docs~~~~
|
||||
- `.continue/docs` - for docs
|
||||
- `.continue/data` - for data
|
||||
- `.continue/mcpServers` - for MCP Servers
|
||||
|
||||
|
|
@ -357,8 +357,6 @@ List of documentation sites to index.
|
|||
|
||||
- `name` (**required**): Name of the documentation site, displayed in dropdowns, etc.
|
||||
- `startUrl` (**required**): Start page for crawling - usually root or intro page for docs
|
||||
|
||||
- `maxDepth`: Maximum link depth for crawling. Default `4`
|
||||
- `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`).
|
||||
- `useLocalCrawling`: Skip the default crawler and only crawl using a local crawler.
|
||||
|
||||
|
|
@ -507,7 +505,6 @@ context:
|
|||
params:
|
||||
startUrl: https://docs.example.com/introduction
|
||||
rootUrl: https://docs.example.com
|
||||
maxDepth: 3
|
||||
mcpServers:
|
||||
- name: DevServer
|
||||
command: npm
|
||||
|
|
|
|||
|
|
@ -4,54 +4,25 @@ description: Set up an MCP server to search Continue documentation
|
|||
keywords: [mcp, documentation, search, mintlify, reference]
|
||||
---
|
||||
|
||||
The continue-docs MCP Server allows you to search and retrieve information from the Continue documentation directly within your agent conversations. This is powered by Mintlify's MCP server generation.
|
||||
The Continue Documentation MCP Server allows you to search and retrieve information from the Continue documentation directly within your agent conversations.
|
||||
|
||||
## Installation
|
||||
## Set up
|
||||
|
||||
### Step 1: Install the MCP Server
|
||||
|
||||
Run the following command to install the continue-docs MCP server:
|
||||
|
||||
```bash
|
||||
npx mint-mcp add docs.continue.dev
|
||||
```
|
||||
|
||||
When prompted, select "All" from the selection menu:
|
||||
|
||||

|
||||
|
||||
This command will:
|
||||
|
||||
- Download and install the MCP server locally
|
||||
- Set up the search tool for Continue documentation
|
||||
- Create the necessary configuration files
|
||||
|
||||
<Info>
|
||||
Take note of the installation path displayed after running the command above. You'll need to replace in the configuration below with your actual installation path.
|
||||
|
||||
It will look like this: `/path/to/user/.mcp/docs.continue.dev/src/index.js`
|
||||
|
||||
</Info>
|
||||
|
||||
### Step 2: Configure Continue
|
||||
### Configure Continue
|
||||
|
||||
1. Create a folder called `.continue/mcpServers` at the top level of your workspace
|
||||
2. Add a file called `continue-docs-mcp.yaml` to this folder
|
||||
3. Write the following contents and save:
|
||||
|
||||
````yaml title=".continue/mcpServers/continue-docs-mcp.yaml"
|
||||
```yaml title=".continue/mcpServers/continue-docs-mcp.yaml"
|
||||
name: Continue Documentation MCP
|
||||
version: 0.0.1
|
||||
schema: v1
|
||||
mcpServers:
|
||||
- name: Continue Docs Search
|
||||
command: node
|
||||
args:
|
||||
- "/path/to/user/.mcp/docs.continue.dev/src/index.js"
|
||||
````
|
||||
- uses: continuedev/continue-docs-mcp
|
||||
```
|
||||
|
||||
### Step 3: Enable Agent Mode
|
||||
### Enable Agent Mode
|
||||
|
||||
MCP servers only work in agent mode. Make sure to switch to agent mode in Continue before testing.
|
||||
|
||||
|
|
@ -62,77 +33,28 @@ Once configured, you can use the MCP server to search Continue documentation:
|
|||
### Model Configuration Help
|
||||
|
||||
```
|
||||
Search for model setup instructions in the Continue docs
|
||||
How do I add Claude 4 Sonnet as a model from Bedrock in Continue?
|
||||
```
|
||||
|
||||
### Context Providers
|
||||
|
||||
```
|
||||
Find documentation about context providers and how to configure them
|
||||
What context providers are available in Continue?
|
||||
```
|
||||
|
||||
### Autocomplete Setup
|
||||
### Customization
|
||||
|
||||
```
|
||||
How do I configure autocomplete in Continue?
|
||||
How do I add custom rules to my assistant in Continue?
|
||||
```
|
||||
|
||||
### Slash Commands
|
||||
|
||||
```
|
||||
Search for information about custom slash commands
|
||||
```
|
||||
|
||||
### Troubleshooting
|
||||
|
||||
```
|
||||
Find troubleshooting information for Continue extension issues
|
||||
```
|
||||
|
||||
## Test Plan
|
||||
|
||||
Use this test plan to verify your MCP server is working correctly:
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Continue extension is installed and running
|
||||
- Agent mode is enabled
|
||||
- MCP server configuration file exists in `.continue/mcpServers/`
|
||||
|
||||
### Test Cases
|
||||
|
||||
#### 1. Basic Documentation Search
|
||||
|
||||
- **Query**: "Search the Continue docs for information about model setup"
|
||||
- **Expected**: Returns structured information about configuring models
|
||||
- **Pass/Fail**: ☐
|
||||
|
||||
#### 2. Context Provider Documentation
|
||||
|
||||
- **Query**: "Find documentation about context providers in Continue"
|
||||
- **Expected**: Returns information about available context providers
|
||||
- **Pass/Fail**: ☐
|
||||
|
||||
#### 3. Feature-Specific Search
|
||||
|
||||
- **Query**: "How do I configure autocomplete in Continue?"
|
||||
- **Expected**: Returns autocomplete setup instructions
|
||||
- **Pass/Fail**: ☐
|
||||
|
||||
#### 4. MCP Documentation Search
|
||||
|
||||
- **Query**: "Search for MCP server setup instructions"
|
||||
- **Expected**: Returns MCP configuration information
|
||||
- **Pass/Fail**: ☐
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### MCP Server Not Loading
|
||||
|
||||
1. **Check configuration**: Ensure your YAML configuration uses the npx command approach
|
||||
2. **Verify installation**: Run `npx mint-mcp add continue-docs` to confirm the server can be accessed
|
||||
3. **Check agent mode**: MCP servers only work in agent mode
|
||||
4. **Restart Continue**: Try restarting the Continue extension
|
||||
1. **Check configuration**: Ensure your YAML configuration uses the correct `uses` field with `continuedev/continue-docs-mcp`
|
||||
2. **Check agent mode**: MCP servers only work in agent mode
|
||||
3. **Restart Continue**: Try restarting the Continue extension
|
||||
|
||||
### No Search Results
|
||||
|
||||
|
|
@ -140,20 +62,6 @@ Use this test plan to verify your MCP server is working correctly:
|
|||
2. **Check query format**: Try rephrasing your search query
|
||||
3. **Test with known topics**: Search for well-documented features like "model configuration"
|
||||
|
||||
### Permission Issues
|
||||
|
||||
If you encounter permission errors, ensure npx has proper permissions:
|
||||
|
||||
```bash
|
||||
npm config get prefix
|
||||
```
|
||||
|
||||
## Advanced Configuration
|
||||
|
||||
### Using Environment Variables
|
||||
|
||||
You can configure the MCP server with environment variables:
|
||||
|
||||
## Related Documentation
|
||||
|
||||
- [MCP Overview](/customize/deep-dives/mcp)
|
||||
|
|
|
|||
|
|
@ -88,7 +88,48 @@ config.json
|
|||
config.yaml
|
||||
|
||||
```
|
||||
models: - name: GPT-4 provider: openai model: gpt-4 apiKey: <YOUR_OPENAI_KEY> defaultCompletionOptions: temperature: 0.5 maxTokens: 2000 roles: - chat - edit - name: My Voyage Reranker provider: voyage apiKey: <YOUR_VOYAGE_KEY> roles: - rerank - name: My Starcoder provider: ollama model: starcoder2:3b roles: - autocomplete - name: My Ada Embedder provider: openai apiKey: <YOUR_ADA_API_KEY> roles: - embed embedOptions: - maxChunkSize: 256 - maxBatchSize: 5 - name: Ollama Autodetect provider: ollama model: AUTODETECT - name: My Open AI Compatible Model - Apply provider: openai model: my-openai-compatible-model apiBase: http://3.3.3.3/v1 requestOptions: headers: X-Auth-Token: <MY_API_KEY> roles: - chat - apply
|
||||
models:
|
||||
- name: GPT-4
|
||||
provider: openai
|
||||
model: gpt-4
|
||||
apiKey: <YOUR_OPENAI_KEY>
|
||||
defaultCompletionOptions:
|
||||
temperature: 0.5
|
||||
maxTokens: 2000
|
||||
roles:
|
||||
- chat
|
||||
- edit
|
||||
- name: My Voyage Reranker
|
||||
provider: voyage
|
||||
apiKey: <YOUR_VOYAGE_KEY>
|
||||
roles:
|
||||
- rerank
|
||||
- name: My Starcoder
|
||||
provider: ollama
|
||||
model: starcoder2:3b
|
||||
roles:
|
||||
- autocomplete
|
||||
- name: My Ada Embedder
|
||||
provider: openai
|
||||
apiKey: <YOUR_ADA_API_KEY>
|
||||
roles:
|
||||
- embed
|
||||
embedOptions:
|
||||
- maxChunkSize: 256
|
||||
- maxBatchSize: 5
|
||||
- name: Ollama Autodetect
|
||||
provider: ollama
|
||||
model: AUTODETECT
|
||||
- name: My Open AI Compatible Model - Apply
|
||||
provider: openai
|
||||
model: my-openai-compatible-model
|
||||
apiBase: http://3.3.3.3/v1
|
||||
requestOptions:
|
||||
headers:
|
||||
X-Auth-Token: <MY_API_KEY>
|
||||
roles:
|
||||
- chat
|
||||
- apply
|
||||
```
|
||||
|
||||
Note that the `repoMapFileSelection` experimental model role has been deprecated and is only available in `config.json`.
|
||||
|
|
@ -119,7 +160,13 @@ config.json
|
|||
config.yaml
|
||||
|
||||
```
|
||||
context: - provider: docs - provider: codebase params: nRetrieve: 30 nFinal: 3 - provider: diff
|
||||
context:
|
||||
- provider: docs
|
||||
- provider: codebase
|
||||
params:
|
||||
nRetrieve: 30
|
||||
nFinal: 3
|
||||
- provider: diff
|
||||
```
|
||||
|
||||
### System Message
|
||||
|
|
@ -139,7 +186,8 @@ config.json
|
|||
config.yaml
|
||||
|
||||
```
|
||||
rules: - Always give concise responses
|
||||
rules:
|
||||
- Always give concise responses
|
||||
```
|
||||
|
||||
### Prompts
|
||||
|
|
@ -167,7 +215,17 @@ config.json
|
|||
config.yaml
|
||||
|
||||
```
|
||||
prompts: - name: check description: Check for mistakes in my code prompt: | Please read the highlighted code and check for any mistakes. You should look for the following, and be extremely vigilant: - Syntax errors - Logic errors - Security vulnerabilities - Performance issues - Anything else that looks wrong Once you find an error, please explain it as clearly as possible, but without using extra words. For example, instead of saying 'I think there is a syntax error on line 5', you should say 'Syntax error on line 5'. Give your answer as one bullet point per mistake found.
|
||||
prompts:
|
||||
- name: check
|
||||
description: Check for mistakes in my code
|
||||
prompt: |
|
||||
Please read the highlighted code and check for any mistakes. You should look for the following, and be extremely vigilant:
|
||||
- Syntax errors
|
||||
- Logic errors
|
||||
- Security vulnerabilities
|
||||
- Performance issues
|
||||
- Anything else that looks wrong
|
||||
Once you find an error, please explain it as clearly as possible, but without using extra words. For example, instead of saying 'I think there is a syntax error on line 5', you should say 'Syntax error on line 5'. Give your answer as one bullet point per mistake found.
|
||||
```
|
||||
|
||||
### Documentation
|
||||
|
|
@ -192,7 +250,11 @@ config.json
|
|||
config.yaml
|
||||
|
||||
```
|
||||
docs: - name: nest.js startUrl: https://docs.nestjs.com/ - name: My site startUrl: https://mysite.com/docs/
|
||||
docs:
|
||||
- name: nest.js
|
||||
startUrl: https://docs.nestjs.com/
|
||||
- name: My site
|
||||
startUrl: https://mysite.com/docs/
|
||||
```
|
||||
|
||||
### MCP Servers
|
||||
|
|
@ -231,7 +293,15 @@ config.json
|
|||
config.yaml
|
||||
|
||||
```
|
||||
mcpServers: - name: My MCP Server command: uvx args: - mcp-server-sqlite - --db-path - /Users/NAME/test.db env: KEY: <VALUE>
|
||||
mcpServers:
|
||||
- name: My MCP Server
|
||||
command: uvx
|
||||
args:
|
||||
- mcp-server-sqlite
|
||||
- --db-path
|
||||
- /Users/NAME/test.db
|
||||
env:
|
||||
KEY: <VALUE>
|
||||
```
|
||||
|
||||
---
|
||||
|
|
|
|||
|
|
@ -92,7 +92,11 @@ If you're seeing a `fetch failed` error and your network requires custom certifi
|
|||
config.yaml
|
||||
|
||||
```
|
||||
models: - name: My Model ... requestOptions: caBundlePath: /path/to/cert.pem
|
||||
models:
|
||||
- name: My Model
|
||||
...
|
||||
requestOptions:
|
||||
caBundlePath: /path/to/cert.pem
|
||||
```
|
||||
|
||||
config.json
|
||||
|
|
|
|||
|
|
@ -9,6 +9,8 @@ fun Sync.prepareSandbox() {
|
|||
}
|
||||
|
||||
val remoteRobotVersion = "0.11.23"
|
||||
val isEap get() = environment("RELEASE_CHANNEL").orNull == "eap"
|
||||
val pluginVersion = properties("pluginVersion").get()
|
||||
|
||||
plugins {
|
||||
id("java")
|
||||
|
|
@ -22,21 +24,14 @@ plugins {
|
|||
}
|
||||
|
||||
group = properties("pluginGroup").get()
|
||||
version = if (isEap) "$pluginVersion-eap" else pluginVersion
|
||||
|
||||
version = properties("pluginVersion").get()
|
||||
|
||||
// Configure project's dependencies
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven { url = uri("https://packages.jetbrains.team/maven/p/ij/intellij-dependencies") }
|
||||
}
|
||||
|
||||
// Dependencies are managed with Gradle version catalog - read more:
|
||||
// https://docs.gradle.org/current/userguide/platforms.html#sub:version-catalog
|
||||
dependencies {
|
||||
implementation("com.squareup.okhttp3:okhttp:4.12.0") {
|
||||
exclude(group = "org.jetbrains.kotlin", module = "kotlin-stdlib")
|
||||
}
|
||||
implementation("org.jetbrains.kotlin:kotlin-stdlib:1.4.32")
|
||||
implementation("com.posthog.java:posthog:1.+")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.0")
|
||||
|
|
@ -48,22 +43,6 @@ dependencies {
|
|||
testImplementation("com.squareup.okhttp3:logging-interceptor:4.12.0")
|
||||
testImplementation("com.automation-remarks:video-recorder-junit5:2.0")
|
||||
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3")
|
||||
|
||||
|
||||
// Exclude vulnerable Log4j from all dependencies
|
||||
configurations.all {
|
||||
resolutionStrategy {
|
||||
eachDependency {
|
||||
if (requested.group == "log4j" && requested.name == "log4j") {
|
||||
useTarget("org.slf4j:log4j-over-slf4j:1.7.36")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add Log4j 2.x explicitly
|
||||
implementation("org.apache.logging.log4j:log4j-core:2.20.0")
|
||||
implementation("org.apache.logging.log4j:log4j-api:2.20.0")
|
||||
testImplementation(kotlin("test"))
|
||||
}
|
||||
|
||||
|
|
@ -105,7 +84,7 @@ koverReport { defaults { xml { onCheck = true } } }
|
|||
|
||||
tasks {
|
||||
downloadRobotServerPlugin {
|
||||
version.set(remoteRobotVersion)
|
||||
version = remoteRobotVersion
|
||||
}
|
||||
|
||||
prepareSandbox {
|
||||
|
|
@ -120,13 +99,14 @@ tasks {
|
|||
prepareSandbox()
|
||||
}
|
||||
|
||||
wrapper { gradleVersion = properties("gradleVersion").get() }
|
||||
wrapper {
|
||||
gradleVersion = properties("gradleVersion").get()
|
||||
}
|
||||
|
||||
patchPluginXml {
|
||||
version.set(properties("pluginVersion"))
|
||||
sinceBuild.set(properties("pluginSinceBuild"))
|
||||
untilBuild.set(properties("pluginUntilBuild"))
|
||||
pluginDescription.set(
|
||||
sinceBuild = properties("pluginSinceBuild")
|
||||
untilBuild = properties("pluginUntilBuild")
|
||||
pluginDescription =
|
||||
providers.fileContents(layout.projectDirectory.file("README.md")).asText.map {
|
||||
val start = "<!-- Plugin description -->"
|
||||
val end = "<!-- Plugin description end -->"
|
||||
|
|
@ -140,7 +120,6 @@ tasks {
|
|||
subList(indexOf(start) + 1, indexOf(end)).joinToString("\n").let(::markdownToHTML)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
// Configure UI tests plugin
|
||||
|
|
@ -167,7 +146,7 @@ tasks {
|
|||
// See ContinueExtensionSettingsService.kt for more info.
|
||||
// Currently commented out however since test fail in CI with this version
|
||||
// intellij {
|
||||
// version.set("2024.1")
|
||||
// version = "2024.1"
|
||||
// }
|
||||
}
|
||||
|
||||
|
|
@ -178,17 +157,10 @@ tasks {
|
|||
}
|
||||
|
||||
publishPlugin {
|
||||
// dependsOn("patchChangelog")
|
||||
token = environment("PUBLISH_TOKEN")
|
||||
// The pluginVersion is based on the SemVer (https://semver.org) and supports pre-release
|
||||
// labels, like 2.1.7-alpha.3
|
||||
// Specify pre-release label to publish the plugin in a custom Release Channel automatically.
|
||||
// Read more:
|
||||
// https://plugins.jetbrains.com/docs/intellij/deployment.html#specifying-a-release-channel
|
||||
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)
|
||||
val channel = if (isEap) "eap" else "default"
|
||||
channels = listOf(channel)
|
||||
}
|
||||
|
||||
runIde {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
package com.github.continuedev.continueintellijextension.auth
|
||||
|
||||
import com.github.continuedev.continueintellijextension.error.ContinueErrorService
|
||||
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
import com.google.gson.Gson
|
||||
|
|
@ -10,24 +11,22 @@ import com.intellij.ide.util.PropertiesComponent
|
|||
import com.intellij.openapi.application.ApplicationManager
|
||||
import com.intellij.openapi.components.Service
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.diagnostic.Logger
|
||||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.remoteServer.util.CloudConfigurationUtil.createCredentialAttributes
|
||||
import com.intellij.util.io.HttpRequests
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import java.net.URL
|
||||
import kotlin.time.Duration.Companion.minutes
|
||||
|
||||
@Service
|
||||
class ContinueAuthService {
|
||||
private val coroutineScope = CoroutineScope(Dispatchers.IO)
|
||||
private val log = Logger.getInstance(ContinueAuthService::class.java)
|
||||
|
||||
companion object {
|
||||
fun getInstance(): ContinueAuthService = service<ContinueAuthService>()
|
||||
private const val CREDENTIALS_USER = "ContinueAuthUser"
|
||||
private const val ACCESS_TOKEN_KEY = "ContinueAccessToken"
|
||||
private const val REFRESH_TOKEN_KEY = "ContinueRefreshToken"
|
||||
|
|
@ -77,73 +76,47 @@ class ContinueAuthService {
|
|||
}
|
||||
|
||||
private fun updateRefreshToken(token: String) {
|
||||
// Launch a coroutine to call the suspend function
|
||||
coroutineScope.launch {
|
||||
try {
|
||||
val response = refreshToken(token)
|
||||
val accessToken = response["accessToken"] as? String
|
||||
val refreshToken = response["refreshToken"] as? String
|
||||
val user = response["user"] as? Map<*, *>
|
||||
val firstName = user?.get("firstName") as? String
|
||||
val lastName = user?.get("lastName") as? String
|
||||
val label = "$firstName $lastName"
|
||||
val id = user?.get("id") as? String
|
||||
val email = user?.get("email") as? String
|
||||
try {
|
||||
val response = refreshToken(token)
|
||||
val accountLabel = "${response.user.firstName} ${response.user.lastName}"
|
||||
|
||||
// Persist the session info
|
||||
setRefreshToken(refreshToken!!)
|
||||
val sessionInfo =
|
||||
ControlPlaneSessionInfo(accessToken!!, ControlPlaneSessionInfo.Account(email!!, label))
|
||||
setControlPlaneSessionInfo(sessionInfo)
|
||||
// Persist the session info
|
||||
setRefreshToken(response.refreshToken)
|
||||
val account = ControlPlaneSessionInfo.Account(response.user.email, accountLabel)
|
||||
val sessionInfo = ControlPlaneSessionInfo(response.accessToken, account)
|
||||
setControlPlaneSessionInfo(sessionInfo)
|
||||
|
||||
// Notify listeners
|
||||
ApplicationManager.getApplication().messageBus.syncPublisher(AuthListener.TOPIC)
|
||||
.handleUpdatedSessionInfo(sessionInfo)
|
||||
|
||||
} catch (e: Exception) {
|
||||
// Handle any exceptions
|
||||
println("Exception while refreshing token: ${e.message}")
|
||||
}
|
||||
// Notify listeners
|
||||
ApplicationManager.getApplication().messageBus.syncPublisher(AuthListener.TOPIC)
|
||||
.handleUpdatedSessionInfo(sessionInfo)
|
||||
} catch (e: Exception) {
|
||||
service<ContinueErrorService>().report(e, "Exception while refreshing token ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
private fun setupRefreshTokenInterval() {
|
||||
// Launch a coroutine to refresh the token every 30 minutes
|
||||
coroutineScope.launch {
|
||||
while (true) {
|
||||
val refreshToken = getRefreshToken()
|
||||
if (refreshToken != null) {
|
||||
updateRefreshToken(refreshToken)
|
||||
}
|
||||
|
||||
kotlinx.coroutines.delay(15 * 60 * 1000) // 15 minutes in milliseconds
|
||||
log.info("Token refreshed, retrying in 15 minutes")
|
||||
delay(15.minutes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun refreshToken(refreshToken: String) = withContext(Dispatchers.IO) {
|
||||
val client = OkHttpClient()
|
||||
val url = URL(getControlPlaneUrl()).toURI().resolve("/auth/refresh").toURL()
|
||||
val jsonBody = mapOf("refreshToken" to refreshToken)
|
||||
val jsonString = Gson().toJson(jsonBody)
|
||||
val requestBody = jsonString.toRequestBody("application/json".toMediaType())
|
||||
|
||||
val request = Request.Builder()
|
||||
.url(url)
|
||||
.post(requestBody)
|
||||
.header("Content-Type", "application/json")
|
||||
.build()
|
||||
|
||||
val response = client.newCall(request).execute()
|
||||
|
||||
val responseBody = response.body?.string()
|
||||
private fun refreshToken(refreshToken: String): RefreshTokenResponse {
|
||||
val gson = Gson()
|
||||
val responseMap = gson.fromJson(responseBody, Map::class.java)
|
||||
|
||||
responseMap
|
||||
val jsonBody = gson.toJson(mapOf("refreshToken" to refreshToken))
|
||||
val url = getControlPlaneUrl() + "/auth/refresh"
|
||||
val response = HttpRequests.post(url, HttpRequests.JSON_CONTENT_TYPE)
|
||||
.connect { connection -> connection.write(jsonBody.toByteArray()) }
|
||||
.toString()
|
||||
return gson.fromJson(response, RefreshTokenResponse::class.java)
|
||||
}
|
||||
|
||||
|
||||
private fun openSignInPage(project: Project, useOnboarding: Boolean): String? {
|
||||
var authUrl: String? = null
|
||||
val coreMessenger = project.service<ContinuePluginService>().coreMessenger
|
||||
|
|
@ -256,6 +229,17 @@ class ContinueAuthService {
|
|||
setAccountLabel(info.account.label)
|
||||
}
|
||||
|
||||
private data class RefreshTokenResponse(
|
||||
val accessToken: String,
|
||||
val refreshToken: String,
|
||||
val user: User,
|
||||
) {
|
||||
data class User(
|
||||
val firstName: String,
|
||||
val lastName: String,
|
||||
val email: String
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Data class to represent the ControlPlaneSessionInfo
|
||||
|
|
|
|||
|
|
@ -7,9 +7,11 @@ import com.github.continuedev.continueintellijextension.`continue`.process.Conti
|
|||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
import com.github.continuedev.continueintellijextension.utils.uuid
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.JsonSyntaxException
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.diagnostic.Logger
|
||||
import com.intellij.openapi.project.Project
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
|
||||
class CoreMessenger(
|
||||
private val project: Project,
|
||||
|
|
@ -20,6 +22,7 @@ class CoreMessenger(
|
|||
private val gson = Gson()
|
||||
private val responseListeners = mutableMapOf<String, (Any?) -> Unit>()
|
||||
private val process = startContinueProcess()
|
||||
private val log = Logger.getInstance(CoreMessenger::class.java)
|
||||
|
||||
fun request(messageType: String, data: Any?, messageId: String?, onResponse: (Any?) -> Unit) {
|
||||
val id = messageId ?: uuid()
|
||||
|
|
@ -38,13 +41,13 @@ class CoreMessenger(
|
|||
}
|
||||
|
||||
private fun handleMessage(json: String) {
|
||||
val responseMap = gson.fromJson(json, Map::class.java)
|
||||
val responseMap = tryToParse(json) ?: return
|
||||
val messageId = responseMap["messageId"].toString()
|
||||
val messageType = responseMap["messageType"].toString()
|
||||
val data = responseMap["data"]
|
||||
|
||||
// IDE listeners
|
||||
if (MessageTypes.IDE_MESSAGE_TYPES.contains(messageType)) {
|
||||
if (messageType in MessageTypes.IDE_MESSAGE_TYPES) {
|
||||
ideProtocolClient.handleMessage(json) { data ->
|
||||
val message = gson.toJson(mapOf("messageId" to messageId, "messageType" to messageType, "data" to data))
|
||||
process.write(message)
|
||||
|
|
@ -52,8 +55,9 @@ class CoreMessenger(
|
|||
}
|
||||
|
||||
// Forward to webview
|
||||
if (MessageTypes.PASS_THROUGH_TO_WEBVIEW.contains(messageType)) {
|
||||
if (messageType in MessageTypes.PASS_THROUGH_TO_WEBVIEW) {
|
||||
val continuePluginService = project.service<ContinuePluginService>()
|
||||
// todo: is this a bug below (messageType = ID)? verify
|
||||
continuePluginService.sendToWebview(messageType, responseMap["data"], messageType)
|
||||
}
|
||||
|
||||
|
|
@ -68,6 +72,15 @@ class CoreMessenger(
|
|||
}
|
||||
}
|
||||
|
||||
// todo: map<*, *> = code smell
|
||||
private fun tryToParse(json: String): Map<*, *>? =
|
||||
try {
|
||||
gson.fromJson(json, Map::class.java)
|
||||
} catch (_: JsonSyntaxException) {
|
||||
log.warn("Invalid message JSON: $json") // example: NODE_ENV undefined
|
||||
null
|
||||
}
|
||||
|
||||
fun killSubProcess() {
|
||||
process.close()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,12 +8,13 @@ import com.github.continuedev.continueintellijextension.editor.DiffStreamService
|
|||
import com.github.continuedev.continueintellijextension.editor.EditorUtils
|
||||
import com.github.continuedev.continueintellijextension.error.ContinueErrorService
|
||||
import com.github.continuedev.continueintellijextension.protocol.*
|
||||
import com.github.continuedev.continueintellijextension.services.*
|
||||
import com.github.continuedev.continueintellijextension.utils.*
|
||||
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
import com.github.continuedev.continueintellijextension.utils.getMachineUniqueID
|
||||
import com.github.continuedev.continueintellijextension.utils.uuid
|
||||
import com.google.gson.Gson
|
||||
import com.intellij.openapi.application.ApplicationManager
|
||||
import com.intellij.openapi.command.WriteCommandAction
|
||||
import com.intellij.openapi.components.ServiceManager
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.editor.SelectionModel
|
||||
import com.intellij.openapi.fileEditor.FileEditorManager
|
||||
|
|
@ -21,7 +22,10 @@ import com.intellij.openapi.project.DumbAware
|
|||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.vfs.VirtualFileManager
|
||||
import com.intellij.openapi.wm.ToolWindowManager
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.launch
|
||||
import java.awt.Toolkit
|
||||
import java.awt.datatransfer.StringSelection
|
||||
|
||||
|
|
@ -323,7 +327,11 @@ class IdeProtocolClient(
|
|||
}
|
||||
|
||||
"runCommand" -> {
|
||||
// Running commands not yet supported in JetBrains
|
||||
val params = Gson().fromJson(
|
||||
dataElement.toString(),
|
||||
RunCommandParams::class.java
|
||||
)
|
||||
ide.runCommand(params.command, params.options)
|
||||
respond(null)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
|
||||
package com.github.continuedev.continueintellijextension.`continue`
|
||||
|
||||
import com.github.continuedev.continueintellijextension.*
|
||||
|
|
@ -27,12 +26,14 @@ import com.intellij.openapi.fileEditor.FileDocumentManager
|
|||
import com.intellij.openapi.fileEditor.FileEditorManager
|
||||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.project.guessProjectDir
|
||||
import com.intellij.openapi.util.IconLoader
|
||||
import com.intellij.openapi.vfs.LocalFileSystem
|
||||
import com.intellij.openapi.vfs.VirtualFileManager
|
||||
import com.intellij.openapi.wm.ToolWindowManager
|
||||
import com.intellij.psi.PsiDocumentManager
|
||||
import com.intellij.testFramework.LightVirtualFile
|
||||
import kotlinx.coroutines.*
|
||||
import org.jetbrains.plugins.terminal.ShellTerminalWidget
|
||||
import org.jetbrains.plugins.terminal.TerminalView
|
||||
import java.awt.Toolkit
|
||||
import java.awt.datatransfer.DataFlavor
|
||||
import java.io.BufferedReader
|
||||
|
|
@ -54,7 +55,7 @@ class IntelliJIDE(
|
|||
init {
|
||||
try {
|
||||
val os = getOS()
|
||||
|
||||
|
||||
if (os == OS.LINUX || os == OS.MAC) {
|
||||
val file = File(ripgrep)
|
||||
if (!file.canExecute()) {
|
||||
|
|
@ -135,7 +136,33 @@ class IntelliJIDE(
|
|||
}
|
||||
|
||||
override suspend fun getTerminalContents(): String {
|
||||
return ""
|
||||
return withContext(Dispatchers.EDT) {
|
||||
try {
|
||||
val toolWindow = ToolWindowManager.getInstance(project).getToolWindow("Terminal")
|
||||
|
||||
val terminalView = TerminalView.getInstance(project)
|
||||
// Find the first terminal widget selected, whatever its state, running command or not.
|
||||
val widget = terminalView.getWidgets().filterIsInstance<ShellTerminalWidget>().firstOrNull {
|
||||
toolWindow?.getContentManager()?.getContent(it)?.isSelected ?: false
|
||||
}
|
||||
|
||||
if (widget != null) {
|
||||
val textBuffer = widget.terminalTextBuffer
|
||||
val stringBuilder = StringBuilder()
|
||||
// Iterate through all lines in the buffer (history + screen)
|
||||
for (i in 0 until textBuffer.historyLinesCount + textBuffer.screenLinesCount) {
|
||||
stringBuilder.append(textBuffer.getLine(i).text).append('\n')
|
||||
}
|
||||
stringBuilder.toString()
|
||||
} else {
|
||||
"" // Return empty if no terminal is available
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
println("Error getting terminal contents: ${e.message}")
|
||||
e.printStackTrace()
|
||||
"" // Return empty on error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun getDebugLocals(threadIndex: Int): String {
|
||||
|
|
@ -220,8 +247,65 @@ class IntelliJIDE(
|
|||
}
|
||||
}
|
||||
|
||||
override suspend fun runCommand(command: String) {
|
||||
throw NotImplementedError("runCommand not implemented in IntelliJ")
|
||||
override suspend fun runCommand(command: String, options: TerminalOptions?) {
|
||||
val terminalOptions =
|
||||
options ?: TerminalOptions(reuseTerminal = true, terminalName = null, waitForCompletion = false)
|
||||
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
try {
|
||||
val toolWindow = ToolWindowManager.getInstance(project).getToolWindow("Terminal")
|
||||
toolWindow?.activate({
|
||||
try {
|
||||
val terminalView = TerminalView.getInstance(project)
|
||||
var widget: ShellTerminalWidget? = null
|
||||
|
||||
// 1. Handle reuseTerminal option
|
||||
if (terminalOptions.reuseTerminal == true && terminalView.getWidgets().isNotEmpty()) {
|
||||
// 2. Find by terminalName if provided
|
||||
if (terminalOptions.terminalName != null) {
|
||||
widget = terminalView.getWidgets().filterIsInstance<ShellTerminalWidget>()
|
||||
.firstOrNull {
|
||||
toolWindow.contentManager.getContent(it).tabName == terminalOptions.terminalName
|
||||
&& !it.hasRunningCommands()
|
||||
}
|
||||
} else {
|
||||
// 3. Find active terminal, or fall back to the first one
|
||||
widget = terminalView.getWidgets().filterIsInstance<ShellTerminalWidget>()
|
||||
.firstOrNull { toolWindow.contentManager.getContent(it).isSelected }
|
||||
?: terminalView.getWidgets().filterIsInstance<ShellTerminalWidget>().firstOrNull {
|
||||
!it.hasRunningCommands()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Create a new terminal if needed
|
||||
if (widget == null) {
|
||||
widget = terminalView.createLocalShellWidget(
|
||||
project.basePath,
|
||||
terminalOptions.terminalName,
|
||||
true
|
||||
)
|
||||
} else {
|
||||
// Ensure the found widget is visible
|
||||
val content = toolWindow.contentManager.getContent(widget)
|
||||
if (content != null) {
|
||||
toolWindow.contentManager.setSelectedContent(content, true)
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Show and send text
|
||||
widget.ttyConnector?.write(command)
|
||||
|
||||
} catch (e: Exception) {
|
||||
println("Error during terminal widget handling: ${e.message}")
|
||||
e.printStackTrace()
|
||||
}
|
||||
}, true)
|
||||
} catch (e: Exception) {
|
||||
println("Error activating terminal tool window: ${e.message}")
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun saveFile(filepath: String) {
|
||||
|
|
@ -343,7 +427,7 @@ class IntelliJIDE(
|
|||
}
|
||||
|
||||
val command = GeneralCommandLine(commandArgs)
|
||||
|
||||
|
||||
command.setWorkDirectory(project.basePath)
|
||||
val results = ExecUtil.execAndGetOutput(command).stdout
|
||||
return results.split("\n")
|
||||
|
|
@ -357,11 +441,12 @@ class IntelliJIDE(
|
|||
throw NotImplementedError("Ripgrep not supported, this workspace is remote")
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun getSearchResults(query: String, maxResults: Int?): String {
|
||||
val ideInfo = this.getIdeInfo()
|
||||
if (ideInfo.remoteName == "local") {
|
||||
try {
|
||||
val commandArgs = mutableListOf(
|
||||
val commandArgs = mutableListOf(
|
||||
ripgrep,
|
||||
"-i",
|
||||
"--ignore-file",
|
||||
|
|
@ -372,20 +457,20 @@ class IntelliJIDE(
|
|||
"2",
|
||||
"--heading"
|
||||
)
|
||||
|
||||
|
||||
// Conditionally add maxResults flag
|
||||
if (maxResults != null) {
|
||||
commandArgs.add("-m")
|
||||
commandArgs.add(maxResults.toString())
|
||||
}
|
||||
|
||||
|
||||
// Add the search query and path
|
||||
commandArgs.add("-e")
|
||||
commandArgs.add(query)
|
||||
commandArgs.add(".")
|
||||
|
||||
val command = GeneralCommandLine(commandArgs)
|
||||
|
||||
|
||||
command.setWorkDirectory(project.basePath)
|
||||
return ExecUtil.execAndGetOutput(command).stdout
|
||||
} catch (exception: Exception) {
|
||||
|
|
@ -594,6 +679,14 @@ class IntelliJIDE(
|
|||
throw NotImplementedError("gotoDefinition not implemented yet")
|
||||
}
|
||||
|
||||
override suspend fun gotoTypeDefinition(location: Location): List<RangeInFile> {
|
||||
throw NotImplementedError("gotoTypeDefinition not implemented yet")
|
||||
}
|
||||
|
||||
override suspend fun getSignatureHelp(location: Location): SignatureHelp? {
|
||||
throw NotImplementedError("getSignatureHelp not implemented yet")
|
||||
}
|
||||
|
||||
override fun onDidChangeActiveTextEditor(callback: (filepath: String) -> Unit) {
|
||||
throw NotImplementedError("onDidChangeActiveTextEditor not implemented yet")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package com.github.continuedev.continueintellijextension.protocol
|
||||
|
||||
import com.github.continuedev.continueintellijextension.*
|
||||
import com.github.continuedev.continueintellijextension.Range
|
||||
import com.github.continuedev.continueintellijextension.TerminalOptions
|
||||
|
||||
data class GetControlPlaneSessionInfoParams(val silent: Boolean, val useOnboarding: Boolean)
|
||||
|
||||
|
|
@ -59,4 +60,6 @@ data class GetGitRootPathParams(val dir: String)
|
|||
|
||||
data class ListDirParams(val dir: String)
|
||||
|
||||
data class GetFileStatsParams(val files: List<String>)
|
||||
data class GetFileStatsParams(val files: List<String>)
|
||||
|
||||
data class RunCommandParams(val command: String, val options: TerminalOptions?)
|
||||
|
|
|
|||
|
|
@ -1,25 +1,25 @@
|
|||
package com.github.continuedev.continueintellijextension.services
|
||||
|
||||
import com.github.continuedev.continueintellijextension.constants.getConfigJsPath
|
||||
import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath
|
||||
import com.intellij.execution.target.value.constant
|
||||
import com.github.continuedev.continueintellijextension.error.ContinueErrorService
|
||||
import com.intellij.openapi.application.ApplicationInfo
|
||||
import com.intellij.openapi.application.ApplicationManager
|
||||
import com.intellij.openapi.components.*
|
||||
import com.intellij.openapi.components.PersistentStateComponent
|
||||
import com.intellij.openapi.components.State
|
||||
import com.intellij.openapi.components.Storage
|
||||
import com.intellij.openapi.components.service
|
||||
import com.intellij.openapi.options.Configurable
|
||||
import com.intellij.openapi.project.DumbAware
|
||||
import com.intellij.openapi.util.SystemInfo
|
||||
import com.intellij.util.concurrency.AppExecutorUtil
|
||||
import com.intellij.util.io.HttpRequests
|
||||
import com.intellij.util.messages.Topic
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.decodeFromString
|
||||
import kotlinx.serialization.json.Json
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import java.awt.GridBagConstraints
|
||||
import java.awt.GridBagLayout
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.net.URL
|
||||
import java.util.concurrent.ScheduledFuture
|
||||
import java.util.concurrent.TimeUnit
|
||||
import javax.swing.*
|
||||
|
|
@ -72,11 +72,10 @@ class ContinueSettingsComponent : DumbAware {
|
|||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
class ContinueRemoteConfigSyncResponse {
|
||||
var configJson: String? = null
|
||||
var configJs: String? = null
|
||||
}
|
||||
data class ContinueRemoteConfigSyncResponse(
|
||||
var configJson: String?,
|
||||
var configJs: String?
|
||||
)
|
||||
|
||||
@State(
|
||||
name = "com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings",
|
||||
|
|
@ -117,50 +116,23 @@ open class ContinueExtensionSettings : PersistentStateComponent<ContinueExtensio
|
|||
|
||||
// Sync remote config from server
|
||||
private fun syncRemoteConfig() {
|
||||
val state = instance.continueState
|
||||
|
||||
if (state.remoteConfigServerUrl != null && state.remoteConfigServerUrl!!.isNotEmpty()) {
|
||||
// download remote config as json file
|
||||
|
||||
val client = OkHttpClient()
|
||||
val baseUrl = state.remoteConfigServerUrl?.removeSuffix("/")
|
||||
|
||||
val requestBuilder = Request.Builder().url("${baseUrl}/sync")
|
||||
|
||||
if (state.userToken != null) {
|
||||
requestBuilder.addHeader("Authorization", "Bearer ${state.userToken}")
|
||||
}
|
||||
|
||||
val request = requestBuilder.build()
|
||||
var configResponse: ContinueRemoteConfigSyncResponse? = null
|
||||
|
||||
val remoteServerUrl = state.remoteConfigServerUrl
|
||||
val token = state.userToken
|
||||
if (remoteServerUrl != null && remoteServerUrl.isNotEmpty()) {
|
||||
val baseUrl = remoteServerUrl.removeSuffix("/")
|
||||
try {
|
||||
client.newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) throw IOException("Unexpected code $response")
|
||||
|
||||
response.body?.string()?.let { responseBody ->
|
||||
try {
|
||||
configResponse =
|
||||
Json.decodeFromString<ContinueRemoteConfigSyncResponse>(responseBody)
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
val url = "$baseUrl/sync"
|
||||
val responseBody = HttpRequests.post(url, HttpRequests.JSON_CONTENT_TYPE)
|
||||
.tuner { connection ->
|
||||
if (token != null)
|
||||
connection.addRequestProperty("Authorization", "Bearer $token")
|
||||
}.readString()
|
||||
val response = Json.decodeFromString<ContinueRemoteConfigSyncResponse>(responseBody)
|
||||
val file = File(getConfigJsonPath(URL(url).host))
|
||||
response.configJs.let { file.writeText(it!!) }
|
||||
response.configJson.let { file.writeText(it!!) }
|
||||
} catch (e: IOException) {
|
||||
e.printStackTrace()
|
||||
return
|
||||
}
|
||||
|
||||
if (configResponse?.configJson?.isNotEmpty()!!) {
|
||||
val file = File(getConfigJsonPath(request.url.host))
|
||||
file.writeText(configResponse!!.configJson!!)
|
||||
}
|
||||
|
||||
if (configResponse?.configJs?.isNotEmpty()!!) {
|
||||
val file = File(getConfigJsPath(request.url.host))
|
||||
file.writeText(configResponse!!.configJs!!)
|
||||
service<ContinueErrorService>().report(e, "Unexpected exception during remote config sync")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -174,7 +146,7 @@ open class ContinueExtensionSettings : PersistentStateComponent<ContinueExtensio
|
|||
|
||||
instance.remoteSyncFuture = AppExecutorUtil.getAppScheduledExecutorService()
|
||||
.scheduleWithFixedDelay(
|
||||
{ syncRemoteConfig() },
|
||||
::syncRemoteConfig,
|
||||
0,
|
||||
continueState.remoteConfigSyncPeriod.toLong(),
|
||||
TimeUnit.MINUTES
|
||||
|
|
|
|||
|
|
@ -64,6 +64,68 @@ data class RangeInFileWithContents(
|
|||
val contents: String
|
||||
)
|
||||
|
||||
/**
|
||||
* Signature help represents the signature of something
|
||||
* callable. There can be multiple signatures but only one
|
||||
* active and only one active parameter.
|
||||
*/
|
||||
data class SignatureHelp(
|
||||
/**
|
||||
* One or more signatures.
|
||||
*/
|
||||
val signatures: List<SignatureInformation>,
|
||||
|
||||
/**
|
||||
* The active signature.
|
||||
*/
|
||||
val activeSignature: Int,
|
||||
|
||||
/**
|
||||
* The active parameter of the active signature.
|
||||
*/
|
||||
val activeParameter: Int
|
||||
)
|
||||
|
||||
/**
|
||||
* Represents the signature of something callable. A signature
|
||||
* can have a label, like a function-name, a doc-comment, and
|
||||
* a set of parameters.
|
||||
*/
|
||||
data class SignatureInformation(
|
||||
/**
|
||||
* The label of this signature. Will be shown in
|
||||
* the UI.
|
||||
*/
|
||||
val label: String,
|
||||
|
||||
/**
|
||||
* The parameters of this signature.
|
||||
*/
|
||||
val parameters: List<ParameterInformation>,
|
||||
|
||||
/**
|
||||
* The index of the active parameter.
|
||||
*
|
||||
* If provided, this is used in place of [SignatureHelp.activeParameter].
|
||||
*/
|
||||
val activeParameter: Int? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* Represents a parameter of a callable-signature. A parameter can
|
||||
* have a label and a doc-comment.
|
||||
*/
|
||||
data class ParameterInformation(
|
||||
/**
|
||||
* The label of this signature.
|
||||
*
|
||||
* Either a string or inclusive start and exclusive end offsets within its containing
|
||||
* [SignatureInformation.label] signature label. *Note*: A label of type string must be
|
||||
* a substring of its containing signature information's [SignatureInformation.label] label.
|
||||
*/
|
||||
val label: String // Note: Kotlin doesn't have union types, so this represents the string case
|
||||
)
|
||||
|
||||
data class ControlPlaneSessionInfo(
|
||||
val accessToken: String,
|
||||
val account: Account
|
||||
|
|
@ -91,6 +153,11 @@ data class ContinueRcJson(
|
|||
val mergeBehavior: ConfigMergeType
|
||||
)
|
||||
|
||||
data class TerminalOptions(
|
||||
val reuseTerminal: Boolean?,
|
||||
val terminalName: String?,
|
||||
val waitForCompletion: Boolean?
|
||||
)
|
||||
|
||||
interface IDE {
|
||||
suspend fun getIdeInfo(): IdeInfo
|
||||
|
|
@ -134,7 +201,7 @@ interface IDE {
|
|||
|
||||
suspend fun openUrl(url: String)
|
||||
|
||||
suspend fun runCommand(command: String)
|
||||
suspend fun runCommand(command: String, options: TerminalOptions?)
|
||||
|
||||
suspend fun saveFile(filepath: String)
|
||||
|
||||
|
|
@ -192,6 +259,8 @@ interface IDE {
|
|||
|
||||
// LSP
|
||||
suspend fun gotoDefinition(location: Location): List<RangeInFile>
|
||||
suspend fun gotoTypeDefinition(location: Location): List<RangeInFile>
|
||||
suspend fun getSignatureHelp(location: Location): SignatureHelp?
|
||||
|
||||
// Callbacks
|
||||
fun onDidChangeActiveTextEditor(callback: (filepath: String) -> Unit)
|
||||
|
|
@ -253,4 +322,4 @@ data class ShowFilePayload(
|
|||
sealed class FimResult {
|
||||
data class FimEdit(val fimText: String) : FimResult()
|
||||
object NotFimEdit : FimResult()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@
|
|||
<![CDATA[View the latest release notes on <a href="https://github.com/continuedev/continue/releases">GitHub</a>]]></change-notes>
|
||||
|
||||
<depends>com.intellij.modules.platform</depends>
|
||||
<depends>org.jetbrains.plugins.terminal</depends>
|
||||
|
||||
<!-- See here for why this is optional: https://github.com/continuedev/continue/issues/2775#issuecomment-2535620877-->
|
||||
<depends optional="true" config-file="continueintellijextension-withJSON.xml">
|
||||
|
|
|
|||
|
|
@ -6,7 +6,10 @@ import { EXTENSION_NAME } from "core/control-plane/env";
|
|||
import * as URI from "uri-js";
|
||||
import * as vscode from "vscode";
|
||||
|
||||
import { executeGotoProvider } from "./autocomplete/lsp";
|
||||
import {
|
||||
executeGotoProvider,
|
||||
executeSignatureHelpProvider,
|
||||
} from "./autocomplete/lsp";
|
||||
import { Repository } from "./otherExtensions/git";
|
||||
import { SecretStorage } from "./stubs/SecretStorage";
|
||||
import { VsCodeIdeUtils } from "./util/ideUtils";
|
||||
|
|
@ -24,6 +27,7 @@ import type {
|
|||
Location,
|
||||
Problem,
|
||||
RangeInFile,
|
||||
SignatureHelp,
|
||||
TerminalOptions,
|
||||
Thread,
|
||||
} from "core";
|
||||
|
|
@ -87,6 +91,28 @@ class VsCodeIde implements IDE {
|
|||
return result;
|
||||
}
|
||||
|
||||
async gotoTypeDefinition(location: Location): Promise<RangeInFile[]> {
|
||||
const result = await executeGotoProvider({
|
||||
uri: vscode.Uri.parse(location.filepath),
|
||||
line: location.position.line,
|
||||
character: location.position.character,
|
||||
name: "vscode.executeTypeDefinitionProvider",
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async getSignatureHelp(location: Location): Promise<SignatureHelp | null> {
|
||||
const result = await executeSignatureHelpProvider({
|
||||
uri: vscode.Uri.parse(location.filepath),
|
||||
line: location.position.line,
|
||||
character: location.position.character,
|
||||
name: "vscode.executeSignatureHelpProvider",
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
onDidChangeActiveTextEditor(callback: (uri: string) => void): void {
|
||||
vscode.window.onDidChangeActiveTextEditor((editor) => {
|
||||
if (editor) {
|
||||
|
|
|
|||
|
|
@ -13,7 +13,13 @@ import { intersection } from "core/util/ranges";
|
|||
import * as URI from "uri-js";
|
||||
import * as vscode from "vscode";
|
||||
|
||||
import type { IDE, Range, RangeInFile, RangeInFileWithContents } from "core";
|
||||
import type {
|
||||
IDE,
|
||||
Range,
|
||||
RangeInFile,
|
||||
RangeInFileWithContents,
|
||||
SignatureHelp,
|
||||
} from "core";
|
||||
import type Parser from "web-tree-sitter";
|
||||
|
||||
type GotoProviderName =
|
||||
|
|
@ -23,6 +29,8 @@ type GotoProviderName =
|
|||
| "vscode.executeImplementationProvider"
|
||||
| "vscode.executeReferenceProvider";
|
||||
|
||||
type SignatureHelpProviderName = "vscode.executeSignatureHelpProvider";
|
||||
|
||||
interface GotoInput {
|
||||
uri: vscode.Uri;
|
||||
line: number;
|
||||
|
|
@ -33,8 +41,19 @@ function gotoInputKey(input: GotoInput) {
|
|||
return `${input.name}${input.uri.toString()}${input.line}${input.character}`;
|
||||
}
|
||||
|
||||
interface SignatureHelpInput {
|
||||
uri: vscode.Uri;
|
||||
line: number;
|
||||
character: number;
|
||||
name: SignatureHelpProviderName;
|
||||
}
|
||||
function signatureHelpKey(input: SignatureHelpInput) {
|
||||
return `${input.name}${input.uri.toString()}${input.line}${input.character}`;
|
||||
}
|
||||
|
||||
const MAX_CACHE_SIZE = 500;
|
||||
const gotoCache = new Map<string, RangeInFile[]>();
|
||||
const signatureHelpCache = new Map<string, vscode.SignatureHelp>();
|
||||
|
||||
export async function executeGotoProvider(
|
||||
input: GotoInput,
|
||||
|
|
@ -382,3 +401,36 @@ export const getDefinitionsFromLsp: GetLspDefinitionsFunction = async (
|
|||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export async function executeSignatureHelpProvider(
|
||||
input: SignatureHelpInput,
|
||||
): Promise<SignatureHelp | null> {
|
||||
const cacheKey = signatureHelpKey(input);
|
||||
const cached = signatureHelpCache.get(cacheKey);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
try {
|
||||
const definitions = (await vscode.commands.executeCommand(
|
||||
input.name,
|
||||
input.uri,
|
||||
new vscode.Position(input.line, input.character),
|
||||
)) as SignatureHelp;
|
||||
|
||||
// Add to cache
|
||||
if (signatureHelpCache.size >= MAX_CACHE_SIZE) {
|
||||
// Remove the oldest item from the cache
|
||||
const oldestKey = signatureHelpCache.keys().next().value;
|
||||
if (oldestKey) {
|
||||
signatureHelpCache.delete(oldestKey);
|
||||
}
|
||||
}
|
||||
signatureHelpCache.set(cacheKey, definitions);
|
||||
|
||||
return definitions;
|
||||
} catch (e) {
|
||||
console.warn(`Error executing ${input.name}:`, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,59 @@
|
|||
;; Capture the variable/function name
|
||||
(variable_declarator
|
||||
name: (identifier) @function.name
|
||||
type: (type_annotation
|
||||
(function_type) @function.type))
|
||||
|
||||
;; Capture the full parameter list
|
||||
(function_type
|
||||
parameters: (formal_parameters) @function.params)
|
||||
|
||||
;; Capture the type identifiers used in the parameters
|
||||
(formal_parameters
|
||||
(required_parameter
|
||||
type: (type_annotation
|
||||
(type_identifier) @param.type))
|
||||
(required_parameter
|
||||
type: (type_annotation
|
||||
(type_identifier) @param.type)))
|
||||
|
||||
;; Capture the return type of the function
|
||||
(function_type
|
||||
return_type: (type_identifier) @return.type)
|
||||
|
||||
;; Capture any parse errors (e.g., the `@`)
|
||||
(ERROR) @error.node
|
||||
|
||||
;; Capture the entire function declaration line
|
||||
(lexical_declaration) @function.decl
|
||||
|
||||
;; Matches import declarations like: import { A, B } from "module";
|
||||
(import_statement
|
||||
(import_clause
|
||||
(named_imports
|
||||
(import_specifier
|
||||
name: (identifier) @import.name)))
|
||||
source: (string) @import.source)
|
||||
|
||||
;; Capture standalone function declarations
|
||||
(function_declaration
|
||||
name: (identifier) @function.name) @function.decl
|
||||
|
||||
;; Capture the function signature including parameters and return type
|
||||
(function_declaration
|
||||
parameters: (formal_parameters) @function.params
|
||||
return_type: (type_annotation)? @function.type)
|
||||
|
||||
;; For function expressions or arrow functions
|
||||
(function_type
|
||||
parameters: (formal_parameters) @function.params) @function.decl
|
||||
|
||||
;; For arrow functions
|
||||
(arrow_function
|
||||
parameters: (formal_parameters) @function.params) @function.decl
|
||||
|
||||
;; For function signatures without a body (like in your example)
|
||||
(function_signature
|
||||
name: (identifier) @function.name
|
||||
parameters: (formal_parameters) @function.params
|
||||
return_type: (type_annotation)? @function.type) @function.decl
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
;; Match top-level `var`, `let`, or `const` declarations
|
||||
(lexical_declaration
|
||||
(variable_declarator
|
||||
name: (identifier) @top.var.name
|
||||
type: (type_annotation
|
||||
(_) @top.var.type))) @top.var.decl
|
||||
|
||||
(variable_declaration
|
||||
(variable_declarator
|
||||
name: (identifier) @top.var.name
|
||||
type: (type_annotation
|
||||
(_) @top.var.type))) @top.var.decl
|
||||
|
||||
;; Match function declarations
|
||||
(function_declaration
|
||||
name: (identifier) @top.fn.name
|
||||
parameters: (formal_parameters
|
||||
(required_parameter
|
||||
pattern: (identifier) @top.fn.param.name
|
||||
type: (type_annotation (_) @top.fn.param.type)))*
|
||||
|
||||
return_type: (type_annotation (_) @top.fn.type)?) @top.fn.decl
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
;; Capture the type alias name (left-hand side)
|
||||
; (type_alias_declaration
|
||||
; name: (type_identifier) @type.name)
|
||||
|
||||
;; Capture all identifiers on the right-hand side (value), recursively
|
||||
; (type_alias_declaration
|
||||
; value: (_) @type.value)
|
||||
|
||||
;; Match all identifiers inside the type value — deeply nested
|
||||
(type_identifier) @type.identifier
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
(type_alias_declaration
|
||||
name: (type_identifier) @type.identifier
|
||||
value: (_) @type.value)
|
||||
|
||||
(interface_declaration
|
||||
name: (type_identifier) @type.identifier
|
||||
body: (_) @type.value)
|
||||
|
||||
(enum_declaration
|
||||
name: (type_identifier) @type.identifier
|
||||
body: (_) @type.value)
|
||||
|
|
@ -79,7 +79,7 @@ export function HistoryTableRow({
|
|||
navigate("/");
|
||||
}}
|
||||
>
|
||||
<div className="flex-1 cursor-pointer space-y-1">
|
||||
<td className="flex-1 cursor-pointer space-y-1">
|
||||
{editing ? (
|
||||
<div>
|
||||
<Input
|
||||
|
|
@ -114,10 +114,10 @@ export function HistoryTableRow({
|
|||
})}
|
||||
</span> */}
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
|
||||
{hovered && !editing && (
|
||||
<div className="bg-badge absolute right-2 top-1/2 ml-auto flex -translate-y-1/2 transform items-center gap-x-1 rounded-full px-2 py-1 shadow-md">
|
||||
<td className="bg-badge absolute right-2 top-1/2 ml-auto flex -translate-y-1/2 transform items-center gap-x-1 rounded-full px-2 py-1 shadow-md">
|
||||
<HeaderButtonWithToolTip
|
||||
text="Edit"
|
||||
onClick={async (e) => {
|
||||
|
|
@ -136,7 +136,7 @@ export function HistoryTableRow({
|
|||
>
|
||||
<TrashIcon width="1em" height="1em" />
|
||||
</HeaderButtonWithToolTip>
|
||||
</div>
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ import { CommandLineIcon } from "@heroicons/react/24/outline";
|
|||
import { useContext } from "react";
|
||||
import { lightGray, vscForeground } from "../..";
|
||||
import { IdeMessengerContext } from "../../../context/IdeMessenger";
|
||||
import { isJetBrains } from "../../../util";
|
||||
import { extractCommand } from "../utils/commandExtractor";
|
||||
|
||||
interface RunInTerminalButtonProps {
|
||||
|
|
@ -12,11 +11,6 @@ interface RunInTerminalButtonProps {
|
|||
export function RunInTerminalButton({ command }: RunInTerminalButtonProps) {
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
|
||||
if (isJetBrains()) {
|
||||
// JetBrains plugin doesn't currently have a way to run the command in the terminal for the user
|
||||
return null;
|
||||
}
|
||||
|
||||
function runInTerminal() {
|
||||
// Extract just the command line
|
||||
const extractedCommand = extractCommand(command);
|
||||
|
|
|
|||
|
|
@ -48,7 +48,9 @@ export function renderMessage(message: ChatMessage, includeRole: boolean) {
|
|||
{includeRole ? renderMessageRole(message.role) : ""}
|
||||
{message.toolCalls
|
||||
? message.toolCalls.map((toolCall) => (
|
||||
<pre>Tool call: {JSON.stringify(toolCall, undefined, 2)}</pre>
|
||||
<pre key={toolCall.id}>
|
||||
Tool call: {JSON.stringify(toolCall, undefined, 2)}
|
||||
</pre>
|
||||
))
|
||||
: ""}
|
||||
{renderMessageContent(message)}
|
||||
|
|
|
|||
|
|
@ -17,11 +17,7 @@ const ContextStatus = () => {
|
|||
return null;
|
||||
}
|
||||
|
||||
const barColorClass = isPruned
|
||||
? "bg-error"
|
||||
: percent > 80
|
||||
? "bg-warning"
|
||||
: "bg-description";
|
||||
const barColorClass = isPruned ? "bg-error" : "bg-description";
|
||||
|
||||
return (
|
||||
<div>
|
||||
|
|
@ -35,28 +31,27 @@ const ContextStatus = () => {
|
|||
}}
|
||||
clickable
|
||||
>
|
||||
<div className="flex flex-col gap-0 text-xs">
|
||||
<div className="flex flex-col gap-0 text-left text-xs">
|
||||
<span className="inline-block">
|
||||
{`${percent}% of context filled`}
|
||||
{`${percent}% of context filled.`}
|
||||
</span>
|
||||
{isPruned && (
|
||||
<span className="inline-block">
|
||||
{`Oldest messages are being removed`}
|
||||
{`Oldest messages are being removed.`}
|
||||
</span>
|
||||
)}
|
||||
{history.length > 0 && (
|
||||
<div className="flex flex-col gap-1 whitespace-pre">
|
||||
<div>
|
||||
<span
|
||||
className="inline-block cursor-pointer underline"
|
||||
className="hover:text-link inline-block cursor-pointer underline"
|
||||
onClick={() => compactConversation(history.length - 1)}
|
||||
>
|
||||
Compact conversation
|
||||
</span>
|
||||
{"\n"}
|
||||
<span className="inline-block">or</span> {"\n"}
|
||||
<span
|
||||
className="inline-block cursor-pointer underline"
|
||||
className="hover:text-link inline-block cursor-pointer underline"
|
||||
onClick={() => {
|
||||
dispatch(
|
||||
saveCurrentSession({
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ interface EditBlockButtonProps<T extends SectionKey> {
|
|||
blockType: T;
|
||||
block?: NonNullable<ConfigYaml[T]>[number];
|
||||
className?: string;
|
||||
sourceFile?: string;
|
||||
}
|
||||
|
||||
function isUsesBlock(block: any): block is { uses: string } {
|
||||
|
|
@ -23,6 +24,7 @@ export default function EditBlockButton<T extends SectionKey>({
|
|||
block,
|
||||
blockType,
|
||||
className = "",
|
||||
sourceFile,
|
||||
}: EditBlockButtonProps<T>) {
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const { selectedProfile } = useAuth();
|
||||
|
|
@ -37,6 +39,7 @@ export default function EditBlockButton<T extends SectionKey>({
|
|||
if (selectedProfile?.profileType === "local") {
|
||||
ideMessenger.post("config/openProfile", {
|
||||
profileId: undefined,
|
||||
element: { sourceFile },
|
||||
});
|
||||
} else if (block && isUsesBlock(block)) {
|
||||
openUrl(`${block.uses}/new-version`);
|
||||
|
|
|
|||
|
|
@ -121,6 +121,7 @@ export function PromptsSection() {
|
|||
} else {
|
||||
ideMessenger.post("config/openProfile", {
|
||||
profileId: undefined,
|
||||
element: { sourceFile: (prompt as any).sourceFile },
|
||||
});
|
||||
}
|
||||
};
|
||||
|
|
@ -149,7 +150,6 @@ export function PromptsSection() {
|
|||
index = index + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return promptsWithSlug.sort((a, b) => {
|
||||
const aBookmarked = isCommandBookmarked(a.name);
|
||||
const bBookmarked = isCommandBookmarked(b.name);
|
||||
|
|
|
|||
|
|
@ -60,6 +60,7 @@ const RuleCard: React.FC<RuleCardProps> = ({ rule }) => {
|
|||
} else {
|
||||
ideMessenger.post("config/openProfile", {
|
||||
profileId: undefined,
|
||||
element: { sourceFile: (rule as any).sourceFile },
|
||||
});
|
||||
}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -123,7 +123,11 @@ function DocsIndexingStatus({
|
|||
/>
|
||||
)}
|
||||
|
||||
<EditBlockButton blockType="docs" block={docFromYaml} />
|
||||
<EditBlockButton
|
||||
blockType="docs"
|
||||
block={docFromYaml}
|
||||
sourceFile={docConfig.sourceFile}
|
||||
/>
|
||||
|
||||
{["aborted", "complete", "failed"].includes(
|
||||
status?.status ?? "",
|
||||
|
|
|
|||
|
|
@ -132,7 +132,11 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) {
|
|||
|
||||
{/* Refresh button */}
|
||||
<div className="flex items-center gap-2">
|
||||
<EditBlockButton blockType={"mcpServers"} block={serverFromYaml} />
|
||||
<EditBlockButton
|
||||
blockType={"mcpServers"}
|
||||
block={serverFromYaml}
|
||||
sourceFile={server.sourceFile}
|
||||
/>
|
||||
<div
|
||||
className="text-lightgray flex cursor-pointer items-center hover:opacity-80"
|
||||
onClick={onRefresh}
|
||||
|
|
|
|||
|
|
@ -161,8 +161,8 @@ function ToolPolicyItem(props: ToolDropdownItemProps) {
|
|||
{parameters ? (
|
||||
<>
|
||||
<span className="text-xs font-bold">Arguments:</span>
|
||||
{parameters.map((param) => (
|
||||
<div className="block">
|
||||
{parameters.map((param, idx) => (
|
||||
<div key={idx} className="block">
|
||||
<code className="">{param[0]}</code>
|
||||
<span className="ml-1">{`(${param[1].type}):`}</span>
|
||||
<span className="ml-1 italic">{param[1].description}</span>
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue