npx prettier --check "core/**/*.{js,jsx,ts,tsx,json,css,md}" --ignore-p
ath .gitignore --ignore-path .prettierignore --write
This commit is contained in:
parent
c4d1d11375
commit
184be8f092
54 changed files with 1592 additions and 1219 deletions
|
|
@ -74,7 +74,6 @@ export class StreamTransformPipeline {
|
|||
|
||||
const timeoutValue = helper.options.modelTimeout;
|
||||
|
||||
|
||||
lineGenerator = showWhateverWeHaveAtXMs(lineGenerator, timeoutValue!);
|
||||
|
||||
const finalGenerator = streamWithNewLines(lineGenerator);
|
||||
|
|
|
|||
|
|
@ -215,21 +215,47 @@ describe("lineStream", () => {
|
|||
});
|
||||
|
||||
it("should handle unfenced code with a code block", async () => {
|
||||
const linesGenerator = await getLineGenerator(["const x = 5;","```bash","ls -al","```"]);
|
||||
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","```"]);
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle unfenced code with two code blocks", async () => {
|
||||
const linesGenerator = await getLineGenerator(["const x = 5;","```bash","ls -al","```","```bash","ls -al","```"]);
|
||||
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","```"]);
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should remove lines before the first valid line", async () => {
|
||||
|
|
@ -242,7 +268,11 @@ describe("lineStream", () => {
|
|||
});
|
||||
|
||||
it("should remove outer blocks", async () => {
|
||||
const linesGenerator = await getLineGenerator(["```ts", "const x = 5;","```"]);
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```ts",
|
||||
"const x = 5;",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
|
@ -251,48 +281,119 @@ describe("lineStream", () => {
|
|||
});
|
||||
|
||||
it("should leave inner blocks intact", async () => {
|
||||
const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","ls -al","```","```"]);
|
||||
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","```"]);
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle included inner ticks", async () => {
|
||||
const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","echo ```test```","```","```"]);
|
||||
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```","```"]);
|
||||
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 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","```"]);
|
||||
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 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`","```"]);
|
||||
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 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","```"]);
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -350,12 +350,10 @@ export async function* filterCodeBlockLines(rawLines: LineStream): LineStream {
|
|||
let nestCount = 0;
|
||||
|
||||
for await (const line of rawLines) {
|
||||
|
||||
|
||||
if (!seenFirstFence) {
|
||||
if (shouldRemoveLineBeforeStart(line)) {
|
||||
// Filter out starting ``` or START block
|
||||
continue
|
||||
continue;
|
||||
}
|
||||
// Regardless of a fence or START block start tracking the nesting level
|
||||
seenFirstFence = true;
|
||||
|
|
|
|||
|
|
@ -14,7 +14,11 @@ export class GeneratorReuseManager {
|
|||
) {
|
||||
this.currentGenerator?.cancel();
|
||||
|
||||
const listenableGen = new ListenableGenerator(gen, this.onError, abortController);
|
||||
const listenableGen = new ListenableGenerator(
|
||||
gen,
|
||||
this.onError,
|
||||
abortController,
|
||||
);
|
||||
listenableGen.listen((chunk) => (this.pendingCompletion += chunk ?? ""));
|
||||
|
||||
this.pendingGeneratorPrefix = prefix;
|
||||
|
|
@ -43,7 +47,11 @@ export class GeneratorReuseManager {
|
|||
if (!this.shouldReuseExistingGenerator(prefix)) {
|
||||
// Create a wrapper over the current generator to fix the prompt
|
||||
const abortController = new AbortController();
|
||||
this._createListenableGenerator(abortController, newGenerator(abortController.signal), prefix);
|
||||
this._createListenableGenerator(
|
||||
abortController,
|
||||
newGenerator(abortController.signal),
|
||||
prefix,
|
||||
);
|
||||
}
|
||||
|
||||
// Already typed characters are those that are new in the prefix from the old generator
|
||||
|
|
|
|||
|
|
@ -113,12 +113,14 @@ const getClipboardSnippets = async (
|
|||
const getDiffSnippets = async (
|
||||
ide: IDE,
|
||||
): Promise<AutocompleteDiffSnippet[]> => {
|
||||
const currentTimestamp = ide.getLastFileSaveTimestamp ?
|
||||
ide.getLastFileSaveTimestamp() :
|
||||
Math.floor(Date.now() / 10000) * 10000; // Defaults to update once in every 10 seconds
|
||||
const currentTimestamp = ide.getLastFileSaveTimestamp
|
||||
? ide.getLastFileSaveTimestamp()
|
||||
: Math.floor(Date.now() / 10000) * 10000; // Defaults to update once in every 10 seconds
|
||||
|
||||
// Check cache first
|
||||
const cached = diffSnippetsCache.get(currentTimestamp) as AutocompleteDiffSnippet[];
|
||||
const cached = diffSnippetsCache.get(
|
||||
currentTimestamp,
|
||||
) as AutocompleteDiffSnippet[];
|
||||
|
||||
if (cached) {
|
||||
return cached;
|
||||
|
|
@ -131,13 +133,15 @@ const getDiffSnippets = async (
|
|||
console.error("Error getting diff for autocomplete", e);
|
||||
}
|
||||
|
||||
return diffSnippetsCache.set(currentTimestamp, diff.map((item) => {
|
||||
return {
|
||||
content: item,
|
||||
type: AutocompleteSnippetType.Diff,
|
||||
};
|
||||
}));
|
||||
|
||||
return diffSnippetsCache.set(
|
||||
currentTimestamp,
|
||||
diff.map((item) => {
|
||||
return {
|
||||
content: item,
|
||||
type: AutocompleteSnippetType.Diff,
|
||||
};
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
export const getAllSnippets = async ({
|
||||
|
|
@ -162,8 +166,12 @@ export const getAllSnippets = async ({
|
|||
clipboardSnippets,
|
||||
] = await Promise.all([
|
||||
racePromise(contextRetrievalService.getRootPathSnippets(helper)),
|
||||
racePromise(contextRetrievalService.getSnippetsFromImportDefinitions(helper)),
|
||||
IDE_SNIPPETS_ENABLED ? racePromise(getIdeSnippets(helper, ide, getDefinitionsFromLsp)) : [],
|
||||
racePromise(
|
||||
contextRetrievalService.getSnippetsFromImportDefinitions(helper),
|
||||
),
|
||||
IDE_SNIPPETS_ENABLED
|
||||
? racePromise(getIdeSnippets(helper, ide, getDefinitionsFromLsp))
|
||||
: [],
|
||||
racePromise(getDiffSnippets(ide)),
|
||||
racePromise(getClipboardSnippets(ide)),
|
||||
]);
|
||||
|
|
|
|||
|
|
@ -72,7 +72,8 @@ const qwenCoderFimTemplate: AutocompleteTemplate = {
|
|||
};
|
||||
|
||||
const seedCoderFimTemplate: AutocompleteTemplate = {
|
||||
template: "<[fim-prefix]>{{{prefix}}}<[fim-suffix]>{{{suffix}}}<[fim-middle]>",
|
||||
template:
|
||||
"<[fim-prefix]>{{{prefix}}}<[fim-suffix]>{{{suffix}}}<[fim-middle]>",
|
||||
completionOptions: {
|
||||
stop: [
|
||||
"<[end▁of▁sentence]>",
|
||||
|
|
|
|||
|
|
@ -42,17 +42,18 @@ export const getSnippets = (
|
|||
helper: HelperVars,
|
||||
payload: SnippetPayload,
|
||||
): AutocompleteSnippet[] => {
|
||||
|
||||
const snippets = {
|
||||
"clipboard": payload.clipboardSnippets,
|
||||
"recentlyVisitedRanges": payload.recentlyVisitedRangesSnippets,
|
||||
"recentlyEditedRanges": payload.recentlyEditedRangeSnippets,
|
||||
"diff": payload.diffSnippets,
|
||||
"base": shuffleArray(filterSnippetsAlreadyInCaretWindow(
|
||||
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
|
||||
helper.prunedCaretWindow,
|
||||
)),
|
||||
}
|
||||
clipboard: payload.clipboardSnippets,
|
||||
recentlyVisitedRanges: payload.recentlyVisitedRangesSnippets,
|
||||
recentlyEditedRanges: payload.recentlyEditedRangeSnippets,
|
||||
diff: payload.diffSnippets,
|
||||
base: shuffleArray(
|
||||
filterSnippetsAlreadyInCaretWindow(
|
||||
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
|
||||
helper.prunedCaretWindow,
|
||||
),
|
||||
),
|
||||
};
|
||||
|
||||
// Define snippets with their priorities
|
||||
const snippetConfigs: {
|
||||
|
|
@ -61,53 +62,60 @@ export const getSnippets = (
|
|||
defaultPriority: number;
|
||||
snippets: AutocompleteSnippet[];
|
||||
}[] = [
|
||||
{
|
||||
key: "clipboard",
|
||||
enabledOrPriority: helper.options.experimental_includeClipboard,
|
||||
defaultPriority: 1,
|
||||
snippets: payload.clipboardSnippets,
|
||||
},
|
||||
{
|
||||
key: "recentlyVisitedRanges",
|
||||
enabledOrPriority: helper.options.experimental_includeRecentlyVisitedRanges,
|
||||
defaultPriority: 2,
|
||||
snippets: payload.recentlyVisitedRangesSnippets,
|
||||
/* TODO: recentlyVisitedRanges also contain contents from other windows like terminal or output
|
||||
{
|
||||
key: "clipboard",
|
||||
enabledOrPriority: helper.options.experimental_includeClipboard,
|
||||
defaultPriority: 1,
|
||||
snippets: payload.clipboardSnippets,
|
||||
},
|
||||
{
|
||||
key: "recentlyVisitedRanges",
|
||||
enabledOrPriority:
|
||||
helper.options.experimental_includeRecentlyVisitedRanges,
|
||||
defaultPriority: 2,
|
||||
snippets: payload.recentlyVisitedRangesSnippets,
|
||||
/* TODO: recentlyVisitedRanges also contain contents from other windows like terminal or output
|
||||
if they are visible. We should handle them separately so that we can control their priority
|
||||
and whether they should be included or not. */
|
||||
},
|
||||
{
|
||||
key: "recentlyEditedRanges",
|
||||
enabledOrPriority: helper.options.experimental_includeRecentlyEditedRanges,
|
||||
defaultPriority: 3,
|
||||
snippets: payload.recentlyEditedRangeSnippets,
|
||||
},
|
||||
{
|
||||
key: "diff",
|
||||
enabledOrPriority: helper.options.experimental_includeDiff,
|
||||
defaultPriority: 4,
|
||||
snippets: payload.diffSnippets,
|
||||
// TODO: diff is commonly too large, thus anything lower in priority is not included.
|
||||
},
|
||||
{
|
||||
key: "base",
|
||||
enabledOrPriority: true,
|
||||
defaultPriority: 99, // make sure it's the last one to be processed, but still possible to override
|
||||
snippets: shuffleArray(filterSnippetsAlreadyInCaretWindow(
|
||||
},
|
||||
{
|
||||
key: "recentlyEditedRanges",
|
||||
enabledOrPriority:
|
||||
helper.options.experimental_includeRecentlyEditedRanges,
|
||||
defaultPriority: 3,
|
||||
snippets: payload.recentlyEditedRangeSnippets,
|
||||
},
|
||||
{
|
||||
key: "diff",
|
||||
enabledOrPriority: helper.options.experimental_includeDiff,
|
||||
defaultPriority: 4,
|
||||
snippets: payload.diffSnippets,
|
||||
// TODO: diff is commonly too large, thus anything lower in priority is not included.
|
||||
},
|
||||
{
|
||||
key: "base",
|
||||
enabledOrPriority: true,
|
||||
defaultPriority: 99, // make sure it's the last one to be processed, but still possible to override
|
||||
snippets: shuffleArray(
|
||||
filterSnippetsAlreadyInCaretWindow(
|
||||
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
|
||||
helper.prunedCaretWindow,
|
||||
)),
|
||||
// TODO: Add this too to experimental config, maybe move upper in the order, since it's almost
|
||||
// always not inlucded due to diff being commonly large
|
||||
},
|
||||
];
|
||||
),
|
||||
),
|
||||
// TODO: Add this too to experimental config, maybe move upper in the order, since it's almost
|
||||
// always not inlucded due to diff being commonly large
|
||||
},
|
||||
];
|
||||
|
||||
// Create a readable order of enabled snippets
|
||||
const snippetOrder = snippetConfigs
|
||||
.filter(({ enabledOrPriority }) => enabledOrPriority)
|
||||
.map(({ key, enabledOrPriority, defaultPriority }) => ({
|
||||
key,
|
||||
priority: typeof enabledOrPriority === 'number' ? enabledOrPriority : defaultPriority,
|
||||
priority:
|
||||
typeof enabledOrPriority === "number"
|
||||
? enabledOrPriority
|
||||
: defaultPriority,
|
||||
}))
|
||||
.sort((a, b) => a.priority - b.priority);
|
||||
|
||||
|
|
@ -121,15 +129,19 @@ export const getSnippets = (
|
|||
// Convert configs to prioritized snippets
|
||||
let prioritizedSnippets = snippetOrder
|
||||
.flatMap(({ key, priority }) =>
|
||||
snippets[key].map(snippet => ({ snippet, priority }))
|
||||
snippets[key].map((snippet) => ({ snippet, priority })),
|
||||
)
|
||||
.sort((a, b) => a.priority - b.priority)
|
||||
.map(({ snippet }) => snippet);
|
||||
|
||||
// Exclude Continue's own output as it makes it super-hard for users to test the autocomplete feature
|
||||
// while looking at the prompts in the Continue's output
|
||||
prioritizedSnippets = prioritizedSnippets.filter((snippet) =>
|
||||
!(snippet as AutocompleteCodeSnippet).filepath?.startsWith("output:extension-output-Continue.continue"));
|
||||
prioritizedSnippets = prioritizedSnippets.filter(
|
||||
(snippet) =>
|
||||
!(snippet as AutocompleteCodeSnippet).filepath?.startsWith(
|
||||
"output:extension-output-Continue.continue",
|
||||
),
|
||||
);
|
||||
|
||||
const finalSnippets = [];
|
||||
let remainingTokenCount = getRemainingTokenCount(helper);
|
||||
|
|
|
|||
|
|
@ -8,23 +8,23 @@ export class AutocompleteDebouncer {
|
|||
// Generate a unique ID for this request
|
||||
const requestId = uuidv4();
|
||||
this.currentRequestId = requestId;
|
||||
|
||||
|
||||
// Clear any existing timeout
|
||||
if (this.debounceTimeout) {
|
||||
clearTimeout(this.debounceTimeout);
|
||||
}
|
||||
|
||||
|
||||
// Create a new promise that resolves after the debounce delay
|
||||
return new Promise<boolean>((resolve) => {
|
||||
this.debounceTimeout = setTimeout(() => {
|
||||
// When the timeout completes, check if this is still the most recent request
|
||||
const shouldDebounce = this.currentRequestId !== requestId;
|
||||
|
||||
|
||||
// If this is the most recent request, it shouldn't be debounced
|
||||
if (!shouldDebounce) {
|
||||
this.currentRequestId = undefined;
|
||||
}
|
||||
|
||||
|
||||
resolve(shouldDebounce);
|
||||
}, debounceDelay);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,65 +1,65 @@
|
|||
import {
|
||||
processTestCase,
|
||||
type CompletionTestCase,
|
||||
processTestCase,
|
||||
type CompletionTestCase,
|
||||
} from "./completionTestUtils";
|
||||
|
||||
describe("processTestCase utility", () => {
|
||||
it("processes simple console.log completion", () => {
|
||||
const testCase: CompletionTestCase = {
|
||||
original: "console.log(|cur||till|)",
|
||||
completion: "\"foo,\", bar",
|
||||
};
|
||||
it("processes simple console.log completion", () => {
|
||||
const testCase: CompletionTestCase = {
|
||||
original: "console.log(|cur||till|)",
|
||||
completion: '"foo,", bar',
|
||||
};
|
||||
|
||||
expect(processTestCase(testCase)).toEqual({
|
||||
input: {
|
||||
lastLineOfCompletionText: "\"foo,\", bar",
|
||||
currentText: ")",
|
||||
cursorPosition: "console.log(".length,
|
||||
},
|
||||
expectedResult: {
|
||||
completionText: "\"foo,\", bar",
|
||||
},
|
||||
});
|
||||
expect(processTestCase(testCase)).toEqual({
|
||||
input: {
|
||||
lastLineOfCompletionText: '"foo,", bar',
|
||||
currentText: ")",
|
||||
cursorPosition: "console.log(".length,
|
||||
},
|
||||
expectedResult: {
|
||||
completionText: '"foo,", bar',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("processes simple console.log completion with overwriting", () => {
|
||||
const testCase: CompletionTestCase = {
|
||||
original: "console.log(|cur|)|till|",
|
||||
completion: "\"foo,\", bar);",
|
||||
};
|
||||
it("processes simple console.log completion with overwriting", () => {
|
||||
const testCase: CompletionTestCase = {
|
||||
original: "console.log(|cur|)|till|",
|
||||
completion: '"foo,", bar);',
|
||||
};
|
||||
|
||||
expect(processTestCase(testCase)).toEqual({
|
||||
input: {
|
||||
lastLineOfCompletionText: "\"foo,\", bar);",
|
||||
currentText: ")",
|
||||
cursorPosition: "console.log(".length,
|
||||
},
|
||||
expectedResult: {
|
||||
completionText: "\"foo,\", bar);",
|
||||
range: {
|
||||
start: "console.log(".length,
|
||||
end: "console.log()".length,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(processTestCase(testCase)).toEqual({
|
||||
input: {
|
||||
lastLineOfCompletionText: '"foo,", bar);',
|
||||
currentText: ")",
|
||||
cursorPosition: "console.log(".length,
|
||||
},
|
||||
expectedResult: {
|
||||
completionText: '"foo,", bar);',
|
||||
range: {
|
||||
start: "console.log(".length,
|
||||
end: "console.log()".length,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("partially applying completion", () => {
|
||||
const testCase: CompletionTestCase = {
|
||||
original: "|cur||till|fetch(\"https://example.com\");",
|
||||
completion: "await fetch(\"https://example.com\");",
|
||||
appliedCompletion: "await ",
|
||||
};
|
||||
it("partially applying completion", () => {
|
||||
const testCase: CompletionTestCase = {
|
||||
original: '|cur||till|fetch("https://example.com");',
|
||||
completion: 'await fetch("https://example.com");',
|
||||
appliedCompletion: "await ",
|
||||
};
|
||||
|
||||
expect(processTestCase(testCase)).toEqual({
|
||||
input: {
|
||||
lastLineOfCompletionText: "await fetch(\"https://example.com\");",
|
||||
currentText: "fetch(\"https://example.com\");",
|
||||
cursorPosition: 0,
|
||||
},
|
||||
expectedResult: {
|
||||
completionText: "await ",
|
||||
},
|
||||
});
|
||||
expect(processTestCase(testCase)).toEqual({
|
||||
input: {
|
||||
lastLineOfCompletionText: 'await fetch("https://example.com");',
|
||||
currentText: 'fetch("https://example.com");',
|
||||
cursorPosition: 0,
|
||||
},
|
||||
expectedResult: {
|
||||
completionText: "await ",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,91 +1,94 @@
|
|||
export interface CompletionTestCase {
|
||||
original: string; // Text with |cur| and |till| markers
|
||||
completion: string; // Text to insert/overwrite
|
||||
appliedCompletion?: string | null;
|
||||
cursorMarker?: string;
|
||||
tillMarker?: string;
|
||||
original: string; // Text with |cur| and |till| markers
|
||||
completion: string; // Text to insert/overwrite
|
||||
appliedCompletion?: string | null;
|
||||
cursorMarker?: string;
|
||||
tillMarker?: string;
|
||||
}
|
||||
|
||||
export interface ProcessedTestCase {
|
||||
input: {
|
||||
lastLineOfCompletionText: string;
|
||||
currentText: string;
|
||||
cursorPosition: number;
|
||||
};
|
||||
expectedResult: {
|
||||
completionText: string;
|
||||
range?: {
|
||||
start: number;
|
||||
end: number;
|
||||
};
|
||||
input: {
|
||||
lastLineOfCompletionText: string;
|
||||
currentText: string;
|
||||
cursorPosition: number;
|
||||
};
|
||||
expectedResult: {
|
||||
completionText: string;
|
||||
range?: {
|
||||
start: number;
|
||||
end: number;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms human-readable test case into input and expected results.
|
||||
*
|
||||
*
|
||||
* - `original`: Your original text with |cur| marking where the cursor is before completion,
|
||||
* and |till| marking where the cursor should be after accepting completion (and this is
|
||||
* the end of the actual applied completion)
|
||||
* - `completion`: LLM completion output
|
||||
* - `appliedCompletion` (optional): part of the LLM completion output that is actually applied
|
||||
* (written between |cur| and |till| in the original)
|
||||
*
|
||||
*
|
||||
* For example, you have this line:
|
||||
*
|
||||
*
|
||||
* console.log("<cursor here>");
|
||||
*
|
||||
*
|
||||
* and expect it to be completed this way:
|
||||
*
|
||||
*
|
||||
* console.log("foo: ", bar<cursor here>);
|
||||
*
|
||||
*
|
||||
* with your completion coming from LLM being: `'foo: ", bar<cursor here>);'`
|
||||
*
|
||||
*
|
||||
* Your input to this function should be:
|
||||
* - original: `'console.log("|cur|"|till|);'`
|
||||
* - completion: `'foo: ", bar);'`
|
||||
* - appliedCompletion: `'foo: ", bar'`
|
||||
*
|
||||
*
|
||||
* Output: input and expected output of {@link core/autocomplete/util/processSingleLineCompletion/processSingleLineCompletion|processSingleLineCompletion()}
|
||||
*
|
||||
*
|
||||
*/
|
||||
export function processTestCase({
|
||||
original,
|
||||
completion,
|
||||
appliedCompletion = null,
|
||||
cursorMarker = "|cur|",
|
||||
tillMarker = "|till|",
|
||||
original,
|
||||
completion,
|
||||
appliedCompletion = null,
|
||||
cursorMarker = "|cur|",
|
||||
tillMarker = "|till|",
|
||||
}: CompletionTestCase): ProcessedTestCase {
|
||||
// Validate cursor marker
|
||||
if (!original.includes(cursorMarker)) {
|
||||
throw new Error("Cursor marker not found in original text");
|
||||
}
|
||||
// Validate cursor marker
|
||||
if (!original.includes(cursorMarker)) {
|
||||
throw new Error("Cursor marker not found in original text");
|
||||
}
|
||||
|
||||
const cursorPos = original.indexOf(cursorMarker);
|
||||
original = original.replace(cursorMarker, "");
|
||||
const cursorPos = original.indexOf(cursorMarker);
|
||||
original = original.replace(cursorMarker, "");
|
||||
|
||||
let tillPos = original.indexOf(tillMarker);
|
||||
if (tillPos < 0) {
|
||||
tillPos = cursorPos;
|
||||
} else {
|
||||
original = original.replace(tillMarker, "")
|
||||
}
|
||||
let tillPos = original.indexOf(tillMarker);
|
||||
if (tillPos < 0) {
|
||||
tillPos = cursorPos;
|
||||
} else {
|
||||
original = original.replace(tillMarker, "");
|
||||
}
|
||||
|
||||
// Calculate currentText based on what's between cursor and till marker
|
||||
const currentText = original.substring(cursorPos);
|
||||
// Calculate currentText based on what's between cursor and till marker
|
||||
const currentText = original.substring(cursorPos);
|
||||
|
||||
return {
|
||||
input: {
|
||||
lastLineOfCompletionText: completion,
|
||||
currentText,
|
||||
cursorPosition: cursorPos,
|
||||
},
|
||||
expectedResult: {
|
||||
completionText: appliedCompletion || completion,
|
||||
range: cursorPos === tillPos ? undefined : {
|
||||
start: cursorPos,
|
||||
end: tillPos,
|
||||
return {
|
||||
input: {
|
||||
lastLineOfCompletionText: completion,
|
||||
currentText,
|
||||
cursorPosition: cursorPos,
|
||||
},
|
||||
expectedResult: {
|
||||
completionText: appliedCompletion || completion,
|
||||
range:
|
||||
cursorPos === tillPos
|
||||
? undefined
|
||||
: {
|
||||
start: cursorPos,
|
||||
end: tillPos,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,96 +2,94 @@ import { processTestCase } from "./completionTestUtils";
|
|||
import { processSingleLineCompletion } from "./processSingleLineCompletion";
|
||||
|
||||
describe("processSingleLineCompletion", () => {
|
||||
|
||||
it("should handle simple end of line completion", () => {
|
||||
const testCase = processTestCase({
|
||||
original: "console.log(|cur|",
|
||||
completion: "\"Hello, world!\")",
|
||||
});
|
||||
|
||||
const result = processSingleLineCompletion(
|
||||
testCase.input.lastLineOfCompletionText,
|
||||
testCase.input.currentText,
|
||||
testCase.input.cursorPosition
|
||||
);
|
||||
|
||||
expect(result).toEqual(testCase.expectedResult);
|
||||
it("should handle simple end of line completion", () => {
|
||||
const testCase = processTestCase({
|
||||
original: "console.log(|cur|",
|
||||
completion: '"Hello, world!")',
|
||||
});
|
||||
|
||||
it("should handle midline insert repeating the end of line", () => {
|
||||
const testCase = processTestCase({
|
||||
original: "console.log(|cur|);|till|",
|
||||
completion: "\"Hello, world!\");",
|
||||
});
|
||||
const result = processSingleLineCompletion(
|
||||
testCase.input.lastLineOfCompletionText,
|
||||
testCase.input.currentText,
|
||||
testCase.input.cursorPosition,
|
||||
);
|
||||
|
||||
const result = processSingleLineCompletion(
|
||||
testCase.input.lastLineOfCompletionText,
|
||||
testCase.input.currentText,
|
||||
testCase.input.cursorPosition
|
||||
);
|
||||
expect(result).toEqual(testCase.expectedResult);
|
||||
});
|
||||
|
||||
expect(result).toEqual(testCase.expectedResult);
|
||||
it("should handle midline insert repeating the end of line", () => {
|
||||
const testCase = processTestCase({
|
||||
original: "console.log(|cur|);|till|",
|
||||
completion: '"Hello, world!");',
|
||||
});
|
||||
|
||||
it("should handle midline insert repeating the end of line plus adding a semicolon", () => {
|
||||
const testCase = processTestCase({
|
||||
original: "console.log(|cur|)|till|",
|
||||
completion: "\"Hello, world!\");",
|
||||
});
|
||||
const result = processSingleLineCompletion(
|
||||
testCase.input.lastLineOfCompletionText,
|
||||
testCase.input.currentText,
|
||||
testCase.input.cursorPosition,
|
||||
);
|
||||
|
||||
const result = processSingleLineCompletion(
|
||||
testCase.input.lastLineOfCompletionText,
|
||||
testCase.input.currentText,
|
||||
testCase.input.cursorPosition
|
||||
);
|
||||
expect(result).toEqual(testCase.expectedResult);
|
||||
});
|
||||
|
||||
expect(result).toEqual(testCase.expectedResult);
|
||||
it("should handle midline insert repeating the end of line plus adding a semicolon", () => {
|
||||
const testCase = processTestCase({
|
||||
original: "console.log(|cur|)|till|",
|
||||
completion: '"Hello, world!");',
|
||||
});
|
||||
|
||||
it("should handle simple midline insert", () => {
|
||||
const testCase = processTestCase({
|
||||
original: "console.log(|cur|)",
|
||||
completion: "\"Hello, world!\"",
|
||||
});
|
||||
const result = processSingleLineCompletion(
|
||||
testCase.input.lastLineOfCompletionText,
|
||||
testCase.input.currentText,
|
||||
testCase.input.cursorPosition,
|
||||
);
|
||||
|
||||
const result = processSingleLineCompletion(
|
||||
testCase.input.lastLineOfCompletionText,
|
||||
testCase.input.currentText,
|
||||
testCase.input.cursorPosition
|
||||
);
|
||||
expect(result).toEqual(testCase.expectedResult);
|
||||
});
|
||||
|
||||
expect(result).toEqual(testCase.expectedResult);
|
||||
it("should handle simple midline insert", () => {
|
||||
const testCase = processTestCase({
|
||||
original: "console.log(|cur|)",
|
||||
completion: '"Hello, world!"',
|
||||
});
|
||||
|
||||
it("should handle complex dif with addition in the beginning", () => {
|
||||
const testCase = processTestCase({
|
||||
original: "console.log(|cur||till|, \"param1\", )", // TODO
|
||||
completion: "\"Hello world!\", \"param1\", param1);",
|
||||
appliedCompletion: "\"Hello world!\""
|
||||
});
|
||||
const result = processSingleLineCompletion(
|
||||
testCase.input.lastLineOfCompletionText,
|
||||
testCase.input.currentText,
|
||||
testCase.input.cursorPosition,
|
||||
);
|
||||
|
||||
const result = processSingleLineCompletion(
|
||||
testCase.input.lastLineOfCompletionText,
|
||||
testCase.input.currentText,
|
||||
testCase.input.cursorPosition
|
||||
);
|
||||
expect(result).toEqual(testCase.expectedResult);
|
||||
});
|
||||
|
||||
expect(result).toEqual(testCase.expectedResult);
|
||||
it("should handle complex dif with addition in the beginning", () => {
|
||||
const testCase = processTestCase({
|
||||
original: 'console.log(|cur||till|, "param1", )', // TODO
|
||||
completion: '"Hello world!", "param1", param1);',
|
||||
appliedCompletion: '"Hello world!"',
|
||||
});
|
||||
|
||||
it("should handle simple insertion even with random equality", () => {
|
||||
const testCase = processTestCase({
|
||||
original: "print(f\"Foobar length: |cur||till|\")",
|
||||
completion: "{len(foobar)}",
|
||||
});
|
||||
const result = processSingleLineCompletion(
|
||||
testCase.input.lastLineOfCompletionText,
|
||||
testCase.input.currentText,
|
||||
testCase.input.cursorPosition,
|
||||
);
|
||||
|
||||
const result = processSingleLineCompletion(
|
||||
testCase.input.lastLineOfCompletionText,
|
||||
testCase.input.currentText,
|
||||
testCase.input.cursorPosition
|
||||
);
|
||||
expect(result).toEqual(testCase.expectedResult);
|
||||
});
|
||||
|
||||
expect(result).toEqual(testCase.expectedResult);
|
||||
it("should handle simple insertion even with random equality", () => {
|
||||
const testCase = processTestCase({
|
||||
original: 'print(f"Foobar length: |cur||till|")',
|
||||
completion: "{len(foobar)}",
|
||||
});
|
||||
|
||||
const result = processSingleLineCompletion(
|
||||
testCase.input.lastLineOfCompletionText,
|
||||
testCase.input.currentText,
|
||||
testCase.input.cursorPosition,
|
||||
);
|
||||
|
||||
expect(result).toEqual(testCase.expectedResult);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,92 +1,93 @@
|
|||
import * as Diff from "diff";
|
||||
|
||||
interface SingleLineCompletionResult {
|
||||
completionText: string;
|
||||
range?: {
|
||||
start: number;
|
||||
end: number;
|
||||
};
|
||||
completionText: string;
|
||||
range?: {
|
||||
start: number;
|
||||
end: number;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
interface DiffType {
|
||||
count?: number;
|
||||
added?: boolean;
|
||||
removed?: boolean;
|
||||
value: string;
|
||||
count?: number;
|
||||
added?: boolean;
|
||||
removed?: boolean;
|
||||
value: string;
|
||||
}
|
||||
|
||||
|
||||
function diffPatternMatches(
|
||||
diffs: DiffType[],
|
||||
pattern: DiffPartType[],
|
||||
diffs: DiffType[],
|
||||
pattern: DiffPartType[],
|
||||
): boolean {
|
||||
if (diffs.length !== pattern.length) {
|
||||
return false;
|
||||
if (diffs.length !== pattern.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (let i = 0; i < diffs.length; i++) {
|
||||
const diff = diffs[i];
|
||||
const diffPartType: DiffPartType =
|
||||
!diff.added && !diff.removed ? "=" : diff.added ? "+" : "-";
|
||||
|
||||
if (diffPartType !== pattern[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < diffs.length; i++) {
|
||||
const diff = diffs[i];
|
||||
const diffPartType: DiffPartType =
|
||||
!diff.added && !diff.removed ? "=" : diff.added ? "+" : "-";
|
||||
|
||||
if (diffPartType !== pattern[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
return true;
|
||||
}
|
||||
|
||||
type DiffPartType = "+" | "-" | "=";
|
||||
|
||||
export function processSingleLineCompletion(
|
||||
lastLineOfCompletionText: string,
|
||||
currentText: string,
|
||||
cursorPosition: number
|
||||
lastLineOfCompletionText: string,
|
||||
currentText: string,
|
||||
cursorPosition: number,
|
||||
): SingleLineCompletionResult | undefined {
|
||||
const diffs: DiffType[] = Diff.diffWords(currentText, lastLineOfCompletionText);
|
||||
const diffs: DiffType[] = Diff.diffWords(
|
||||
currentText,
|
||||
lastLineOfCompletionText,
|
||||
);
|
||||
|
||||
if (diffPatternMatches(diffs, ["+"])) {
|
||||
// Just insert, we're already at the end of the line
|
||||
return {
|
||||
completionText: lastLineOfCompletionText,
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
diffPatternMatches(diffs, ["+", "="]) ||
|
||||
diffPatternMatches(diffs, ["+", "=", "+"])
|
||||
) {
|
||||
// The model repeated the text after the cursor to the end of the line
|
||||
return {
|
||||
completionText: lastLineOfCompletionText,
|
||||
range: {
|
||||
start: cursorPosition,
|
||||
end: currentText.length + cursorPosition,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
diffPatternMatches(diffs, ["+", "-"]) ||
|
||||
diffPatternMatches(diffs, ["-", "+"])
|
||||
) {
|
||||
// We are midline and the model just inserted without repeating to the end of the line
|
||||
return {
|
||||
completionText: lastLineOfCompletionText,
|
||||
};
|
||||
}
|
||||
|
||||
// For any other diff pattern, just use the first added part if available
|
||||
if (diffs[0]?.added) {
|
||||
return {
|
||||
completionText: diffs[0].value,
|
||||
};
|
||||
}
|
||||
|
||||
// Default case: treat as simple insertion
|
||||
if (diffPatternMatches(diffs, ["+"])) {
|
||||
// Just insert, we're already at the end of the line
|
||||
return {
|
||||
completionText: lastLineOfCompletionText,
|
||||
completionText: lastLineOfCompletionText,
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
diffPatternMatches(diffs, ["+", "="]) ||
|
||||
diffPatternMatches(diffs, ["+", "=", "+"])
|
||||
) {
|
||||
// The model repeated the text after the cursor to the end of the line
|
||||
return {
|
||||
completionText: lastLineOfCompletionText,
|
||||
range: {
|
||||
start: cursorPosition,
|
||||
end: currentText.length + cursorPosition,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
diffPatternMatches(diffs, ["+", "-"]) ||
|
||||
diffPatternMatches(diffs, ["-", "+"])
|
||||
) {
|
||||
// We are midline and the model just inserted without repeating to the end of the line
|
||||
return {
|
||||
completionText: lastLineOfCompletionText,
|
||||
};
|
||||
}
|
||||
|
||||
// For any other diff pattern, just use the first added part if available
|
||||
if (diffs[0]?.added) {
|
||||
return {
|
||||
completionText: diffs[0].value,
|
||||
};
|
||||
}
|
||||
|
||||
// Default case: treat as simple insertion
|
||||
return {
|
||||
completionText: lastLineOfCompletionText,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,14 +19,14 @@ const GenerateTerminalCommand: SlashCommand = {
|
|||
return;
|
||||
}
|
||||
|
||||
const gen =
|
||||
llm.streamComplete(`The user has made a request to run a shell command. Their description of what it should do is:
|
||||
const gen = llm.streamComplete(
|
||||
`The user has made a request to run a shell command. Their description of what it should do is:
|
||||
|
||||
"${input}"
|
||||
|
||||
Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested. Here is the command:`,
|
||||
new AbortController().signal
|
||||
);
|
||||
new AbortController().signal,
|
||||
);
|
||||
|
||||
const lines = streamLines(gen);
|
||||
let cmd = "";
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ class ContinueProxyContextProvider extends BaseContextProvider {
|
|||
this.options.title || ContinueProxyContextProvider.description.title,
|
||||
displayTitle:
|
||||
this.options.displayTitle ||
|
||||
this.options.name ||
|
||||
this.options.name ||
|
||||
ContinueProxyContextProvider.description.displayTitle,
|
||||
description:
|
||||
this.options.description ||
|
||||
|
|
|
|||
|
|
@ -124,10 +124,10 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider {
|
|||
let urlMatches: RegExpExecArray | null;
|
||||
if (/https?.*/.test(remoteUrl)) {
|
||||
const pathname = new URL(remoteUrl).pathname;
|
||||
urlMatches = /\/(?<projectPath>.*?)(?:(?=\.git)|$)/.exec(pathname)
|
||||
urlMatches = /\/(?<projectPath>.*?)(?:(?=\.git)|$)/.exec(pathname);
|
||||
} else {
|
||||
// ssh
|
||||
urlMatches = /:(?<projectPath>.*).git/.exec(remoteUrl)
|
||||
urlMatches = /:(?<projectPath>.*).git/.exec(remoteUrl);
|
||||
}
|
||||
|
||||
const project = urlMatches?.groups?.projectPath ?? null;
|
||||
|
|
|
|||
|
|
@ -20,10 +20,11 @@ class HttpContextProvider extends BaseContextProvider {
|
|||
try {
|
||||
const currentFile = await ide.getCurrentFile();
|
||||
// `isLocalhost` actually also returns true for other local addresses, not just localhost
|
||||
return await isLocalhost(url.hostname) ?
|
||||
(await ide.getWorkspaceDirs()).find(workspaceDirectory => {
|
||||
return currentFile?.path.startsWith(workspaceDirectory)
|
||||
}) : undefined
|
||||
return (await isLocalhost(url.hostname))
|
||||
? (await ide.getWorkspaceDirs()).find((workspaceDirectory) => {
|
||||
return currentFile?.path.startsWith(workspaceDirectory);
|
||||
})
|
||||
: undefined;
|
||||
} catch (e) {
|
||||
return undefined;
|
||||
}
|
||||
|
|
@ -44,12 +45,12 @@ class HttpContextProvider extends BaseContextProvider {
|
|||
HttpContextProvider.description.renderInlineAs,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const parsedUrl = new URL(this.options.url)
|
||||
const parsedUrl = new URL(this.options.url);
|
||||
const response = await extras.fetch(parsedUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ class JiraIssuesContextProvider extends BaseContextProvider {
|
|||
issueQuery: this.options.issueQuery,
|
||||
apiVersion: this.options.apiVersion,
|
||||
requestOptions: this.options.requestOptions,
|
||||
maxResults: this.options.maxResults
|
||||
maxResults: this.options.maxResults,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -85,7 +85,7 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
|
|||
}
|
||||
|
||||
const tokens = this.getCleanedTrigrams(args.query).join(" OR ");
|
||||
|
||||
|
||||
return await this.ftsIndex.retrieve({
|
||||
n,
|
||||
text: tokens,
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ const modelDescriptionSchema = z.object({
|
|||
"nebius",
|
||||
"siliconflow",
|
||||
"scaleway",
|
||||
"watsonx"
|
||||
"watsonx",
|
||||
]),
|
||||
model: z.string(),
|
||||
apiKey: z.string().optional(),
|
||||
|
|
@ -94,7 +94,7 @@ const embeddingsProviderSchema = z.object({
|
|||
"nebius",
|
||||
"siliconflow",
|
||||
"scaleway",
|
||||
"watsonx"
|
||||
"watsonx",
|
||||
]),
|
||||
apiBase: z.string().optional(),
|
||||
apiKey: z.string().optional(),
|
||||
|
|
|
|||
|
|
@ -83,10 +83,13 @@ export async function* getReplacementWithLlm(
|
|||
\`\`\`
|
||||
`;
|
||||
|
||||
const completion = await llm.streamChat([
|
||||
{ role: "user", content: userPrompt },
|
||||
{ role: "assistant", content: assistantPrompt },
|
||||
], new AbortController().signal);
|
||||
const completion = await llm.streamChat(
|
||||
[
|
||||
{ role: "user", content: userPrompt },
|
||||
{ role: "assistant", content: assistantPrompt },
|
||||
],
|
||||
new AbortController().signal,
|
||||
);
|
||||
|
||||
let lines = streamLines(completion);
|
||||
lines = filterLeadingNewline(lines);
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@ describe("isUnifiedDiffFormat", () => {
|
|||
expect(isUnifiedDiffFormat(diffWithoutFileHeaders)).toBe(true);
|
||||
});
|
||||
|
||||
it("should return true in case of empty lines", () => {
|
||||
it("should return true in case of empty lines", () => {
|
||||
const diffWithoutFileHeaders = `@@ -1,3 +1,4 @@
|
||||
line1
|
||||
|
||||
|
|
@ -83,16 +83,25 @@ describe("applyUnifiedDiff", () => {
|
|||
const expected = [
|
||||
{ type: "same", line: "func main() {" },
|
||||
{ type: "same", line: " scanner := bufio.NewScanner(os.Stdin)" },
|
||||
{ type: "same", line: " fmt.Println(\"Calculator started! Available operations:\")" },
|
||||
{ type: "same", line: " fmt.Println(\" + : Addition\")" },
|
||||
{ type: "same", line: " fmt.Println(\" - : Subtraction\")" },
|
||||
{ type: "same", line: " fmt.Println(\" * : Multiplication\")" },
|
||||
{ type: "same", line: " fmt.Println(\" / : Division\")" },
|
||||
{ type: "same", line: " fmt.Println(\" ^ : Power\")" },
|
||||
{ type: "same", line: " fmt.Println(\" √ : Square root (use only one number)\")" },
|
||||
{ type: "new", line: " fmt.Println(\" log: Logarithm (use 'log base number')\")" },
|
||||
{
|
||||
type: "same",
|
||||
line: ' fmt.Println("Calculator started! Available operations:")',
|
||||
},
|
||||
{ type: "same", line: ' fmt.Println(" + : Addition")' },
|
||||
{ type: "same", line: ' fmt.Println(" - : Subtraction")' },
|
||||
{ type: "same", line: ' fmt.Println(" * : Multiplication")' },
|
||||
{ type: "same", line: ' fmt.Println(" / : Division")' },
|
||||
{ type: "same", line: ' fmt.Println(" ^ : Power")' },
|
||||
{
|
||||
type: "same",
|
||||
line: ' fmt.Println(" √ : Square root (use only one number)")',
|
||||
},
|
||||
{
|
||||
type: "new",
|
||||
line: " fmt.Println(\" log: Logarithm (use 'log base number')\")",
|
||||
},
|
||||
{ type: "same", line: "}" },
|
||||
{ type: "same", line: "// End of file" }
|
||||
{ type: "same", line: "// End of file" },
|
||||
];
|
||||
|
||||
expect(result).toEqual(expected);
|
||||
|
|
@ -130,18 +139,18 @@ func main() {
|
|||
const expected = [
|
||||
{ type: "same", line: "package main" },
|
||||
{ type: "same", line: "" },
|
||||
{ type: "old", line: "import \"fmt\"" },
|
||||
{ type: "old", line: 'import "fmt"' },
|
||||
{ type: "new", line: "import (" },
|
||||
{ type: "new", line: " \"fmt\"" },
|
||||
{ type: "new", line: " \"time\"" },
|
||||
{ type: "new", line: ' "fmt"' },
|
||||
{ type: "new", line: ' "time"' },
|
||||
{ type: "new", line: ")" },
|
||||
{ type: "same", line: "" },
|
||||
{ type: "same", line: "func main() {" },
|
||||
{ type: "old", line: " fmt.Println(\"Hello\")" },
|
||||
{ type: "new", line: " fmt.Printf(\"The time is: %v\\n\", time.Now())" },
|
||||
{ type: "old", line: " fmt.Println(\"World\")" },
|
||||
{ type: "new", line: " fmt.Println(\"Goodbye!\")" },
|
||||
{ type: "same", line: "}" }
|
||||
{ type: "old", line: ' fmt.Println("Hello")' },
|
||||
{ type: "new", line: ' fmt.Printf("The time is: %v\\n", time.Now())' },
|
||||
{ type: "old", line: ' fmt.Println("World")' },
|
||||
{ type: "new", line: ' fmt.Println("Goodbye!")' },
|
||||
{ type: "same", line: "}" },
|
||||
];
|
||||
|
||||
expect(result).toEqual(expected);
|
||||
|
|
@ -379,29 +388,47 @@ func TestLargeNumbers(t *testing.T) {
|
|||
|
||||
expect(result[0].line).toEqual("package main");
|
||||
// 1st block
|
||||
expect(result[18].line).toEqual("\tfmt.Println(\" √ : Square root (use only one number)\")");
|
||||
expect(result[19].line).toEqual(" fmt.Println(\" log: Logarithm (use 'log base number')\")");
|
||||
expect(result[20].line).toEqual(" fmt.Println(\" Base must be > 0 and != 1, number must be > 0\")");
|
||||
// 2nd block
|
||||
expect(result[56]).toEqual({type: "same", line: "\t}"});
|
||||
expect(result[57]).toEqual({type: "new", line: "\t"});
|
||||
expect(result[58]).toEqual({type: "new", line: "\t// Handle logarithmic operations"});
|
||||
expect(result[73]).toEqual({type: "new", line: ""});
|
||||
expect(result[74]).toEqual({type: "same", line: "\tif len(parts) != 3 {"});
|
||||
// 3rd block
|
||||
expect(result[140]).toEqual({type: "same", line: "}"});
|
||||
expect(result[141]).toEqual({type: "new", line: ""});
|
||||
expect(result[142]).toEqual({type: "new", line: "func TestLogarithmicCases(t *testing.T) {"});
|
||||
expect(result[153]).toEqual({type: "new", line: "\t}"});
|
||||
expect(result[154]).toEqual({type: "same", line: "func TestSpecialCases(t *testing.T) {"});
|
||||
});
|
||||
expect(result[18].line).toEqual(
|
||||
'\tfmt.Println(" √ : Square root (use only one number)")',
|
||||
);
|
||||
expect(result[19].line).toEqual(
|
||||
" fmt.Println(\" log: Logarithm (use 'log base number')\")",
|
||||
);
|
||||
expect(result[20].line).toEqual(
|
||||
' fmt.Println(" Base must be > 0 and != 1, number must be > 0")',
|
||||
);
|
||||
// 2nd block
|
||||
expect(result[56]).toEqual({ type: "same", line: "\t}" });
|
||||
expect(result[57]).toEqual({ type: "new", line: "\t" });
|
||||
expect(result[58]).toEqual({
|
||||
type: "new",
|
||||
line: "\t// Handle logarithmic operations",
|
||||
});
|
||||
expect(result[73]).toEqual({ type: "new", line: "" });
|
||||
expect(result[74]).toEqual({
|
||||
type: "same",
|
||||
line: "\tif len(parts) != 3 {",
|
||||
});
|
||||
// 3rd block
|
||||
expect(result[140]).toEqual({ type: "same", line: "}" });
|
||||
expect(result[141]).toEqual({ type: "new", line: "" });
|
||||
expect(result[142]).toEqual({
|
||||
type: "new",
|
||||
line: "func TestLogarithmicCases(t *testing.T) {",
|
||||
});
|
||||
expect(result[153]).toEqual({ type: "new", line: "\t}" });
|
||||
expect(result[154]).toEqual({
|
||||
type: "same",
|
||||
line: "func TestSpecialCases(t *testing.T) {",
|
||||
});
|
||||
});
|
||||
|
||||
it("should throw error when hunk cannot be matched to source", () => {
|
||||
const sourceCode = `line1
|
||||
it("should throw error when hunk cannot be matched to source", () => {
|
||||
const sourceCode = `line1
|
||||
line2
|
||||
line3`;
|
||||
|
||||
const diffText = `--- a.txt
|
||||
const diffText = `--- a.txt
|
||||
+++ b.txt
|
||||
@@ -1,3 +1,4 @@
|
||||
missing1
|
||||
|
|
@ -409,7 +436,8 @@ missing1
|
|||
+newline2
|
||||
missing3`;
|
||||
|
||||
expect(() => applyUnifiedDiff(sourceCode, diffText))
|
||||
.toThrow("Hunk could not be applied cleanly to source code.");
|
||||
});
|
||||
expect(() => applyUnifiedDiff(sourceCode, diffText)).toThrow(
|
||||
"Hunk could not be applied cleanly to source code.",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -8,7 +8,9 @@ import { DiffLine } from "../../index";
|
|||
export function isUnifiedDiffFormat(diff: string): boolean {
|
||||
const lines = diff.trim().split("\n");
|
||||
|
||||
if (lines.length < 3) {return false;}
|
||||
if (lines.length < 3) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let hasHunkHeader = false;
|
||||
let hasValidContent = false;
|
||||
|
|
@ -35,10 +37,13 @@ function extractBeforeLines(hunkLines: string[]): string[] {
|
|||
/**
|
||||
* Applies a unified diff to source code and returns an array of DiffLine objects.
|
||||
* Each DiffLine contains a type ("same", "new", or "old") and the line content.
|
||||
*
|
||||
*
|
||||
* @throws Error if the diff cannot be cleanly applied to the source
|
||||
*/
|
||||
export function applyUnifiedDiff(sourceCode: string, unifiedDiffText: string): DiffLine[] {
|
||||
export function applyUnifiedDiff(
|
||||
sourceCode: string,
|
||||
unifiedDiffText: string,
|
||||
): DiffLine[] {
|
||||
const sourceLines = sourceCode.split(/\r?\n/);
|
||||
const hunks = parseUnifiedDiff(unifiedDiffText);
|
||||
const diffResult: DiffLine[] = [];
|
||||
|
|
@ -46,7 +51,11 @@ export function applyUnifiedDiff(sourceCode: string, unifiedDiffText: string): D
|
|||
|
||||
for (const hunk of hunks) {
|
||||
const hunkBeforeLines = extractBeforeLines(hunk.lines);
|
||||
const hunkStart = findHunkInSource(sourceLines, hunkBeforeLines, currentPos);
|
||||
const hunkStart = findHunkInSource(
|
||||
sourceLines,
|
||||
hunkBeforeLines,
|
||||
currentPos,
|
||||
);
|
||||
if (hunkStart === -1) {
|
||||
// All hunks must be found in the source code. If not, throw an error.
|
||||
throw new Error("Hunk could not be applied cleanly to source code.");
|
||||
|
|
@ -124,8 +133,16 @@ function parseUnifiedDiff(diffText: string): Hunk[] {
|
|||
*
|
||||
* Returns the index in sourceLines where the block begins, or -1 if no match is found.
|
||||
*/
|
||||
function findHunkInSource(sourceLines: string[], hunkBeforeLines: string[], startIndex: number): number {
|
||||
for (let i = startIndex; i <= sourceLines.length - hunkBeforeLines.length; i++) {
|
||||
function findHunkInSource(
|
||||
sourceLines: string[],
|
||||
hunkBeforeLines: string[],
|
||||
startIndex: number,
|
||||
): number {
|
||||
for (
|
||||
let i = startIndex;
|
||||
i <= sourceLines.length - hunkBeforeLines.length;
|
||||
i++
|
||||
) {
|
||||
let match = true;
|
||||
for (let j = 0; j < hunkBeforeLines.length; j++) {
|
||||
const sl = sourceLines[i + j];
|
||||
|
|
|
|||
|
|
@ -14,12 +14,14 @@ export async function* basicChunker(
|
|||
let startLine = 0;
|
||||
let currLine = 0;
|
||||
|
||||
const lineTokens = await Promise.all(contents.split("\n").map(async l => {
|
||||
return {
|
||||
line: l,
|
||||
tokenCount: await countTokensAsync(l),
|
||||
};
|
||||
}));
|
||||
const lineTokens = await Promise.all(
|
||||
contents.split("\n").map(async (l) => {
|
||||
return {
|
||||
line: l,
|
||||
tokenCount: await countTokensAsync(l),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
for (const lt of lineTokens) {
|
||||
if (chunkTokens + lt.tokenCount > maxChunkSize - 5) {
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ describe.skip("codeChunker", () => {
|
|||
test("should capture small class and function from large python file", async () => {
|
||||
const extraLine = "# This is a comment";
|
||||
const myClass = "class MyClass:\n def __init__(self):\n pass";
|
||||
const myFunction = "def my_function():\n return \"Hello, World!\"";
|
||||
const myFunction = 'def my_function():\n return "Hello, World!"';
|
||||
|
||||
const file =
|
||||
Array(100).fill(extraLine).join("\n") +
|
||||
|
|
@ -67,7 +67,7 @@ describe.skip("codeChunker", () => {
|
|||
chunks[0].startsWith("class MyClass:\n def method1():\n ..."),
|
||||
).toBe(true);
|
||||
// The extra spaces seem to be a bug with tree-sitter-python
|
||||
expect(chunks).toContain("def method1():\n return \"Hello, 1!\"");
|
||||
expect(chunks).toContain("def method20():\n return \"Hello, 20!\"");
|
||||
expect(chunks).toContain('def method1():\n return "Hello, 1!"');
|
||||
expect(chunks).toContain('def method20():\n return "Hello, 20!"');
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -389,6 +389,5 @@ export {
|
|||
autodetectTemplateType,
|
||||
llmCanGenerateInParallel,
|
||||
modelSupportsImages,
|
||||
modelSupportsTools
|
||||
modelSupportsTools,
|
||||
};
|
||||
|
||||
|
|
|
|||
25
core/llm/llamaTokenizer.d.ts
vendored
25
core/llm/llamaTokenizer.d.ts
vendored
|
|
@ -1,11 +1,20 @@
|
|||
export declare class LlamaTokenizer {
|
||||
vocabById: string[];
|
||||
vocabByString: Map<string, number>;
|
||||
merges: Map<string, number>;
|
||||
constructor(vocab_base64?: string, merges_binary?: string);
|
||||
encode(prompt: string, add_bos_token?: boolean, add_preceding_space?: boolean, log_performance?: boolean): number[];
|
||||
decode(tokenIds: number[], add_bos_token?: boolean, add_preceding_space?: boolean): string;
|
||||
runTests(tests?: (tokenizer: LlamaTokenizer) => boolean): void
|
||||
vocabById: string[];
|
||||
vocabByString: Map<string, number>;
|
||||
merges: Map<string, number>;
|
||||
constructor(vocab_base64?: string, merges_binary?: string);
|
||||
encode(
|
||||
prompt: string,
|
||||
add_bos_token?: boolean,
|
||||
add_preceding_space?: boolean,
|
||||
log_performance?: boolean,
|
||||
): number[];
|
||||
decode(
|
||||
tokenIds: number[],
|
||||
add_bos_token?: boolean,
|
||||
add_preceding_space?: boolean,
|
||||
): string;
|
||||
runTests(tests?: (tokenizer: LlamaTokenizer) => boolean): void;
|
||||
}
|
||||
declare const llamaTokenizer: LlamaTokenizer;
|
||||
export default llamaTokenizer;
|
||||
export default llamaTokenizer;
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
|
|
@ -1,7 +1,12 @@
|
|||
import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime";
|
||||
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
|
||||
import Bedrock from "./Bedrock.js";
|
||||
import { ChatMessage, Chunk, CompletionOptions, UserChatMessage } from "../../index.js";
|
||||
import {
|
||||
ChatMessage,
|
||||
Chunk,
|
||||
CompletionOptions,
|
||||
UserChatMessage,
|
||||
} from "../../index.js";
|
||||
|
||||
// Mock AWS SDK
|
||||
jest.mock("@aws-sdk/client-bedrock-runtime", () => ({
|
||||
|
|
@ -34,7 +39,7 @@ class TestBedrock extends Bedrock {
|
|||
public async *streamChat(
|
||||
messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
options: TestCompletionOptions
|
||||
options: TestCompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
if (options.mockError) {
|
||||
throw new Error(options.mockError);
|
||||
|
|
@ -44,14 +49,16 @@ class TestBedrock extends Bedrock {
|
|||
yield {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [{
|
||||
id: "tool-1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "test_tool",
|
||||
arguments: '{"arg1":"value1"}'
|
||||
}
|
||||
}],
|
||||
toolCalls: [
|
||||
{
|
||||
id: "tool-1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "test_tool",
|
||||
arguments: '{"arg1":"value1"}',
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
|
@ -97,7 +104,9 @@ describe("Bedrock", () => {
|
|||
|
||||
expect(bedrock.region).toBe("us-east-1");
|
||||
expect(bedrock.profile).toBe("bedrock");
|
||||
expect(bedrock.apiBase).toBe("https://bedrock-runtime.us-east-1.amazonaws.com");
|
||||
expect(bedrock.apiBase).toBe(
|
||||
"https://bedrock-runtime.us-east-1.amazonaws.com",
|
||||
);
|
||||
});
|
||||
|
||||
it("should use custom options when provided", () => {
|
||||
|
|
@ -131,14 +140,20 @@ describe("Bedrock", () => {
|
|||
});
|
||||
|
||||
it("should handle text streaming correctly", async () => {
|
||||
const messages: ChatMessage[] = [{
|
||||
role: "user",
|
||||
content: "Hi"
|
||||
} as UserChatMessage];
|
||||
const messages: ChatMessage[] = [
|
||||
{
|
||||
role: "user",
|
||||
content: "Hi",
|
||||
} as UserChatMessage,
|
||||
];
|
||||
|
||||
const results = [];
|
||||
|
||||
for await (const message of bedrock.streamChat(messages, mockAbortSignal, defaultOptions)) {
|
||||
for await (const message of bedrock.streamChat(
|
||||
messages,
|
||||
mockAbortSignal,
|
||||
defaultOptions,
|
||||
)) {
|
||||
results.push(message);
|
||||
}
|
||||
|
||||
|
|
@ -149,18 +164,24 @@ describe("Bedrock", () => {
|
|||
});
|
||||
|
||||
it("should handle tool use streaming correctly", async () => {
|
||||
const messages: ChatMessage[] = [{
|
||||
role: "user",
|
||||
content: "Use a tool"
|
||||
} as UserChatMessage];
|
||||
const messages: ChatMessage[] = [
|
||||
{
|
||||
role: "user",
|
||||
content: "Use a tool",
|
||||
} as UserChatMessage,
|
||||
];
|
||||
|
||||
const results = [];
|
||||
const options: TestCompletionOptions = {
|
||||
...defaultOptions,
|
||||
mockToolUse: true
|
||||
mockToolUse: true,
|
||||
};
|
||||
|
||||
for await (const message of bedrock.streamChat(messages, mockAbortSignal, options)) {
|
||||
for await (const message of bedrock.streamChat(
|
||||
messages,
|
||||
mockAbortSignal,
|
||||
options,
|
||||
)) {
|
||||
results.push(message);
|
||||
}
|
||||
|
||||
|
|
@ -168,31 +189,39 @@ describe("Bedrock", () => {
|
|||
{
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [{
|
||||
id: "tool-1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "test_tool",
|
||||
arguments: '{"arg1":"value1"}'
|
||||
}
|
||||
}],
|
||||
toolCalls: [
|
||||
{
|
||||
id: "tool-1",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "test_tool",
|
||||
arguments: '{"arg1":"value1"}',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle API errors", async () => {
|
||||
const messages: ChatMessage[] = [{
|
||||
role: "user",
|
||||
content: "Hi"
|
||||
} as UserChatMessage];
|
||||
const messages: ChatMessage[] = [
|
||||
{
|
||||
role: "user",
|
||||
content: "Hi",
|
||||
} as UserChatMessage,
|
||||
];
|
||||
|
||||
const options: TestCompletionOptions = {
|
||||
...defaultOptions,
|
||||
mockError: "API Error"
|
||||
mockError: "API Error",
|
||||
};
|
||||
|
||||
await expect(async () => {
|
||||
for await (const _ of bedrock.streamChat(messages, mockAbortSignal, options)) {
|
||||
for await (const _ of bedrock.streamChat(
|
||||
messages,
|
||||
mockAbortSignal,
|
||||
options,
|
||||
)) {
|
||||
// consume generator
|
||||
}
|
||||
}).rejects.toThrow("API Error");
|
||||
|
|
@ -239,7 +268,7 @@ describe("Bedrock", () => {
|
|||
filepath: "file1",
|
||||
index: 0,
|
||||
startLine: 1,
|
||||
endLine: 1
|
||||
endLine: 1,
|
||||
},
|
||||
{
|
||||
content: "doc2",
|
||||
|
|
@ -247,8 +276,8 @@ describe("Bedrock", () => {
|
|||
filepath: "file2",
|
||||
index: 1,
|
||||
startLine: 1,
|
||||
endLine: 1
|
||||
}
|
||||
endLine: 1,
|
||||
},
|
||||
];
|
||||
|
||||
const result = await bedrock.rerank("query", chunks);
|
||||
|
|
@ -262,16 +291,18 @@ describe("Bedrock", () => {
|
|||
filepath: "file1",
|
||||
index: 0,
|
||||
startLine: 1,
|
||||
endLine: 1
|
||||
endLine: 1,
|
||||
};
|
||||
|
||||
await expect(
|
||||
bedrock.rerank("error", [chunk])
|
||||
).rejects.toThrow("Reranking Error");
|
||||
await expect(bedrock.rerank("error", [chunk])).rejects.toThrow(
|
||||
"Reranking Error",
|
||||
);
|
||||
});
|
||||
|
||||
it("should throw error for empty input", async () => {
|
||||
await expect(bedrock.rerank("", [])).rejects.toThrow("Query and chunks must not be empty");
|
||||
await expect(bedrock.rerank("", [])).rejects.toThrow(
|
||||
"Query and chunks must not be empty",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -289,7 +320,7 @@ describe("Bedrock", () => {
|
|||
it("should convert text messages correctly", () => {
|
||||
const message: ChatMessage = {
|
||||
role: "user",
|
||||
content: "Hello"
|
||||
content: "Hello",
|
||||
} as UserChatMessage;
|
||||
const converted = bedrock["_convertMessage"](message);
|
||||
expect(converted).toEqual({
|
||||
|
|
@ -307,12 +338,14 @@ describe("Bedrock", () => {
|
|||
const converted = bedrock["_convertMessage"](message);
|
||||
expect(converted).toEqual({
|
||||
role: "user",
|
||||
content: [{
|
||||
toolResult: {
|
||||
toolUseId: "tool-1",
|
||||
content: [{ text: "Tool result" }],
|
||||
content: [
|
||||
{
|
||||
toolResult: {
|
||||
toolUseId: "tool-1",
|
||||
content: [{ text: "Tool result" }],
|
||||
},
|
||||
},
|
||||
}],
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -320,25 +353,29 @@ describe("Bedrock", () => {
|
|||
const message: ChatMessage = {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: [{
|
||||
id: "tool-1",
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: "test_tool",
|
||||
arguments: '{"arg":"value"}',
|
||||
toolCalls: [
|
||||
{
|
||||
id: "tool-1",
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: "test_tool",
|
||||
arguments: '{"arg":"value"}',
|
||||
},
|
||||
},
|
||||
}],
|
||||
],
|
||||
};
|
||||
const converted = bedrock["_convertMessage"](message);
|
||||
expect(converted).toEqual({
|
||||
role: "assistant",
|
||||
content: [{
|
||||
toolUse: {
|
||||
toolUseId: "tool-1",
|
||||
name: "test_tool",
|
||||
input: { arg: "value" },
|
||||
content: [
|
||||
{
|
||||
toolUse: {
|
||||
toolUseId: "tool-1",
|
||||
name: "test_tool",
|
||||
input: { arg: "value" },
|
||||
},
|
||||
},
|
||||
}],
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -292,9 +292,12 @@ class Bedrock extends BaseLLM {
|
|||
const convertedMessages = this._convertMessages(messages);
|
||||
|
||||
const shouldCacheSystemMessage =
|
||||
!!systemMessage && this.cacheBehavior?.cacheSystemMessage || this.completionOptions.promptCaching;
|
||||
(!!systemMessage && this.cacheBehavior?.cacheSystemMessage) ||
|
||||
this.completionOptions.promptCaching;
|
||||
const enablePromptCaching =
|
||||
shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation || this.completionOptions.promptCaching;
|
||||
shouldCacheSystemMessage ||
|
||||
this.cacheBehavior?.cacheConversation ||
|
||||
this.completionOptions.promptCaching;
|
||||
const shouldCacheToolsConfig = this.completionOptions.promptCaching;
|
||||
|
||||
// Add header for prompt caching
|
||||
|
|
@ -306,21 +309,24 @@ class Bedrock extends BaseLLM {
|
|||
}
|
||||
|
||||
const supportsTools =
|
||||
(this.capabilities?.tools || PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ?? false;
|
||||
(this.capabilities?.tools ||
|
||||
PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ??
|
||||
false;
|
||||
|
||||
let toolConfig = supportsTools && options.tools
|
||||
? {
|
||||
tools: options.tools.map((tool) => ({
|
||||
toolSpec: {
|
||||
name: tool.function.name,
|
||||
description: tool.function.description,
|
||||
inputSchema: {
|
||||
json: tool.function.parameters,
|
||||
},
|
||||
},
|
||||
})),
|
||||
} as ToolConfiguration
|
||||
: undefined;
|
||||
let toolConfig =
|
||||
supportsTools && options.tools
|
||||
? ({
|
||||
tools: options.tools.map((tool) => ({
|
||||
toolSpec: {
|
||||
name: tool.function.name,
|
||||
description: tool.function.description,
|
||||
inputSchema: {
|
||||
json: tool.function.parameters,
|
||||
},
|
||||
},
|
||||
})),
|
||||
} as ToolConfiguration)
|
||||
: undefined;
|
||||
|
||||
if (toolConfig?.tools && shouldCacheToolsConfig) {
|
||||
toolConfig.tools.push({ cachePoint: { type: "default" } });
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import {
|
||||
BedrockRuntimeClient,
|
||||
InvokeModelWithResponseStreamCommand,
|
||||
BedrockRuntimeClient,
|
||||
InvokeModelWithResponseStreamCommand,
|
||||
} from "@aws-sdk/client-bedrock-runtime";
|
||||
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
|
||||
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ class Cerebras extends OpenAI {
|
|||
private static modelConversion: { [key: string]: string } = {
|
||||
"llama3.1-8b": "llama3.1-8b",
|
||||
"llama3.1-70b": "llama3.1-70b",
|
||||
"llama-4-scout-17b-16e-instruct": "llama-4-scout-17b-16e-instruct"
|
||||
"llama-4-scout-17b-16e-instruct": "llama-4-scout-17b-16e-instruct",
|
||||
};
|
||||
protected _convertModelName(model: string): string {
|
||||
return Cerebras.modelConversion[model] ?? model;
|
||||
|
|
|
|||
|
|
@ -38,11 +38,11 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseLLM {
|
|||
const headers: Record<string, string> = {
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
|
||||
|
||||
if (this.apiKey) {
|
||||
headers["Authorization"] = `Bearer ${this.apiKey}`;
|
||||
}
|
||||
|
||||
|
||||
const resp = await this.fetch(new URL("embed", this.apiBase), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
|
|
|
|||
|
|
@ -6,9 +6,9 @@ import OpenAI from "./OpenAI.js";
|
|||
class NCompass extends OpenAI {
|
||||
static providerName = "ncompass";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.ncompass.tech/v1"
|
||||
apiBase: "https://api.ncompass.tech/v1",
|
||||
};
|
||||
static embeddingsApiEndpoint: "https://api.gcp.ncompass.tech/v1/embeddings"
|
||||
static embeddingsApiEndpoint: "https://api.gcp.ncompass.tech/v1/embeddings";
|
||||
|
||||
private static modelConversion: { [key: string]: string } = {
|
||||
"qwen2.5-coder-7b": "Qwen/Qwen2.5-Coder-7B-Instruct",
|
||||
|
|
@ -30,7 +30,12 @@ class NCompass extends OpenAI {
|
|||
}
|
||||
|
||||
protected _getHeaders() {
|
||||
const headers = super._getHeaders() as { "Content-Type": string; Authorization: string; "api-key": string; Accept?: string };
|
||||
const headers = super._getHeaders() as {
|
||||
"Content-Type": string;
|
||||
Authorization: string;
|
||||
"api-key": string;
|
||||
Accept?: string;
|
||||
};
|
||||
headers["Accept"] = "text/event-stream";
|
||||
return headers;
|
||||
}
|
||||
|
|
@ -56,7 +61,6 @@ class NCompass extends OpenAI {
|
|||
const data = (await resp.json()) as any;
|
||||
return data.data.map((result: { embedding: number[] }) => result.embedding);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export default NCompass;
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ class Novita extends OpenAI {
|
|||
|
||||
private static MODEL_IDS: { [name: string]: string } = {
|
||||
"deepseek-r1": "deepseek/deepseek-r1",
|
||||
"deepseek_v3": "deepseek/deepseek_v3",
|
||||
deepseek_v3: "deepseek/deepseek_v3",
|
||||
"llama3-8b": "meta-llama/llama-3-8b-instruct",
|
||||
"llama3-70b": "meta-llama/llama-3-70b-instruct",
|
||||
"llama3.1-8b": "meta-llama/llama-3.1-8b-instruct",
|
||||
|
|
|
|||
|
|
@ -20,20 +20,23 @@ export class OVHcloud extends OpenAI {
|
|||
"mistral-7b": "Mistral-7B-Instruct-v0.3",
|
||||
"mistral-8x7b": "Mixtral-8x7B-Instruct-v0.1",
|
||||
"mistral-nemo": "Mistral-Nemo-Instruct-2407",
|
||||
"DeepSeek-R1-Distill-Llama-70B": "DeepSeek-R1-Distill-Llama-70B"
|
||||
"DeepSeek-R1-Distill-Llama-70B": "DeepSeek-R1-Distill-Llama-70B",
|
||||
};
|
||||
|
||||
protected _convertModelName(model: string) {
|
||||
return OVHcloud.MODEL_IDS[model] || this.model;
|
||||
}
|
||||
|
||||
protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]): ChatCompletionCreateParams {
|
||||
protected _convertArgs(
|
||||
options: CompletionOptions,
|
||||
messages: ChatMessage[],
|
||||
): ChatCompletionCreateParams {
|
||||
const modifiedOptions = {
|
||||
...options,
|
||||
model: this._convertModelName(options.model)
|
||||
model: this._convertModelName(options.model),
|
||||
};
|
||||
return super._convertArgs(modifiedOptions, messages);
|
||||
}
|
||||
}
|
||||
|
||||
export default OVHcloud;
|
||||
export default OVHcloud;
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import {
|
||||
InvokeEndpointCommand,
|
||||
InvokeEndpointWithResponseStreamCommand,
|
||||
SageMakerRuntimeClient,
|
||||
InvokeEndpointCommand,
|
||||
InvokeEndpointWithResponseStreamCommand,
|
||||
SageMakerRuntimeClient,
|
||||
} from "@aws-sdk/client-sagemaker-runtime";
|
||||
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
|
||||
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@ import OpenAI from "./OpenAI";
|
|||
import { LLMOptions, CompletionOptions, ChatMessage } from "../../index.js";
|
||||
import { ChatCompletionCreateParams } from "openai/resources/index";
|
||||
|
||||
|
||||
class Scaleway extends OpenAI {
|
||||
static providerName = "scaleway";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
|
|
@ -17,17 +16,20 @@ class Scaleway extends OpenAI {
|
|||
"llama3.1-70b": "llama-3.1-70b-instruct",
|
||||
"mistral-nemo": "mistral-nemo-instruct-2407",
|
||||
"qwen2.5-coder-32b": "qwen2.5-coder-32b-instruct",
|
||||
"pixtral": "pixtral-12b-2409",
|
||||
pixtral: "pixtral-12b-2409",
|
||||
};
|
||||
|
||||
protected _convertModelName(model: string) {
|
||||
return Scaleway.MODEL_IDS[model] || this.model;
|
||||
}
|
||||
protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]): ChatCompletionCreateParams {
|
||||
protected _convertArgs(
|
||||
options: CompletionOptions,
|
||||
messages: ChatMessage[],
|
||||
): ChatCompletionCreateParams {
|
||||
// Convert model name in the options before passing to parent
|
||||
const modifiedOptions = {
|
||||
...options,
|
||||
model: this._convertModelName(options.model)
|
||||
model: this._convertModelName(options.model),
|
||||
};
|
||||
return super._convertArgs(modifiedOptions, messages);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,14 +9,22 @@ class Venice extends OpenAI {
|
|||
apiBase: "https://api.venice.ai/api/v1",
|
||||
};
|
||||
|
||||
protected _convertArgs(options: CompletionOptions, messages: ChatMessage[]): ChatCompletionCreateParams {
|
||||
const finalOptions = super._convertArgs(options, messages) as ChatCompletionCreateParams & { venice_parameters?: any };
|
||||
if ("venice_parameters" in options && typeof options.venice_parameters === "object") {
|
||||
protected _convertArgs(
|
||||
options: CompletionOptions,
|
||||
messages: ChatMessage[],
|
||||
): ChatCompletionCreateParams {
|
||||
const finalOptions = super._convertArgs(
|
||||
options,
|
||||
messages,
|
||||
) as ChatCompletionCreateParams & { venice_parameters?: any };
|
||||
if (
|
||||
"venice_parameters" in options &&
|
||||
typeof options.venice_parameters === "object"
|
||||
) {
|
||||
finalOptions.venice_parameters = { ...options.venice_parameters };
|
||||
}
|
||||
return finalOptions;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export default Venice;
|
||||
export default Venice;
|
||||
|
|
|
|||
|
|
@ -95,11 +95,11 @@ function llama2TemplateMessages(msgs: ChatMessage[]): string {
|
|||
|
||||
// Llama2 template with added \n to prevent Codestral from continuing user message
|
||||
function codestralTemplateMessages(msgs: ChatMessage[]): string {
|
||||
let template = llama2TemplateMessages(msgs);
|
||||
if (template.length === 0) {
|
||||
return template;
|
||||
}
|
||||
return template + "\n";
|
||||
let template = llama2TemplateMessages(msgs);
|
||||
if (template.length === 0) {
|
||||
return template;
|
||||
}
|
||||
return template + "\n";
|
||||
}
|
||||
|
||||
function anthropicTemplateMessages(messages: ChatMessage[]): string {
|
||||
|
|
|
|||
|
|
@ -115,21 +115,39 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
|
|||
const supportsFn = PROVIDER_TOOL_SUPPORT["bedrock"];
|
||||
|
||||
it("should return true for Claude 3.5 Sonnet models", () => {
|
||||
expect(supportsFn("anthropic.claude-3-5-sonnet-20240620-v1:0")).toBe(true);
|
||||
expect(supportsFn("anthropic.claude-3.5-sonnet-20240620-v1:0")).toBe(true);
|
||||
expect(supportsFn("anthropic.claude-3-5-sonnet-20240620-v1:0")).toBe(
|
||||
true,
|
||||
);
|
||||
expect(supportsFn("anthropic.claude-3.5-sonnet-20240620-v1:0")).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("should return true for Claude 3.7 Sonnet models", () => {
|
||||
expect(supportsFn("anthropic.claude-3-7-sonnet-20240620-v1:0")).toBe(true);
|
||||
expect(supportsFn("anthropic.claude-3.7-sonnet-20240620-v1:0")).toBe(true);
|
||||
expect(supportsFn("anthropic.claude-3-7-sonnet-20240620-v1:0")).toBe(
|
||||
true,
|
||||
);
|
||||
expect(supportsFn("anthropic.claude-3.7-sonnet-20240620-v1:0")).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("should return undefined for Claude Haiku and Opus models", () => {
|
||||
expect(supportsFn("anthropic.claude-3-5-haiku-20240307-v1:0")).toBeUndefined();
|
||||
expect(supportsFn("anthropic.claude-3.5-haiku-20240620-v1:0")).toBeUndefined();
|
||||
expect(supportsFn("anthropic.claude-3-7-haiku-20240620-v1:0")).toBeUndefined();
|
||||
expect(supportsFn("anthropic.claude-3-5-opus-20240620-v1:0")).toBeUndefined();
|
||||
expect(supportsFn("anthropic.claude-3.7-opus-20240620-v1:0")).toBeUndefined();
|
||||
expect(
|
||||
supportsFn("anthropic.claude-3-5-haiku-20240307-v1:0"),
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
supportsFn("anthropic.claude-3.5-haiku-20240620-v1:0"),
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
supportsFn("anthropic.claude-3-7-haiku-20240620-v1:0"),
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
supportsFn("anthropic.claude-3-5-opus-20240620-v1:0"),
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
supportsFn("anthropic.claude-3.7-opus-20240620-v1:0"),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should return undefined for other unsupported models", () => {
|
||||
|
|
@ -138,8 +156,12 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
|
|||
});
|
||||
|
||||
it("should handle case insensitivity", () => {
|
||||
expect(supportsFn("ANTHROPIC.CLAUDE-3-5-SONNET-20240620-v1:0")).toBe(true);
|
||||
expect(supportsFn("ANTHROPIC.CLAUDE-3.7-SONNET-20240620-v1:0")).toBe(true);
|
||||
expect(supportsFn("ANTHROPIC.CLAUDE-3-5-SONNET-20240620-v1:0")).toBe(
|
||||
true,
|
||||
);
|
||||
expect(supportsFn("ANTHROPIC.CLAUDE-3.7-SONNET-20240620-v1:0")).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -25,9 +25,13 @@ export const PROVIDER_TOOL_SUPPORT: Record<
|
|||
},
|
||||
anthropic: (model) => {
|
||||
if (
|
||||
["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7","claude-sonnet-4"].some((part) =>
|
||||
model.toLowerCase().startsWith(part),
|
||||
)
|
||||
[
|
||||
"claude-3-5",
|
||||
"claude-3.5",
|
||||
"claude-3-7",
|
||||
"claude-3.7",
|
||||
"claude-sonnet-4",
|
||||
].some((part) => model.toLowerCase().startsWith(part))
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
|
@ -77,9 +81,13 @@ export const PROVIDER_TOOL_SUPPORT: Record<
|
|||
// For Bedrock, only support Claude Sonnet models with versions 3.5/3-5 and 3.7/3-7
|
||||
if (
|
||||
model.toLowerCase().includes("sonnet") &&
|
||||
["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7","claude-sonnet-4"].some((part) =>
|
||||
model.toLowerCase().includes(part),
|
||||
)
|
||||
[
|
||||
"claude-3-5",
|
||||
"claude-3.5",
|
||||
"claude-3-7",
|
||||
"claude-3.7",
|
||||
"claude-sonnet-4",
|
||||
].some((part) => model.toLowerCase().includes(part))
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,13 +1,13 @@
|
|||
import { getSecureID } from '../getSecureID';
|
||||
import { getSecureID } from "../getSecureID";
|
||||
|
||||
// Mock the crypto.randomUUID function
|
||||
const mockRandomUUID = jest.fn();
|
||||
global.crypto = {
|
||||
...global.crypto,
|
||||
randomUUID: mockRandomUUID
|
||||
randomUUID: mockRandomUUID,
|
||||
};
|
||||
|
||||
describe('getSecureID', () => {
|
||||
describe("getSecureID", () => {
|
||||
beforeEach(() => {
|
||||
// Reset the static property before each test
|
||||
(getSecureID as any).uuid = undefined;
|
||||
|
|
@ -15,16 +15,16 @@ describe('getSecureID', () => {
|
|||
// Reset the mock implementation
|
||||
mockRandomUUID.mockReset();
|
||||
// Setup a mock implementation that returns a fixed value for testing
|
||||
mockRandomUUID.mockReturnValue('test-uuid-1234');
|
||||
mockRandomUUID.mockReturnValue("test-uuid-1234");
|
||||
});
|
||||
|
||||
test('should generate a UUID on first call', () => {
|
||||
test("should generate a UUID on first call", () => {
|
||||
const result = getSecureID();
|
||||
expect(mockRandomUUID).toHaveBeenCalledTimes(1);
|
||||
expect(result).toBe('<!-- SID: test-uuid-1234 -->');
|
||||
expect(result).toBe("<!-- SID: test-uuid-1234 -->");
|
||||
});
|
||||
|
||||
test('should reuse the same UUID on subsequent calls', () => {
|
||||
test("should reuse the same UUID on subsequent calls", () => {
|
||||
const firstResult = getSecureID();
|
||||
const secondResult = getSecureID();
|
||||
|
||||
|
|
@ -33,17 +33,17 @@ describe('getSecureID', () => {
|
|||
|
||||
// Both results should be identical
|
||||
expect(firstResult).toBe(secondResult);
|
||||
expect(firstResult).toBe('<!-- SID: test-uuid-1234 -->');
|
||||
expect(firstResult).toBe("<!-- SID: test-uuid-1234 -->");
|
||||
});
|
||||
|
||||
test('should maintain the same UUID across different test cases if not reset', () => {
|
||||
test("should maintain the same UUID across different test cases if not reset", () => {
|
||||
// Don't reset the UUID here to test persistence
|
||||
(getSecureID as any).uuid = 'persistent-uuid';
|
||||
(getSecureID as any).uuid = "persistent-uuid";
|
||||
|
||||
const result = getSecureID();
|
||||
|
||||
// No new UUID should be generated
|
||||
expect(mockRandomUUID).not.toHaveBeenCalled();
|
||||
expect(result).toBe('<!-- SID: persistent-uuid -->');
|
||||
expect(result).toBe("<!-- SID: persistent-uuid -->");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ describe("extractPathsFromCodeBlocks", () => {
|
|||
});
|
||||
|
||||
it("should handle multiple code blocks with different formats", () => {
|
||||
const content =
|
||||
const content =
|
||||
"```typescript src/main.ts\nconst x = 1;\n```\n" +
|
||||
"```test.js\nclass Calculator { }\n```\n" +
|
||||
"```js utils.js (19-25)\nfunction test() {}\n```";
|
||||
|
|
@ -32,4 +32,4 @@ describe("extractPathsFromCodeBlocks", () => {
|
|||
const content = "```typescript\nconst x = 1;\n```";
|
||||
expect(extractPathsFromCodeBlocks(content)).toEqual([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -17,21 +17,21 @@ export const runTerminalCommandTool: Tool = {
|
|||
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.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["command"],
|
||||
properties: {
|
||||
command: {
|
||||
type: "string",
|
||||
description:
|
||||
"The command to run. This will be passed directly into the IDE shell.",
|
||||
},
|
||||
waitForCompletion: {
|
||||
type: "boolean",
|
||||
description:
|
||||
"Whether to wait for the command to complete before returning. Default is true. Set to false to run the command in the background. Set to true to run the command in the foreground and wait to collect the output.",
|
||||
},
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["command"],
|
||||
properties: {
|
||||
command: {
|
||||
type: "string",
|
||||
description:
|
||||
"The command to run. This will be passed directly into the IDE shell.",
|
||||
},
|
||||
waitForCompletion: {
|
||||
type: "boolean",
|
||||
description:
|
||||
"Whether to wait for the command to complete before returning. Default is true. Set to false to run the command in the background. Set to true to run the command in the foreground and wait to collect the output.",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -17,26 +17,31 @@ describe("runTerminalCommandImpl", () => {
|
|||
const mockGetWorkspaceDirs = jest.fn();
|
||||
const mockOnPartialOutput = jest.fn();
|
||||
const mockRunCommand = jest.fn();
|
||||
|
||||
|
||||
// Use a simple approach to ensure background processes are terminated
|
||||
let testPid: number | null = null;
|
||||
|
||||
|
||||
// Create a temp directory for our tests
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'terminal-command-test-'));
|
||||
const tempDir = fs.mkdtempSync(
|
||||
path.join(os.tmpdir(), "terminal-command-test-"),
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks();
|
||||
|
||||
|
||||
// Setup backgrounded processes handling - don't mock, just make sure it's empty
|
||||
// Get any processes that might be already tracked and clear them
|
||||
const processMap = (processBackgroundStates as any).processTerminalBackgroundStates;
|
||||
if (processMap && typeof processMap.clear === 'function') {
|
||||
const processMap = (processBackgroundStates as any)
|
||||
.processTerminalBackgroundStates;
|
||||
if (processMap && typeof processMap.clear === "function") {
|
||||
processMap.clear();
|
||||
}
|
||||
|
||||
|
||||
// Setup IDE mocks
|
||||
mockGetIdeInfo.mockReturnValue(Promise.resolve({ remoteName: "local" }));
|
||||
mockGetWorkspaceDirs.mockReturnValue(Promise.resolve([`file://${tempDir}`]));
|
||||
mockGetWorkspaceDirs.mockReturnValue(
|
||||
Promise.resolve([`file://${tempDir}`]),
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
|
|
@ -44,9 +49,11 @@ describe("runTerminalCommandImpl", () => {
|
|||
if (testPid !== null) {
|
||||
try {
|
||||
// Platform-independent way to kill a process
|
||||
if (process.platform === 'win32') {
|
||||
await new Promise(resolve => {
|
||||
childProcess.exec(`taskkill /F /PID ${testPid}`, () => resolve(null));
|
||||
if (process.platform === "win32") {
|
||||
await new Promise((resolve) => {
|
||||
childProcess.exec(`taskkill /F /PID ${testPid}`, () =>
|
||||
resolve(null),
|
||||
);
|
||||
});
|
||||
} else {
|
||||
process.kill(testPid);
|
||||
|
|
@ -57,20 +64,24 @@ describe("runTerminalCommandImpl", () => {
|
|||
testPid = null;
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
afterAll(() => {
|
||||
// Clean up the temp directory after tests
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
// Helper function to create a ToolExtras object
|
||||
const createMockExtras = (overrides: Partial<{
|
||||
onPartialOutput?: jest.Mock;
|
||||
remoteName?: string;
|
||||
}> = {}): ToolExtras => {
|
||||
const createMockExtras = (
|
||||
overrides: Partial<{
|
||||
onPartialOutput?: jest.Mock;
|
||||
remoteName?: string;
|
||||
}> = {},
|
||||
): ToolExtras => {
|
||||
// Update IDE info if remoteName is provided
|
||||
if (overrides.remoteName) {
|
||||
mockGetIdeInfo.mockReturnValue(Promise.resolve({ remoteName: overrides.remoteName }));
|
||||
mockGetIdeInfo.mockReturnValue(
|
||||
Promise.resolve({ remoteName: overrides.remoteName }),
|
||||
);
|
||||
}
|
||||
|
||||
// Create a minimally compliant IDE mock
|
||||
|
|
@ -97,7 +108,7 @@ describe("runTerminalCommandImpl", () => {
|
|||
llm: {} as any,
|
||||
fetch: {} as any,
|
||||
tool: {} as any,
|
||||
toolCallId: "test-tool-call"
|
||||
toolCallId: "test-tool-call",
|
||||
} as ToolExtras;
|
||||
|
||||
// Apply overrides
|
||||
|
|
@ -115,7 +126,7 @@ describe("runTerminalCommandImpl", () => {
|
|||
const extras = createMockExtras();
|
||||
|
||||
const result = await runTerminalCommandImpl(args, extras);
|
||||
|
||||
|
||||
// Verify real command output
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].name).toBe("Terminal");
|
||||
|
|
@ -134,27 +145,27 @@ describe("runTerminalCommandImpl", () => {
|
|||
console.error('error output');
|
||||
}, 50);
|
||||
"`;
|
||||
|
||||
|
||||
const args = { command, waitForCompletion: true };
|
||||
const mockOutputFn = jest.fn();
|
||||
const extras = createMockExtras({ onPartialOutput: mockOutputFn });
|
||||
|
||||
// Execute the command with streaming
|
||||
const result = await runTerminalCommandImpl(args, extras);
|
||||
|
||||
|
||||
// Verify onPartialOutput was called with increasing content
|
||||
expect(mockOutputFn).toHaveBeenCalled();
|
||||
|
||||
|
||||
// Verify final result has all output
|
||||
expect(result[0].content).toContain('first output');
|
||||
expect(result[0].content).toContain('second output');
|
||||
expect(result[0].content).toContain('error output');
|
||||
expect(result[0].content).toContain("first output");
|
||||
expect(result[0].content).toContain("second output");
|
||||
expect(result[0].content).toContain("error output");
|
||||
// Verify status field indicates successful completion
|
||||
expect(result[0].status).toBe("Command completed");
|
||||
|
||||
|
||||
// Verify that initial streaming updates have empty status for regular commands
|
||||
const firstCall = mockOutputFn.mock.calls[0][0];
|
||||
if (firstCall && typeof firstCall === 'object') {
|
||||
if (firstCall && typeof firstCall === "object") {
|
||||
const contextItems = (firstCall as any).contextItems;
|
||||
if (contextItems && Array.isArray(contextItems) && contextItems[0]) {
|
||||
// For commands with waitForCompletion=true, status should be empty while streaming
|
||||
|
|
@ -166,8 +177,8 @@ describe("runTerminalCommandImpl", () => {
|
|||
it("should run commands in background when waitForCompletion is false", async () => {
|
||||
// Create a self-identifying background process that writes its PID
|
||||
// to a file we can access to kill it later
|
||||
const pidFile = path.join(tempDir, 'test-pid.txt');
|
||||
|
||||
const pidFile = path.join(tempDir, "test-pid.txt");
|
||||
|
||||
// This script creates a long-running process and writes its PID to our file
|
||||
// Using a fixed duration timeout so we can be sure to clean it up
|
||||
const command = `node -e "
|
||||
|
|
@ -178,59 +189,66 @@ describe("runTerminalCommandImpl", () => {
|
|||
console.log('background process completed');
|
||||
}, 500);
|
||||
"`;
|
||||
|
||||
|
||||
const args = { command, waitForCompletion: false };
|
||||
const mockOutputFn = jest.fn();
|
||||
const extras = createMockExtras({ onPartialOutput: mockOutputFn });
|
||||
|
||||
const result = await runTerminalCommandImpl(args, extras);
|
||||
|
||||
|
||||
// Result should indicate background running in either content or status
|
||||
expect(result[0].content || result[0].status).toContain("running in the background");
|
||||
expect(result[0].content || result[0].status).toContain(
|
||||
"running in the background",
|
||||
);
|
||||
// Verify status field indicates background running
|
||||
expect(result[0].status).toBe("Command is running in the background...");
|
||||
|
||||
|
||||
// Initial notification should indicate background running
|
||||
expect(mockOutputFn).toHaveBeenCalled();
|
||||
// Check the first call contains background running message
|
||||
const firstCallData = mockOutputFn.mock.calls[0][0];
|
||||
if (firstCallData && typeof firstCallData === 'object') {
|
||||
if (firstCallData && typeof firstCallData === "object") {
|
||||
const contextItems = (firstCallData as any).contextItems;
|
||||
if (contextItems && Array.isArray(contextItems) && contextItems[0]) {
|
||||
expect(contextItems[0].content).toContain("");
|
||||
expect(contextItems[0].status).toMatch(/Command is running in the background.../);
|
||||
expect(contextItems[0].status).toMatch(
|
||||
/Command is running in the background.../,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Wait a bit to make sure the PID file is written
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
// Read the PID file to get the process ID so we can kill it later
|
||||
if (fs.existsSync(pidFile)) {
|
||||
testPid = Number(fs.readFileSync(pidFile, 'utf-8'));
|
||||
testPid = Number(fs.readFileSync(pidFile, "utf-8"));
|
||||
}
|
||||
|
||||
|
||||
// Wait a bit longer for the process to complete and onPartialOutput to be called again
|
||||
await new Promise(resolve => setTimeout(resolve, 400));
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 400));
|
||||
|
||||
// Check for background process completion message in mockOutputFn calls
|
||||
// Note: This is optional and depends on timing, so we don't want to strictly enforce it
|
||||
let foundCompletionMessage = false;
|
||||
|
||||
|
||||
for (let i = 0; i < mockOutputFn.mock.calls.length; i++) {
|
||||
const call = mockOutputFn.mock.calls[i][0];
|
||||
if (call && typeof call === 'object') {
|
||||
if (call && typeof call === "object") {
|
||||
const contextItems = (call as any).contextItems;
|
||||
if (contextItems && Array.isArray(contextItems) && contextItems[0]) {
|
||||
if (contextItems[0].status === "\nBackground command completed" ||
|
||||
(contextItems[0].status && contextItems[0].status.includes("Background command"))) {
|
||||
if (
|
||||
contextItems[0].status === "\nBackground command completed" ||
|
||||
(contextItems[0].status &&
|
||||
contextItems[0].status.includes("Background command"))
|
||||
) {
|
||||
foundCompletionMessage = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// If we found any completion message in the output, great!
|
||||
// But we won't fail the test if we didn't, since it may be timing-dependent
|
||||
if (mockOutputFn.mock.calls.length > 1) {
|
||||
|
|
@ -244,7 +262,7 @@ describe("runTerminalCommandImpl", () => {
|
|||
const extras = createMockExtras({ remoteName: "ssh" });
|
||||
|
||||
const result = await runTerminalCommandImpl(args, extras);
|
||||
|
||||
|
||||
// In remote environments, it should use the IDE's runCommand
|
||||
expect(mockRunCommand).toHaveBeenCalledWith("echo 'test'");
|
||||
// Match the actual output message
|
||||
|
|
@ -256,23 +274,26 @@ describe("runTerminalCommandImpl", () => {
|
|||
|
||||
it("should handle errors when executing invalid commands", async () => {
|
||||
// Use a command that should fail on any platform
|
||||
const args = { command: "non-existent-command-xyz", waitForCompletion: true };
|
||||
const args = {
|
||||
command: "non-existent-command-xyz",
|
||||
waitForCompletion: true,
|
||||
};
|
||||
const extras = createMockExtras();
|
||||
|
||||
const result = await runTerminalCommandImpl(args, extras);
|
||||
|
||||
|
||||
expect(result[0].name).toBe("Terminal");
|
||||
expect(result[0].description).toBe("Terminal command output");
|
||||
|
||||
|
||||
// The exact error message varies by platform, but should contain error information
|
||||
const errorContent = result[0].content;
|
||||
expect(
|
||||
errorContent.includes("Command failed") ||
|
||||
errorContent.includes("not found") ||
|
||||
errorContent.includes("recognized") ||
|
||||
/error/i.test(errorContent)
|
||||
errorContent.includes("Command failed") ||
|
||||
errorContent.includes("not found") ||
|
||||
errorContent.includes("recognized") ||
|
||||
/error/i.test(errorContent),
|
||||
).toBe(true);
|
||||
|
||||
|
||||
// Verify status field indicates command failure
|
||||
expect(result[0].status).toContain("Command failed with:");
|
||||
});
|
||||
|
|
@ -284,23 +305,23 @@ describe("runTerminalCommandImpl", () => {
|
|||
const extras = createMockExtras();
|
||||
|
||||
const result = await runTerminalCommandImpl(args, extras);
|
||||
|
||||
|
||||
// Verify we still get a result with a name and description
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].name).toBe("Terminal");
|
||||
expect(result[0].description).toBe("Terminal command output");
|
||||
|
||||
|
||||
// The command should have executed and returned content
|
||||
expect(result[0].content).toBeDefined();
|
||||
|
||||
|
||||
// We should see the error message we wrote to stderr
|
||||
expect(result[0].content).toContain("This is an error message");
|
||||
|
||||
|
||||
// Verify status field indicates command failure - the exact message format can vary
|
||||
// between different node versions and platforms
|
||||
expect(result[0].status).toContain("Command failed");
|
||||
});
|
||||
|
||||
|
||||
it("should set appropriate status when a command completes successfully", async () => {
|
||||
// Use a simple command that will succeed
|
||||
const command = `node -e "console.log('success test')"`;
|
||||
|
|
@ -308,14 +329,14 @@ describe("runTerminalCommandImpl", () => {
|
|||
const extras = createMockExtras();
|
||||
|
||||
const result = await runTerminalCommandImpl(args, extras);
|
||||
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].name).toBe("Terminal");
|
||||
expect(result[0].content).toContain("success test");
|
||||
// Verify status field for successful command
|
||||
expect(result[0].status).toBe("Command completed");
|
||||
});
|
||||
|
||||
|
||||
it("should include status info for background commands in non-streaming mode", async () => {
|
||||
// Use a simple background command
|
||||
const command = `node -e "setTimeout(() => console.log('done'), 300)"`;
|
||||
|
|
@ -324,7 +345,7 @@ describe("runTerminalCommandImpl", () => {
|
|||
const extras = createMockExtras();
|
||||
|
||||
const result = await runTerminalCommandImpl(args, extras);
|
||||
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0].name).toBe("Terminal");
|
||||
// Verify both content and status fields for background commands
|
||||
|
|
|
|||
|
|
@ -3,7 +3,10 @@ import util from "node:util";
|
|||
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { ToolImpl } from ".";
|
||||
import { isProcessBackgrounded, removeBackgroundedProcess } from "../../util/processTerminalBackgroundStates";
|
||||
import {
|
||||
isProcessBackgrounded,
|
||||
removeBackgroundedProcess,
|
||||
} from "../../util/processTerminalBackgroundStates";
|
||||
|
||||
const asyncExec = util.promisify(childProcess.exec);
|
||||
|
||||
|
|
@ -56,7 +59,9 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
|
||||
// Send partial output to UI
|
||||
if (extras.onPartialOutput) {
|
||||
const status = waitForCompletion ? "" : "Command is running in the background...";
|
||||
const status = waitForCompletion
|
||||
? ""
|
||||
: "Command is running in the background...";
|
||||
extras.onPartialOutput({
|
||||
toolCallId,
|
||||
contextItems: [
|
||||
|
|
@ -116,9 +121,10 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
if (!waitForCompletion) {
|
||||
// Already resolved, just update the UI with final output
|
||||
if (extras.onPartialOutput) {
|
||||
const status = (code === 0 || !code
|
||||
? "\nBackground command completed"
|
||||
: `\nBackground command failed with exit code ${code}`)
|
||||
const status =
|
||||
code === 0 || !code
|
||||
? "\nBackground command completed"
|
||||
: `\nBackground command failed with exit code ${code}`;
|
||||
extras.onPartialOutput({
|
||||
toolCallId,
|
||||
contextItems: [
|
||||
|
|
@ -140,7 +146,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
name: "Terminal",
|
||||
description: "Terminal command output",
|
||||
content: terminalOutput,
|
||||
status: status
|
||||
status: status,
|
||||
},
|
||||
]);
|
||||
} else {
|
||||
|
|
@ -149,9 +155,8 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
{
|
||||
name: "Terminal",
|
||||
description: "Terminal command output",
|
||||
content:
|
||||
terminalOutput,
|
||||
status: status,
|
||||
content: terminalOutput,
|
||||
status: status,
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
|
@ -191,7 +196,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
// Detach the process so it's not tied to the parent
|
||||
detached: true,
|
||||
// Redirect to /dev/null equivalent (works cross-platform)
|
||||
stdio: 'ignore',
|
||||
stdio: "ignore",
|
||||
});
|
||||
|
||||
// Even for detached processes, add event handlers to clean up the background process map
|
||||
|
|
@ -225,7 +230,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
name: "Terminal",
|
||||
description: "Terminal command output",
|
||||
content: status,
|
||||
status: status
|
||||
status: status,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
|
@ -269,4 +274,4 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
status: "Command failed",
|
||||
},
|
||||
];
|
||||
}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
|
||||
/**
|
||||
* Recursively retrieves the root cause of an error by traversing through its `cause` property.
|
||||
*
|
||||
|
|
@ -6,8 +5,8 @@
|
|||
* @returns The root cause of the error, or the original error if no further cause is found.
|
||||
*/
|
||||
export function getRootCause(err: any): any {
|
||||
if (err.cause) {
|
||||
return getRootCause(err.cause);
|
||||
}
|
||||
return err;
|
||||
}
|
||||
if (err.cause) {
|
||||
return getRootCause(err.cause);
|
||||
}
|
||||
return err;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ export async function findFaviconPath(url: URL): Promise<string | undefined> {
|
|||
const document = dom.window.document;
|
||||
|
||||
// Look for favicon in <link> tags
|
||||
const linkTags = document.querySelectorAll("link[rel*=\"icon\"]");
|
||||
const linkTags = document.querySelectorAll('link[rel*="icon"]');
|
||||
|
||||
for (const link of linkTags) {
|
||||
const href = link.getAttribute("href");
|
||||
|
|
|
|||
|
|
@ -74,7 +74,7 @@ export function getMarkdownLanguageTagForFile(filepath: string): string {
|
|||
tsx: "tsx",
|
||||
ts: "typescript",
|
||||
java: "java",
|
||||
class:"java", //.class files decompile to Java
|
||||
class: "java", //.class files decompile to Java
|
||||
go: "go",
|
||||
rb: "ruby",
|
||||
rs: "rust",
|
||||
|
|
@ -101,8 +101,7 @@ export function getMarkdownLanguageTagForFile(filepath: string): string {
|
|||
return ext ? (extToLangMap[ext] ?? ext) : "";
|
||||
}
|
||||
|
||||
|
||||
function sanitizeExtension(ext?: string): string|undefined {
|
||||
function sanitizeExtension(ext?: string): string | undefined {
|
||||
if (ext) {
|
||||
//ignore ranges in extension eg. "java (11-23)"
|
||||
const match = ext.match(/^(\S+)\s*(\(.*\))?$/);
|
||||
|
|
@ -208,6 +207,6 @@ export function removeCodeBlocksAndTrim(text: string): string {
|
|||
export function splitCamelCaseAndNonAlphaNumeric(value: string) {
|
||||
return value
|
||||
.split(/(?<=[a-z0-9])(?=[A-Z])|[^a-zA-Z0-9]/)
|
||||
.filter(t => t.length > 0)
|
||||
.map(t => t.toLowerCase());
|
||||
.filter((t) => t.length > 0)
|
||||
.map((t) => t.toLowerCase());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ describe("mergeJson", () => {
|
|||
expect(result).toEqual({ a: 1, b: 3, c: 4 });
|
||||
});
|
||||
|
||||
it("should overwrite values when mergeBehavior is \"overwrite\"", () => {
|
||||
it('should overwrite values when mergeBehavior is "overwrite"', () => {
|
||||
const first = { a: 1, b: 2 };
|
||||
const second = { b: 3, c: 4 };
|
||||
const result = mergeJson(first, second, "overwrite");
|
||||
|
|
|
|||
|
|
@ -1,5 +1,15 @@
|
|||
import { stripImages, renderChatMessage, renderContextItems, normalizeToMessageParts } from "./messageContent.js";
|
||||
import { ChatMessage, ContextItem, MessageContent, MessagePart } from "../index.js";
|
||||
import {
|
||||
stripImages,
|
||||
renderChatMessage,
|
||||
renderContextItems,
|
||||
normalizeToMessageParts,
|
||||
} from "./messageContent.js";
|
||||
import {
|
||||
ChatMessage,
|
||||
ContextItem,
|
||||
MessageContent,
|
||||
MessagePart,
|
||||
} from "../index.js";
|
||||
|
||||
describe("messageContent utility functions", () => {
|
||||
describe("stripImages", () => {
|
||||
|
|
@ -11,7 +21,10 @@ describe("messageContent utility functions", () => {
|
|||
it("should strip out image parts and join text parts of a message", () => {
|
||||
const content: MessageContent = [
|
||||
{ type: "text", text: "This is" },
|
||||
{ type: "imageUrl", imageUrl: { url: "http://example.com/image1.png" } },
|
||||
{
|
||||
type: "imageUrl",
|
||||
imageUrl: { url: "http://example.com/image1.png" },
|
||||
},
|
||||
{ type: "text", text: "a test message." },
|
||||
];
|
||||
expect(stripImages(content)).toBe("This is\na test message.");
|
||||
|
|
@ -24,7 +37,10 @@ describe("messageContent utility functions", () => {
|
|||
role: "assistant",
|
||||
content: [
|
||||
{ type: "text", text: "Hello," },
|
||||
{ type: "imageUrl", imageUrl: { url: "http://example.com/image.png" } },
|
||||
{
|
||||
type: "imageUrl",
|
||||
imageUrl: { url: "http://example.com/image.png" },
|
||||
},
|
||||
{ type: "text", text: "world!" },
|
||||
],
|
||||
};
|
||||
|
|
@ -44,10 +60,20 @@ describe("messageContent utility functions", () => {
|
|||
describe("renderContextItems", () => {
|
||||
it("should concatenate the content of context items with two newlines", () => {
|
||||
const items: ContextItem[] = [
|
||||
{ content: "Context Item 1", name: "Item1", description: "Description1" },
|
||||
{ content: "Context Item 2", name: "Item2", description: "Description2" },
|
||||
{
|
||||
content: "Context Item 1",
|
||||
name: "Item1",
|
||||
description: "Description1",
|
||||
},
|
||||
{
|
||||
content: "Context Item 2",
|
||||
name: "Item2",
|
||||
description: "Description2",
|
||||
},
|
||||
];
|
||||
expect(renderContextItems(items)).toBe("Context Item 1\n\nContext Item 2");
|
||||
expect(renderContextItems(items)).toBe(
|
||||
"Context Item 1\n\nContext Item 2",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -57,7 +83,9 @@ describe("messageContent utility functions", () => {
|
|||
role: "user",
|
||||
content: "This is a test message.",
|
||||
};
|
||||
const expected: MessagePart[] = [{ type: "text", text: "This is a test message." }];
|
||||
const expected: MessagePart[] = [
|
||||
{ type: "text", text: "This is a test message." },
|
||||
];
|
||||
expect(normalizeToMessageParts(message)).toEqual(expected);
|
||||
});
|
||||
|
||||
|
|
@ -67,8 +95,10 @@ describe("messageContent utility functions", () => {
|
|||
content: "Tool message content",
|
||||
toolCallId: "1",
|
||||
};
|
||||
const expected: MessagePart[] = [{ type: "text", text: "Tool message content" }];
|
||||
const expected: MessagePart[] = [
|
||||
{ type: "text", text: "Tool message content" },
|
||||
];
|
||||
expect(normalizeToMessageParts(message)).toEqual(expected);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -4,96 +4,100 @@ import path from "node:path";
|
|||
import { IDE } from "..";
|
||||
|
||||
export interface ModelInfo {
|
||||
id: string;
|
||||
size: number;
|
||||
digest: string;
|
||||
id: string;
|
||||
size: number;
|
||||
digest: string;
|
||||
}
|
||||
|
||||
export async function isOllamaInstalled(): Promise<boolean> {
|
||||
return new Promise((resolve, _reject) => {
|
||||
const command = process.platform === "win32" ? "where.exe ollama" : "which ollama";
|
||||
exec(command, (error, _stdout, _stderr) => {
|
||||
resolve(!error);
|
||||
});
|
||||
return new Promise((resolve, _reject) => {
|
||||
const command =
|
||||
process.platform === "win32" ? "where.exe ollama" : "which ollama";
|
||||
exec(command, (error, _stdout, _stderr) => {
|
||||
resolve(!error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function startLocalOllama(ide: IDE): Promise<any> {
|
||||
let startCommand: string | undefined;
|
||||
let startCommand: string | undefined;
|
||||
|
||||
switch (process.platform) {
|
||||
case "darwin"://MacOS
|
||||
startCommand = "open -a Ollama.app\n";
|
||||
break;
|
||||
switch (process.platform) {
|
||||
case "darwin": //MacOS
|
||||
startCommand = "open -a Ollama.app\n";
|
||||
break;
|
||||
|
||||
case "win32"://Windows
|
||||
startCommand = "& \"ollama app.exe\"\n";
|
||||
break;
|
||||
case "win32": //Windows
|
||||
startCommand = '& "ollama app.exe"\n';
|
||||
break;
|
||||
|
||||
default: //Linux...
|
||||
const start_script_path = path.resolve(__dirname, "./start_ollama.sh");
|
||||
if (await ide.fileExists(`file:/${start_script_path}`)) {
|
||||
startCommand = `set -e && chmod +x ${start_script_path} && ${start_script_path}\n`;
|
||||
console.log(`Ollama Linux startup script at : ${start_script_path}`);
|
||||
} else {
|
||||
return ide.showToast("error", `Cannot start Ollama: could not find ${start_script_path}!`)
|
||||
}
|
||||
}
|
||||
if (startCommand) {
|
||||
return ide.runCommand(startCommand, {
|
||||
reuseTerminal: true,
|
||||
terminalName: "Start Ollama"
|
||||
});
|
||||
}
|
||||
default: //Linux...
|
||||
const start_script_path = path.resolve(__dirname, "./start_ollama.sh");
|
||||
if (await ide.fileExists(`file:/${start_script_path}`)) {
|
||||
startCommand = `set -e && chmod +x ${start_script_path} && ${start_script_path}\n`;
|
||||
console.log(`Ollama Linux startup script at : ${start_script_path}`);
|
||||
} else {
|
||||
return ide.showToast(
|
||||
"error",
|
||||
`Cannot start Ollama: could not find ${start_script_path}!`,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (startCommand) {
|
||||
return ide.runCommand(startCommand, {
|
||||
reuseTerminal: true,
|
||||
terminalName: "Start Ollama",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function getRemoteModelInfo(
|
||||
modelId: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<ModelInfo | undefined> {
|
||||
const start = Date.now();
|
||||
const [modelName, tag = "latest"] = modelId.split(":");
|
||||
const url = `https://registry.ollama.ai/v2/library/${modelName}/manifests/${tag}`;
|
||||
try {
|
||||
const sig = signal ? signal : AbortSignal.timeout(3000);
|
||||
const response = await fetch(url, { signal: sig });
|
||||
modelId: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<ModelInfo | undefined> {
|
||||
const start = Date.now();
|
||||
const [modelName, tag = "latest"] = modelId.split(":");
|
||||
const url = `https://registry.ollama.ai/v2/library/${modelName}/manifests/${tag}`;
|
||||
try {
|
||||
const sig = signal ? signal : AbortSignal.timeout(3000);
|
||||
const response = await fetch(url, { signal: sig });
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch the model page: ${response.statusText}`);
|
||||
}
|
||||
|
||||
// First, read the response body as an ArrayBuffer to compute the digest
|
||||
const buffer = await response.arrayBuffer();
|
||||
const digest = getDigest(buffer);
|
||||
|
||||
// Then, decode the ArrayBuffer into a string and parse it as JSON
|
||||
const text = new TextDecoder().decode(buffer);
|
||||
const manifest = JSON.parse(text) as {
|
||||
config: { size: number };
|
||||
layers: { size: number }[];
|
||||
};
|
||||
const modelSize =
|
||||
manifest.config.size +
|
||||
manifest.layers.reduce((sum, layer) => sum + layer.size, 0);
|
||||
|
||||
const data: ModelInfo = {
|
||||
id: modelId,
|
||||
size: modelSize,
|
||||
digest,
|
||||
};
|
||||
// Cache the successful result
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error(`Error fetching or parsing model info: ${error}`);
|
||||
} finally {
|
||||
const elapsed = Date.now() - start;
|
||||
console.log(`Fetched remote information for ${modelId} in ${elapsed} ms`);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch the model page: ${response.statusText}`);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function getDigest(buffer: ArrayBuffer): string {
|
||||
const hash = crypto.createHash("sha256");
|
||||
hash.update(new Uint8Array(buffer));
|
||||
return hash.digest("hex");
|
||||
}
|
||||
// First, read the response body as an ArrayBuffer to compute the digest
|
||||
const buffer = await response.arrayBuffer();
|
||||
const digest = getDigest(buffer);
|
||||
|
||||
// Then, decode the ArrayBuffer into a string and parse it as JSON
|
||||
const text = new TextDecoder().decode(buffer);
|
||||
const manifest = JSON.parse(text) as {
|
||||
config: { size: number };
|
||||
layers: { size: number }[];
|
||||
};
|
||||
const modelSize =
|
||||
manifest.config.size +
|
||||
manifest.layers.reduce((sum, layer) => sum + layer.size, 0);
|
||||
|
||||
const data: ModelInfo = {
|
||||
id: modelId,
|
||||
size: modelSize,
|
||||
digest,
|
||||
};
|
||||
// Cache the successful result
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error(`Error fetching or parsing model info: ${error}`);
|
||||
} finally {
|
||||
const elapsed = Date.now() - start;
|
||||
console.log(`Fetched remote information for ${modelId} in ${elapsed} ms`);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function getDigest(buffer: ArrayBuffer): string {
|
||||
const hash = crypto.createHash("sha256");
|
||||
hash.update(new Uint8Array(buffer));
|
||||
return hash.digest("hex");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,71 +1,73 @@
|
|||
import {
|
||||
markProcessAsBackgrounded,
|
||||
isProcessBackgrounded,
|
||||
removeBackgroundedProcess
|
||||
} from './processTerminalBackgroundStates';
|
||||
removeBackgroundedProcess,
|
||||
} from "./processTerminalBackgroundStates";
|
||||
|
||||
describe('processTerminalBackgroundStates', () => {
|
||||
describe("processTerminalBackgroundStates", () => {
|
||||
beforeEach(() => {
|
||||
// Clear any backgrounded processes before each test
|
||||
const backgroundedProcesses = Array.from(
|
||||
Object.getOwnPropertySymbols(global)
|
||||
).find(symbol => String(symbol) === 'Symbol(processTerminalBackgroundStates)');
|
||||
|
||||
Object.getOwnPropertySymbols(global),
|
||||
).find(
|
||||
(symbol) => String(symbol) === "Symbol(processTerminalBackgroundStates)",
|
||||
);
|
||||
|
||||
if (backgroundedProcesses) {
|
||||
// Reset the map by reimporting the module
|
||||
jest.resetModules();
|
||||
}
|
||||
});
|
||||
|
||||
test('should mark a process as backgrounded', () => {
|
||||
const toolCallId = 'test-123';
|
||||
test("should mark a process as backgrounded", () => {
|
||||
const toolCallId = "test-123";
|
||||
markProcessAsBackgrounded(toolCallId);
|
||||
expect(isProcessBackgrounded(toolCallId)).toBe(true);
|
||||
});
|
||||
|
||||
test('should correctly identify non-backgrounded processes', () => {
|
||||
const toolCallId = 'test-123';
|
||||
const anotherToolCallId = 'test-456';
|
||||
|
||||
test("should correctly identify non-backgrounded processes", () => {
|
||||
const toolCallId = "test-123";
|
||||
const anotherToolCallId = "test-456";
|
||||
|
||||
markProcessAsBackgrounded(toolCallId);
|
||||
|
||||
|
||||
expect(isProcessBackgrounded(toolCallId)).toBe(true);
|
||||
expect(isProcessBackgrounded(anotherToolCallId)).toBe(false);
|
||||
});
|
||||
|
||||
test('should remove a process from backgrounded state', () => {
|
||||
const toolCallId = 'test-123';
|
||||
|
||||
test("should remove a process from backgrounded state", () => {
|
||||
const toolCallId = "test-123";
|
||||
|
||||
markProcessAsBackgrounded(toolCallId);
|
||||
expect(isProcessBackgrounded(toolCallId)).toBe(true);
|
||||
|
||||
|
||||
removeBackgroundedProcess(toolCallId);
|
||||
expect(isProcessBackgrounded(toolCallId)).toBe(false);
|
||||
});
|
||||
|
||||
test('should handle removing non-existent processes', () => {
|
||||
const toolCallId = 'test-123';
|
||||
|
||||
test("should handle removing non-existent processes", () => {
|
||||
const toolCallId = "test-123";
|
||||
|
||||
// Should not throw an error
|
||||
removeBackgroundedProcess(toolCallId);
|
||||
expect(isProcessBackgrounded(toolCallId)).toBe(false);
|
||||
});
|
||||
|
||||
test('should handle multiple processes', () => {
|
||||
const toolCallId1 = 'test-123';
|
||||
const toolCallId2 = 'test-456';
|
||||
const toolCallId3 = 'test-789';
|
||||
|
||||
test("should handle multiple processes", () => {
|
||||
const toolCallId1 = "test-123";
|
||||
const toolCallId2 = "test-456";
|
||||
const toolCallId3 = "test-789";
|
||||
|
||||
markProcessAsBackgrounded(toolCallId1);
|
||||
markProcessAsBackgrounded(toolCallId2);
|
||||
|
||||
|
||||
expect(isProcessBackgrounded(toolCallId1)).toBe(true);
|
||||
expect(isProcessBackgrounded(toolCallId2)).toBe(true);
|
||||
expect(isProcessBackgrounded(toolCallId3)).toBe(false);
|
||||
|
||||
|
||||
removeBackgroundedProcess(toolCallId1);
|
||||
|
||||
|
||||
expect(isProcessBackgrounded(toolCallId1)).toBe(false);
|
||||
expect(isProcessBackgrounded(toolCallId2)).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -14,4 +14,4 @@ export function isProcessBackgrounded(toolCallId: string): boolean {
|
|||
// Function to remove a process from the backgrounded processes map
|
||||
export function removeBackgroundedProcess(toolCallId: string): void {
|
||||
processTerminalBackgroundStates.delete(toolCallId);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue