Merge branch 'main' of github.com:continuedev/continue into jacob/enhancement/next-editable-region

This commit is contained in:
Jacob Kim 2025-07-28 16:29:39 -07:00
commit afa6320149
302 changed files with 16718 additions and 2606 deletions

View file

@ -0,0 +1,6 @@
---
globs: "**/*.{ts,tsx}"
alwaysApply: false
---
Use enums instead of simple string unions when possible in TypeScript code

View file

@ -11,6 +11,8 @@ body:
attributes:
label: Before submitting your bug report
options:
- label: I've tried using the "Ask AI" feature on the [Continue docs site](https://docs.continue.dev/) to see if the docs have an answer
required: false
- label: I believe this is a bug. I'll try to join the [Continue Discord](https://discord.gg/NWtdYexhMs) for questions
required: false
- label: I'm not able to find an [open issue](https://github.com/continuedev/continue/issues?q=is%3Aopen+is%3Aissue) that reports the same bug

View file

@ -63,7 +63,6 @@ jobs:
- name: Bump version in gradle.properties
run: |
cd extensions/intellij
awk '/pluginVersion=/{split($0,a,"="); split(a[2],b,"."); b[3]+=1; printf "%s=%s.%s.%s\n",a[1],b[1],b[2],b[3];next}1' gradle.properties > tmp && mv tmp gradle.properties
rm -rf tmp
NEW_VERSION=$(grep 'pluginVersion=' gradle.properties | cut -d'=' -f2)
@ -224,10 +223,6 @@ jobs:
# apple-product-id: dev.continue.continue-binary
# options: --options runtime --entitlements entitlements.xml
# Build plugin
- name: Build plugin
run: ./gradlew buildPlugin
# Publish the plugin to JetBrains Marketplace
- name: Publish EAP Plugin
if: github.event_name == 'release' || github.event.inputs.publish_build == 'true'
@ -237,7 +232,7 @@ jobs:
PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }}
PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }}
RELEASE_CHANNEL: eap
run: ./gradlew publishPlugin
run: ./gradlew publishPlugin --info --stacktrace
- name: Publish Stable Plugin
if: github.event_name == 'release' || github.event.inputs.publish_build == 'true'
@ -247,7 +242,7 @@ jobs:
PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }}
PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }}
RELEASE_CHANNEL: default
run: ./gradlew publishPlugin
run: ./gradlew publishPlugin --info --stacktrace
# Prepare plugin archive content for creating artifact
- name: Prepare Plugin Artifact

View file

@ -50,7 +50,10 @@ jobs:
install-config-yaml:
needs: install-root
runs-on: ubuntu-latest
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest]
steps:
- uses: actions/checkout@v4
@ -77,7 +80,10 @@ jobs:
install-openai-adapters:
needs: install-root
runs-on: ubuntu-latest
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest]
steps:
- uses: actions/checkout@v4
@ -133,7 +139,10 @@ jobs:
install-core:
needs: install-root
runs-on: ubuntu-latest
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest]
steps:
- uses: actions/checkout@v4
@ -381,7 +390,10 @@ jobs:
install-vscode:
needs:
[install-root, install-core, install-config-yaml, install-openai-adapters]
runs-on: ubuntu-latest
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest]
steps:
- uses: actions/checkout@v4
@ -659,7 +671,10 @@ jobs:
echo "Test files: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }}"
vscode-package-extension:
runs-on: ubuntu-latest
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest]
needs:
[
install-vscode,
@ -716,7 +731,7 @@ jobs:
- name: Upload build artifact
uses: actions/upload-artifact@v4
with:
name: vscode-extension-build
name: vscode-extension-build-${{ runner.os }}
path: extensions/vscode/build
vscode-download-e2e-dependencies:
@ -812,7 +827,7 @@ jobs:
- name: Download build artifact
uses: actions/download-artifact@v4
with:
name: vscode-extension-build
name: vscode-extension-build-Linux
path: extensions/vscode/build
- name: Download e2e dependencies

2
.idea/gradle.xml generated
View file

@ -5,7 +5,7 @@
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="externalProjectPath" value="$PROJECT_DIR$/extensions/intellij" />
<option name="gradleJvm" value="homebrew-17" />
<option name="gradleJvm" value="#JAVA_HOME" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$/extensions/intellij" />

2
.idea/kotlinc.xml generated
View file

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="KotlinJpsPluginSettings">
<option name="version" value="1.9.0" />
<option name="version" value="1.8.0" />
</component>
</project>

View file

@ -22,7 +22,13 @@
},
"overrides": [
{
"files": ["**/*.vitest.ts"],
"files": [
"**/*.test.ts",
"**/*.test.tsx",
"**/*.spec.ts",
"**/*.spec.tsx",
"**/*.vitest.ts"
],
"rules": {
"max-lines-per-function": "off"
}

View file

@ -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

View file

@ -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,

View 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;
}
}

View 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;
}

View 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[]>;
}

View file

@ -0,0 +1,146 @@
import { LineStream } from "../../../diff/util";
import {
collectAllLines,
MarkdownBlockStateTracker,
} from "../../../utils/markdownUtils";
import {
processBlockNesting,
shouldStopAtMarkdownBlock,
} from "../../../utils/streamMarkdownUtils";
import { hasNestedMarkdownBlocks, shouldChangeLineAndStop } from "./lineStream";
/**
* Filters and processes lines from a code block, removing unnecessary markers and handling edge cases.
* Now includes markdown-aware processing to handle nested markdown blocks properly.
*
* @param {LineStream} rawLines - The input stream of lines to filter.
* @param {string} filepath - Optional filepath to determine if this is a markdown file.
* @yields {string} Filtered and processed lines from the code block.
*
* @description
* This generator function performs the following tasks:
* 1. Removes initial lines that should be removed before the actual code starts.
* 2. For markdown files, applies nested markdown block logic to avoid premature termination.
* 3. For mixed content, uses simplified processing to avoid premature termination.
* 4. For traditional code blocks, uses original logic.
* 5. Yields processed lines that are part of the actual code block content.
*/
export async function* filterCodeBlockLines(
rawLines: LineStream,
filepath?: string,
): LineStream {
// Collect all lines for analysis
const allLines = await collectAllLines(rawLines);
// Check if it has nested markdown blocks (like ```markdown or ```md)
const firstLine = allLines[0] || "";
const hasNestedMarkdown = hasNestedMarkdownBlocks(firstLine, filepath);
// TARGETED FIX: Detect if this is mixed content (markdown headers + code blocks)
// But exclude cases where we have nested markdown blocks
const hasMarkdownHeaders = allLines.some(
(line) => line.trim().startsWith("#") && !line.trim().startsWith("```"),
);
const hasCodeBlocks = allLines.some(
(line) => line.trim().startsWith("```") && line.trim().length >= 3,
);
const isMixedContent =
hasMarkdownHeaders && hasCodeBlocks && !hasNestedMarkdown;
// If this is mixed content, use simplified processing
if (isMixedContent) {
for (let i = 0; i < allLines.length; i++) {
const line = allLines[i];
// Skip initial wrapper lines if they exist
if (i === 0 && shouldRemoveLineBeforeStart(line)) {
continue;
}
yield line;
}
return;
}
// Original logic for non-mixed content
let seenFirstFence = false;
let nestCount = 0;
// Create optimized state tracker for markdown block analysis if needed
let markdownStateTracker: MarkdownBlockStateTracker | undefined;
if (hasNestedMarkdown) {
markdownStateTracker = new MarkdownBlockStateTracker(allLines);
}
for (let i = 0; i < allLines.length; i++) {
const line = allLines[i];
// Process block nesting logic for the first fence
const nesting = processBlockNesting(
line,
seenFirstFence,
shouldRemoveLineBeforeStart,
);
if (nesting.shouldSkip) {
continue; // Filter out starting ``` or START block
}
if (!seenFirstFence && nesting.newSeenFirstFence) {
seenFirstFence = true;
nestCount = 1;
}
if (nestCount > 0) {
// Inside a block including the outer block
const changedEndLine = shouldChangeLineAndStop(line);
if (typeof changedEndLine === "string") {
// Ending a block with just backticks (```) or STOP
// For markdown files with nested markdown blocks, apply special logic
if (
hasNestedMarkdown &&
line.trim() === "```" &&
markdownStateTracker
) {
if (shouldStopAtMarkdownBlock(markdownStateTracker, i)) {
return; // Stop without yielding the final closing ```
} else {
// This is an inner block delimiter, yield it as content
yield line;
continue;
}
}
// Original logic for non-markdown files or simple cases
nestCount--;
if (nestCount === 0) {
// We've closed the outer wrapper - stop without yielding the closing ```
return;
} else {
// This is a nested block closing, yield it as content
yield line;
}
} else if (line.startsWith("```")) {
// Going into a nested codeblock
nestCount++;
yield line;
} else {
// Otherwise just yield the line as content
yield line;
}
}
}
}
function shouldRemoveLineBeforeStart(line: string): boolean {
return (
line.trimStart().startsWith("```") ||
line.trim() === "[CODE]" ||
line.trim() === "<COMPLETION>" ||
line.trim() === "<START EDITING HERE>" ||
line.trim() === "{{FILL_HERE}}"
);
}

View file

@ -0,0 +1,452 @@
// eslint-disable-next-line max-lines-per-function
import { beforeEach, describe, expect, it, Mock, vi } from "vitest";
import * as lineStream from "./lineStream";
describe("filterCodeBlock", () => {
let mockFullStop: Mock;
async function getLineGenerator(lines: any) {
return (async function* () {
for (const line of lines) {
yield line;
}
})();
}
async function getFilteredLines(results: any) {
const output = [];
for await (const line of results) {
output.push(line);
}
return output;
}
beforeEach(() => {
mockFullStop = vi.fn();
});
it("should handle unfenced code", async () => {
const linesGenerator = await getLineGenerator(["const x = 5;"]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;"]);
});
it("should handle unfenced code with a code block", async () => {
const linesGenerator = await getLineGenerator([
"const x = 5;",
"```bash",
"ls -al",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]);
});
it("should handle unfenced code with a complex code block", async () => {
const linesGenerator = await getLineGenerator([
"# Manual Testing Sandbox",
"",
"## Project Structure",
"",
"```",
"manual-testing-sandbox/",
"├── readme.md # Project documentation",
"├── package.json # Node.js dependencies and scripts",
"├── tsconfig.json # TypeScript configuration",
"├── jest.config.js # Jest testing configuration",
"├── requirements.txt # Python dependencies",
"├── Dockerfile # Docker container configuration",
"├── data.json # Sample JSON data",
"├── example.ipynb # Jupyter notebook example",
"│",
"├── src/ # Source code directory",
"│ ├── example.ts # TypeScript example",
"│ ├── JsonToMarkdownConverter.ts # JSON to Markdown converter",
"│ ├── JsonToMarkdownConverter.test.ts # Tests for JSON converter",
"│ ├── MarkdownProcessor.ts # Markdown processing utility",
"│ └── MarkdownProcessor.test.ts # Tests for Markdown processor",
"│",
"├── react-calculator/ # React calculator application",
"├── calculator_test/ # Java calculator implementation",
"│ ├── Calculator.java # Calculator class",
"│ └── Main.java # Main application entry",
"│",
"├── nested-folder/ # Nested project example",
"│ ├── helloNested.py # Python script",
"│ ├── package.json # Nested package configuration",
"│ └── rules.md # Documentation",
"│",
"├── coverage/ # Test coverage reports",
"├── logs/ # Application logs",
"│",
"└── Test Files # Various language examples",
" ├── AdvancedPage.tsx # React TypeScript component",
" ├── Calculator.java # Java calculator",
" ├── program.cs # C# program",
" ├── query.sql # SQL query example",
" ├── test.css # CSS styles",
" ├── test.html # HTML page",
" ├── test.js # JavaScript code",
" ├── test.kt # Kotlin example",
" ├── test.php # PHP script",
" ├── test.py # Python script",
" ├── test.rb # Ruby script",
" ├── test.rs # Rust code",
" ├── test.sh # Shell script",
" └── test.ts # TypeScript code",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"# Manual Testing Sandbox",
"",
"## Project Structure",
"",
"```",
"manual-testing-sandbox/",
"├── readme.md # Project documentation",
"├── package.json # Node.js dependencies and scripts",
"├── tsconfig.json # TypeScript configuration",
"├── jest.config.js # Jest testing configuration",
"├── requirements.txt # Python dependencies",
"├── Dockerfile # Docker container configuration",
"├── data.json # Sample JSON data",
"├── example.ipynb # Jupyter notebook example",
"│",
"├── src/ # Source code directory",
"│ ├── example.ts # TypeScript example",
"│ ├── JsonToMarkdownConverter.ts # JSON to Markdown converter",
"│ ├── JsonToMarkdownConverter.test.ts # Tests for JSON converter",
"│ ├── MarkdownProcessor.ts # Markdown processing utility",
"│ └── MarkdownProcessor.test.ts # Tests for Markdown processor",
"│",
"├── react-calculator/ # React calculator application",
"├── calculator_test/ # Java calculator implementation",
"│ ├── Calculator.java # Calculator class",
"│ └── Main.java # Main application entry",
"│",
"├── nested-folder/ # Nested project example",
"│ ├── helloNested.py # Python script",
"│ ├── package.json # Nested package configuration",
"│ └── rules.md # Documentation",
"│",
"├── coverage/ # Test coverage reports",
"├── logs/ # Application logs",
"│",
"└── Test Files # Various language examples",
" ├── AdvancedPage.tsx # React TypeScript component",
" ├── Calculator.java # Java calculator",
" ├── program.cs # C# program",
" ├── query.sql # SQL query example",
" ├── test.css # CSS styles",
" ├── test.html # HTML page",
" ├── test.js # JavaScript code",
" ├── test.kt # Kotlin example",
" ├── test.php # PHP script",
" ├── test.py # Python script",
" ├── test.rb # Ruby script",
" ├── test.rs # Rust code",
" ├── test.sh # Shell script",
" └── test.ts # TypeScript code",
"```",
]);
});
it("should handle unfenced code with two code blocks", async () => {
const linesGenerator = await getLineGenerator([
"const x = 5;",
"```bash",
"ls -al",
"```",
"```bash",
"ls -al",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"const x = 5;",
"```bash",
"ls -al",
"```",
"```bash",
"ls -al",
"```",
]);
});
it("should remove lines before the first valid line", async () => {
const linesGenerator = await getLineGenerator(["```ts", "const x = 5;"]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;"]);
});
it("should remove outer blocks", async () => {
const linesGenerator = await getLineGenerator([
"```ts",
"const x = 5;",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;"]);
});
it("should leave inner blocks intact", async () => {
const linesGenerator = await getLineGenerator([
"```md",
"const x = 5;",
"```bash",
"ls -al",
"```",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]);
});
it("should ignore ticks inside of code blocks such as tests", async () => {
const linesGenerator = await getLineGenerator([
"```typescript",
'it("should handle included inner ticks", async () => {',
" const linesGenerator = await getLineGenerator([`",
' "```md"',
' "const x = 5;"',
' "```bash"',
' "echo ```test```"',
' "```"',
' "```"',
"]);",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
'it("should handle included inner ticks", async () => {',
" const linesGenerator = await getLineGenerator([`",
' "```md"',
' "const x = 5;"',
' "```bash"',
' "echo ```test```"',
' "```"',
' "```"',
"]);",
]);
});
it("should handle included inner ticks", async () => {
const linesGenerator = await getLineGenerator([
"```md",
"const x = 5;",
"```bash",
"echo ```test```",
"```",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"const x = 5;",
"```bash",
"echo ```test```",
"```",
]);
});
it("should leave single inner blocks intact but not return trailing text", async () => {
const linesGenerator = await getLineGenerator([
"```md",
"const x = 5;",
"```bash",
"ls -al",
"```",
"```",
"trailing text",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]);
});
it("should leave double inner blocks intact but not return trailing text", async () => {
const linesGenerator = await getLineGenerator([
"```md",
"const x = 5;",
"```bash",
"ls -al",
"```",
"const y = 10;",
"```sh",
"echo `hello world`",
"```",
"```",
"trailing text",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"const x = 5;",
"```bash",
"ls -al",
"```",
"const y = 10;",
"```sh",
"echo `hello world`",
"```",
]);
});
it("should leave inner blocks intact but not return trailing or leading text", async () => {
const linesGenerator = await getLineGenerator([
"[CODE]",
"const x = 5;",
"```bash",
"ls -al",
"```",
"[/CODE]",
"trailing text",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]);
});
// Markdown-aware tests
it("should handle markdown files with nested code blocks and a filename is included", async () => {
const linesGenerator = await getLineGenerator([
"```markdown README.md",
"# Project Structure",
"",
"```",
"debug-test-folder/",
"├── AdvancedPage.tsx",
"├── Calculator.java",
"└── test.ts",
"```",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator, "README.md");
const filteredLines = await getFilteredLines(result);
// Should include all content up to the final closing ```
expect(filteredLines).toEqual([
"# Project Structure",
"",
"```",
"debug-test-folder/",
"├── AdvancedPage.tsx",
"├── Calculator.java",
"└── test.ts",
"```",
]);
});
// Markdown-aware tests
it("should handle markdown files with nested code blocks and a filename is excluded", async () => {
const linesGenerator = await getLineGenerator([
"```markdown README.md",
"# Project Structure",
"",
"```",
"debug-test-folder/",
"├── AdvancedPage.tsx",
"├── Calculator.java",
"└── test.ts",
"```",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
// Should include all content up to the final closing ```
expect(filteredLines).toEqual([
"# Project Structure",
"",
"```",
"debug-test-folder/",
"├── AdvancedPage.tsx",
"├── Calculator.java",
"└── test.ts",
"```",
]);
});
it("should handle non-markdown files normally with filepath parameter", async () => {
const linesGenerator = await getLineGenerator([
"```",
"function test() {",
" return 'hello';",
"}",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator, "test.js");
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"function test() {",
" return 'hello';",
"}",
]);
});
it("should handle simple markdown code blocks", async () => {
const linesGenerator = await getLineGenerator([
"```",
"Here's some code:",
"```",
"function example() {",
" console.log('test');",
"}",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator, "README.md");
const filteredLines = await getFilteredLines(result);
// Should remove the outer markdown wrapper, and return just the inner content.
// The lack of an end tag should cause it to return all remaining lines.
expect(filteredLines).toEqual([
"Here's some code:",
"```",
"function example() {",
" console.log('test');",
"}",
"```",
]);
});
});

View file

@ -3,6 +3,11 @@ import { distance } from "fastest-levenshtein";
import { DiffLine } from "../../..";
import { LineStream } from "../../../diff/util";
import { headerIsMarkdown, isMarkdownFile } from "../../../utils/markdownUtils";
import { processBlockNesting as processBlockNestingUtil } from "../../../utils/streamMarkdownUtils";
export { filterCodeBlockLines } from "./filterCodeBlock";
export type LineFilter = (args: {
lines: LineStream;
fullStop: () => void;
@ -50,13 +55,72 @@ function shouldRemoveLineBeforeStart(line: string): boolean {
);
}
function shouldChangeLineAndStop(line: string): string | undefined {
/**
* Shared utility for validating patterns in lines to avoid code duplication.
* Checks if a pattern appears in a valid context (not inside quotes or identifiers).
*/
export function validatePatternInLine(
line: string,
pattern: string,
): {
isValid: boolean;
patternIndex: number;
beforePattern: string;
} {
const patternIndex = line.indexOf(pattern);
if (patternIndex === -1) {
return { isValid: false, patternIndex: -1, beforePattern: "" };
}
// Check if pattern is preceded by a non-whitespace character
// If so, it might be part of an identifier, so don't handle it
if (patternIndex > 0) {
const charBefore = line[patternIndex - 1];
if (charBefore && !charBefore.match(/\s/)) {
return { isValid: false, patternIndex, beforePattern: "" };
}
}
// Check if pattern appears to be inside quotes
// Simple heuristic: count unmatched quotes before the pattern
const beforePattern = line.substring(0, patternIndex);
const singleQuotes = (beforePattern.match(/'/g) || []).length;
const doubleQuotes = (beforePattern.match(/"/g) || []).length;
// If there's an odd number of quotes before pattern, we're likely inside quotes
if (singleQuotes % 2 !== 0 || doubleQuotes % 2 !== 0) {
return { isValid: false, patternIndex, beforePattern };
}
return { isValid: true, patternIndex, beforePattern };
}
export function shouldChangeLineAndStop(line: string): string | undefined {
if (line.trimStart() === "```") {
return line;
}
// Check if [/CODE] appears in the line
if (line.includes(CODE_STOP_BLOCK)) {
return line.split(CODE_STOP_BLOCK)[0].trimEnd();
const validation = validatePatternInLine(line, CODE_STOP_BLOCK);
if (!validation.isValid) {
return undefined;
}
// Get the trimmed line to check if [/CODE] is at logical start
const trimmedLine = line.trimStart();
if (trimmedLine.startsWith(CODE_STOP_BLOCK)) {
// [/CODE] is at the logical start (after whitespace only)
if (trimmedLine === CODE_STOP_BLOCK) {
return line; // Return the whole line including leading whitespace
}
}
// [/CODE] appears after some content (separated by whitespace) - return part before
return validation.beforePattern.trimEnd();
}
return undefined;
@ -71,6 +135,32 @@ function isUselessLine(line: string): boolean {
return hasUselessLine || trimmed.startsWith("// end");
}
/**
* Determines if the code block has nested markdown blocks.
*/
export function hasNestedMarkdownBlocks(
firstLine: string,
filepath?: string,
): boolean {
return (
(firstLine.startsWith("```") &&
headerIsMarkdown(firstLine.replace(/`/g, ""))) ||
Boolean(filepath && isMarkdownFile(filepath))
);
}
// Wrapper for processBlockNesting with local shouldRemoveLineBeforeStart function
export function processBlockNesting(
line: string,
seenFirstFence: boolean,
): { newSeenFirstFence: boolean; shouldSkip: boolean } {
return processBlockNestingUtil(
line,
seenFirstFence,
shouldRemoveLineBeforeStart,
);
}
export const USELESS_LINES = [""];
export const CODE_KEYWORDS_ENDING_IN_SEMICOLON = ["def"];
export const CODE_STOP_BLOCK = "[/CODE]";
@ -138,7 +228,7 @@ export async function* avoidPathLine(
// Sometimes the model with copy this pattern, which is unwanted
for await (const line of stream) {
if (line.startsWith(`${comment} Path: `)) {
continue;
continue; // continue in the Continue codebase! How meta!
}
yield line;
}
@ -261,7 +351,40 @@ export async function* stopAtLines(
linesToStopAt: string[] = LINES_TO_STOP_AT,
): LineStream {
for await (const line of stream) {
if (linesToStopAt.some((stopAt) => line.trim().includes(stopAt))) {
let shouldStop = false;
// Check each stop phrase
for (const stopAt of linesToStopAt) {
if (line.includes(stopAt)) {
const validation = validatePatternInLine(line, stopAt);
if (!validation.isValid) {
continue;
}
// Get the trimmed line to check if stop phrase is at logical start
const trimmedLine = line.trimStart();
if (trimmedLine.startsWith(stopAt)) {
// Stop phrase is at the logical start (after whitespace only) - should stop
shouldStop = true;
break;
} else {
// Stop phrase appears after some content - check if it's separated by whitespace
const contentBeforeStopPhrase = validation.beforePattern.trimEnd();
if (
contentBeforeStopPhrase.length < validation.beforePattern.length
) {
// There's whitespace before the stop phrase, so it's properly separated
shouldStop = true;
break;
}
// If no whitespace separation, it's part of larger text, so continue
}
}
}
if (shouldStop) {
fullStop();
break;
}
@ -329,64 +452,6 @@ export async function* removeTrailingWhitespace(
}
}
/**
* Filters and processes lines from a code block, removing unnecessary markers and handling edge cases.
*
* @param {LineStream} rawLines - The input stream of lines to filter.
* @yields {string} Filtered and processed lines from the code block.
*
* @description
* This generator function performs the following tasks:
* 1. Removes initial lines that should be removed before the actual code starts.
* 2. Filters out ending code block markers (```) unless they are the last line.
* 3. Handles special cases where lines should be changed and the stream should stop.
* 4. Yields processed lines that are part of the actual code block content.
*/
export async function* filterCodeBlockLines(rawLines: LineStream): LineStream {
let seenFirstFence = false;
// nestCount is set to 1 when the entire code block is wrapped with ``` or START blocks. It's then incremented
// when an inner code block is discovered to avoid exiting the function prematurly. The function will exit early
// when all blocks are matched. When no outer fence is discovered the function will always continue to the end.
let nestCount = 0;
for await (const line of rawLines) {
if (!seenFirstFence) {
if (shouldRemoveLineBeforeStart(line)) {
// Filter out starting ``` or START block
continue;
}
// Regardless of a fence or START block start tracking the nesting level
seenFirstFence = true;
nestCount = 1;
}
if (nestCount > 0) {
// Inside a block including the outer block
const changedEndLine = shouldChangeLineAndStop(line);
if (typeof changedEndLine === "string") {
// Ending a block with just backticks (```) or STOP
nestCount--;
if (nestCount === 0) {
// if we are closing the outer block then exit early
// only exit early if the outer block was started with a block
// it it was text, we will never exit early
return;
} else {
// otherwise just yield the line
yield line;
}
} else if (line.startsWith("```")) {
// Going into a nested codeblock
nestCount++;
yield line;
} else {
// otherwise just yield the line
yield line;
}
}
}
}
/**
* Filters out English explanations at the start of a code block.
*

View file

@ -1,5 +1,10 @@
import { beforeEach, describe, expect, it, Mock, vi } from "vitest";
import {
collectAllLines,
MarkdownBlockStateTracker,
} from "../../../utils/markdownUtils";
import { shouldStopAtMarkdownBlock } from "../../../utils/streamMarkdownUtils";
import * as lineStream from "./lineStream";
// eslint-disable-next-line max-lines-per-function
@ -174,6 +179,93 @@ describe("lineStream", () => {
expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
expect(mockFullStop).toHaveBeenCalledTimes(1);
});
it("should stop at lines with leading whitespace", async () => {
const linesGenerator = await getLineGenerator([
"const x = 5;",
"let y = 10;",
` ${lineStream.LINES_TO_STOP_AT[0]}`,
"const z = 15;",
]);
const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
expect(mockFullStop).toHaveBeenCalledTimes(1);
});
it("should NOT stop when stop phrase is inside quotes", async () => {
const linesGenerator = await getLineGenerator([
"const x = 5;",
'console.log("# End of file. not really");',
"let y = 10;",
"const z = 15;",
]);
const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
const filteredLines = await getFilteredLines(result);
// Should not stop, should yield all lines
expect(filteredLines).toEqual([
"const x = 5;",
'console.log("# End of file. not really");',
"let y = 10;",
"const z = 15;",
]);
expect(mockFullStop).toHaveBeenCalledTimes(0);
});
it("should NOT stop when stop phrase is inside single quotes", async () => {
const linesGenerator = await getLineGenerator([
"const x = 5;",
"const message = '# End of file. not really';",
"let y = 10;",
]);
const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"const x = 5;",
"const message = '# End of file. not really';",
"let y = 10;",
]);
expect(mockFullStop).toHaveBeenCalledTimes(0);
});
it("should NOT stop when stop phrase is part of larger text", async () => {
const linesGenerator = await getLineGenerator([
"const x = 5;",
"// This function stops<STOP EDITING HERE>after processing",
"let y = 10;",
]);
const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"const x = 5;",
"// This function stops<STOP EDITING HERE>after processing",
"let y = 10;",
]);
expect(mockFullStop).toHaveBeenCalledTimes(0);
});
it("should stop when stop phrase appears properly at start of content", async () => {
const linesGenerator = await getLineGenerator([
"const x = 5;",
"let y = 10;",
"# End of file. Done here",
"const z = 15;",
]);
const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
expect(mockFullStop).toHaveBeenCalledTimes(1);
});
});
describe("skipPrefixes", () => {
@ -301,6 +393,37 @@ describe("lineStream", () => {
]);
});
it("should ignore ticks inside of code blocks such as tests", async () => {
const linesGenerator = await getLineGenerator([
"```typescript",
'it("should handle included inner ticks", async () => {',
" const linesGenerator = await getLineGenerator([`",
' "```md"',
' "const x = 5;"',
' "```bash"',
' "echo ```test```"',
' "```"',
' "```"',
"]);",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
'it("should handle included inner ticks", async () => {',
" const linesGenerator = await getLineGenerator([`",
' "```md"',
' "const x = 5;"',
' "```bash"',
' "echo ```test```"',
' "```"',
' "```"',
"]);",
]);
});
it("should handle included inner ticks", async () => {
const linesGenerator = await getLineGenerator([
"```md",
@ -395,6 +518,119 @@ describe("lineStream", () => {
"```",
]);
});
// Markdown-aware tests
it("should handle markdown files with nested code blocks and a filename is included", async () => {
const linesGenerator = await getLineGenerator([
"```markdown README.md",
"# Project Structure",
"",
"```",
"debug-test-folder/",
"├── AdvancedPage.tsx",
"├── Calculator.java",
"└── test.ts",
"```",
"```",
]);
const result = lineStream.filterCodeBlockLines(
linesGenerator,
"README.md",
);
const filteredLines = await getFilteredLines(result);
// Should include all content up to the final closing ```
expect(filteredLines).toEqual([
"# Project Structure",
"",
"```",
"debug-test-folder/",
"├── AdvancedPage.tsx",
"├── Calculator.java",
"└── test.ts",
"```",
]);
});
// Markdown-aware tests
it("should handle markdown files with nested code blocks and a filename is excluded", async () => {
const linesGenerator = await getLineGenerator([
"```markdown README.md",
"# Project Structure",
"",
"```",
"debug-test-folder/",
"├── AdvancedPage.tsx",
"├── Calculator.java",
"└── test.ts",
"```",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
// Should include all content up to the final closing ```
expect(filteredLines).toEqual([
"# Project Structure",
"",
"```",
"debug-test-folder/",
"├── AdvancedPage.tsx",
"├── Calculator.java",
"└── test.ts",
"```",
]);
});
it("should handle non-markdown files normally with filepath parameter", async () => {
const linesGenerator = await getLineGenerator([
"```",
"function test() {",
" return 'hello';",
"}",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator, "test.js");
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"function test() {",
" return 'hello';",
"}",
]);
});
it("should handle simple markdown code blocks", async () => {
const linesGenerator = await getLineGenerator([
"```",
"Here's some code:",
"```",
"function example() {",
" console.log('test');",
"}",
"```",
]);
const result = lineStream.filterCodeBlockLines(
linesGenerator,
"README.md",
);
const filteredLines = await getFilteredLines(result);
// Should remove the outer markdown wrapper, and return just the inner content.
// The lack of an end tag should cause it to return all remaining lines.
expect(filteredLines).toEqual([
"Here's some code:",
"```",
"function example() {",
" console.log('test');",
"}",
"```",
]);
});
});
describe("filterEnglishLinesAtStart", () => {
@ -613,4 +849,453 @@ describe("lineStream", () => {
expect(mockFullStop).toHaveBeenCalledTimes(1);
});
});
// Tests for new helper functions
describe("hasNestedMarkdownBlocks", () => {
it("should detect nested markdown blocks from first line", () => {
expect(lineStream.hasNestedMarkdownBlocks("```markdown", undefined)).toBe(
true,
);
expect(lineStream.hasNestedMarkdownBlocks("```md", undefined)).toBe(true);
expect(lineStream.hasNestedMarkdownBlocks("```gfm", undefined)).toBe(
true,
);
});
it("should detect nested markdown blocks from filepath", () => {
expect(
lineStream.hasNestedMarkdownBlocks("```typescript", "README.md"),
).toBe(true);
expect(
lineStream.hasNestedMarkdownBlocks("```javascript", "docs.markdown"),
).toBe(true);
});
it("should return false for non-markdown scenarios", () => {
expect(
lineStream.hasNestedMarkdownBlocks("```typescript", "script.js"),
).toBe(false);
expect(lineStream.hasNestedMarkdownBlocks("```python", undefined)).toBe(
false,
);
expect(
lineStream.hasNestedMarkdownBlocks("const x = 5;", undefined),
).toBe(false);
});
it("should handle complex first line scenarios", () => {
expect(
lineStream.hasNestedMarkdownBlocks("```markdown README.md", undefined),
).toBe(true);
expect(
lineStream.hasNestedMarkdownBlocks("```md with extra text", undefined),
).toBe(true);
});
});
describe("collectAllLines", () => {
it("should collect all lines from a stream", async () => {
const linesGenerator = await getLineGenerator([
"line1",
"line2",
"line3",
]);
const result = await collectAllLines(linesGenerator);
expect(result).toEqual(["line1", "line2", "line3"]);
});
it("should handle empty stream", async () => {
const linesGenerator = await getLineGenerator([]);
const result = await collectAllLines(linesGenerator);
expect(result).toEqual([]);
});
it("should handle stream with empty lines", async () => {
const linesGenerator = await getLineGenerator(["", "line2", "", "line4"]);
const result = await collectAllLines(linesGenerator);
expect(result).toEqual(["", "line2", "", "line4"]);
});
});
describe("shouldStopAtMarkdownBlock", () => {
it("should return false when current line is not closing backticks", () => {
const allLines = ["```markdown", "content", "more content"];
const state = new MarkdownBlockStateTracker(allLines);
expect(shouldStopAtMarkdownBlock(state, 2)).toBe(false);
});
it("should handle simple nested markdown case", () => {
const allLines = ["```markdown", "# Title", "```"];
const state = new MarkdownBlockStateTracker(allLines);
expect(shouldStopAtMarkdownBlock(state, 2)).toBe(true);
});
it("should handle complex nested markdown with inner code blocks", () => {
const allLines = [
"```markdown",
"# Title",
"```javascript",
"console.log('hello');",
"```",
"```",
];
const state = new MarkdownBlockStateTracker(allLines);
// At index 4 (first inner closing), should not stop
expect(shouldStopAtMarkdownBlock(state, 4)).toBe(false);
// At index 5 (outer closing), should stop
expect(shouldStopAtMarkdownBlock(state, 5)).toBe(true);
});
it("should handle multiple bare backticks scenario", () => {
const allLines = [
"```markdown",
"Content with ```inline code```",
"```",
"More content",
"```",
];
const state = new MarkdownBlockStateTracker(allLines);
// At index 2, should not stop (not the last bare backticks)
expect(shouldStopAtMarkdownBlock(state, 2)).toBe(false);
// At index 4, should stop (last bare backticks)
expect(shouldStopAtMarkdownBlock(state, 4)).toBe(true);
});
});
describe("shouldChangeLineAndStop", () => {
it("should handle [/CODE] at start of line", () => {
const result = lineStream.shouldChangeLineAndStop("[/CODE]");
expect(result).toBe("[/CODE]");
});
it("should handle [/CODE] with leading whitespace", () => {
const result = lineStream.shouldChangeLineAndStop(" [/CODE]");
expect(result).toBe(" [/CODE]");
});
it("should return partial line before [/CODE] when at start/after whitespace", () => {
const result = lineStream.shouldChangeLineAndStop(
"some code [/CODE] more text",
);
expect(result).toBe("some code");
});
it("should NOT trigger on [/CODE] within quotes or non-whitespace preceded", () => {
// This test demonstrates the current bug - it WILL fail initially
const result = lineStream.shouldChangeLineAndStop(
'console.log("test [/CODE] end");',
);
expect(result).toBeUndefined(); // Should not trigger stopping
});
it("should NOT trigger on [/CODE] in middle of identifier", () => {
// Another case that shows the bug
const result = lineStream.shouldChangeLineAndStop(
'const var[/CODE]Name = "test";',
);
expect(result).toBeUndefined(); // Should not trigger stopping
});
it("should handle ``` with trimStart correctly", () => {
const result = lineStream.shouldChangeLineAndStop(" ```");
expect(result).toBe(" ```");
});
it("should NOT handle ``` in middle of line", () => {
const result = lineStream.shouldChangeLineAndStop(
'console.log("test ``` end");',
);
expect(result).toBeUndefined();
});
});
describe("MarkdownBlockState", () => {
it("should initialize with correct state", () => {
const allLines = ["```markdown", "content", "```", "more content", "```"];
const state = new MarkdownBlockStateTracker(allLines);
// Test basic initialization - we can't directly test private properties,
// but we can test the behavior through shouldStopAtPosition
expect(state).toBeDefined();
});
it("should correctly identify bare backticks positions", () => {
const allLines = ["```markdown", "```", "content", "```"];
const state = new MarkdownBlockStateTracker(allLines);
// At position 1 (first bare backticks), should not stop
expect(state.shouldStopAtPosition(1)).toBe(false);
// At position 3 (last bare backticks), should stop
expect(state.shouldStopAtPosition(3)).toBe(true);
});
it("should maintain state across multiple calls", () => {
const allLines = [
"```markdown",
"# Title",
"```javascript",
"console.log('test');",
"```",
"More content",
"```",
];
const state = new MarkdownBlockStateTracker(allLines);
// Process positions incrementally
expect(state.shouldStopAtPosition(2)).toBe(false); // Start of inner block
expect(state.shouldStopAtPosition(4)).toBe(false); // End of inner block
expect(state.shouldStopAtPosition(6)).toBe(true); // End of outer block
});
it("should handle complex nesting scenarios efficiently", () => {
const allLines = [
"```markdown",
"# Documentation",
"```typescript",
"interface Config {",
" name: string;",
"}",
"```",
"",
"```bash",
"npm install",
"```",
"",
"Final notes",
"```",
];
const state = new MarkdownBlockStateTracker(allLines);
// Test multiple positions in sequence
expect(state.shouldStopAtPosition(6)).toBe(false); // End of first inner block
expect(state.shouldStopAtPosition(10)).toBe(false); // End of second inner block
expect(state.shouldStopAtPosition(13)).toBe(true); // End of outer markdown block
});
it("should handle non-backtick lines correctly", () => {
const allLines = ["```markdown", "regular content", "```"];
const state = new MarkdownBlockStateTracker(allLines);
// Position 1 is not backticks, should return false
expect(state.shouldStopAtPosition(1)).toBe(false);
});
it("should handle empty lines and edge cases", () => {
const allLines = ["```markdown", "", "```"];
const state = new MarkdownBlockStateTracker(allLines);
expect(state.shouldStopAtPosition(1)).toBe(false); // Empty line
expect(state.shouldStopAtPosition(2)).toBe(true); // Closing backticks
});
it("should reset nest count when reaching final bare backticks", () => {
const allLines = ["```markdown", "content", "```"];
const state = new MarkdownBlockStateTracker(allLines);
// First call should stop and reset count
expect(state.shouldStopAtPosition(2)).toBe(true);
// If we had more content, it should start fresh
// (This tests the internal state management)
});
});
describe("shouldStopAtMarkdownBlock optimization", () => {
it("should maintain performance benefits with state reuse", () => {
const allLines = Array.from({ length: 100 }, (_, i) => {
if (i === 0) return "```markdown";
if (i === 99) return "```";
if (i % 10 === 0) return "```javascript";
if (i % 10 === 5) return "```";
return `line ${i}`;
});
const state = new MarkdownBlockStateTracker(allLines);
// Test that we can call multiple times without recomputing everything
const start = performance.now();
// Test several positions in sequence
for (let i = 10; i < 90; i += 10) {
if (allLines[i].trim() === "```") {
shouldStopAtMarkdownBlock(state, i);
}
}
const duration = performance.now() - start;
expect(duration).toBeLessThan(10); // Should be very fast due to state caching
});
});
describe("filterCodeBlockLines with optimized MarkdownBlockState", () => {
it("should use optimized state tracker for markdown files", async () => {
const linesGenerator = await getLineGenerator([
"```markdown",
"# Documentation",
"```typescript",
"const config = { name: 'test' };",
"```",
"Final notes",
"```",
]);
const result = lineStream.filterCodeBlockLines(
linesGenerator,
"README.md",
);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"# Documentation",
"```typescript",
"const config = { name: 'test' };",
"```",
"Final notes",
]);
});
it("should fall back to legacy behavior when no markdown nesting detected", async () => {
const linesGenerator = await getLineGenerator([
"```typescript",
"const x = 5;",
"```",
]);
const result = lineStream.filterCodeBlockLines(
linesGenerator,
"script.ts",
);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual(["const x = 5;"]);
});
it("should handle mixed markdown and code scenarios with optimization", async () => {
const linesGenerator = await getLineGenerator([
"```md",
"## API Reference",
"",
"```javascript",
"async function fetchData() {",
" return await fetch('/api/data');",
"}",
"```",
"",
"Usage notes and more documentation.",
"```",
]);
const result = lineStream.filterCodeBlockLines(linesGenerator);
const filteredLines = await getFilteredLines(result);
expect(filteredLines).toEqual([
"## API Reference",
"",
"```javascript",
"async function fetchData() {",
" return await fetch('/api/data');",
"}",
"```",
"",
"Usage notes and more documentation.",
]);
});
});
describe("validatePatternInLine", () => {
it("should return false when pattern is not found", () => {
const result = lineStream.validatePatternInLine(
"const x = 5;",
"[/CODE]",
);
expect(result.isValid).toBe(false);
expect(result.patternIndex).toBe(-1);
expect(result.beforePattern).toBe("");
});
it("should return false when pattern is preceded by non-whitespace", () => {
const result = lineStream.validatePatternInLine(
'const var[/CODE]Name = "test";',
"[/CODE]",
);
expect(result.isValid).toBe(false);
expect(result.patternIndex).toBe(9);
});
it("should return false when pattern is inside double quotes", () => {
const result = lineStream.validatePatternInLine(
'console.log("test [/CODE] end");',
"[/CODE]",
);
expect(result.isValid).toBe(false);
expect(result.patternIndex).toBe(18);
});
it("should return false when pattern is inside single quotes", () => {
const result = lineStream.validatePatternInLine(
"const message = 'test [/CODE] end';",
"[/CODE]",
);
expect(result.isValid).toBe(false);
expect(result.patternIndex).toBe(22);
});
it("should return true when pattern is properly separated by whitespace", () => {
const result = lineStream.validatePatternInLine(
"some code [/CODE] more text",
"[/CODE]",
);
expect(result.isValid).toBe(true);
expect(result.patternIndex).toBe(10);
expect(result.beforePattern).toBe("some code ");
});
it("should return true when pattern is at start of line", () => {
const result = lineStream.validatePatternInLine("[/CODE]", "[/CODE]");
expect(result.isValid).toBe(true);
expect(result.patternIndex).toBe(0);
expect(result.beforePattern).toBe("");
});
it("should return true when pattern has only whitespace before it", () => {
const result = lineStream.validatePatternInLine(" [/CODE]", "[/CODE]");
expect(result.isValid).toBe(true);
expect(result.patternIndex).toBe(4);
expect(result.beforePattern).toBe(" ");
});
it("should handle complex quote scenarios correctly", () => {
// Unmatched quote should make it invalid
const result1 = lineStream.validatePatternInLine(
'const x = "unclosed quote [/CODE]',
"[/CODE]",
);
expect(result1.isValid).toBe(false);
// Matched quotes should make it valid
const result2 = lineStream.validatePatternInLine(
'const x = "closed"; [/CODE]',
"[/CODE]",
);
expect(result2.isValid).toBe(true);
});
it("should work with different patterns", () => {
const result1 = lineStream.validatePatternInLine(
"# End of file. Done",
"# End of file.",
);
expect(result1.isValid).toBe(true);
const result2 = lineStream.validatePatternInLine(" ```", "```");
expect(result2.isValid).toBe(true);
});
});
});

View file

@ -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,
};
};

View file

@ -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;

View file

@ -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,
),
),

View file

@ -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) => {

View file

@ -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);
}
}

View file

@ -42,4 +42,5 @@ export interface AutocompleteOutcome extends TabAutocompleteOptions {
completionId: string;
uniqueId: string;
timestamp: string;
enabledStaticContextualization?: boolean;
}

View file

@ -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
};
}

View file

@ -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
};
}

View file

@ -438,7 +438,7 @@ export class ConfigHandler {
if (!this.currentProfile) {
return {
config: undefined,
errors: [],
errors: [{ message: "Current profile not found", fatal: true }],
configLoadInterrupted: true,
};
}
@ -494,7 +494,7 @@ export class ConfigHandler {
if (!this.currentProfile) {
return {
config: undefined,
errors: [],
errors: [{ message: "Current profile not found", fatal: true }],
configLoadInterrupted: true,
};
}
@ -507,7 +507,7 @@ export class ConfigHandler {
if (!this.currentProfile) {
return {
config: undefined,
errors: [],
errors: [{ message: "Current profile not found", fatal: true }],
configLoadInterrupted: true,
};
}
@ -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}`);

View file

@ -0,0 +1,31 @@
import * as JSONC from "comment-json";
import { ContinueRcJson, FileType, IDE } from "../..";
import { joinPathsToUri } from "../../util/uri";
export async function getWorkspaceRcConfigs(
ide: IDE,
): Promise<ContinueRcJson[]> {
try {
const workspaces = await ide.getWorkspaceDirs();
const rcFiles = await Promise.all(
workspaces.map(async (dir) => {
const ls = await ide.listDir(dir);
const rcFiles = ls
.filter(
(entry) =>
(entry[1] === (1 as FileType.File) ||
entry[1] === (64 as FileType.SymbolicLink)) &&
entry[0].endsWith(".continuerc.json"),
)
.map((entry) => joinPathsToUri(dir, entry[0]));
return await Promise.all(rcFiles.map(ide.readFile));
}),
);
return rcFiles
.flat()
.map((file) => JSONC.parse(file) as unknown as ContinueRcJson);
} catch (e) {
console.debug("Failed to load workspace configs: ", e);
return [];
}
}

View file

@ -64,6 +64,7 @@ import { localPathToUri } from "../util/pathToUri";
import { getToolsForIde } from "../tools";
import { resolveRelativePathInDir } from "../util/ideUtils";
import { getWorkspaceRcConfigs } from "./json/loadRcConfigs";
import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
import {
getModelByRole,
@ -652,6 +653,7 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
configurationStatus: llm.getConfigurationStatus(),
apiKeyLocation: llm.apiKeyLocation,
envSecretLocations: llm.envSecretLocations,
sourceFile: llm.sourceFile,
};
}
@ -876,7 +878,6 @@ async function buildConfigTsandReadConfigJs(ide: IDE, ideType: IdeType) {
async function loadContinueConfigFromJson(
ide: IDE,
workspaceConfigs: ContinueRcJson[],
ideSettings: IdeSettings,
ideInfo: IdeInfo,
uniqueId: string,
@ -884,6 +885,7 @@ async function loadContinueConfigFromJson(
workOsAccessToken: string | undefined,
overrideConfigJson: SerializedContinueConfig | undefined,
): Promise<ConfigResult<ContinueConfig>> {
const workspaceConfigs = await getWorkspaceRcConfigs(ide);
// Serialized config
let {
config: serialized,

View file

@ -10,7 +10,6 @@ import {
import {
ContinueConfig,
ContinueRcJson,
IDE,
IdeSettings,
ILLMLogger,
@ -86,7 +85,6 @@ export default async function doLoadConfig(options: {
packageIdentifier,
} = options;
const workspaceConfigs = await getWorkspaceConfigs(ide);
const ideInfo = await ide.getIdeInfo();
const uniqueId = await ide.getUniqueId();
const ideSettings = await ideSettingsPromise;
@ -126,7 +124,6 @@ export default async function doLoadConfig(options: {
} else {
const result = await loadContinueConfigFromJson(
ide,
workspaceConfigs,
ideSettings,
ideInfo,
uniqueId,
@ -365,21 +362,3 @@ async function injectControlPlaneProxyInfo(
return config;
}
async function getWorkspaceConfigs(ide: IDE): Promise<ContinueRcJson[]> {
const ideInfo = await ide.getIdeInfo();
let workspaceConfigs: ContinueRcJson[] = [];
try {
workspaceConfigs = await ide.getWorkspaceConfigs();
// Config is sent over the wire from JB so we need to parse it
if (ideInfo.ideType === "jetbrains") {
workspaceConfigs = (workspaceConfigs as any).map(JSON.parse);
}
} catch (e) {
console.debug("Failed to load workspace configs: ", e);
}
return workspaceConfigs;
}

View file

@ -21,7 +21,9 @@ export const sharedConfigSchema = z
useCurrentFileAsContext: z.boolean(),
optInNextEditFeature: z.boolean(),
enableExperimentalTools: z.boolean(),
onlyUseSystemMessageTools: z.boolean(),
codebaseToolCallingOnly: z.boolean(),
enableStaticContextualization: z.boolean(),
// `ui` in `ContinueConfig`
showSessionTabs: z.boolean(),
@ -184,10 +186,19 @@ export function modifyAnyConfigWithSharedConfig<
configCopy.experimental.optInNextEditFeature =
sharedConfig.optInNextEditFeature;
}
if (sharedConfig.onlyUseSystemMessageTools !== undefined) {
configCopy.experimental.onlyUseSystemMessageTools =
sharedConfig.onlyUseSystemMessageTools;
}
if (sharedConfig.codebaseToolCallingOnly !== undefined) {
configCopy.experimental.codebaseToolCallingOnly =
sharedConfig.codebaseToolCallingOnly;
}
if (sharedConfig.enableStaticContextualization !== undefined) {
configCopy.experimental.enableStaticContextualization =
sharedConfig.enableStaticContextualization;
}
return configCopy;
}

View file

@ -682,8 +682,6 @@ declare global {
getWorkspaceDirs(): Promise<string[]>;
getWorkspaceConfigs(): Promise<ContinueRcJson[]>;
fileExists(filepath: string): Promise<boolean>;
writeFile(path: string, contents: string): Promise<void>;
@ -1059,6 +1057,7 @@ declare global {
numDiffs?: number;
filepath?: string;
fileContent?: string;
originalFileContent?: string;
}
export interface RangeInFileWithContents {
@ -1124,7 +1123,6 @@ declare global {
* This is needed to crawl a large number of documentation sites that are dynamically rendered.
*/
useChromiumForDocsCrawling?: boolean;
useTools?: boolean;
modelContextProtocolServers?: MCPOptions[];
}

View file

@ -0,0 +1,62 @@
import {
AssistantUnrolled,
ConfigResult,
PackageIdentifier,
RegistryClient,
unrollAssistantFromContent,
} from "@continuedev/config-yaml";
import { IDE } from "../..";
import { ControlPlaneClient } from "../../control-plane/client";
import { LocalPlatformClient } from "./LocalPlatformClient";
// This is a certain approach to unrolling local YAML where it
// 1. creates an assistant out of all local blocks
// 2. unrolls it like a local assistant
export async function unrollLocalYamlBlocks(
packageIdentifiers: PackageIdentifier[],
ide: IDE,
registryClient: RegistryClient,
orgScopeId: string | null,
controlPlaneClient: ControlPlaneClient,
): Promise<ConfigResult<AssistantUnrolled>> {
try {
const unrollResult = await unrollAssistantFromContent(
{
uriType: "file",
filePath: "",
},
"name: FILLER\nschema: v1\nversion: 0.0.1",
registryClient,
{
currentUserSlug: "",
onPremProxyUrl: null,
orgScopeId,
platformClient: new LocalPlatformClient(
orgScopeId,
controlPlaneClient,
ide,
),
renderSecrets: true,
injectBlocks: packageIdentifiers,
},
);
const config =
"config" in unrollResult ? unrollResult.config : unrollResult;
const errors = "errors" in unrollResult ? unrollResult.errors : [];
return {
config,
errors,
configLoadInterrupted: false,
};
} catch (error) {
let message = "An unknown error occurred while loading local YAML blocks";
if (error instanceof Error) {
message += ": " + error.message;
}
return {
config: undefined,
errors: [{ message, fatal: false }],
configLoadInterrupted: false,
};
}
}

View file

@ -4,11 +4,10 @@ import {
ConfigResult,
ConfigValidationError,
isAssistantUnrolledNonNullable,
MCPServer,
mergeUnrolledAssistants,
ModelRole,
PackageIdentifier,
RegistryClient,
Rule,
TEMPLATE_VAR_REGEX,
unrollAssistant,
validateConfigYaml,
@ -17,13 +16,11 @@ import { dirname } from "node:path";
import {
ContinueConfig,
ExperimentalMCPOptions,
IContextProvider,
IDE,
IdeInfo,
IdeSettings,
ILLMLogger,
RuleWithSource,
} from "../..";
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
import DocsContextProvider from "../../context/providers/DocsContextProvider";
@ -41,39 +38,13 @@ import { getControlPlaneEnvSync } from "../../control-plane/env";
import { getToolsForIde } from "../../tools";
import { getCleanUriPath } from "../../util/uri";
import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
import { unrollLocalYamlBlocks } from "./loadLocalYamlBlocks";
import { LocalPlatformClient } from "./LocalPlatformClient";
import { llmsFromModelConfig } from "./models";
function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
if (typeof rule === "string") {
return {
rule: rule,
source: "rules-block",
};
} else {
return {
source: "rules-block",
rule: rule.rule,
globs: rule.globs,
name: rule.name,
};
}
}
function convertYamlMcpToContinueMcp(
server: MCPServer,
): ExperimentalMCPOptions {
return {
transport: {
type: "stdio",
command: server.command,
args: server.args ?? [],
env: server.env,
cwd: server.cwd,
} as any, // TODO: Fix the mcpServers types in config-yaml (discriminated union)
timeout: server.connectionTimeout,
};
}
import {
convertYamlMcpToContinueMcp,
convertYamlRuleToContinueRule,
} from "./yamlToContinueConfig";
async function loadConfigYaml(options: {
overrideConfigYaml: AssistantUnrolled | undefined;
@ -93,46 +64,65 @@ async function loadConfigYaml(options: {
} = options;
// Add local .continue blocks
const allLocalBlocks: PackageIdentifier[] = [];
for (const blockType of BLOCK_TYPES) {
const localBlockPromises = BLOCK_TYPES.map(async (blockType) => {
const localBlocks = await getAllDotContinueDefinitionFiles(
ide,
{ includeGlobal: true, includeWorkspace: true, fileExtType: "yaml" },
blockType,
);
allLocalBlocks.push(
...localBlocks.map((b) => ({
uriType: "file" as const,
filePath: b.path,
})),
);
}
const rootPath =
packageIdentifier.uriType === "file"
? dirname(getCleanUriPath(packageIdentifier.filePath))
: undefined;
return localBlocks.map((b) => ({
uriType: "file" as const,
filePath: b.path,
}));
});
const localPackageIdentifiers: PackageIdentifier[] = (
await Promise.all(localBlockPromises)
).flat();
// logger.info(
// `Loading config.yaml from ${JSON.stringify(packageIdentifier)} with root path ${rootPath}`,
// );
// Registry client is only used if local blocks are present, but logic same for hub/local assistants
const getRegistryClient = async () => {
const rootPath =
packageIdentifier.uriType === "file"
? dirname(getCleanUriPath(packageIdentifier.filePath))
: undefined;
return new RegistryClient({
accessToken: await controlPlaneClient.getAccessToken(),
apiBase: getControlPlaneEnvSync(ideSettings.continueTestEnvironment)
.CONTROL_PLANE_URL,
rootPath,
});
};
const errors: ConfigValidationError[] = [];
let config: AssistantUnrolled | undefined;
if (overrideConfigYaml) {
config = overrideConfigYaml;
if (localPackageIdentifiers.length > 0) {
const unrolledLocal = await unrollLocalYamlBlocks(
localPackageIdentifiers,
ide,
await getRegistryClient(),
orgScopeId,
controlPlaneClient,
);
if (unrolledLocal.errors) {
errors.push(...unrolledLocal.errors);
}
if (unrolledLocal.config) {
config = mergeUnrolledAssistants(config, unrolledLocal.config);
}
}
} else {
// This is how we allow use of blocks locally
const unrollResult = await unrollAssistant(
packageIdentifier,
new RegistryClient({
accessToken: await controlPlaneClient.getAccessToken(),
apiBase: getControlPlaneEnvSync(ideSettings.continueTestEnvironment)
.CONTROL_PLANE_URL,
rootPath,
}),
await getRegistryClient(),
{
renderSecrets: true,
currentUserSlug: "",
@ -143,7 +133,7 @@ async function loadConfigYaml(options: {
controlPlaneClient,
ide,
),
injectBlocks: allLocalBlocks,
injectBlocks: localPackageIdentifiers,
},
);
config = unrollResult.config;
@ -235,8 +225,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 +419,7 @@ async function configYamlToContinueConfig(options: {
(config.mcpServers ?? []).map((server) => ({
id: server.name,
name: server.name,
sourceFile: server.sourceFile,
transport: {
type: "stdio",
args: [],

View file

@ -0,0 +1,35 @@
import { MCPServer, Rule } from "@continuedev/config-yaml";
import { ExperimentalMCPOptions, RuleWithSource } from "../..";
export function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
if (typeof rule === "string") {
return {
rule: rule,
source: "rules-block",
};
} else {
return {
source: "rules-block",
rule: rule.rule,
globs: rule.globs,
name: rule.name,
ruleFile: rule.sourceFile,
alwaysApply: rule.alwaysApply,
};
}
}
export function convertYamlMcpToContinueMcp(
server: MCPServer,
): ExperimentalMCPOptions {
return {
transport: {
type: "stdio",
command: server.command,
args: server.args ?? [],
env: server.env,
cwd: server.cwd,
} as any, // TODO: Fix the mcpServers types in config-yaml (discriminated union)
timeout: server.connectionTimeout,
};
}

View file

@ -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) => {
@ -397,7 +400,10 @@ export class Core {
on("controlPlane/openUrl", async (msg) => {
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
let url = `${env.APP_URL}${msg.data.path}`;
const urlPath = msg.data.path.startsWith("/")
? msg.data.path.slice(1)
: msg.data.path;
let url = `${env.APP_URL}${urlPath}`;
if (msg.data.orgSlug) {
url += `?org=${msg.data.orgSlug}`;
}

View file

@ -1,8 +1,5 @@
import { ILLM } from "../..";
import {
filterLeadingNewline,
stopAtLines,
} from "../../autocomplete/filtering/streamTransforms/lineStream";
import { filterLeadingNewline } from "../../autocomplete/filtering/streamTransforms/lineStream";
import { streamLines } from "../../diff/util";
import { dedent } from "../../util";
@ -90,11 +87,18 @@ export async function* getReplacementWithLlm(
{ role: "assistant", content: assistantPrompt },
],
abortController.signal,
{
raw: true,
prediction: undefined,
reasoning: false,
},
);
let lines = streamLines(completion);
lines = filterLeadingNewline(lines);
lines = stopAtLines(lines, () => {}, ["```"]);
// We want to retrive everything from the llm
// then let the filterCodeBlocks function clean up for any trailing text.
// if we stop here early, we run the risk of loosing inner markdown content.
for await (const line of lines) {
yield line;

View file

@ -0,0 +1,459 @@
import { streamLazyApply } from "./streamLazyApply";
// Mock LLM for testing
class MockLLM {
model = "claude-3-5-sonnet-20241022";
providerName = "anthropic";
async *streamChat(messages: any[], signal?: AbortSignal) {
// Simulate LLM response for markdown file with nested blocks
const lines = [
"# Project Structure",
"",
"```markdown README.md",
"# Project Structure",
"",
"```",
".",
"├── src/",
"│ └── main.js",
"└── package.json",
"```",
"```",
];
// Yield each line separately (more realistic streaming)
for (const line of lines) {
yield line;
}
}
}
class MockJavaScriptLLM {
model = "claude-3-5-sonnet-20241022";
providerName = "anthropic";
async *streamChat(messages: any[], signal?: AbortSignal) {
// Simulate LLM response for JavaScript file
const lines = [
"function calculateSum(a, b) {",
" return a + b;",
"}",
"",
"function calculateProduct(a, b) {",
" return a * b;",
"}",
];
for (const line of lines) {
yield line;
}
}
}
class MockPythonLLM {
model = "claude-3-5-sonnet-20241022";
providerName = "anthropic";
async *streamChat(messages: any[], signal?: AbortSignal) {
// Simulate LLM response for Python file
const lines = [
"def calculate_sum(a, b):",
" return a + b",
"",
"def calculate_product(a, b):",
" return a * b",
];
for (const line of lines) {
yield line;
}
}
}
class MockWithUnchangedCodeLLM {
model = "claude-3-5-sonnet-20241022";
providerName = "anthropic";
async *streamChat(messages: any[], signal?: AbortSignal) {
// Simulate LLM response with UNCHANGED_CODE markers
const lines = [
"function newFunction() {",
" return 'new';",
"}",
"",
"// ... unchanged code ...",
"",
"function anotherFunction() {",
" return 'updated';",
"}",
];
for (const line of lines) {
yield line;
}
}
}
class MockTypeScriptLLM {
model = "claude-3-5-sonnet-20241022";
providerName = "anthropic";
async *streamChat(messages: any[], signal?: AbortSignal) {
const lines = [
"interface User {",
" id: number;",
" name: string;",
"}",
"",
"function getUser(id: number): User {",
" return { id, name: 'Test User' };",
"}",
];
for (const line of lines) {
yield line;
}
}
}
class MockEmptyLLM {
model = "claude-3-5-sonnet-20241022";
providerName = "anthropic";
async *streamChat(messages: any[], signal?: AbortSignal) {
// Empty response
return;
}
}
class MockSimpleLLM {
model = "claude-3-5-sonnet-20241022";
providerName = "anthropic";
async *streamChat(messages: any[], signal?: AbortSignal) {
const lines = ["function test() {", " return true;", "}"];
for (const line of lines) {
yield line;
}
}
}
class MockRegularMarkdownLLM {
model = "claude-3-5-sonnet-20241022";
providerName = "anthropic";
async *streamChat(messages: any[], signal?: AbortSignal) {
// Simulate regular markdown with simple code block
const lines = [
"# Debug Test Folder",
"The sole purpose of this folder is to open it when debugging.",
"",
"## File Structure",
"```",
"debug-test-folder/",
"├── AdvancedPage.tsx",
"├── Calculator.java",
"├── Dockerfile",
"└── test.ts",
"```",
];
for (const line of lines) {
yield line;
}
}
}
describe("streamLazyApply", () => {
test("should handle markdown files with nested blocks without stopping early", async () => {
const oldCode = "# Project\n\nBasic readme content.";
const newCode = `# Project Structure
\`\`\`markdown README.md
# Project Structure
\`\`\`
.
├── src/
│ └── main.js
└── package.json
\`\`\`
\`\`\``;
const filename = "README.md";
const llm = new MockLLM() as any;
const abortController = new AbortController();
const diffLines = [];
for await (const diffLine of streamLazyApply(
oldCode,
filename,
newCode,
llm,
abortController,
)) {
diffLines.push(diffLine);
}
// Should have received diff lines (not empty)
expect(diffLines.length).toBeGreaterThan(0);
// Should contain the nested markdown content
const allContent = diffLines.map((d) => d.line).join("\n");
expect(allContent).toContain("```markdown README.md");
expect(allContent).toContain("└── package.json");
// Should not have been truncated at the first ```
expect(allContent).toContain("src/");
});
test("should handle JavaScript files correctly", async () => {
const oldCode = "function calculateSum(a, b) {\n return a + b;\n}";
const newCode = `function calculateSum(a, b) {
return a + b;
}
function calculateProduct(a, b) {
return a * b;
}`;
const filename = "calculator.js";
const llm = new MockJavaScriptLLM() as any;
const abortController = new AbortController();
const diffLines = [];
for await (const diffLine of streamLazyApply(
oldCode,
filename,
newCode,
llm,
abortController,
)) {
diffLines.push(diffLine);
}
// Should have received diff lines
expect(diffLines.length).toBeGreaterThan(0);
// Should contain the JavaScript functions
const allContent = diffLines.map((d) => d.line).join("\n");
expect(allContent).toContain("calculateSum");
expect(allContent).toContain("calculateProduct");
});
test("should handle Python files correctly", async () => {
const oldCode = "def calculate_sum(a, b):\n return a + b";
const newCode = `def calculate_sum(a, b):
return a + b
def calculate_product(a, b):
return a * b`;
const filename = "calculator.py";
const llm = new MockPythonLLM() as any;
const abortController = new AbortController();
const diffLines = [];
for await (const diffLine of streamLazyApply(
oldCode,
filename,
newCode,
llm,
abortController,
)) {
diffLines.push(diffLine);
}
// Should have received diff lines
expect(diffLines.length).toBeGreaterThan(0);
// Should contain the Python functions
const allContent = diffLines.map((d) => d.line).join("\n");
expect(allContent).toContain("calculate_sum");
expect(allContent).toContain("calculate_product");
});
test("should handle UNCHANGED_CODE markers in responses", async () => {
const oldCode = `function oldFunction() {
return 'old';
}
function existingFunction() {
return 'existing';
}`;
const newCode = `function newFunction() {
return 'new';
}
function existingFunction() {
return 'existing';
}
function anotherFunction() {
return 'updated';
}`;
const filename = "example.js";
const llm = new MockWithUnchangedCodeLLM() as any;
const abortController = new AbortController();
const diffLines = [];
for await (const diffLine of streamLazyApply(
oldCode,
filename,
newCode,
llm,
abortController,
)) {
diffLines.push(diffLine);
}
// Should have received diff lines
expect(diffLines.length).toBeGreaterThan(0);
// Should contain new and updated functions
const allContent = diffLines.map((d) => d.line).join("\n");
expect(allContent).toContain("newFunction");
expect(allContent).toContain("anotherFunction");
});
test("should handle TypeScript files correctly", async () => {
const oldCode = "interface User {\n id: number;\n}";
const newCode = `interface User {
id: number;
name: string;
}
function getUser(id: number): User {
return { id, name: 'Test User' };
}`;
const filename = "user.ts";
const llm = new MockTypeScriptLLM() as any;
const abortController = new AbortController();
const diffLines = [];
for await (const diffLine of streamLazyApply(
oldCode,
filename,
newCode,
llm,
abortController,
)) {
diffLines.push(diffLine);
}
// Should have received diff lines
expect(diffLines.length).toBeGreaterThan(0);
// Should contain TypeScript interface and function
const allContent = diffLines.map((d) => d.line).join("\n");
expect(allContent).toContain("interface User");
expect(allContent).toContain("getUser");
expect(allContent).toContain("name: string");
});
test("should work with empty LLM responses", async () => {
const oldCode = "function test() { return 1; }";
const newCode = "function test() { return 2; }";
const filename = "test.js";
const llm = new MockEmptyLLM() as any;
const abortController = new AbortController();
const diffLines = [];
for await (const diffLine of streamLazyApply(
oldCode,
filename,
newCode,
llm,
abortController,
)) {
diffLines.push(diffLine);
}
// Should handle empty response gracefully
expect(diffLines).toBeDefined();
});
test("should correctly identify markdown vs non-markdown files", async () => {
// Test that our isMarkdownFile logic works
const markdownFiles = ["README.md", "docs.markdown", "example.gfm"];
const nonMarkdownFiles = [
"script.js",
"code.py",
"style.css",
"component.tsx",
];
// This is more of a unit test, but verifies our file detection logic
// We can test this indirectly by checking that different file types
// are processed through different code paths
const oldCode = "function test() { return false; }";
const newCode = "function test() { return true; }";
const llm = new MockSimpleLLM() as any;
// Test each file type
for (const filename of [...markdownFiles, ...nonMarkdownFiles]) {
const abortController = new AbortController();
const diffLines = [];
for await (const diffLine of streamLazyApply(
oldCode,
filename,
newCode,
llm,
abortController,
)) {
diffLines.push(diffLine);
}
// Should work for all file types
expect(diffLines.length).toBeGreaterThan(0);
const allContent = diffLines.map((d) => d.line).join("\n");
expect(allContent).toContain("test");
}
});
test("should handle regular markdown files with simple code blocks", async () => {
const oldCode = "# Old Content";
const newCode = `# Debug Test Folder
The sole purpose of this folder is to open it when debugging.
## File Structure
\`\`\`
debug-test-folder/
├── AdvancedPage.tsx
├── Calculator.java
├── Dockerfile
└── test.ts
\`\`\``;
const filename = "README.md";
const llm = new MockRegularMarkdownLLM() as any;
const abortController = new AbortController();
const diffLines = [];
for await (const diffLine of streamLazyApply(
oldCode,
filename,
newCode,
llm,
abortController,
)) {
diffLines.push(diffLine);
}
// Should have received diff lines (not empty)
expect(diffLines.length).toBeGreaterThan(0);
// Should contain the full file structure
const allContent = diffLines.map((d) => d.line).join("\n");
expect(allContent).toContain("Debug Test Folder");
expect(allContent).toContain("File Structure");
expect(allContent).toContain("debug-test-folder/");
expect(allContent).toContain("├── AdvancedPage.tsx");
expect(allContent).toContain("└── test.ts");
// Should not have been truncated at the opening ```
expect(allContent).toContain("Calculator.java");
expect(allContent).toContain("Dockerfile");
});
});

View file

@ -2,11 +2,11 @@ import {
filterLeadingAndTrailingNewLineInsertion,
filterLeadingNewline,
removeTrailingWhitespace,
stopAtLines,
} from "../../autocomplete/filtering/streamTransforms/lineStream.js";
import { streamDiff } from "../../diff/streamDiff.js";
import { LineStream, streamLines } from "../../diff/util.js";
import { DiffLine, ILLM } from "../../index.js";
import { stopAtLinesWithMarkdownSupport } from "../../utils/streamMarkdownUtils.js";
import { lazyApplyPromptForModel, UNCHANGED_CODE } from "./prompts.js";
import { BUFFER_LINES_BELOW, getReplacementWithLlm } from "./replace.js";
@ -44,9 +44,12 @@ export async function* streamLazyApply(
}
let lazyCompletionLines = streamLines(lazyCompletion, true);
// Process line output
// lazyCompletionLines = filterEnglishLinesAtStart(lazyCompletionLines);
lazyCompletionLines = stopAtLines(lazyCompletionLines, () => {}, ["```"]);
lazyCompletionLines = stopAtLinesWithMarkdownSupport(
lazyCompletionLines,
filename,
);
lazyCompletionLines = filterLeadingNewline(lazyCompletionLines);
lazyCompletionLines = removeTrailingWhitespace(lazyCompletionLines);
@ -92,7 +95,6 @@ async function* streamFillUnchangedCode(
newLines.push(replacementLine);
replacement += replacementLine + "\n";
}
// Yield the buffered lines
for (const bufferedLine of buffer) {
yield bufferedLine;

View file

@ -63,7 +63,8 @@ export async function* recursiveStream(
}
} else {
const generator = llm.streamChat(prompt, abortController.signal, {
prediction,
raw: true,
prediction: undefined,
reasoning: false,
});

View file

@ -55,11 +55,7 @@ export async function* addIndentation(
}
function modelIsInept(model: string): boolean {
return !(
model.includes("gpt") ||
model.includes("claude") ||
model.includes("nova")
);
return !(model.includes("gpt") || model.includes("claude"));
}
export async function* streamDiffLines({

83
core/index.d.ts vendored
View file

@ -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<
@ -803,8 +806,6 @@ export interface IDE {
getWorkspaceDirs(): Promise<string[]>;
getWorkspaceConfigs(): Promise<ContinueRcJson[]>;
fileExists(fileUri: string): Promise<boolean>;
writeFile(path: string, contents: string): Promise<void>;
@ -871,6 +872,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
getReferences(location: Location): Promise<RangeInFile[]>;
getDocumentSymbols(textDocumentIdentifier: string): Promise<DocumentSymbol[]>;
@ -1037,6 +1040,7 @@ export interface CustomCommand {
name: string;
prompt: string;
description?: string;
sourceFile?: string;
}
export interface Prediction {
@ -1082,6 +1086,7 @@ export interface Tool {
faviconUrl?: string;
group: string;
originalFunctionName?: string;
systemMessageDescription?: string;
}
interface ToolChoice {
@ -1154,6 +1159,8 @@ export interface ModelDescription {
capabilities?: ModelCapability;
roles?: ModelRole[];
configurationStatus?: LLMConfigurationStatuses;
sourceFile?: string;
}
export interface JSONEmbedOptions {
@ -1211,6 +1218,7 @@ export interface TabAutocompleteOptions {
experimental_includeRecentlyVisitedRanges: boolean | number;
experimental_includeRecentlyEditedRanges: boolean | number;
experimental_includeDiff: boolean | number;
experimental_enableStaticContextualization: boolean;
}
export interface StdioOptions {
@ -1308,6 +1316,7 @@ export interface MCPServerStatus extends MCPOptions {
tools: MCPTool[];
resources: MCPResource[];
resourceTemplates: MCPResourceTemplate[];
sourceFile?: string;
}
export interface ContinueUIConfig {
@ -1352,6 +1361,7 @@ export interface ApplyState {
numDiffs?: number;
filepath?: string;
fileContent?: string;
originalFileContent?: string;
toolCallId?: string;
}
@ -1410,6 +1420,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.
@ -1445,6 +1517,7 @@ export interface ExperimentalConfig {
defaultContext?: DefaultContextProvider[];
promptPath?: string;
enableExperimentalTools?: boolean;
onlyUseSystemMessageTools?: boolean;
/**
* Quick actions are a way to add custom commands to the Code Lens of
@ -1480,6 +1553,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 {

View file

@ -1,6 +1,8 @@
import path from "path";
import { shouldChunk } from "./chunk";
import { Chunk, ChunkWithoutID } from "../../index.js";
import { cleanupAsyncEncoders } from "../../llm/countTokens.js";
import { chunkDocument, chunkDocumentWithoutId, shouldChunk } from "./chunk";
describe("shouldChunk", () => {
test("should chunk a typescript file", () => {
@ -28,6 +30,126 @@ describe("shouldChunk", () => {
});
});
describe("chunkDocument", () => {
afterAll(async () => {
// Clean up the global async encoders to prevent Jest from hanging
await cleanupAsyncEncoders();
});
test("should return multiple chunks for large content with small maxChunkSize", async () => {
const filepath = "/test/file.txt";
const maxChunkSize = 10; // small limit
const digest = "test-digest";
// Create content with multiple short lines - each line should fit within maxChunkSize
const lines = ["short line", "another line", "third line"];
const contents = lines.join("\n");
const chunks: Chunk[] = [];
for await (const chunk of chunkDocument({
filepath,
contents,
maxChunkSize,
digest,
})) {
chunks.push(chunk);
}
// Verify chunks have valid content
chunks.forEach((chunk) => {
expect(chunk.content.length).toBeGreaterThan(0);
});
});
test("should filter out chunks that exceed maxChunkSize in tokens", async () => {
const filepath = "/test/large.txt";
const maxChunkSize = 10; // small limit
const digest = "test-digest-2";
const contents =
"This is a much longer line with many words that will likely exceed the maxChunkSize token limit and should be filtered out by the chunkDocument function. This is a much longer line with many words that will likely exceed the maxChunkSize token limit and should be filtered out by the chunkDocument function.";
const chunks: Chunk[] = [];
for await (const chunk of chunkDocument({
filepath,
contents,
maxChunkSize,
digest,
})) {
chunks.push(chunk);
}
// Verify that no chunks were created since the content exceeds maxChunkSize
chunks.forEach((chunk) => {
expect(chunk.content.length).toBe(0);
});
});
});
describe("chunkDocumentWithoutId", () => {
afterAll(async () => {
await cleanupAsyncEncoders();
});
test("should return no chunks for empty content", async () => {
const contents = "";
const chunks: ChunkWithoutID[] = [];
for await (const chunk of chunkDocumentWithoutId(
"file.txt",
contents,
100,
)) {
chunks.push(chunk);
}
expect(chunks).toHaveLength(0);
});
test("should chunk text files", async () => {
const contents = "Line 1\nLine 2\nLine 3";
const chunks: ChunkWithoutID[] = [];
for await (const chunk of chunkDocumentWithoutId(
"file.txt",
contents,
100,
)) {
chunks.push(chunk);
}
expect(chunks.length).toBeGreaterThan(0);
expect(chunks[0].content).toContain("Line 1");
});
test("should chunk for code files", async () => {
const contents = "function test() {\n return 42;\n}";
const chunks: ChunkWithoutID[] = [];
for await (const chunk of chunkDocumentWithoutId(
"file.js",
contents,
100,
)) {
chunks.push(chunk);
}
expect(chunks.length).toBeGreaterThan(0);
expect(chunks[0].content).toContain("function test");
});
test("should chunk large content", async () => {
const contents = Array(100).fill("short line").join("\n"); // Large content with many lines
const maxChunkSize = 50;
const chunks: ChunkWithoutID[] = [];
for await (const chunk of chunkDocumentWithoutId(
"file.txt",
contents,
maxChunkSize,
)) {
chunks.push(chunk);
}
expect(chunks.length).toBeGreaterThan(1); // Should create multiple chunks
chunks.forEach((chunk) => {
expect(chunk.content.length).toBeGreaterThan(0); // Each chunk should have content
});
});
});
function generateString(length: number) {
return "a".repeat(length);
}

View file

@ -13,7 +13,7 @@ export type ChunkDocumentParam = {
digest: string;
};
async function* chunkDocumentWithoutId(
export async function* chunkDocumentWithoutId(
fileUri: string,
contents: string,
maxChunkSize: number,

View file

@ -1,9 +1,4 @@
import {
ChatMessage,
ModelCapability,
ModelDescription,
TemplateType,
} from "../index.js";
import { ChatMessage, ModelCapability, TemplateType } from "../index.js";
import {
anthropicTemplateMessages,
@ -41,7 +36,6 @@ import {
xWinCoderEditPrompt,
zephyrEditPrompt,
} from "./templates/edit.js";
import { PROVIDER_TOOL_SUPPORT } from "./toolSupport.js";
const PROVIDER_HANDLES_TEMPLATING: string[] = [
"lmstudio",
@ -107,17 +101,6 @@ const MODEL_SUPPORTS_IMAGES: string[] = [
"granite-vision",
];
function modelSupportsTools(modelDescription: ModelDescription) {
if (modelDescription.capabilities?.tools !== undefined) {
return modelDescription.capabilities.tools;
}
const providerSupport = PROVIDER_TOOL_SUPPORT[modelDescription.provider];
if (!providerSupport) {
return false;
}
return providerSupport(modelDescription.model) ?? false;
}
function modelSupportsImages(
provider: string,
model: string,
@ -400,5 +383,4 @@ export {
autodetectTemplateType,
llmCanGenerateInParallel,
modelSupportsImages,
modelSupportsTools,
};

View file

@ -1,6 +1,7 @@
const DEFAULT_MAX_TOKENS = 4096;
const DEFAULT_CONTEXT_LENGTH = 32_768;
const DEFAULT_TEMPERATURE = 0.5;
const DEFAULT_PRUNING_LENGTH = 128000;
const DEFAULT_ARGS = {
maxTokens: DEFAULT_MAX_TOKENS,
@ -24,5 +25,6 @@ export {
DEFAULT_MAX_BATCH_SIZE,
DEFAULT_MAX_CHUNK_SIZE,
DEFAULT_MAX_TOKENS,
DEFAULT_PRUNING_LENGTH,
PROXY_URL,
};

View file

@ -2,6 +2,7 @@
// Generated by continue
import { ChatMessage, MessagePart, ToolCall } from "../index.js";
import {
cleanupAsyncEncoders,
compileChatMessages,
countTokens,
countTokensAsync,
@ -27,7 +28,12 @@ describe.skip("countTokens", () => {
});
});
describe.skip("countTokensAsync", () => {
describe("countTokensAsync", () => {
afterAll(async () => {
// Clean up the global async encoders to prevent Jest from hanging
await cleanupAsyncEncoders();
});
it("should count tokens asynchronously for a simple string", async () => {
const content = "Hello world!";
const tokenCount = await countTokensAsync(content, "gpt-4");

View file

@ -17,6 +17,7 @@ import {
import { renderChatMessage } from "../util/messageContent.js";
import { AsyncEncoder, LlamaAsyncEncoder } from "./asyncEncoder.js";
import { DEFAULT_PRUNING_LENGTH } from "./constants.js";
import llamaTokenizer from "./llamaTokenizer.js";
interface Encoding {
encode: Tiktoken["encode"];
@ -409,14 +410,14 @@ function pruneRawPromptFromTop(
function compileChatMessages({
modelName,
msgs,
contextLength,
knownContextLength,
maxTokens,
supportsImages,
tools,
}: {
modelName: string;
msgs: ChatMessage[];
contextLength: number;
knownContextLength: number | undefined;
maxTokens: number;
supportsImages: boolean;
tools?: Tool[];
@ -465,6 +466,7 @@ function compileChatMessages({
toolTokens = countToolsTokens(tools, modelName);
}
const contextLength = knownContextLength ?? DEFAULT_PRUNING_LENGTH;
const countingSafetyBuffer = getTokenCountingBufferSafety(contextLength);
const minOutputTokens = Math.min(MIN_RESPONSE_TOKENS, maxTokens);
@ -480,12 +482,12 @@ function compileChatMessages({
inputTokensAvailable -= lastMessagesTokens;
// Make sure there's enough context for the non-excludable items
if (inputTokensAvailable < 0) {
if (knownContextLength !== undefined && inputTokensAvailable < 0) {
throw new Error(
`Not enough context available to include the system message, last user message, and tools.
There must be at least ${minOutputTokens} tokens remaining for output.
Request had the following token counts:
- contextLength: ${contextLength}
- contextLength: ${knownContextLength}
- counting safety buffer: ${countingSafetyBuffer}
- tools: ~${toolTokens}
- system message: ~${systemMsgTokens}
@ -536,7 +538,14 @@ function compileChatMessages({
};
}
async function cleanupAsyncEncoders(): Promise<void> {
try {
await llamaAsyncEncoder.close();
} catch (e) {}
}
export {
cleanupAsyncEncoders,
compileChatMessages,
countTokens,
countTokensAsync,

View file

@ -145,7 +145,7 @@ export abstract class BaseLLM implements ILLM {
baseChatSystemMessage?: string;
basePlanSystemMessage?: string;
baseAgentSystemMessage?: string;
contextLength: number;
_contextLength: number | undefined;
maxStopWords?: number | undefined;
completionOptions: CompletionOptions;
requestOptions?: RequestOptions;
@ -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;
@ -217,8 +220,7 @@ export abstract class BaseLLM implements ILLM {
this.baseAgentSystemMessage = options.baseAgentSystemMessage;
this.basePlanSystemMessage = options.basePlanSystemMessage;
this.baseChatSystemMessage = options.baseChatSystemMessage;
this.contextLength =
options.contextLength ?? llmInfo?.contextLength ?? DEFAULT_CONTEXT_LENGTH;
this._contextLength = options.contextLength ?? llmInfo?.contextLength;
this.maxStopWords = options.maxStopWords ?? this.maxStopWords;
this.completionOptions = {
...options.completionOptions,
@ -290,6 +292,11 @@ export abstract class BaseLLM implements ILLM {
this.embeddingId = `${this.constructor.name}::${this.model}::${this.maxEmbeddingChunkSize}`;
this.autocompleteOptions = options.autocompleteOptions;
this.sourceFile = options.sourceFile;
}
get contextLength() {
return this._contextLength ?? DEFAULT_CONTEXT_LENGTH;
}
getConfigurationStatus() {
@ -524,7 +531,7 @@ export abstract class BaseLLM implements ILLM {
let contentToShow = "";
if (msg.role === "tool") {
contentToShow = msg.content;
} else if (msg.role === "assistant" && msg.toolCalls) {
} else if (msg.role === "assistant" && msg.toolCalls?.length) {
contentToShow = msg.toolCalls
?.map(
(toolCall) =>
@ -532,10 +539,7 @@ export abstract class BaseLLM implements ILLM {
)
.join("\n");
} else if ("content" in msg) {
if (Array.isArray(msg.content)) {
msg.content = renderChatMessage(msg);
}
contentToShow = msg.content;
contentToShow = renderChatMessage(msg);
}
return `<${msg.role}>\n${contentToShow}\n\n`;
@ -895,7 +899,7 @@ export abstract class BaseLLM implements ILLM {
return compileChatMessages({
modelName: completionOptions.model,
msgs: message,
contextLength: this.contextLength,
knownContextLength: this._contextLength,
maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
supportsImages: this.supportsImages(),
tools: options.tools,
@ -944,7 +948,7 @@ export abstract class BaseLLM implements ILLM {
const { compiledChatMessages } = compileChatMessages({
modelName: completionOptions.model,
msgs: _messages,
contextLength: this.contextLength,
knownContextLength: this._contextLength,
maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
supportsImages: this.supportsImages(),
tools: options.tools,

View file

@ -172,52 +172,10 @@ class Anthropic extends BaseLLM {
}
}
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
async *handleResponse(
response: any,
stream: boolean | undefined,
): AsyncGenerator<ChatMessage> {
if (!this.apiKey || this.apiKey === "") {
throw new Error(
"Request not sent. You have an Anthropic model configured in your config.json, but the API key is not set.",
);
}
const systemMessage = stripImages(
messages.filter((m) => m.role === "system")[0]?.content ?? "",
);
const shouldCacheSystemMessage = !!(
this.cacheBehavior?.cacheSystemMessage && systemMessage
);
const msgs = this.convertMessages(messages);
const response = await this.fetch(new URL("messages", this.apiBase), {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": this.apiKey as string,
...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation
? { "anthropic-beta": "prompt-caching-2024-07-31" }
: {}),
},
body: JSON.stringify({
...this.convertArgs(options),
messages: msgs,
system: shouldCacheSystemMessage
? [
{
type: "text",
text: systemMessage,
cache_control: { type: "ephemeral" },
},
]
: systemMessage,
}),
signal,
});
if (response.status === 499) {
return; // Aborted by user
}
@ -237,7 +195,7 @@ class Anthropic extends BaseLLM {
);
}
if (options.stream === false) {
if (stream === false) {
const data = await response.json();
const cost = data.usage
? {
@ -348,6 +306,55 @@ class Anthropic extends BaseLLM {
usage,
};
}
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
if (!this.apiKey || this.apiKey === "") {
throw new Error(
"Request not sent. You have an Anthropic model configured in your config.json, but the API key is not set.",
);
}
const systemMessage = stripImages(
messages.filter((m) => m.role === "system")[0]?.content ?? "",
);
const shouldCacheSystemMessage = !!(
this.cacheBehavior?.cacheSystemMessage && systemMessage
);
const msgs = this.convertMessages(messages);
const response = await this.fetch(new URL("messages", this.apiBase), {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": this.apiKey as string,
...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation
? { "anthropic-beta": "prompt-caching-2024-07-31" }
: {}),
},
body: JSON.stringify({
...this.convertArgs(options),
messages: msgs,
system: shouldCacheSystemMessage
? [
{
type: "text",
text: systemMessage,
cache_control: { type: "ephemeral" },
},
]
: systemMessage,
}),
signal,
});
yield* this.handleResponse(response, options.stream);
}
}
export default Anthropic;

View file

@ -200,6 +200,7 @@ class Gemini extends BaseLLM {
messages: ChatMessage[],
options: CompletionOptions,
isV1API: boolean,
includeToolIds: boolean,
): GeminiChatRequestBody {
const toolCallIdToNameMap = new Map<string, string>();
messages.forEach((msg) => {
@ -231,7 +232,7 @@ class Gemini extends BaseLLM {
parts: [
{
functionResponse: {
id: msg.toolCallId,
id: includeToolIds ? msg.toolCallId : undefined,
name: functionName || "unknown",
response: {
output: msg.content, // "output" key is opinionated - not all functions will output objects
@ -406,7 +407,7 @@ class Gemini extends BaseLLM {
const isV1API = !!this.apiBase?.includes("/v1/");
// Convert chat messages to contents
const body = this.prepareBody(messages, options, isV1API);
const body = this.prepareBody(messages, options, isV1API, true);
const response = await this.fetch(apiURL, {
method: "POST",

View file

@ -25,7 +25,7 @@ class HuggingFaceTGI extends BaseLLM {
}
const json = await response.json();
this.model = json.model_id;
this.contextLength = Number.parseInt(json.max_input_length);
this._contextLength = Number.parseInt(json.max_input_length);
})
.catch((e) => {
console.log(`Failed to list models for HuggingFace TGI: ${e.message}`);

View file

@ -67,7 +67,7 @@ class Mistral extends OpenAI {
return Mistral.modelConversion[model] ?? model;
}
protected _convertArgs(options: any, messages: ChatMessage[]) {
_convertArgs(options: any, messages: ChatMessage[]) {
const finalOptions = super._convertArgs(options, messages);
const lastMessage = finalOptions.messages[finalOptions.messages.length - 1];

View file

@ -184,7 +184,7 @@ class Ollama extends BaseLLM implements ModelInstaller {
let value = parts[2];
switch (key) {
case "num_ctx":
this.contextLength =
this._contextLength =
options.contextLength ?? Number.parseInt(value);
break;
case "stop":

View file

@ -254,24 +254,7 @@ class VertexAI extends BaseLLM {
signal,
});
if (response.status === 499) {
return; // Aborted by user
}
if (options.stream === false) {
const data = await response.json();
yield { role: "assistant", content: data.content[0].text };
return;
}
for await (const value of streamSse(response)) {
if (value.type === "message_start") {
console.log(value);
}
if (value.delta?.text) {
yield { role: "assistant", content: value.delta.text };
}
}
yield* this.anthropicInstance.handleResponse(response, options.stream);
}
// Gemini
@ -285,17 +268,19 @@ class VertexAI extends BaseLLM {
this.apiBase,
);
const body = this.geminiInstance.prepareBody(messages, options, false);
// For some reason gemini through vertex does not support ids in functionResponses yet
const body = this.geminiInstance.prepareBody(
messages,
options,
false,
false,
);
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
signal,
});
for await (const message of this.geminiInstance.processGeminiResponse(
streamResponse(response),
)) {
yield message;
}
yield* this.geminiInstance.processGeminiResponse(streamResponse(response));
}
private async *streamChatBison(

View file

@ -72,7 +72,7 @@ class Vllm extends OpenAI {
const json = await response.json();
const data = json.data[0];
this.model = data.id;
this.contextLength = Number.parseInt(data.max_model_len);
this._contextLength = Number.parseInt(data.max_model_len);
})
.catch((e) => {
console.log(`Failed to list models for vLLM: ${e.message}`);

View file

@ -1,4 +1,5 @@
import { parseProxyModelName } from "@continuedev/config-yaml";
import { ModelDescription } from "..";
export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
{
@ -83,11 +84,12 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
return model.toLowerCase().includes("gemini");
},
vertexai: (model) => {
const lowerCaseModel = model.toLowerCase();
// All gemini models except flash 2.0 lite support function calling
return (
model.toLowerCase().includes("gemini") &&
!model.toLowerCase().includes("lite")
);
if (lowerCaseModel.includes("lite")) {
return false;
}
return ["claude", "gemini"].some((val) => lowerCaseModel.includes(val));
},
bedrock: (model) => {
if (
@ -287,3 +289,31 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
return false;
},
};
export function isRecommendedAgentModel(modelName: string): boolean {
// AND behavior
const recs: RegExp[][] = [
[/o[134]/],
[/deepseek/, /r1|reasoner/],
[/gemini/, /2\.5/, /pro/],
[/gpt/, /4/],
[/claude/, /sonnet/, /3\.5|3\.7|3-5|3-7|-4/],
[/claude/, /opus/, /-4/],
];
for (const combo of recs) {
if (combo.every((regex) => modelName.toLowerCase().match(regex))) {
return true;
}
}
return false;
}
export function modelSupportsNativeTools(modelDescription: ModelDescription) {
if (modelDescription.capabilities?.tools !== undefined) {
return modelDescription.capabilities.tools;
}
const providerSupport = PROVIDER_TOOL_SUPPORT[modelDescription.provider];
if (!providerSupport) {
return false;
}
return providerSupport(modelDescription.model) ?? false;
}

View file

@ -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": [
{

View file

@ -1,5 +1,4 @@
import type {
ContinueRcJson,
DocumentSymbol,
FileStatsMap,
FileType,
@ -11,6 +10,7 @@ import type {
Problem,
Range,
RangeInFile,
SignatureHelp,
TerminalOptions,
Thread,
} from "../";
@ -52,7 +52,6 @@ export type ToIdeFromWebviewOrCoreProtocol = {
showLines: [{ filepath: string; startLine: number; endLine: number }, void];
readRangeInFile: [{ filepath: string; range: Range }, string];
getDiff: [{ includeUnstaged: boolean }, string[]];
getWorkspaceConfigs: [undefined, ContinueRcJson[]];
getTerminalContents: [undefined, string];
getDebugLocals: [{ threadIndex: number }, string];
getTopLevelCallStackSources: [
@ -83,6 +82,8 @@ export type ToIdeFromWebviewOrCoreProtocol = {
getFileStats: [{ files: string[] }, FileStatsMap];
gotoDefinition: [{ location: Location }, RangeInFile[]];
gotoTypeDefinition: [{ location: Location }, RangeInFile[]];
getSignatureHelp: [{ location: Location }, SignatureHelp | null];
getReferences: [{ location: Location }, RangeInFile[]];
getDocumentSymbols: [{ textDocumentIdentifier: string }, DocumentSymbol[]];

View file

@ -2,7 +2,6 @@ import { FromIdeProtocol } from "..";
import { ToIdeFromWebviewOrCoreProtocol } from "../ide";
import type {
ContinueRcJson,
DocumentSymbol,
FileStatsMap,
FileType,
@ -14,6 +13,7 @@ import type {
Problem,
Range,
RangeInFile,
SignatureHelp,
TerminalOptions,
Thread,
} from "../..";
@ -46,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 });
}
async getReferences(location: Location): Promise<RangeInFile[]> {
return this.request("getReferences", { location });
}
@ -125,10 +133,6 @@ export class MessageIde implements IDE {
return this.request("getUniqueId", undefined);
}
getWorkspaceConfigs(): Promise<ContinueRcJson[]> {
return this.request("getWorkspaceConfigs", undefined);
}
async getDiff(includeUnstaged: boolean) {
return await this.request("getDiff", { includeUnstaged });
}

View file

@ -89,10 +89,6 @@ export class ReverseMessageIde {
return this.ide.getUniqueId();
});
this.on("getWorkspaceConfigs", () => {
return this.ide.getWorkspaceConfigs();
});
this.on("getIdeSettings", () => {
return this.ide.getIdeSettings();
});

2
core/tools/constants.ts Normal file
View file

@ -0,0 +1,2 @@
export const NO_TOOL_CALL_OUTPUT_MESSAGE = "No tool output";
export const CANCELLED_TOOL_CALL_MESSAGE = "The user cancelled this tool call.";

View file

@ -1,5 +1,6 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const codebaseTool: Tool = {
type: "function",
@ -26,4 +27,9 @@ export const codebaseTool: Tool = {
},
},
},
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.CodebaseTool,
`To search the codebase, use the ${BuiltInToolNames.CodebaseTool} tool with a natural language query. For example, to find authentication logic, you might respond with:`,
[["query", "How is user authentication handled in this codebase?"]],
),
};

View file

@ -1,5 +1,6 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const createNewFileTool: Tool = {
type: "function",
@ -30,4 +31,12 @@ export const createNewFileTool: Tool = {
},
},
},
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.CreateNewFile,
`To create a NEW file, use the ${BuiltInToolNames.CreateNewFile} tool with the relative filepath and new contents. For example, to create a file located at 'path/to/file.txt', you would respond with:`,
[
["filepath", "path/to/the_file.txt"],
["contents", "Contents of the file"],
],
),
};

View file

@ -1,5 +1,20 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
const NAME_ARG_DESC =
"Short, descriptive name summarizing the rule's purpose (e.g. 'React Standards', 'Type Hints')";
const RULE_ARG_DESC =
"Clear, imperative instruction for future code generation (e.g. 'Use named exports', 'Add Python type hints'). Each rule should focus on one specific standard.";
const DESC_ARG_DESC =
"Description of when this rule should be applied. Required for Agent Requested rules (AI decides when to apply). Optional for other types.";
const GLOB_ARG_DESC =
"Optional file patterns to which this rule applies (e.g. ['**/*.{ts,tsx}'] or ['src/**/*.ts', 'tests/**/*.ts'])";
const REGEX_ARG_DESC =
"Optional regex patterns to match against file content. Rule applies only to files whose content matches the pattern (e.g. 'useEffect' for React hooks or '\\bclass\\b' for class definitions)";
const ALWAYS_APPLY_DESC =
"Whether this rule should always be applied. Set to false for Agent Requested and Manual rules. Omit or set to true for Always and Auto Attached rules.";
export const createRuleBlock: Tool = {
type: "function",
@ -20,35 +35,54 @@ export const createRuleBlock: Tool = {
properties: {
name: {
type: "string",
description:
"Short, descriptive name summarizing the rule's purpose (e.g. 'React Standards', 'Type Hints')",
description: NAME_ARG_DESC,
},
rule: {
type: "string",
description:
"Clear, imperative instruction for future code generation (e.g. 'Use named exports', 'Add Python type hints'). Each rule should focus on one specific standard.",
description: RULE_ARG_DESC,
},
description: {
type: "string",
description:
"Description of when this rule should be applied. Required for Agent Requested rules (AI decides when to apply). Optional for other types.",
description: DESC_ARG_DESC,
},
globs: {
type: "string",
description:
"Optional file patterns to which this rule applies (e.g. ['**/*.{ts,tsx}'] or ['src/**/*.ts', 'tests/**/*.ts'])",
description: GLOB_ARG_DESC,
},
regex: {
type: "string",
description:
"Optional regex patterns to match against file content. Rule applies only to files whose content matches the pattern (e.g. 'useEffect' for React hooks or '\\bclass\\b' for class definitions)",
description: REGEX_ARG_DESC,
},
alwaysApply: {
type: "boolean",
description:
"Whether this rule should always be applied. Set to false for Agent Requested and Manual rules. Omit or set to true for Always and Auto Attached rules.",
description: ALWAYS_APPLY_DESC,
},
},
},
},
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.CreateRuleBlock,
`Sometimes the user will provide feedback or guidance on your output. If you were not aware of these "rules", consider using the ${BuiltInToolNames.CreateRuleBlock} tool to persist the rule for future interactions.
This tool cannot be used to edit existing rules, but you can search in the ".continue/rules" folder and use the edit tool to manage rules.
To create a rule, respond with a ${BuiltInToolNames.CreateRuleBlock} tool call and the following arguments:
- name: ${NAME_ARG_DESC}
- rule: ${RULE_ARG_DESC}
- description: ${DESC_ARG_DESC}
- globs: ${GLOB_ARG_DESC}
- alwaysApply: ${ALWAYS_APPLY_DESC}
For example:`,
[
["name", "Use PropTypes"],
[
"rule",
"Always use PropTypes when declaring React component properties",
],
[
"description",
"Ensure that all prop types are explicitly declared for better type safety and code maintainability in React components.",
],
["globs", "**/*.js"],
["alwaysApply", "false"],
],
),
};

View file

@ -1,6 +1,7 @@
import { Tool } from "../..";
import { EDIT_CODE_INSTRUCTIONS } from "../../llm/defaultSystemMessages";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
import { NO_PARALLEL_TOOL_CALLING_INSRUCTION } from "./searchAndReplaceInFile";
export interface EditToolArgs {
@ -8,6 +9,9 @@ export interface EditToolArgs {
changes: string;
}
const CHANGES_DESCRIPTION =
"Any modifications to the file, showing only needed changes. Do NOT wrap this in a codeblock or write anything besides the code changes. In larger files, use brief language-appropriate placeholders for large unmodified sections, e.g. '// ... existing code ...'";
export const editFileTool: Tool = {
type: "function",
displayTitle: "Edit File",
@ -31,10 +35,24 @@ export const editFileTool: Tool = {
},
changes: {
type: "string",
description:
"Any modifications to the file, showing only needed changes. Do NOT wrap this in a codeblock or write anything besides the code changes. In larger files, use brief language-appropriate placeholders for large unmodified sections, e.g. '// ... existing code ...'",
description: CHANGES_DESCRIPTION,
},
},
},
},
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.EditExistingFile,
`To edit an EXISTING file, use the ${BuiltInToolNames.EditExistingFile} tool with
- filepath: the relative filepath to the file.
- changes: ${CHANGES_DESCRIPTION}
Only use this tool if you already know the contents of the file. Otherwise, use the ${BuiltInToolNames.ReadFile} or ${BuiltInToolNames.ReadCurrentlyOpenFile} tool to read it first.
For example:`,
[
["filepath", "path/to/the_file.ts"],
[
"changes",
"// ... existing code ...\nfunction subtract(a: number, b: number): number {\n return a - b;\n}\n// ... rest of code ...",
],
],
),
};

View file

@ -1,5 +1,6 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const fetchUrlContentTool: Tool = {
type: "function",
@ -25,4 +26,9 @@ export const fetchUrlContentTool: Tool = {
},
},
},
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.FetchUrlContent,
`To fetch the content of a URL, use the ${BuiltInToolNames.FetchUrlContent} tool. For example, to read the contents of a webpage, you might respond with:`,
[["url", "https://example.com"]],
),
};

View file

@ -1,5 +1,6 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const globSearchTool: Tool = {
type: "function",
@ -25,4 +26,9 @@ export const globSearchTool: Tool = {
},
},
},
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.FileGlobSearch,
`To return a list of files based on a glob search pattern, use the ${BuiltInToolNames.FileGlobSearch} tool`,
[["pattern", "*.py"]],
),
};

View file

@ -1,5 +1,6 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const grepSearchTool: Tool = {
type: "function",
@ -26,4 +27,9 @@ export const grepSearchTool: Tool = {
},
},
},
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.GrepSearch,
`To perform a grep search within the project, call the ${BuiltInToolNames.GrepSearch} tool with the query pattern to match. For example:`,
[["query", ".*main_services.*"]],
),
};

View file

@ -1,6 +1,7 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const lsTool: Tool = {
type: "function",
@ -30,4 +31,12 @@ export const lsTool: Tool = {
},
},
},
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.LSTool,
`To list files and folders in a given directory, call the ${BuiltInToolNames.LSTool} tool with "dirPath" and "recursive". For example:`,
[
["dirPath", "path/to/dir"],
["recursive", "false"],
],
),
};

View file

@ -1,5 +1,6 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const readCurrentlyOpenFileTool: Tool = {
type: "function",
@ -19,4 +20,10 @@ export const readCurrentlyOpenFileTool: Tool = {
properties: {},
},
},
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.ReadCurrentlyOpenFile,
`To view the user's currently open file, use the ${BuiltInToolNames.ReadCurrentlyOpenFile} tool.
If the user is asking about a file and you don't see any code, use this to check the current file`,
[],
),
};

View file

@ -1,5 +1,6 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const readFileTool: Tool = {
type: "function",
@ -26,4 +27,9 @@ export const readFileTool: Tool = {
},
},
},
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.ReadFile,
`To read a file with a known filepath, use the ${BuiltInToolNames.ReadFile} tool. For example, to read a file located at 'path/to/file.txt', you would respond with this:`,
[["filepath", "path/to/the_file.txt"]],
),
};

View file

@ -25,7 +25,8 @@ describe("getRequestRuleDescription", () => {
const result = getRequestRuleDescription(rules);
expect(result).toBe(
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\nNo rules available.",
"Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" +
"No rules available.",
);
});
@ -69,7 +70,7 @@ describe("getRequestRuleDescription", () => {
const result = getRequestRuleDescription(rules);
const expected =
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" +
"Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" +
"Agent Rule 1: First agent-requested rule\n" +
"Agent Rule 2: Second agent-requested rule";
@ -90,7 +91,7 @@ describe("getRequestRuleDescription", () => {
const result = getRequestRuleDescription(rules);
const expected =
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" +
"Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" +
"Rule Without Description: undefined";
expect(result).toBe(expected);
@ -110,7 +111,7 @@ describe("getRequestRuleDescription", () => {
const result = getRequestRuleDescription(rules);
const expected =
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" +
"Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" +
"undefined: Rule without name";
expect(result).toBe(expected);
@ -130,7 +131,7 @@ describe("getRequestRuleDescription", () => {
const result = getRequestRuleDescription(rules);
const expected =
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" +
"Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" +
"Rule Without File: Rule without file path";
expect(result).toBe(expected);
@ -159,7 +160,7 @@ describe("getRequestRuleDescription", () => {
const result = getRequestRuleDescription(rules);
const expected =
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" +
"Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" +
"Valid Agent Rule: This should be included";
expect(result).toBe(expected);
@ -198,7 +199,7 @@ describe("getRequestRuleDescription", () => {
const result = getRequestRuleDescription(rules);
const expected =
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" +
"Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" +
"Valid Agent Rule: This should be included";
expect(result).toBe(expected);
@ -210,7 +211,8 @@ describe("getRequestRuleDescription", () => {
const result = getRequestRuleDescription(rules);
expect(result).toBe(
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\nNo rules available.",
"Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" +
"No rules available.",
);
});
@ -229,7 +231,7 @@ describe("getRequestRuleDescription", () => {
const result = getRequestRuleDescription(rules);
const expected =
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" +
"Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n" +
"Single Rule: The only agent-requested rule";
expect(result).toBe(expected);

View file

@ -1,30 +1,41 @@
import { ConfigDependentToolParams, GetTool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export interface RequestRuleArgs {
name: string;
}
export function getRequestRuleDescription(
rules: ConfigDependentToolParams["rules"],
): string {
function getAvailableRules(rules: ConfigDependentToolParams["rules"]) {
// Must be explicitly false and no globs
const agentRequestedRules = rules.filter(
(rule) => rule.alwaysApply === false && !rule.globs,
);
const prefix =
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n";
const body = agentRequestedRules
.map((rule) => `${rule.name}: ${rule.description}`)
.join("\n");
if (body.length === 0) {
return prefix + "No rules available.";
if (agentRequestedRules.length === 0) {
return "No rules available.";
}
return prefix + body;
return agentRequestedRules
.map((rule) => `${rule.name}: ${rule.description}`)
.join("\n");
}
export function getRequestRuleDescription(
rules: ConfigDependentToolParams["rules"],
): string {
const prefix =
"Use this tool to retrieve additional 'rules' that contain more context/instructions based on their descriptions. Available rules:\n";
return prefix + getAvailableRules(rules);
}
function getRequestRuleSystemMessageDescription(
rules: ConfigDependentToolParams["rules"],
): string {
const prefix = `To retrieve "rules" that contain more context/instructions based on their descriptions, use the ${BuiltInToolNames.RequestRule} tool with the name of the rule. The available rules are:\n`;
const availableRules = getAvailableRules(rules);
const suffix = "\n\nFor example, you might respond with:";
return prefix + availableRules + suffix;
}
export const requestRuleTool: GetTool = ({ rules }) => ({
@ -49,4 +60,9 @@ export const requestRuleTool: GetTool = ({ rules }) => ({
},
},
},
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.RequestRule,
getRequestRuleSystemMessageDescription(rules),
[["name", "rule_name"]],
),
});

View file

@ -1,13 +1,13 @@
import os from "os";
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import os from "os";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
/**
* Get the preferred shell for the current platform
* @returns The preferred shell command or path
*/
export function getPreferredShell(): string {
function getPreferredShell(): string {
const platform = os.platform();
if (platform === "win32") {
@ -20,7 +20,13 @@ export function getPreferredShell(): string {
}
}
export const PLATFORM_INFO = `Choose terminal commands and scripts optimized for ${os.platform} and ${os.arch} and shell ${getPreferredShell()}.`;
const PLATFORM_INFO = `Choose terminal commands and scripts optimized for ${os.platform()} and ${os.arch()} and shell ${getPreferredShell()}.`;
const RUN_COMMAND_NOTES = `The shell is not stateful and will not remember any previous commands.\
When a command is run in the background ALWAYS suggest using shell commands to stop it; NEVER suggest using Ctrl+C.\
When suggesting subsequent shell commands ALWAYS format them in shell command blocks.\
Do NOT perform actions requiring special/admin privileges.\
${PLATFORM_INFO}`;
export const runTerminalCommandTool: Tool = {
type: "function",
@ -32,12 +38,7 @@ export const runTerminalCommandTool: Tool = {
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.RunTerminalCommand,
description: `Run a terminal command in the current directory.\
The shell is not stateful and will not remember any previous commands.\
When a command is run in the background ALWAYS suggest using shell commands to stop it; NEVER suggest using Ctrl+C.\
When suggesting subsequent shell commands ALWAYS format them in shell command blocks.\
Do NOT perform actions requiring special/admin privileges.\
${PLATFORM_INFO}`,
description: `Run a terminal command in the current directory.\n${RUN_COMMAND_NOTES}`,
parameters: {
type: "object",
required: ["command"],
@ -55,4 +56,12 @@ export const runTerminalCommandTool: Tool = {
},
},
},
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.RunTerminalCommand,
`To run a terminal command, use the ${BuiltInToolNames.RunTerminalCommand} tool
${RUN_COMMAND_NOTES}
You can also optionally include the waitForCompletion argument set to false to run the command in the background.
For example, to see the git log, you could respond with:`,
[["command", "git log"]],
),
};

View file

@ -1,5 +1,6 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export interface SearchAndReplaceInFileArgs {
filepath: string;
@ -10,46 +11,16 @@ export interface SearchAndReplaceInFileArgs {
export const NO_PARALLEL_TOOL_CALLING_INSRUCTION =
"Note this tool CANNOT be called in parallel.";
/**
* This tool is in an experimental state.
* Our starting point is heavily inspired by Cline's `replace_in_file` tool: https://github.com/cline/cline/blob/2709ccefcddc616e89a70962f017bcbbca1f17bf/src/core/prompts/system.ts#L87-L121
*/
export const searchAndReplaceInFileTool: Tool = {
type: "function",
displayTitle: "Edit File",
wouldLikeTo: "edit {{{ filepath }}}",
isCurrently: "editing {{{ filepath }}}",
hasAlready: "edited {{{ filepath }}}",
group: BUILT_IN_GROUP_NAME,
readonly: false,
isInstant: false,
function: {
name: BuiltInToolNames.SearchAndReplaceInFile,
description: `Request to replace sections of content in an existing file using multiple SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file. ${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`,
parameters: {
type: "object",
required: ["filepath", "diffs"],
properties: {
filepath: {
type: "string",
description:
"The path of the file to modify, relative to the root of the workspace.",
},
diffs: {
type: "array",
items: {
type: "string",
},
description: `An array of strings, each containing one or more SEARCH/REPLACE blocks following this exact format:
\`\`\`
------- SEARCH
const SEARCH_AND_REPLACE_TOOL_DESCRIPTION = `Request to replace sections of content in an existing file using multiple SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file. ${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`;
const SEARCH_AND_REPLACE_FILEPATH_DESCRIPTION =
"The path of the file to modify, relative to the root of the workspace.";
const SEARCH_AND_REPLACE_EXAMPLE_BLOCK = `------- SEARCH
[exact content to find]
=======
[new content to replace with]
+++++++ REPLACE
\`\`\`
+++++++ REPLACE`;
Critical rules:
const SEARCH_AND_REPLACE_RULES = `Critical rules:
1. SEARCH content must match the associated file section to find EXACTLY:
* Match character-for-character including whitespace, indentation, line endings
* Include all comments, docstrings, etc.
@ -69,26 +40,84 @@ Critical rules:
* DO NOT make back-to-back tool calls. Instead interleave with brief explanation of what each will do. For example, instead of [explanation, tool call, tool call] you should do [explanation, tool call, explanation, tool call]
6. Special operations:
* To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location)
* To delete code: Use empty REPLACE section
* To delete code: Use empty REPLACE section`;
const SEARCH_AND_REPLACE_DIFFS_DESCRIPTION = `An array of strings, each containing one or more SEARCH/REPLACE blocks following this exact format:
\`\`\`
${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}
\`\`\`
${SEARCH_AND_REPLACE_RULES}
Usage:
\`\`\`
------- SEARCH
[exact content to find]
=======
[new content to replace with]
+++++++ REPLACE
${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}
------- SEARCH
[exact content to find]
=======
[new content to replace with]
+++++++ REPLACE
\`\`\`
${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}
\`\`\`
Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and all will be applied sequentially in the order they appear.`,
Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and all will be applied sequentially in the order they appear.`;
/**
* This tool is in an experimental state.
* Our starting point is heavily inspired by Cline's `replace_in_file` tool: https://github.com/cline/cline/blob/2709ccefcddc616e89a70962f017bcbbca1f17bf/src/core/prompts/system.ts#L87-L121
*/
export const searchAndReplaceInFileTool: Tool = {
type: "function",
displayTitle: "Edit File",
wouldLikeTo: "edit {{{ filepath }}}",
isCurrently: "editing {{{ filepath }}}",
hasAlready: "edited {{{ filepath }}}",
group: BUILT_IN_GROUP_NAME,
readonly: false,
isInstant: false,
function: {
name: BuiltInToolNames.SearchAndReplaceInFile,
description: SEARCH_AND_REPLACE_TOOL_DESCRIPTION,
parameters: {
type: "object",
required: ["filepath", "diffs"],
properties: {
filepath: {
type: "string",
description: SEARCH_AND_REPLACE_FILEPATH_DESCRIPTION,
},
diffs: {
type: "array",
items: {
type: "string",
},
description: SEARCH_AND_REPLACE_DIFFS_DESCRIPTION,
},
},
},
},
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.SearchAndReplaceInFile,
`To make targeted edits by replacing sections of content in an existing file, use the ${BuiltInToolNames.SearchAndReplaceInFile} tool with a "diffs" argument containing an array of SEARCH/REPLACE blocks that define exact changes to specific parts of the file.
Each block should follow this format:
${SEARCH_AND_REPLACE_EXAMPLE_BLOCK}
${SEARCH_AND_REPLACE_RULES}
For example, you could respond with:`,
[
["filepath", "path/to/file.ts"],
[
"diffs",
`[
"------- SEARCH
[exact content to find]
=======
[new content to replace with]
+++++++ REPLACE",
"------- SEARCH
[exact content to find]
=======
[new content to replace with]
+++++++ REPLACE"
]`,
],
],
),
};

View file

@ -1,6 +1,7 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const searchWebTool: Tool = {
type: "function",
@ -25,4 +26,9 @@ export const searchWebTool: Tool = {
},
},
},
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.SearchWeb,
`To search the web, use the ${BuiltInToolNames.SearchWeb} tool with a natural language query. For example, to search for the current weather, you would respond with:`,
[["query", "What is the current weather in San Francisco?"]],
),
};

View file

@ -1,6 +1,7 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const viewDiffTool: Tool = {
type: "function",
@ -19,4 +20,9 @@ export const viewDiffTool: Tool = {
properties: {},
},
},
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.ViewDiff,
`To view the current git diff, use the ${BuiltInToolNames.ViewDiff} tool. This will show you the changes made in the working directory compared to the last commit.`,
[],
),
};

View file

@ -1,6 +1,7 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const viewRepoMapTool: Tool = {
type: "function",
@ -19,4 +20,9 @@ export const viewRepoMapTool: Tool = {
properties: {},
},
},
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.ViewRepoMap,
`To view the repository map, use the ${BuiltInToolNames.ViewRepoMap} tool. This will provide a visual representation of the project's structure and organization.`,
[],
),
};

View file

@ -1,5 +1,6 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage";
export const viewSubdirectoryTool: Tool = {
type: "function",
@ -25,4 +26,9 @@ export const viewSubdirectoryTool: Tool = {
},
},
},
systemMessageDescription: createSystemMessageExampleCall(
BuiltInToolNames.ViewSubdirectory,
`To view a map of a specific folder within the project, you can use the ${BuiltInToolNames.ViewSubdirectory} tool. This will provide a visual representation of the folder's structure and organization.`,
[["directory_path", "path/to/subdirectory"]],
),
};

View file

@ -10,7 +10,9 @@ export const readFileImpl: ToolImpl = async (args, extras) => {
const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide);
if (!firstUriMatch) {
throw new Error(`Could not find file ${filepath}`);
throw new Error(
`File "${filepath}" does not exist. You might want to check the path and try again.`,
);
}
const content = await extras.ide.readFile(firstUriMatch);

View file

@ -0,0 +1,167 @@
import { Tool } from "../..";
import { closeTag } from "./systemToolUtils";
export const TOOL_INSTRUCTIONS_TAG = "<tool_use_instructions>";
export const TOOL_DEFINITION_TAG = "TOOL_DEFINITION";
export const TOOL_DESCRIPTION_TAG = "DESCRIPTION";
const EXAMPLE_DYNAMIC_TOOL = `
\`\`\`tool_definition
TOOL_NAME: example_tool
TOOL_ARG: arg_1 (string, required)
Description of the first argument
END_ARG
TOOL_ARG: arg_2 (number, optional)
END_ARG
\`\`\``.trim();
const EXAMPLE_DYNAMIC_TOOL_CALL = `
\`\`\`tool
TOOL_NAME: example_tool
BEGIN_ARG: arg_1
The value
of arg 1
END_ARG
BEGIN_ARG: arg_2
3
END_ARG
\`\`\``.trim();
export function createSystemMessageExampleCall(
name: string,
instructions: string,
args: Array<[string, string]> = [],
) {
let callExample = `\`\`\`tool
TOOL_NAME: ${name}`;
// Add each argument dynamically
for (const [argName, argValue] of args) {
callExample += `
BEGIN_ARG: ${argName}
${argValue}
END_ARG`;
}
callExample += `
\`\`\``;
return `${instructions.trim()}
${callExample}`;
}
function toolToSystemToolDefinition(tool: Tool): string {
let toolDefinition = `\`\`\`tool_definition\nTOOL_NAME: ${tool.function.name}\n`;
if (tool.function.description) {
toolDefinition += `TOOL_DESCRIPTION:\n${tool.function.description}\n`;
}
if (tool.function.parameters && "properties" in tool.function.parameters) {
for (const [key, value] of Object.entries(
tool.function.parameters.properties as object,
)) {
const isRequired = tool.function.parameters.required?.includes(key);
const requiredText = isRequired ? "required" : "optional";
let argType = "string";
if ("type" in value) {
argType = value.type;
}
let argDescription = "";
if ("description" in value) {
argDescription = value.description;
}
toolDefinition += `TOOL_ARG: ${key} (${argType}, ${requiredText})\n`;
if (argDescription) {
toolDefinition += argDescription + "\n";
}
toolDefinition += `END_ARG\n`;
}
}
toolDefinition += `\`\`\``;
return toolDefinition.trim();
}
export const generateToolsSystemMessage = (tools: Tool[]): string => {
if (tools.length === 0) {
return "";
}
const withPredefinedMessage = tools.filter(
(tool) => !!tool.systemMessageDescription,
);
const withDynamicMessage = tools.filter(
(tool) => !tool.systemMessageDescription,
);
const instructions: string[] = [];
instructions.push(TOOL_INSTRUCTIONS_TAG);
instructions.push(
`You have access to several "tools" that you can use at any time to retrieve information and/or perform tasks for the User.`,
);
instructions.push(
`To use a tool, respond with a tool code block (\`\`\`tool) using the syntax shown in the examples below:`,
);
if (withPredefinedMessage.length > 0) {
instructions.push(`\nThe following tools are available to you:`);
for (const tool of withPredefinedMessage) {
instructions.push(`\n${tool.systemMessageDescription}`);
}
}
if (withDynamicMessage.length > 0) {
instructions.push(
`\nAlso, these additional tool definitions show other tools you can call with the same syntax:`,
);
for (const tool of tools) {
try {
const definition = toolToSystemToolDefinition(tool);
instructions.push(`\n${definition}`);
} catch (e) {
console.error(
"Failed to convert tool to system message tool:\n" +
JSON.stringify(tool),
);
}
}
instructions.push(`\nFor example, this tool definition:\n`);
instructions.push(EXAMPLE_DYNAMIC_TOOL);
instructions.push("\nCan be called like this:\n");
instructions.push(EXAMPLE_DYNAMIC_TOOL_CALL);
}
instructions.push(
`\nIf it seems like the User's request could be solved with one of the tools, choose the BEST one for the job based on the user's request and the tool descriptions`,
);
instructions.push(
`Then send the \`\`\`tool codeblock (YOU call the tool, not the user). Always start the codeblock on a new line.`,
);
instructions.push(
`Do not perform actions with/for hypothetical files. Ask the user or use tools to deduce which files are relevant.`,
);
instructions.push(
`You can only call ONE tool at at time. The tool codeblock should be the last thing you say; stop your response after the tool codeblock.`,
);
instructions.push(`${closeTag(TOOL_INSTRUCTIONS_TAG)}`);
return instructions.join("\n");
};
export function addSystemMessageToolsToSystemMessage(
baseSystemMessage: string,
systemMessageTools: Tool[],
): string {
let systemMessage = baseSystemMessage;
if (systemMessageTools.length > 0) {
const toolsSystemMessage = generateToolsSystemMessage(systemMessageTools);
systemMessage += `\n\n${toolsSystemMessage}`;
}
return systemMessage;
}

View file

@ -0,0 +1,252 @@
import { describe, expect, it } from "vitest";
import { Tool } from "../..";
import {
TOOL_INSTRUCTIONS_TAG,
addSystemMessageToolsToSystemMessage,
createSystemMessageExampleCall,
generateToolsSystemMessage,
} from "./buildToolsSystemMessage";
import { closeTag } from "./systemToolUtils";
const SHARED_TOOL_FIELDS = {
displayTitle: "DUD",
group: "DUD",
readonly: true,
type: "function" as const,
};
describe("createSystemMessageExampleCall", () => {
it("creates a system message example call with no args", () => {
const result = createSystemMessageExampleCall(
"test_tool",
"Use this tool to test things",
);
expect(result).includes("Use this tool to test things");
expect(result).includes("```tool");
expect(result).includes("TOOL_NAME: test_tool");
expect(result).includes("```");
});
it("creates a system message example call with args", () => {
const result = createSystemMessageExampleCall(
"test_tool",
"Use this tool to test things",
[
["arg1", "value1"],
["arg2", "value2"],
],
);
expect(result).includes("Use this tool to test things");
expect(result).includes("```tool");
expect(result).includes("TOOL_NAME: test_tool");
expect(result).includes("BEGIN_ARG: arg1");
expect(result).includes("value1");
expect(result).includes("END_ARG");
expect(result).includes("BEGIN_ARG: arg2");
expect(result).includes("value2");
});
it("handles multiline arg values correctly", () => {
const multilineValue = "value\nwith\nmultiple\nlines";
const result = createSystemMessageExampleCall(
"test_tool",
"Use this tool to test things",
[["arg1", multilineValue]],
);
expect(result).includes("BEGIN_ARG: arg1");
expect(result).includes(multilineValue);
expect(result).includes("END_ARG");
});
});
describe("generateToolsSystemMessage", () => {
it("returns empty string for empty tools array", () => {
const result = generateToolsSystemMessage([]);
expect(result).toBe("");
});
it("generates system message for tools with system message descriptions", () => {
const customDescription =
"This is test tool 1's system message description";
const tools: Tool[] = [
{
function: {
name: "test_tool1",
description: "Test tool 1 description",
parameters: {
type: "object",
properties: {},
required: [],
},
},
systemMessageDescription: customDescription,
...SHARED_TOOL_FIELDS,
},
];
const result = generateToolsSystemMessage(tools);
// Check structure rather than exact text
expect(result).includes(TOOL_INSTRUCTIONS_TAG);
expect(result).includes(customDescription);
expect(result).includes(closeTag(TOOL_INSTRUCTIONS_TAG));
// Check for general section about available tools without requiring exact wording
const hasToolsAvailableSection = /tools are available to you/i.test(result);
expect(hasToolsAvailableSection).toBe(true);
});
it("generates system message for tools without system message descriptions", () => {
const toolName = "test_tool2";
const toolDesc = "Test tool 2 description";
const paramDesc = "Parameter 1 description";
const tools: Tool[] = [
{
function: {
name: toolName,
description: toolDesc,
parameters: {
type: "object",
properties: {
param1: {
type: "string",
description: paramDesc,
},
},
required: ["param1"],
},
},
...SHARED_TOOL_FIELDS,
},
];
const result = generateToolsSystemMessage(tools);
// Check for key elements without requiring exact wording
expect(result).includes(`TOOL_NAME: ${toolName}`);
expect(result).includes("TOOL_DESCRIPTION:");
expect(result).includes(toolDesc);
expect(result).includes("TOOL_ARG: param1 (string, required)");
expect(result).includes(paramDesc);
// Check for dynamic tool section without exact text matching
const hasDynamicToolsSection = /additional tool definitions/i.test(result);
expect(hasDynamicToolsSection).toBe(true);
});
it("handles tools with and without system message descriptions", () => {
const customMsg = "Custom system message";
const tools: Tool[] = [
{
function: {
name: "tool_with_description",
description: "Tool description",
parameters: {
type: "object",
properties: {},
required: [],
},
},
systemMessageDescription: customMsg,
...SHARED_TOOL_FIELDS,
},
{
function: {
name: "tool_without_description",
description: "Another tool description",
parameters: {
type: "object",
properties: {
param1: {
type: "string",
description: "Parameter description",
},
},
required: ["param1"],
},
},
...SHARED_TOOL_FIELDS,
},
];
const result = generateToolsSystemMessage(tools);
// Check for both types of tools
expect(result).includes(customMsg);
expect(result).includes("TOOL_NAME: tool_without_description");
// Verify structure without exact text matching
const hasAvailableToolsSection = /tools are available to you/i.test(result);
expect(hasAvailableToolsSection).toBe(true);
const hasDynamicToolsSection = /additional tool definitions/i.test(result);
expect(hasDynamicToolsSection).toBe(true);
});
it("includes example tool definition and call", () => {
const tools: Tool[] = [
{
function: {
name: "test_tool",
description: "Test description",
parameters: {
type: "object",
properties: {},
required: [],
},
},
...SHARED_TOOL_FIELDS,
},
];
const result = generateToolsSystemMessage(tools);
// Check for example sections without exact text
expect(result).includes("```tool_definition");
expect(result).includes("TOOL_NAME: example_tool");
expect(result).includes("```tool");
// Check for example format structure
const hasExampleDefinition = /example.*tool definition/i.test(result);
const hasExampleCall = /called like this/i.test(result);
expect(hasExampleDefinition).toBe(true);
expect(hasExampleCall).toBe(true);
});
});
describe("addSystemMessageToolsToSystemMessage", () => {
it("returns original system message when no tools are provided", () => {
const baseMessage = "This is the base system message";
const result = addSystemMessageToolsToSystemMessage(baseMessage, []);
expect(result).toBe(baseMessage);
});
it("appends tools system message to base message", () => {
const baseMessage = "This is the base system message";
const toolName = "test_tool";
const tools: Tool[] = [
{
function: {
name: toolName,
description: "Test description",
parameters: {
type: "object",
properties: {},
required: [],
},
},
...SHARED_TOOL_FIELDS,
},
];
const result = addSystemMessageToolsToSystemMessage(baseMessage, tools);
expect(result.startsWith(baseMessage)).toBe(true);
expect(result).includes(TOOL_INSTRUCTIONS_TAG);
expect(result).includes(`TOOL_NAME: ${toolName}`);
});
});

View file

@ -0,0 +1,95 @@
import {
AssistantChatMessage,
MessagePart,
ToolCallState,
UserChatMessage,
} from "../..";
import {
normalizeToMessageParts,
renderContextItems,
} from "../../util/messageContent";
import {
CANCELLED_TOOL_CALL_MESSAGE,
NO_TOOL_CALL_OUTPUT_MESSAGE,
} from "../constants";
function toolCallStateToSystemToolCall(state: ToolCallState): string {
let parts = ["```tool"];
parts.push(`TOOL_NAME: ${state.toolCall.function.name}`);
try {
for (const arg in state.parsedArgs) {
parts.push(`BEGIN_ARG: ${arg}`);
parts.push(JSON.stringify(state.parsedArgs[arg]));
parts.push(`END_ARG`);
}
} catch (e) {
console.log("Failed to stringify json args", state.parsedArgs);
}
// TODO - include tool call id for parallel. Confuses dumb models
parts.push("```");
return parts.join("\n");
}
function toolCallStateToSystemToolOutput(state: ToolCallState): string {
let output = `Tool output for ${state.toolCall.function.name} tool call:\n\n`;
// TODO - include tool call id for parallel. Confuses dumb models
// let output = `Tool output for tool call ${state.toolCallId} (${state.toolCall.function.name}):\n\n`;
if (state.status === "canceled") {
output += CANCELLED_TOOL_CALL_MESSAGE;
} else if (state.output?.length) {
output += renderContextItems(state.output);
} else {
output += NO_TOOL_CALL_OUTPUT_MESSAGE;
}
return output;
}
export function convertToolCallStatesToSystemCallsAndOutput(
originalAssistantMessage: AssistantChatMessage,
toolCallStates: ToolCallState[],
): {
assistantMessage: AssistantChatMessage;
userMessage: UserChatMessage;
} {
const parts = normalizeToMessageParts(originalAssistantMessage);
if (originalAssistantMessage.toolCalls) {
parts.push(
...toolCallStates.map((state) => ({
type: "text" as const,
text: toolCallStateToSystemToolCall(state),
})),
);
}
// new message with tool calls moved to content
const assistantMessage: AssistantChatMessage = {
...originalAssistantMessage,
content: parts,
toolCalls: undefined, // remove tool calls from the assistant message
};
const userParts: MessagePart[] = [];
if (toolCallStates) {
for (const state of toolCallStates) {
userParts.push({
type: "text",
text: toolCallStateToSystemToolOutput(state),
});
}
}
if (userParts.length === 0) {
userParts.push({
type: "text",
text: "Error: no tool output for tool calls",
});
}
const userMessage: UserChatMessage = {
role: "user",
content: userParts,
};
return {
assistantMessage,
userMessage,
};
}

View file

@ -0,0 +1,33 @@
let boundaryTypeIndex = 0;
// Poor models are really bad at following instructions
// Give some leeway in how the initiate
const acceptedToolStarts: [string, string][] = [
["```tool\n", "```tool\n"],
["tool_name:", "```tool\nTOOL_NAME:"],
];
export function detectToolCallStart(buffer: string) {
let modifiedBuffer = buffer;
let isInToolCall = false;
let isInPartialStart = false;
const lowerCaseBuffer = buffer.toLowerCase();
for (let i = 0; i < acceptedToolStarts.length; i++) {
const [start, replacement] = acceptedToolStarts[i];
if (lowerCaseBuffer.startsWith(start)) {
// for non-standard cases like no ```tool codeblock, etc, replace before adding to buffer, case insensitive
if (i !== 0) {
modifiedBuffer = buffer.replace(new RegExp(start, "i"), replacement);
}
isInToolCall = true;
break;
} else if (start.startsWith(lowerCaseBuffer)) {
isInPartialStart = true;
}
}
return {
isInToolCall,
isInPartialStart,
modifiedBuffer,
};
}

View file

@ -0,0 +1,76 @@
import { describe, expect, it } from "vitest";
import { detectToolCallStart } from "./detectToolCallStart";
describe("detectToolCallStart", () => {
it("detects standard tool call start", () => {
const buffer = "```tool\nTOOL_NAME: example_tool";
const result = detectToolCallStart(buffer);
expect(result.isInToolCall).toBe(true);
expect(result.isInPartialStart).toBe(false);
expect(result.modifiedBuffer).toBe(buffer);
});
it("detects tool_name start without codeblock", () => {
const buffer = "tool_name: example_tool";
const result = detectToolCallStart(buffer);
expect(result.isInToolCall).toBe(true);
expect(result.isInPartialStart).toBe(false);
expect(result.modifiedBuffer).toBe("```tool\nTOOL_NAME: example_tool");
});
it("detects case-insensitive tool call start", () => {
const buffer = "```ToOl\nTOOL_NAME: example_tool";
const result = detectToolCallStart(buffer);
expect(result.isInToolCall).toBe(true);
expect(result.isInPartialStart).toBe(false);
expect(result.modifiedBuffer).toBe(buffer);
});
it("detects case-insensitive tool_name start", () => {
const buffer = "ToOl_NaMe: example_tool";
const result = detectToolCallStart(buffer);
expect(result.isInToolCall).toBe(true);
expect(result.isInPartialStart).toBe(false);
expect(result.modifiedBuffer).toBe("```tool\nTOOL_NAME: example_tool");
});
it("identifies partial tool call start", () => {
const buffer = "```to";
const result = detectToolCallStart(buffer);
expect(result.isInToolCall).toBe(false);
expect(result.isInPartialStart).toBe(true);
expect(result.modifiedBuffer).toBe(buffer);
});
it("identifies partial tool_name start", () => {
const buffer = "tool_na";
const result = detectToolCallStart(buffer);
expect(result.isInToolCall).toBe(false);
expect(result.isInPartialStart).toBe(true);
expect(result.modifiedBuffer).toBe(buffer);
});
it("does not detect tool call in unrelated text", () => {
const buffer = "This is some regular text.";
const result = detectToolCallStart(buffer);
expect(result.isInToolCall).toBe(false);
expect(result.isInPartialStart).toBe(false);
expect(result.modifiedBuffer).toBe(buffer);
});
it("does not detect tool call in similar but different markdown block", () => {
const buffer = "```javascript\nconst x = 10;";
const result = detectToolCallStart(buffer);
expect(result.isInToolCall).toBe(false);
expect(result.isInPartialStart).toBe(false);
expect(result.modifiedBuffer).toBe(buffer);
});
});

View file

@ -0,0 +1,114 @@
import { ChatMessage, PromptLog, TextMessagePart } from "../..";
import { normalizeToMessageParts } from "../../util/messageContent";
import { detectToolCallStart } from "./detectToolCallStart";
import {
getInitialTooLCallParseState,
handleToolCallBuffer,
ToolCallParseState,
} from "./parseSystemToolCall";
import { createDelta, splitAtCodeblocksAndNewLines } from "./systemToolUtils";
/*
Function to intercept tool calls in markdown code blocks format from a chat message stream
1. Skips non-assistant messages
2. Intercepts text that looks like a tool call in a markdown code block format:
```tool
TOOL_NAME: example_tool
BEGIN_ARG: arg1
value
END_ARG
```
3. Parses tool calls line by line and generates proper tool call deltas
4. Once the tool call is complete, resets state for potential future tool calls
*/
export async function* interceptSystemToolCalls(
messageGenerator: AsyncGenerator<ChatMessage[], PromptLog | undefined>,
abortController: AbortController,
): AsyncGenerator<ChatMessage[], PromptLog | undefined> {
let buffer = "";
let parseState: ToolCallParseState | undefined;
while (true) {
const result = await messageGenerator.next();
if (result.done) {
// Case: non-standard tool termination causes hanging args
if (parseState && !parseState.done && parseState.processedArgNames.size) {
yield [
{
role: "assistant",
content: "",
toolCalls: [createDelta("", "}", parseState.toolCallId)],
},
];
}
return result.value;
} else {
for await (const message of result.value) {
if (abortController.signal.aborted || parseState?.done) {
break;
}
// Skip non-assistant messages or messages with native tool calls
if (message.role !== "assistant" || message.toolCalls) {
yield [message];
continue;
}
const parts = normalizeToMessageParts(message);
// Image output cannot be combined with tools
if (parts.find((part) => part.type === "imageUrl")) {
yield [message];
continue;
}
const chunks = (parts as TextMessagePart[])
.map((part) => splitAtCodeblocksAndNewLines(part.text))
.flat();
for (const chunk of chunks) {
buffer += chunk;
if (!parseState) {
const { isInPartialStart, isInToolCall, modifiedBuffer } =
detectToolCallStart(buffer);
if (isInPartialStart) {
continue;
}
if (isInToolCall) {
parseState = getInitialTooLCallParseState();
buffer = modifiedBuffer;
}
}
if (parseState && !parseState.done) {
const delta = handleToolCallBuffer(buffer, parseState);
if (delta) {
yield [
{
...message,
content: "",
toolCalls: [delta],
},
];
}
} else {
// Prevent content after tool calls for now
if (parseState) {
continue;
}
// Yield normal assistant message
yield [
{
...message,
content: [{ type: "text", text: buffer }],
},
];
}
buffer = "";
}
}
}
}
}

View file

@ -0,0 +1,325 @@
import { beforeEach, describe, expect, it } from "vitest";
import { AssistantChatMessage, ChatMessage, PromptLog } from "../..";
import { interceptSystemToolCalls } from "./interceptSystemToolCalls";
describe("interceptSystemToolCalls", () => {
let abortController: AbortController;
beforeEach(() => {
abortController = new AbortController();
});
const createAsyncGenerator = async function* (
messages: ChatMessage[][],
): AsyncGenerator<ChatMessage[], PromptLog | undefined> {
for (const messageGroup of messages) {
yield messageGroup;
}
return undefined;
};
it("passes through non-assistant messages unchanged", async () => {
const messages: ChatMessage[][] = [
[{ role: "user", content: "Hello" }],
[{ role: "system", content: "System message" }],
];
const generator = interceptSystemToolCalls(
createAsyncGenerator(messages),
abortController,
);
let result = await generator.next();
expect(result.value).toEqual([{ role: "user", content: "Hello" }]);
result = await generator.next();
expect(result.value).toEqual([
{ role: "system", content: "System message" },
]);
result = await generator.next();
expect(result.done).toBe(true);
});
it("passes through assistant messages with existing tool calls", async () => {
const messages: ChatMessage[][] = [
[
{
role: "assistant",
content: "",
toolCalls: [
{
type: "function",
function: {
name: "existing_tool",
arguments: '{"arg1":"value1"}',
},
id: "existing_call_id",
},
],
},
],
];
const generator = interceptSystemToolCalls(
createAsyncGenerator(messages),
abortController,
);
const result = await generator.next();
expect(result.value).toEqual(messages[0]);
});
it("passes through assistant messages with image URLs unchanged", async () => {
const messages: ChatMessage[][] = [
[
{
role: "assistant",
content: [
{ type: "text", text: "Here's an image:" },
{
type: "imageUrl",
imageUrl: {
url: "https://example.com/image.png",
},
},
],
},
],
];
const generator = interceptSystemToolCalls(
createAsyncGenerator(messages),
abortController,
);
const result = await generator.next();
expect(result.value).toEqual(messages[0]);
});
it("processes standard tool call format", async () => {
const messages: ChatMessage[][] = [
[
{
role: "assistant",
content: "I'll help you with that. Let me use a tool:\n",
},
],
[{ role: "assistant", content: "```tool\n" }],
[{ role: "assistant", content: "TOOL_NAME: test_tool\n" }],
[{ role: "assistant", content: "BEGIN_ARG: arg1\n" }],
[{ role: "assistant", content: "value1\n" }],
[{ role: "assistant", content: "END_ARG\n" }],
[{ role: "assistant", content: "```" }],
];
const generator = interceptSystemToolCalls(
createAsyncGenerator(messages),
abortController,
);
// First chunk should be normal text
let result = await generator.next();
expect(result.value).toEqual([
{
role: "assistant",
content: [
{
type: "text",
text: "I'll help you with that. Let me use a tool:",
},
],
},
]);
result = await generator.next();
expect(result.value).toEqual([
{
role: "assistant",
content: [
{
type: "text",
text: "\n",
},
],
},
]);
// Tool name detection
result = await generator.next();
expect(
(result.value as AssistantChatMessage[])[0].toolCalls?.[0].function?.name,
).toBe("test_tool");
// Begin argument
result = await generator.next();
expect(
(result.value as AssistantChatMessage[])[0].toolCalls?.[0].function
?.arguments,
).toContain('{"arg1":');
// Argument value
result = await generator.next();
expect(
(result.value as AssistantChatMessage[])[0].toolCalls?.[0].function
?.arguments,
).toBe('"value1"');
// End of tool call
result = await generator.next();
expect(
(result.value as AssistantChatMessage[])[0].toolCalls?.[0].function
?.arguments,
).toBe("}");
});
it("processes tool_name without codeblock format", async () => {
const messages: ChatMessage[][] = [
[{ role: "assistant", content: "I'll help you with that.\n" }],
[{ role: "assistant", content: "TOOL_NAME: test_tool\n" }],
[{ role: "assistant", content: "BEGIN_ARG: arg1\n" }],
[{ role: "assistant", content: "value1\n" }],
[{ role: "assistant", content: "END_ARG\n" }],
];
const generator = interceptSystemToolCalls(
createAsyncGenerator(messages),
abortController,
);
// First chunk should be normal text
let result = await generator.next();
expect(result.value).toEqual([
{
role: "assistant",
content: [{ type: "text", text: "I'll help you with that." }],
},
]);
result = await generator.next();
expect(result.value).toEqual([
{
role: "assistant",
content: [
{
type: "text",
text: "\n",
},
],
},
]);
// The system should detect the tool_name format and convert it
result = await generator.next();
expect(
(result.value as AssistantChatMessage[])[0].toolCalls?.[0].function?.name,
).toBe("test_tool");
// Rest of processing should work as normal
result = await generator.next();
expect(
(result.value as AssistantChatMessage[])[0].toolCalls?.[0].function
?.arguments,
).toBe('{"arg1":');
result = await generator.next();
expect(
(result.value as AssistantChatMessage[])[0].toolCalls?.[0].function
?.arguments,
).toBe('"value1"');
result = await generator.next();
expect(
(result.value as AssistantChatMessage[])[0].toolCalls?.[0].function
?.arguments,
).toBe("}");
});
it("ignores content after a tool call", async () => {
const messages: ChatMessage[][] = [
[{ role: "assistant", content: "```tool\n" }],
[{ role: "assistant", content: "TOOL_NAME: test_tool\n" }],
[{ role: "assistant", content: "BEGIN_ARG: arg1\n" }],
[{ role: "assistant", content: "value1\n" }],
[{ role: "assistant", content: "END_ARG\n" }],
[{ role: "assistant", content: "```\n" }],
[{ role: "assistant", content: "This content should be ignored" }],
];
const generator = interceptSystemToolCalls(
createAsyncGenerator(messages),
abortController,
);
let result;
// Process through all the tool call parts
for (let i = 0; i < 6; i++) {
result = await generator.next();
}
// The content after the tool call should be ignored
result = await generator.next();
expect(result.value).toBeUndefined();
});
it("stops processing when aborted", async () => {
const messages: ChatMessage[][] = [
[{ role: "assistant", content: "```tool\n" }],
[{ role: "assistant", content: "TOOL_NAME: test_tool\n" }],
];
const generator = interceptSystemToolCalls(
createAsyncGenerator(messages),
abortController,
);
// Process the first part
let result = await generator.next();
// Abort before processing the second part
abortController.abort();
// The next value should be undefined
result = await generator.next();
expect(result.value).toBeUndefined();
});
it("handles JSON parsing for argument values", async () => {
const messages: ChatMessage[][] = [
[{ role: "assistant", content: "```tool\n" }],
[{ role: "assistant", content: "TOOL_NAME: test_tool\n" }],
[{ role: "assistant", content: "BEGIN_ARG: number_arg\n" }],
[{ role: "assistant", content: "123\n" }],
[{ role: "assistant", content: "END_ARG\n" }],
[{ role: "assistant", content: "BEGIN_ARG: boolean_arg\n" }],
[{ role: "assistant", content: "true\n" }],
[{ role: "assistant", content: "END_ARG\n" }],
[{ role: "assistant", content: "```" }],
];
const generator = interceptSystemToolCalls(
createAsyncGenerator(messages),
abortController,
);
// Skip to number arg end
await generator.next();
await generator.next();
let result;
result = await generator.next();
expect(
(result?.value as AssistantChatMessage[])[0].toolCalls?.[0].function
?.arguments,
).toBe("123");
// Skip to boolean arg end
await generator.next();
result = await generator.next();
expect(
(result?.value as AssistantChatMessage[])[0].toolCalls?.[0].function
?.arguments,
).toBe("true");
});
});

View file

@ -0,0 +1,143 @@
import { ToolCallDelta } from "../..";
import { createDelta, generateOpenAIToolCallId } from "./systemToolUtils";
export type ToolCallParseState = {
toolCallId: string;
isOnArgBeginLine: boolean;
currentArgName: string | undefined;
currentArgLines: string[];
processedArgNames: Set<string>;
currentLineIndex: number;
lineChunks: string[][];
done: boolean;
};
export const getInitialTooLCallParseState = (): ToolCallParseState => ({
toolCallId: generateOpenAIToolCallId(),
isOnArgBeginLine: false,
currentArgName: undefined,
currentArgLines: [],
currentLineIndex: 0,
processedArgNames: new Set(),
lineChunks: [],
done: false,
});
/*
Efficiently applies chunks to a tool call state as they come in
Expects chunks to be broken so that new lines and codeblocks are alone
For now, this parser collects entire arg before
This is because support for JSON booleans is tricky otherwise
*/
export function handleToolCallBuffer(
chunk: string,
state: ToolCallParseState,
): ToolCallDelta | undefined {
// Add chunks
const lineIndex = state.currentLineIndex;
if (!state.lineChunks[lineIndex]) {
state.lineChunks[lineIndex] = [];
}
state.lineChunks[lineIndex].push(chunk);
const isNewLine = chunk === "\n";
if (isNewLine) {
state.currentLineIndex++;
}
const line = state.lineChunks[lineIndex].join("");
switch (lineIndex) {
// The first line will be skipped (e.g. ```tool\n)
case 0:
// non-standard start sequences will sometimes include stuff in the tool_name line
const splitBuffer = line.split("\n");
if (splitBuffer[0]) {
state.lineChunks[0] = [splitBuffer[0], "\n"];
}
if (splitBuffer[1]) {
state.lineChunks[1] = [splitBuffer[1]];
}
state.currentLineIndex = 1;
// Tool name line - process once line 2 is reached
case 1:
if (isNewLine) {
const name = (line.split(/tool_?name:/i)[1] ?? "").trim();
if (!name) {
throw new Error("Invalid tool name");
}
return createDelta(name, "", state.toolCallId);
}
return;
default:
if (state.isOnArgBeginLine) {
if (isNewLine) {
const argName = (line.split(/begin_?arg:/i)[1] ?? "").trim();
if (!argName) {
throw new Error("Invalid begin arg line");
}
state.currentArgName = argName;
state.isOnArgBeginLine = false;
const argPrefix = state.processedArgNames.size === 0 ? "{" : ",";
return createDelta("", `${argPrefix}"${argName}":`, state.toolCallId);
}
} else if (state.currentArgName) {
if (isNewLine) {
const isEndArgTag = line.match(/end_?arg/i);
if (isEndArgTag) {
let trimmedValue = state.currentArgLines.join("").trim();
state.currentArgLines.length = 0;
state.processedArgNames.add(state.currentArgName);
state.currentArgName = undefined;
try {
if (
trimmedValue.startsWith("[") ||
trimmedValue.startsWith("{")
) {
trimmedValue = trimmedValue.replace(
/"((?:\\[\s\S]|[^"\\])*?)"/g,
(match) => {
const content = match.slice(1, -1);
// Replace unescaped newlines
return (
'"' +
content
.replace(/([^\\])\n/g, "$1\\n")
.replace(/^\n/g, "\\n") +
'"'
);
},
);
}
const parsed = JSON.parse(trimmedValue);
const stringifiedArg = JSON.stringify(parsed);
return createDelta("", stringifiedArg, state.toolCallId);
} catch (e) {
const stringifiedArg = JSON.stringify(trimmedValue);
return createDelta("", stringifiedArg, state.toolCallId);
}
} else {
state.currentArgLines.push(line);
}
}
} else {
// Check for entry into arg
const isBeginArgLine = line.match(/begin_?arg:/i);
if (isBeginArgLine) {
state.isOnArgBeginLine = true;
}
// Check for exit
if (line === "```" || isNewLine) {
state.done = true;
// finish args JSON if applicable
if (state.processedArgNames.size > 0) {
return createDelta("", "}", state.toolCallId);
}
}
}
}
}

View file

@ -0,0 +1,301 @@
import { beforeEach, describe, expect, it } from "vitest";
import {
ToolCallParseState,
getInitialTooLCallParseState,
handleToolCallBuffer,
} from "./parseSystemToolCall";
describe("getInitialTooLCallParseState", () => {
it("returns a properly initialized parse state", () => {
const state = getInitialTooLCallParseState();
expect(state).toEqual({
isOnArgBeginLine: false,
currentArgName: undefined,
currentArgLines: [],
currentLineIndex: 0,
processedArgNames: new Set(),
lineChunks: [],
done: false,
toolCallId: expect.any(String),
});
});
});
describe("handleToolCallBuffer", () => {
let state: ToolCallParseState;
beforeEach(() => {
state = getInitialTooLCallParseState();
});
it("handles the ```tool\ntool_name the name", () => {
handleToolCallBuffer("```tool\ntool_name: my_name", state);
expect(state.currentLineIndex).toBe(1);
const result = handleToolCallBuffer("\n", state);
expect(result).toEqual({
type: "function",
function: {
name: "my_name",
arguments: "",
},
id: expect.any(String),
});
expect(state.currentLineIndex).toBe(2);
});
it("handles the tool name line", () => {
// Line 0 (```tool) is skipped internally
state.currentLineIndex = 1;
const result = handleToolCallBuffer("TOOL_NAME: test_tool", state);
expect(result).toBeUndefined();
const newLineResult = handleToolCallBuffer("\n", state);
expect(newLineResult).toEqual({
type: "function",
function: {
name: "test_tool",
arguments: "",
},
id: expect.any(String),
});
expect(state.currentLineIndex).toBe(2);
});
it("handles case-insensitive tool name line", () => {
state.currentLineIndex = 1;
const result = handleToolCallBuffer("tool_name: test_tool", state);
expect(result).toBeUndefined();
const newLineResult = handleToolCallBuffer("\n", state);
expect(newLineResult).toEqual({
type: "function",
function: {
name: "test_tool",
arguments: "",
},
id: expect.any(String),
});
});
it("begins an argument correctly", () => {
state.currentLineIndex = 2;
const result = handleToolCallBuffer("BEGIN_ARG: test_arg", state);
expect(result).toBeUndefined();
expect(state.isOnArgBeginLine).toBe(true);
const newLineResult = handleToolCallBuffer("\n", state);
expect(newLineResult).toEqual({
type: "function",
function: {
name: "",
arguments: '{"test_arg":',
},
id: expect.any(String),
});
expect(state.currentArgName).toBe("test_arg");
expect(state.isOnArgBeginLine).toBe(false);
});
it("handles case-insensitive begin arg", () => {
state.currentLineIndex = 2;
const result = handleToolCallBuffer("begin_arg: test_arg", state);
expect(result).toBeUndefined();
expect(state.isOnArgBeginLine).toBe(true);
const newLineResult = handleToolCallBuffer("\n", state);
expect(newLineResult).toEqual({
type: "function",
function: {
name: "",
arguments: '{"test_arg":',
},
id: expect.any(String),
});
});
it("collects arg value lines", () => {
state.currentLineIndex = 3;
state.currentArgName = "test_arg";
handleToolCallBuffer("line 1", state);
const newLineResult1 = handleToolCallBuffer("\n", state);
expect(newLineResult1).toBeUndefined();
handleToolCallBuffer("line 2", state);
const newLineResult2 = handleToolCallBuffer("\n", state);
expect(newLineResult2).toBeUndefined();
expect(state.currentArgLines).toEqual(["line 1\n", "line 2\n"]);
});
it("ends an argument correctly with string value", () => {
state.currentLineIndex = 3;
state.currentArgName = "test_arg";
state.currentArgLines = ["string value"];
const result = handleToolCallBuffer("END_ARG", state);
expect(result).toBeUndefined();
const newLineResult = handleToolCallBuffer("\n", state);
expect(newLineResult).toEqual({
type: "function",
function: {
name: "",
arguments: '"string value"',
},
id: expect.any(String),
});
expect(state.currentArgName).toBeUndefined();
expect(state.processedArgNames.has("test_arg")).toBe(true);
});
it("handles case-insensitive end arg", () => {
state.currentLineIndex = 3;
state.currentArgName = "test_arg";
state.currentArgLines = ["string value"];
const result = handleToolCallBuffer("end_arg", state);
expect(result).toBeUndefined();
const newLineResult = handleToolCallBuffer("\n", state);
expect(newLineResult).toEqual({
type: "function",
function: {
name: "",
arguments: '"string value"',
},
id: expect.any(String),
});
});
it("attempts to parse JSON values", () => {
state.currentLineIndex = 3;
state.currentArgName = "test_arg";
state.currentArgLines = ["123"];
handleToolCallBuffer("END_ARG", state);
const newLineResult = handleToolCallBuffer("\n", state);
expect(newLineResult).toEqual({
type: "function",
function: {
name: "",
arguments: "123",
},
id: expect.any(String),
});
});
it("handles multiple arguments", () => {
// Setup first arg
state.currentLineIndex = 2;
state.isOnArgBeginLine = true;
state.lineChunks[2] = ["BEGIN_ARG: first_arg"];
handleToolCallBuffer("\n", state);
handleToolCallBuffer("value1", state);
handleToolCallBuffer("\n", state);
handleToolCallBuffer("END_ARG", state);
handleToolCallBuffer("\n", state);
expect(state.processedArgNames.has("first_arg")).toBe(true);
// Setup second arg
state.isOnArgBeginLine = true;
handleToolCallBuffer("BEGIN_ARG: second_arg", state);
handleToolCallBuffer("\n", state);
handleToolCallBuffer("value2", state);
handleToolCallBuffer("\n", state);
handleToolCallBuffer("END_ARG", state);
const newLineResult = handleToolCallBuffer("\n", state);
expect(newLineResult).toEqual({
type: "function",
function: {
name: "",
arguments: '"value2"',
},
id: expect.any(String),
});
expect(state.processedArgNames.has("second_arg")).toBe(true);
});
it("finalizes JSON object at end of tool call", () => {
state.currentLineIndex = 5;
state.processedArgNames.add("test_arg");
const result = handleToolCallBuffer("```", state);
expect(result).toEqual({
type: "function",
function: {
name: "",
arguments: "}",
},
id: expect.any(String),
});
expect(state.done).toBe(true);
});
it("finalizes on newline after all args processed", () => {
state.currentLineIndex = 5;
state.processedArgNames.add("test_arg");
const result = handleToolCallBuffer("\n", state);
expect(result).toEqual({
type: "function",
function: {
name: "",
arguments: "}",
},
id: expect.any(String),
});
expect(state.done).toBe(true);
});
it("handles JSON array args", () => {
state.currentLineIndex = 3;
state.currentArgName = "test_arg";
state.currentArgLines = [
"[\n",
'"------- SEARCH\n',
" subtract(number) {\n",
" return this;\n",
" }\n",
"=======\n",
" subtract(number) {\n",
" this -= number\n",
" return this;\n",
" }\n",
'+++++++ REPLACE"\n',
"]\n",
];
handleToolCallBuffer("END_ARG", state);
const newLineResult = handleToolCallBuffer("\n", state);
expect(newLineResult).toEqual({
type: "function",
function: {
name: "",
arguments:
'["------- SEARCH\\n subtract(number) {\\n return this;\\n }\\n=======\\n subtract(number) {\\n this -= number\\n return this;\\n }\\n+++++++ REPLACE"]',
},
id: expect.any(String),
});
});
});

View file

@ -0,0 +1,38 @@
import { ToolCallDelta } from "../..";
export function closeTag(openingTag: string): string {
return `</${openingTag.slice(1)}`;
}
export function splitAtCodeblocksAndNewLines(content: string) {
return content.split(/(```|\n)/g).filter(Boolean);
}
function randomLettersAndNumbers(length: number): string {
const characters =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
let result = "";
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * characters.length));
}
return result;
}
export function generateOpenAIToolCallId(): string {
return `call_${randomLettersAndNumbers(24)}`;
}
export function createDelta(
name: string,
args: string,
id: string,
): ToolCallDelta {
return {
type: "function",
function: {
name,
arguments: args,
},
id,
};
}

View file

@ -0,0 +1,57 @@
import { describe, expect, test } from "vitest";
import { closeTag, splitAtCodeblocksAndNewLines } from "./systemToolUtils";
describe("closeTag", () => {
const testCases = [
{
input: "<div>",
expectedOutput: "</div>",
},
{
input: "<p>",
expectedOutput: "</p>",
},
// Add more test cases as needed
];
testCases.forEach((testCase) => {
test(`closes tag "${testCase.input}" to "</${testCase.input.slice(1)}"`, () => {
const result = closeTag(testCase.input);
expect(result).toEqual(testCase.expectedOutput);
});
});
});
describe("splitAtCodeblocks", () => {
test("doesn't split plain text without codeblocks", () => {
expect(splitAtCodeblocksAndNewLines("hello world")).toEqual([
"hello world",
]);
});
test("splits at codeblocks", () => {
expect(splitAtCodeblocksAndNewLines("```<one>middle```<two>")).toEqual([
"```",
"<one>middle",
"```",
"<two>",
]);
});
test("splits at new lines", () => {
expect(splitAtCodeblocksAndNewLines("hello\nhoware\n you\n")).toEqual([
"hello",
"\n",
"howare",
"\n",
" you",
"\n",
]);
});
test("splits at both codeblocks and new lines", () => {
expect(splitAtCodeblocksAndNewLines("hello```\nho```ware\n you\n")).toEqual(
["hello", "```", "\n", "ho", "```", "ware", "\n", " you", "\n"],
);
});
});

View file

@ -0,0 +1,102 @@
import {
AssistantChatMessage,
MessagePart,
ToolCallState,
UserChatMessage,
} from "../..";
import {
normalizeToMessageParts,
renderContextItems,
} from "../../util/messageContent";
import {
CANCELLED_TOOL_CALL_MESSAGE,
NO_TOOL_CALL_OUTPUT_MESSAGE,
} from "../constants";
function toolCallStateToSystemToolCall(state: ToolCallState): string {
let parts = ["```tool"];
parts.push(`TOOL_NAME: ${state.toolCall.function.name}`);
try {
for (const arg in state.parsedArgs) {
parts.push(`BEGIN_ARG: ${arg}`);
parts.push(JSON.stringify(state.parsedArgs[arg]));
parts.push(`END_ARG`);
}
} catch (e) {
console.log("Failed to stringify json args", state.parsedArgs);
}
// TODO - include tool call id for parallel. Confuses dumb models
parts.push("```");
return parts.join("\n");
}
function toolCallStateToSystemToolOutput(state: ToolCallState): string {
let output = `Tool output for ${state.toolCall.function.name} tool call:\n\n`;
// TODO - include tool call id for parallel. Confuses dumb models
// let output = `Tool output for tool call ${state.toolCallId} (${state.toolCall.function.name}):\n\n`;
if (state.status === "canceled") {
output += CANCELLED_TOOL_CALL_MESSAGE;
} else if (state.output?.length) {
output += renderContextItems(state.output);
} else {
output += NO_TOOL_CALL_OUTPUT_MESSAGE;
}
return output;
}
export function convertToolCallStatesToSystemCallsAndOutput(
originalAssistantMessage: AssistantChatMessage,
toolCallStates: ToolCallState[],
): {
assistantMessage: AssistantChatMessage;
userMessage: UserChatMessage;
} {
const assistantParts = normalizeToMessageParts(originalAssistantMessage);
if (originalAssistantMessage.toolCalls) {
assistantParts.push(
...toolCallStates.map((state) => ({
type: "text" as const,
text: toolCallStateToSystemToolCall(state),
})),
);
}
const userParts: MessagePart[] = [];
if (toolCallStates) {
for (const state of toolCallStates) {
userParts.push({
type: "text",
text: toolCallStateToSystemToolOutput(state),
});
}
}
if (userParts.length === 0) {
userParts.push({
type: "text",
text: "No tool output for tool calls",
});
}
const nonEmptyAssistantParts = assistantParts.filter(
(p) => p.type !== "text" || !!p.text,
);
const nonEmptyUserParts = userParts.filter(
(p) => p.type !== "text" || !!p.text,
);
// new message with tool calls moved to content
const assistantMessage: AssistantChatMessage = {
...originalAssistantMessage,
content: nonEmptyAssistantParts,
toolCalls: undefined, // remove tool calls from the assistant message
};
const userMessage: UserChatMessage = {
role: "user",
content: nonEmptyUserParts,
};
return {
assistantMessage,
userMessage,
};
}

View file

@ -2,7 +2,6 @@ import * as fs from "node:fs";
import { fileURLToPath } from "node:url";
import {
ContinueRcJson,
DocumentSymbol,
FileStatsMap,
FileType,
@ -14,6 +13,7 @@ import {
Problem,
Range,
RangeInFile,
SignatureHelp,
TerminalOptions,
Thread,
ToastType,
@ -45,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);
}
getReferences(location: Location): Promise<RangeInFile[]> {
return Promise.resolve([]);
}
@ -145,10 +153,6 @@ class FileSystemIde implements IDE {
return Promise.resolve("NOT_UNIQUE");
}
getWorkspaceConfigs(): Promise<ContinueRcJson[]> {
return Promise.resolve([]);
}
getDiff(includeUnstaged: boolean): Promise<string[]> {
return Promise.resolve([]);
}

View file

@ -55,7 +55,7 @@ describe.skip("generateRepoMap", () => {
});
// Set testLLM properties
testLLM.contextLength = 2048;
testLLM._contextLength = 2048;
testLLM.countTokens = jest.fn().mockReturnValue(10);
// Act
@ -115,7 +115,7 @@ describe.skip("generateRepoMap", () => {
});
// Set testLLM properties
testLLM.contextLength = 2048;
testLLM._contextLength = 2048;
testLLM.countTokens = jest.fn().mockReturnValue(10);
// Act
@ -184,7 +184,7 @@ describe.skip("generateRepoMap", () => {
.mockImplementation(() => {});
// Set testLLM properties
testLLM.contextLength = 2048;
testLLM._contextLength = 2048;
testLLM.countTokens = jest.fn().mockReturnValue(10);
// Act

View file

@ -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;

136
core/utils/markdownUtils.ts Normal file
View file

@ -0,0 +1,136 @@
/**
* Utility functions for working with markdown files and code blocks
*/
/**
* Determines if a code block header indicates markdown content
*/
export function headerIsMarkdown(header: string): boolean {
return (
header === "md" ||
header === "markdown" ||
header === "gfm" ||
header === "github-markdown" ||
header.includes(" md") ||
header.includes(" markdown") ||
header.includes(" gfm") ||
header.includes(" github-markdown") ||
header.split(" ")[0]?.split(".").pop() === "md" ||
header.split(" ")[0]?.split(".").pop() === "markdown" ||
header.split(" ")[0]?.split(".").pop() === "gfm"
);
}
/**
* Determines if a file is a markdown file based on its filepath.
*/
export function isMarkdownFile(filepath?: string): boolean {
if (!filepath) {
return false;
}
const ext = filepath.split(".").pop()?.toLowerCase() || "";
return ["md", "markdown", "gfm"].includes(ext);
}
/**
* State tracker for markdown block analysis to avoid recomputing on each call.
* Optimized to handle nested markdown code blocks.
*/
export class MarkdownBlockStateTracker {
protected trimmedLines: string[];
protected bareBacktickPositions: number[];
private markdownNestCount: number = 0;
private lastProcessedIndex: number = -1;
constructor(allLines: string[]) {
this.trimmedLines = allLines.map((l) => l.trim());
// Pre-compute positions of all bare backtick lines for faster lookup
this.bareBacktickPositions = [];
for (let i = 0; i < this.trimmedLines.length; i++) {
if (this.trimmedLines[i].match(/^`+$/)) {
this.bareBacktickPositions.push(i);
}
}
}
/**
* Determines if we should stop at the given markdown block position.
* Maintains state across calls to avoid redundant computation.
*/
shouldStopAtPosition(currentIndex: number): boolean {
if (this.trimmedLines[currentIndex] !== "```") {
return false;
}
// Process any lines we haven't seen yet up to currentIndex
for (let j = this.lastProcessedIndex + 1; j <= currentIndex; j++) {
const currentLine = this.trimmedLines[j];
if (this.markdownNestCount > 0) {
// Inside a markdown block
if (currentLine.match(/^`+$/)) {
// Found bare backticks - check if this is the last one
if (j === currentIndex) {
const remainingBareBackticks =
this.getRemainingBareBackticksAfter(j);
if (remainingBareBackticks === 0) {
this.markdownNestCount = 0;
this.lastProcessedIndex = j;
return true;
}
}
} else if (currentLine.startsWith("```")) {
// Going into a nested codeblock
this.markdownNestCount++;
}
} else {
// Not inside a markdown block yet
if (currentLine.startsWith("```")) {
const header = currentLine.replaceAll("`", "");
if (headerIsMarkdown(header)) {
this.markdownNestCount = 1;
}
}
}
}
this.lastProcessedIndex = currentIndex;
return false;
}
/**
* Efficiently determines if there are remaining bare backticks after the given position.
*/
getRemainingBareBackticksAfter(currentIndex: number): number {
return this.bareBacktickPositions.filter((pos) => pos > currentIndex)
.length;
}
/**
* Checks if the line at the given index is a bare backtick line.
*/
isBareBacktickLine(index: number): boolean {
return this.bareBacktickPositions.includes(index);
}
/**
* Gets the trimmed lines array.
*/
getTrimmedLines(): string[] {
return this.trimmedLines;
}
}
/**
* Collects all lines from a LineStream into an array for analysis.
*/
export async function collectAllLines<T>(
stream: AsyncGenerator<T>,
): Promise<T[]> {
const allLines: T[] = [];
for await (const line of stream) {
allLines.push(line);
}
return allLines;
}

View file

@ -0,0 +1,306 @@
import { describe, expect, it } from "vitest";
import {
collectAllLines,
headerIsMarkdown,
isMarkdownFile,
MarkdownBlockStateTracker,
} from "./markdownUtils";
describe("headerIsMarkdown", () => {
// Test exact match with common Markdown identifiers
it("should identify exact matches with common Markdown identifiers", () => {
expect(headerIsMarkdown("md")).toBe(true);
expect(headerIsMarkdown("markdown")).toBe(true);
expect(headerIsMarkdown("gfm")).toBe(true);
expect(headerIsMarkdown("github-markdown")).toBe(true);
});
// Test identifiers preceded by a space
it("should identify identifiers preceded by a space", () => {
expect(headerIsMarkdown("lang md")).toBe(true);
expect(headerIsMarkdown("something markdown")).toBe(true);
expect(headerIsMarkdown("language gfm")).toBe(true);
expect(headerIsMarkdown("spec github-markdown")).toBe(true);
});
// Test file extensions
it("should identify file names with markdown extensions", () => {
expect(headerIsMarkdown("example.md")).toBe(true);
expect(headerIsMarkdown("document.markdown")).toBe(true);
expect(headerIsMarkdown("readme.gfm")).toBe(true);
});
// Test more complex cases with extensions
it("should identify file names with markdown extensions followed by other text", () => {
expect(headerIsMarkdown("example.md additional text")).toBe(true);
expect(headerIsMarkdown("document.markdown with some description")).toBe(
true,
);
expect(headerIsMarkdown("readme.gfm v2.0")).toBe(true);
});
// Test non-markdown cases
it("should not identify non-markdown headers", () => {
expect(headerIsMarkdown("javascript")).toBe(false);
expect(headerIsMarkdown("typescript")).toBe(false);
expect(headerIsMarkdown("plain")).toBe(false);
expect(headerIsMarkdown("python")).toBe(false);
});
// Test edge cases
it("should handle edge cases correctly", () => {
expect(headerIsMarkdown("")).toBe(false);
expect(headerIsMarkdown("mdx")).toBe(false); // Similar but not exactly "md"
expect(headerIsMarkdown("readme md")).toBe(true);
expect(headerIsMarkdown("md.js")).toBe(false); // "md" is not the extension
});
// Test case sensitivity
it("should respect case sensitivity", () => {
expect(headerIsMarkdown("MD")).toBe(false);
expect(headerIsMarkdown("MARKDOWN")).toBe(false);
expect(headerIsMarkdown("example.MD")).toBe(false);
expect(headerIsMarkdown("lang MD")).toBe(false);
});
// Test with special characters and spacing
it("should handle special characters and spacing correctly", () => {
expect(headerIsMarkdown(" md")).toBe(true); // Space before "md"
expect(headerIsMarkdown("md ")).toBe(true); // Space after "md"
expect(headerIsMarkdown("hello-md")).toBe(false); // "md" with hyphen prefix
expect(headerIsMarkdown("markdown:")).toBe(false); // "markdown" with suffix
});
});
describe("isMarkdownFile", () => {
it("should identify markdown files by .md extension", () => {
expect(isMarkdownFile("README.md")).toBe(true);
expect(isMarkdownFile("docs/guide.md")).toBe(true);
expect(isMarkdownFile("/path/to/file.md")).toBe(true);
});
it("should identify markdown files by .markdown extension", () => {
expect(isMarkdownFile("README.markdown")).toBe(true);
expect(isMarkdownFile("docs/guide.markdown")).toBe(true);
expect(isMarkdownFile("/path/to/file.markdown")).toBe(true);
});
it("should identify markdown files by .gfm extension", () => {
expect(isMarkdownFile("README.gfm")).toBe(true);
expect(isMarkdownFile("docs/guide.gfm")).toBe(true);
expect(isMarkdownFile("/path/to/file.gfm")).toBe(true);
});
it("should handle case insensitive extensions", () => {
expect(isMarkdownFile("README.MD")).toBe(true);
expect(isMarkdownFile("guide.MARKDOWN")).toBe(true);
expect(isMarkdownFile("file.GFM")).toBe(true);
});
it("should return false for non-markdown files", () => {
expect(isMarkdownFile("script.js")).toBe(false);
expect(isMarkdownFile("style.css")).toBe(false);
expect(isMarkdownFile("data.json")).toBe(false);
expect(isMarkdownFile("document.txt")).toBe(false);
});
it("should return false for undefined or empty filepath", () => {
expect(isMarkdownFile(undefined)).toBe(false);
expect(isMarkdownFile("")).toBe(false);
});
it("should return false for files without extensions", () => {
expect(isMarkdownFile("README")).toBe(false);
expect(isMarkdownFile("Dockerfile")).toBe(false);
});
it("should handle files with multiple dots", () => {
expect(isMarkdownFile("file.backup.md")).toBe(true);
expect(isMarkdownFile("config.test.js")).toBe(false);
});
});
describe("MarkdownBlockStateTracker", () => {
it("should initialize correctly with empty lines", () => {
const tracker = new MarkdownBlockStateTracker([]);
expect(tracker.shouldStopAtPosition(0)).toBe(false);
});
it("should initialize correctly with non-markdown lines", () => {
const tracker = new MarkdownBlockStateTracker([
"const x = 5;",
"console.log(x);",
]);
expect(tracker.shouldStopAtPosition(0)).toBe(false);
expect(tracker.shouldStopAtPosition(1)).toBe(false);
});
it("should detect simple markdown blocks", () => {
const tracker = new MarkdownBlockStateTracker([
"```markdown",
"# Title",
"```",
]);
expect(tracker.shouldStopAtPosition(0)).toBe(false); // Opening
expect(tracker.shouldStopAtPosition(1)).toBe(false); // Content
expect(tracker.shouldStopAtPosition(2)).toBe(true); // Closing
});
it("should handle nested code blocks within markdown", () => {
const tracker = new MarkdownBlockStateTracker([
"```md",
"Here's some code:",
"```javascript",
"console.log('hello');",
"```",
"More content",
"```",
]);
expect(tracker.shouldStopAtPosition(2)).toBe(false); // Inner opening
expect(tracker.shouldStopAtPosition(4)).toBe(false); // Inner closing
expect(tracker.shouldStopAtPosition(6)).toBe(true); // Outer closing
});
it("should handle multiple bare backticks", () => {
const tracker = new MarkdownBlockStateTracker([
"```markdown",
"Content with ```inline``` code",
"```",
"More content",
"```",
]);
expect(tracker.shouldStopAtPosition(2)).toBe(false); // First bare backticks
expect(tracker.shouldStopAtPosition(4)).toBe(true); // Last bare backticks
});
it("should handle non-markdown code blocks", () => {
const tracker = new MarkdownBlockStateTracker([
"```javascript",
"console.log('hello');",
"```",
]);
expect(tracker.shouldStopAtPosition(2)).toBe(false); // Not a markdown block
});
it("should handle mixed markdown types", () => {
const tracker = new MarkdownBlockStateTracker([
"```gfm",
"# GitHub Flavored Markdown",
"```",
]);
expect(tracker.shouldStopAtPosition(2)).toBe(true);
});
it("should handle state persistence across multiple calls", () => {
const tracker = new MarkdownBlockStateTracker([
"```markdown",
"# Documentation",
"```typescript",
"interface Config {}",
"```",
"Final notes",
"```",
]);
// Process incrementally
expect(tracker.shouldStopAtPosition(2)).toBe(false); // Inner opening
expect(tracker.shouldStopAtPosition(4)).toBe(false); // Inner closing
expect(tracker.shouldStopAtPosition(6)).toBe(true); // Outer closing
});
it("should handle lines that are not closing backticks", () => {
const tracker = new MarkdownBlockStateTracker([
"```markdown",
"Regular content line",
"```",
]);
expect(tracker.shouldStopAtPosition(1)).toBe(false); // Not backticks
});
it("should provide access to trimmed lines", () => {
const tracker = new MarkdownBlockStateTracker([
" ```markdown ",
" # Title ",
" ``` ",
]);
const trimmedLines = tracker.getTrimmedLines();
expect(trimmedLines).toEqual(["```markdown", "# Title", "```"]);
});
it("should identify bare backtick lines correctly", () => {
const tracker = new MarkdownBlockStateTracker([
"```markdown",
"```",
"content",
"```",
]);
expect(tracker.isBareBacktickLine(0)).toBe(false); // Has language
expect(tracker.isBareBacktickLine(1)).toBe(true); // Bare backticks
expect(tracker.isBareBacktickLine(2)).toBe(false); // Content
expect(tracker.isBareBacktickLine(3)).toBe(true); // Bare backticks
});
it("should count remaining bare backticks correctly", () => {
const tracker = new MarkdownBlockStateTracker([
"```markdown",
"```",
"content",
"```",
"more content",
"```",
]);
expect(tracker.getRemainingBareBackticksAfter(0)).toBe(3); // After opening
expect(tracker.getRemainingBareBackticksAfter(1)).toBe(2); // After first bare
expect(tracker.getRemainingBareBackticksAfter(3)).toBe(1); // After second bare
expect(tracker.getRemainingBareBackticksAfter(5)).toBe(0); // After last bare
});
});
describe("collectAllLines", () => {
async function* createAsyncGenerator<T>(items: T[]): AsyncGenerator<T> {
for (const item of items) {
yield item;
}
}
it("should collect all lines from a stream", async () => {
const stream = createAsyncGenerator(["line1", "line2", "line3"]);
const result = await collectAllLines(stream);
expect(result).toEqual(["line1", "line2", "line3"]);
});
it("should handle empty streams", async () => {
const stream = createAsyncGenerator([]);
const result = await collectAllLines(stream);
expect(result).toEqual([]);
});
it("should handle streams with mixed types", async () => {
const stream = createAsyncGenerator([1, "text", null, true]);
const result = await collectAllLines(stream);
expect(result).toEqual([1, "text", null, true]);
});
it("should handle streams with empty strings", async () => {
const stream = createAsyncGenerator(["", "line2", "", "line4"]);
const result = await collectAllLines(stream);
expect(result).toEqual(["", "line2", "", "line4"]);
});
it("should handle large streams", async () => {
const largeArray = Array.from({ length: 1000 }, (_, i) => `line${i}`);
const stream = createAsyncGenerator(largeArray);
const result = await collectAllLines(stream);
expect(result).toEqual(largeArray);
});
it("should handle object streams", async () => {
const objects = [
{ type: "new", line: "const x = 5;" },
{ type: "old", line: "let y = 10;" },
];
const stream = createAsyncGenerator(objects);
const result = await collectAllLines(stream);
expect(result).toEqual(objects);
});
});

View file

@ -0,0 +1,98 @@
import { LineStream } from "../diff/util";
import { isMarkdownFile, MarkdownBlockStateTracker } from "./markdownUtils";
/**
* Determines if we should stop at a markdown block based on nested markdown logic.
* This handles the complex case where markdown blocks contain other markdown blocks.
* Uses optimized state tracking to avoid redundant computation.
*/
export function shouldStopAtMarkdownBlock(
stateTracker: MarkdownBlockStateTracker,
currentIndex: number,
): boolean {
return stateTracker.shouldStopAtPosition(currentIndex);
}
/**
* Processes block nesting logic and returns updated state.
*/
export function processBlockNesting(
line: string,
seenFirstFence: boolean,
shouldRemoveLineBeforeStart: (line: string) => boolean,
): { newSeenFirstFence: boolean; shouldSkip: boolean } {
if (!seenFirstFence && shouldRemoveLineBeforeStart(line)) {
return { newSeenFirstFence: false, shouldSkip: true };
}
if (!seenFirstFence) {
return { newSeenFirstFence: true, shouldSkip: false };
}
return { newSeenFirstFence: seenFirstFence, shouldSkip: false };
}
/**
* Stream transformation that stops when encountering a markdown code block ending.
* Handles nested markdown blocks in markdown files.
*/
export async function* stopAtLinesWithMarkdownSupport(
lines: LineStream,
filename: string,
): LineStream {
if (!isMarkdownFile(filename)) {
for await (const line of lines) {
if (line.trim() === "```") {
return;
}
yield line;
}
return;
}
const allLines: string[] = [];
for await (const line of lines) {
allLines.push(line);
}
const source = allLines.join("\n");
if (!source.match(/```(\w*|.*)(md|markdown|gfm|github-markdown)/)) {
// No nested markdown blocks detected, check for simple ``` stopping condition
let foundStandaloneBackticks = false;
for (let i = 0; i < allLines.length; i++) {
if (allLines[i].trim() === "```") {
// Found standalone backticks, yield lines up to this point
for (let j = 0; j < i; j++) {
yield allLines[j];
}
foundStandaloneBackticks = true;
return;
}
}
// No standalone backticks found, yield all lines
if (!foundStandaloneBackticks) {
for (const line of allLines) {
yield line;
}
}
return;
}
// Use optimized state tracker for markdown block analysis
const stateTracker = new MarkdownBlockStateTracker(allLines);
for (let i = 0; i < allLines.length; i++) {
if (stateTracker.shouldStopAtPosition(i)) {
for (let j = 0; j < i; j++) {
yield allLines[j];
}
return;
}
}
// If we get here, yield all lines
for (const line of allLines) {
yield line;
}
}

View file

@ -0,0 +1,102 @@
import { expect, test } from "vitest";
import { LineStream } from "../diff/util";
import {
processBlockNesting,
stopAtLinesWithMarkdownSupport,
} from "./streamMarkdownUtils";
test("processBlockNesting correctly handles starting blocks", () => {
// Mock function to determine which lines should be removed
const shouldRemoveLineBeforeStart = (line: string) =>
line === "[CODE]" || line === "```";
// Test not seeing first fence yet
const result1 = processBlockNesting(
"[CODE]",
false,
shouldRemoveLineBeforeStart,
);
expect(result1.newSeenFirstFence).toBe(false);
expect(result1.shouldSkip).toBe(true);
// Test not seeing first fence but line shouldn't be removed
const result2 = processBlockNesting(
"normal code",
false,
shouldRemoveLineBeforeStart,
);
expect(result2.newSeenFirstFence).toBe(true);
expect(result2.shouldSkip).toBe(false);
// Test already seen first fence
const result3 = processBlockNesting(
"more code",
true,
shouldRemoveLineBeforeStart,
);
expect(result3.newSeenFirstFence).toBe(true);
expect(result3.shouldSkip).toBe(false);
});
test("stopAtLinesWithMarkdownSupport handles non-markdown files", async () => {
// Create a mock line stream
const mockLines = ["line 1", "line 2", "```", "line 4"];
const lineStream: LineStream = (async function* () {
for (const line of mockLines) {
yield line;
}
})();
// Test with a non-markdown file
const filename = "test.js";
const result = stopAtLinesWithMarkdownSupport(lineStream, filename);
// Should only yield lines up to the backticks
const collected = [];
for await (const line of result) {
collected.push(line);
}
expect(collected).toEqual(["line 1", "line 2"]);
});
test("stopAtLinesWithMarkdownSupport handles markdown files with no nested blocks", async () => {
// Create a mock line stream with markdown content - but NOT nested markdown blocks
const mockLines = [
"Some markdown text",
"",
"```javascript",
"function test() {",
" return true;",
"}",
"```",
"More text",
];
const lineStream: LineStream = (async function* () {
for (const line of mockLines) {
yield line;
}
})();
// Test with a markdown file
const filename = "test.md";
const result = stopAtLinesWithMarkdownSupport(lineStream, filename);
// Should yield everything since there's no nested markdown blocks
const collected = [];
for await (const line of result) {
collected.push(line);
}
// The function should stop at the standalone ``` line (not yield it or lines after)
// This is the correct behavior - it stops when it encounters standalone backticks
expect(collected).toEqual([
"Some markdown text",
"",
"```javascript",
"function test() {",
" return true;",
"}",
]);
});

View file

@ -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.

View file

@ -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>

Some files were not shown because too many files have changed in this diff Show more