merge main
This commit is contained in:
commit
ef9625ce52
288 changed files with 54708 additions and 53082 deletions
79
.continue/prompts/update-llm-info.prompt
Normal file
79
.continue/prompts/update-llm-info.prompt
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
name: Update LLM Info
|
||||
description: Updates Gemini blocks with latest information
|
||||
version: 2
|
||||
---
|
||||
I need you to update this repo with the latest information about large language models from certain providers.
|
||||
The information is stored in the `packages/llm-info` directory, which operates as its own npm package.
|
||||
Information is stored in a simple JSON format, with one file of models per "provider" (e.g. gemini, ollama, openai, etc).
|
||||
For example, Gemini model information is stored in `packages/llm-info/src/providers/gemini.ts`.
|
||||
|
||||
To make these updates for a given provider, perform the following steps one at a time:
|
||||
|
||||
1. VIEW CURRENT INFORMATION
|
||||
|
||||
To view the current llm info, read the file (e.g. `packages/llm-info/src/providers/gemini.ts`) using the read_file tool.
|
||||
If you do not see a tool for reading files, let me know.
|
||||
|
||||
For reference, here is the LLMInfo interface used to store the information:
|
||||
|
||||
```typescript
|
||||
export interface LlmInfo {
|
||||
model: string; // the model name used to distinguish the model at the API layer, e.g. "gemini-2.5-pro-preview-05-06"
|
||||
displayName?: string; // A fitting display name, e.g. "Gemini 2.5 Pro Preview"
|
||||
description?: string; // A short description of the model, as similar as possible to descriptions found on the provider's website
|
||||
contextLength?: number; // The size of the context window in tokens, often called "max input tokens" or "context length"
|
||||
maxCompletionTokens?: number; // The maximum number of tokens the model can output
|
||||
regex?: RegExp; // A regex expression to uniquely match the model name if it had some slight modifications/upgrades, e.g. /gemini-2\.5-pro-preview/i
|
||||
mediaTypes?: MediaType[]; // Input/output types supported by the model, e.g. [MediaType.Text, MediaType.Image]
|
||||
}
|
||||
|
||||
export enum MediaType {
|
||||
Text = "text",
|
||||
Image = "image",
|
||||
Audio = "audio",
|
||||
Video = "video",
|
||||
}
|
||||
|
||||
export const AllMediaTypes = [
|
||||
MediaType.Text,
|
||||
MediaType.Image,
|
||||
MediaType.Audio,
|
||||
MediaType.Video,
|
||||
];
|
||||
```
|
||||
|
||||
2. EXTRACT NEW INFORMATION
|
||||
|
||||
New information will be pulled from the internet.
|
||||
If you do not see a web search tool, let me know.
|
||||
|
||||
Retrieve the following sites per these providers, and consider these notes on how to extract the information:
|
||||
- "gemini": https://ai.google.dev/gemini-api/docs/models - maxCompletionTokens is called "Output token limit", contextLength is called "Input token limit"
|
||||
// TODO: add info for openai, ollama, etc
|
||||
|
||||
For any other providers, search the web for "latest [provider] models" and find the most relevant model information using your best judgement.
|
||||
Generally, ignore models that do not support text output. These models will be used in a coding assistant client that only supports text/image input and text/output, so extraneous capabilities can be ignored.
|
||||
Sometimes, "Experimental", "Preview", or similar versions of models are available. The latest-date version of each should have its own information maintained.
|
||||
|
||||
3. UPDATE THE INFORMATION
|
||||
|
||||
Use the edit file tool to submit updates to the relevant provider file (e.g. `packages/llm-info/src/providers/gemini.ts`).
|
||||
Let me know if you do not see a tool for editing files.
|
||||
|
||||
Generally, avoid making changes to existing information, as it is probably up to date.
|
||||
Primarily, focus on adding new models or adding missing information to existing models.
|
||||
NEVER delete any existing models, but let me know if you think one should be removed.
|
||||
Stop to ask me if you are unsure about any changes, and let me know if there are updates that seem nuanced, complex, or extremely notable.
|
||||
Provide a summary of changes after the fact.
|
||||
|
||||
4. ASK IF I WANT TO PUBLISH TO NPM
|
||||
After you are done updating everything, remind me that I need to publish the changes to npm.
|
||||
|
||||
// TODO too sensitive for now
|
||||
// If yes, update `packages/llm-info/package.json` with the new version number and then
|
||||
// - use the terminal tool to commit the changes
|
||||
// - use the terminal tool to publish changes to npm
|
||||
// If you do not see a tool for running terminal commands, let me know.
|
||||
|
||||
// User input
|
||||
Please update LLM Info for the following providers. If "all", update all providers mentioned above:
|
||||
|
|
@ -13,4 +13,4 @@ description: Standards for writing and maintaining Continue Docs
|
|||
- Include cross-references to related documentation
|
||||
- Reference other docs with relative paths
|
||||
- Keep paragraphs concise and scannable
|
||||
- Use code blocks with appropriate language tags
|
||||
- Use code blocks with appropriate language tags
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@
|
|||
},
|
||||
"plugins": ["@typescript-eslint", "import"],
|
||||
"rules": {
|
||||
"no-negated-condition": "warn",
|
||||
"@typescript-eslint/naming-convention": "off",
|
||||
"@typescript-eslint/no-floating-promises": "warn",
|
||||
"@typescript-eslint/semi": "warn",
|
||||
|
|
|
|||
19
.github/workflows/pr_checks.yaml
vendored
19
.github/workflows/pr_checks.yaml
vendored
|
|
@ -30,6 +30,24 @@ jobs:
|
|||
if: steps.root-cache.outputs.cache-hit != 'true'
|
||||
run: npm ci
|
||||
|
||||
prettier-check:
|
||||
needs: install-root
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: node_modules
|
||||
key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }}
|
||||
|
||||
- name: Check code formatting with Prettier
|
||||
run: npx prettier --check "**/*.{js,jsx,ts,tsx,json,css,md}" --ignore-path .gitignore --ignore-path .prettierignore
|
||||
|
||||
install-config-yaml:
|
||||
needs: install-root
|
||||
runs-on: ubuntu-latest
|
||||
|
|
@ -860,6 +878,7 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- install-root
|
||||
- prettier-check
|
||||
- install-core
|
||||
- core-checks
|
||||
- install-gui
|
||||
|
|
|
|||
|
|
@ -15,4 +15,11 @@ gui/dist
|
|||
CHANGELOG.md
|
||||
**/continue_tutorial.py
|
||||
**/node_modules
|
||||
**/CODEOWNERS
|
||||
**/CODEOWNERS
|
||||
core/vendor
|
||||
coverage
|
||||
e2e
|
||||
extensions/vscode/gui
|
||||
extensions/vscode/models
|
||||
extensions/intellij/src/main/resources
|
||||
packages/continue-sdk
|
||||
|
|
@ -14,21 +14,21 @@ religion, or sexual identity and orientation.
|
|||
Examples of behavior that contributes to creating a positive environment
|
||||
include:
|
||||
|
||||
* Using welcoming and inclusive language
|
||||
* Being respectful of differing viewpoints and experiences
|
||||
* Gracefully accepting constructive criticism
|
||||
* Focusing on what is best for the community
|
||||
* Showing empathy towards other community members
|
||||
- Using welcoming and inclusive language
|
||||
- Being respectful of differing viewpoints and experiences
|
||||
- Gracefully accepting constructive criticism
|
||||
- Focusing on what is best for the community
|
||||
- Showing empathy towards other community members
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
* The use of sexualized language or imagery and unwelcome sexual attention or
|
||||
- The use of sexualized language or imagery and unwelcome sexual attention or
|
||||
advances
|
||||
* Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or electronic
|
||||
- Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
- Public or private harassment
|
||||
- Publishing others' private information, such as a physical or electronic
|
||||
address, without explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
- Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Our Responsibilities
|
||||
|
|
|
|||
|
|
@ -58,7 +58,6 @@ file
|
|||
|
||||

|
||||
|
||||
|
||||
</div>
|
||||
|
||||
## Getting Started
|
||||
|
|
|
|||
|
|
@ -1,6 +1,10 @@
|
|||
const path = require('path');
|
||||
const path = require("path");
|
||||
process.env.CONTINUE_DEVELOPMENT = true;
|
||||
|
||||
process.env.CONTINUE_GLOBAL_DIR = path.join(process.env.PROJECT_DIR, 'extensions', '.continue-debug');
|
||||
process.env.CONTINUE_GLOBAL_DIR = path.join(
|
||||
process.env.PROJECT_DIR,
|
||||
"extensions",
|
||||
".continue-debug",
|
||||
);
|
||||
|
||||
require('./out/index.js');
|
||||
require("./out/index.js");
|
||||
|
|
|
|||
|
|
@ -1,7 +1,13 @@
|
|||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const logDirPath = path.join(__dirname, '..', 'extensions', '.continue-debug', 'logs');
|
||||
const logDirPath = path.join(
|
||||
__dirname,
|
||||
"..",
|
||||
"extensions",
|
||||
".continue-debug",
|
||||
"logs",
|
||||
);
|
||||
const logFilePath = path.join(logDirPath, "prompt.log");
|
||||
|
||||
// Ensure the log directory exists
|
||||
|
|
@ -12,7 +18,7 @@ if (!fs.existsSync(logDirPath)) {
|
|||
|
||||
// Create the log file if it doesn't exist
|
||||
if (!fs.existsSync(logFilePath)) {
|
||||
fs.writeFileSync(logFilePath, ''); // Create an empty file synchronously
|
||||
fs.writeFileSync(logFilePath, ""); // Create an empty file synchronously
|
||||
console.log("Created empty log file at " + logFilePath);
|
||||
}
|
||||
|
||||
|
|
@ -25,14 +31,16 @@ try {
|
|||
// console.clear();
|
||||
const stream = fs.createReadStream(logFilePath);
|
||||
stream.pipe(process.stdout);
|
||||
stream.on('error', (err) => {
|
||||
console.error('Error reading log file:', err.message);
|
||||
stream.on("error", (err) => {
|
||||
console.error("Error reading log file:", err.message);
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Error while handling file change:', err.message);
|
||||
console.error("Error while handling file change:", err.message);
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Error setting up file watcher:', err.message);
|
||||
console.log('You may need to restart the script after the extension generates the first log entry.');
|
||||
}
|
||||
console.error("Error setting up file watcher:", err.message);
|
||||
console.log(
|
||||
"You may need to restart the script after the extension generates the first log entry.",
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -39,4 +39,4 @@ module.exports = {
|
|||
TARGET_TO_RIPGREP_RELEASE,
|
||||
TARGET_TO_LANCEDB,
|
||||
RIPGREP_VERSION,
|
||||
};
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import {
|
|||
ContextItem,
|
||||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
FetchFunction,
|
||||
} from "../../index.js";
|
||||
import { fetchFavicon } from "../../util/fetchFavicon";
|
||||
|
||||
|
|
@ -22,42 +23,49 @@ class URLContextProvider extends BaseContextProvider {
|
|||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
try {
|
||||
const url = new URL(query);
|
||||
const icon = await fetchFavicon(url);
|
||||
const resp = await extras.fetch(url);
|
||||
const html = await resp.text();
|
||||
|
||||
const dom = new JSDOM(html);
|
||||
let reader = new Readability(dom.window.document);
|
||||
let article = reader.parse();
|
||||
const content = article?.content || "";
|
||||
const markdown = NodeHtmlMarkdown.translate(
|
||||
content,
|
||||
{},
|
||||
undefined,
|
||||
undefined,
|
||||
);
|
||||
|
||||
const title = article?.title || url.pathname;
|
||||
|
||||
return [
|
||||
{
|
||||
icon,
|
||||
description: url.toString(),
|
||||
content: markdown,
|
||||
name: title,
|
||||
uri: {
|
||||
type: "url",
|
||||
value: url.toString(),
|
||||
},
|
||||
},
|
||||
];
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
return [];
|
||||
}
|
||||
return await getUrlContextItems(query, extras.fetch);
|
||||
}
|
||||
}
|
||||
|
||||
export default URLContextProvider;
|
||||
|
||||
export async function getUrlContextItems(
|
||||
query: string,
|
||||
fetchFn: FetchFunction,
|
||||
): Promise<ContextItem[]> {
|
||||
try {
|
||||
const url = new URL(query);
|
||||
const icon = await fetchFavicon(url);
|
||||
const resp = await fetchFn(url);
|
||||
const html = await resp.text();
|
||||
|
||||
const dom = new JSDOM(html);
|
||||
let reader = new Readability(dom.window.document);
|
||||
let article = reader.parse();
|
||||
const content = article?.content || "";
|
||||
const markdown = NodeHtmlMarkdown.translate(
|
||||
content,
|
||||
{},
|
||||
undefined,
|
||||
undefined,
|
||||
);
|
||||
|
||||
const title = article?.title || url.pathname;
|
||||
|
||||
return [
|
||||
{
|
||||
icon,
|
||||
description: url.toString(),
|
||||
content: markdown,
|
||||
name: title,
|
||||
uri: {
|
||||
type: "url",
|
||||
value: url.toString(),
|
||||
},
|
||||
},
|
||||
];
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -23,6 +23,14 @@ export interface ControlPlaneWorkspace {
|
|||
|
||||
export interface ControlPlaneModelDescription extends ModelDescription {}
|
||||
|
||||
export interface FreeTrialStatus {
|
||||
optedInToFreeTrial: boolean;
|
||||
chatCount?: number;
|
||||
autocompleteCount?: number;
|
||||
chatLimit: number;
|
||||
autocompleteLimit: number;
|
||||
}
|
||||
|
||||
export const TRIAL_PROXY_URL =
|
||||
"https://proxy-server-blue-l6vsfbzhba-uw.a.run.app";
|
||||
|
||||
|
|
@ -159,4 +167,19 @@ export class ControlPlaneClient {
|
|||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public async getFreeTrialStatus(): Promise<FreeTrialStatus | null> {
|
||||
if (!(await this.isSignedIn())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const resp = await this.request("ide/free-trial-status", {
|
||||
method: "GET",
|
||||
});
|
||||
return (await resp.json()) as FreeTrialStatus;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import {
|
|||
getStagingEnvironmentDotFilePath,
|
||||
} from "../util/paths";
|
||||
import { AuthType, ControlPlaneEnv } from "./AuthTypes";
|
||||
import { getMdmKeys } from "./mdm";
|
||||
import { getLicenseKeyData } from "./mdm/mdm";
|
||||
|
||||
export const EXTENSION_NAME = "continue";
|
||||
|
||||
|
|
@ -59,9 +59,9 @@ export function getControlPlaneEnvSync(
|
|||
ideTestEnvironment: IdeSettings["continueTestEnvironment"],
|
||||
): ControlPlaneEnv {
|
||||
// MDM override
|
||||
const mdmKeys = getMdmKeys();
|
||||
if (mdmKeys) {
|
||||
const { apiUrl } = mdmKeys;
|
||||
const licenseKeyData = getLicenseKeyData();
|
||||
if (licenseKeyData?.unsignedData?.apiUrl) {
|
||||
const { apiUrl } = licenseKeyData.unsignedData;
|
||||
return {
|
||||
AUTH_TYPE: AuthType.OnPrem,
|
||||
DEFAULT_CONTROL_PLANE_PROXY_URL: apiUrl,
|
||||
|
|
|
|||
|
|
@ -1,127 +0,0 @@
|
|||
import * as crypto from "crypto";
|
||||
import { LicenseData, validateLicenseKey } from "./mdm";
|
||||
|
||||
// We'll create a real key pair once for all tests
|
||||
const testKeyPair = crypto.generateKeyPairSync("rsa", {
|
||||
modulusLength: 2048,
|
||||
publicKeyEncoding: {
|
||||
type: "spki",
|
||||
format: "pem",
|
||||
},
|
||||
privateKeyEncoding: {
|
||||
type: "pkcs8",
|
||||
format: "pem",
|
||||
},
|
||||
});
|
||||
|
||||
// Custom function to create test licenses (replaces the original mock-dependent one)
|
||||
function createTestLicense(
|
||||
licenseData: LicenseData,
|
||||
useValidSignature: boolean = true,
|
||||
): string {
|
||||
// Convert license data to a string
|
||||
const licenseDataStr = JSON.stringify(licenseData);
|
||||
|
||||
// Create a signature with our generated private key
|
||||
const sign = crypto.createSign("SHA256");
|
||||
sign.update(licenseDataStr);
|
||||
sign.end();
|
||||
|
||||
let signature: string;
|
||||
if (useValidSignature) {
|
||||
signature = sign.sign(testKeyPair.privateKey, "base64");
|
||||
} else {
|
||||
// For invalid tests, create an intentionally wrong signature by signing different data
|
||||
const wrongSign = crypto.createSign("SHA256");
|
||||
wrongSign.update(licenseDataStr + "tampered");
|
||||
wrongSign.end();
|
||||
signature = wrongSign.sign(testKeyPair.privateKey, "base64");
|
||||
}
|
||||
// Combine data and signature into a license key
|
||||
const licenseKeyObj = {
|
||||
data: licenseDataStr,
|
||||
signature: signature,
|
||||
};
|
||||
|
||||
return Buffer.from(JSON.stringify(licenseKeyObj)).toString("base64");
|
||||
}
|
||||
|
||||
// We need to test the actual implementation - which we can't mock with ESM
|
||||
// Instead, we'll have tests that bypass validation or are expected to fail
|
||||
// depending on what we're testing
|
||||
|
||||
test("validateLicenseKey returns false for malformed license key", () => {
|
||||
// Test with a completely invalid license key
|
||||
const invalidLicenseKey = "not-a-valid-license-key";
|
||||
|
||||
// Test - no mocks, real validation
|
||||
const result = validateLicenseKey(invalidLicenseKey);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
test("validateLicenseKey returns false for invalid JSON in license key", () => {
|
||||
// Create a malformed but base64-encoded string
|
||||
const malformedLicenseKey = Buffer.from("this is not valid JSON").toString(
|
||||
"base64",
|
||||
);
|
||||
|
||||
// Test - no mocks, real validation
|
||||
const result = validateLicenseKey(malformedLicenseKey);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
test("validateLicenseKey returns false for expired license", () => {
|
||||
// Without mocking, we expect this to fail signature verification
|
||||
// We're testing the date logic by itself
|
||||
const licenseData: LicenseData = {
|
||||
customerId: "customer123",
|
||||
createdAt: new Date(Date.now() - 2000 * 60 * 60 * 24).toISOString(), // Created 2 days ago
|
||||
expiresAt: new Date(Date.now() - 1000 * 60 * 60 * 24).toISOString(), // Expired 1 day ago
|
||||
};
|
||||
|
||||
// Create a license key - will fail verification but test logic still works
|
||||
const expiredLicenseKey = createTestLicense(licenseData);
|
||||
|
||||
// Test - expect false, either due to signature or expiration - both are valid test cases
|
||||
const result = validateLicenseKey(expiredLicenseKey);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
test("validateLicenseKey returns false for invalid signature", () => {
|
||||
// Create license data with valid dates
|
||||
const licenseData: LicenseData = {
|
||||
customerId: "customer123",
|
||||
createdAt: new Date().toISOString(),
|
||||
expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(), // Valid for 1 day
|
||||
};
|
||||
|
||||
// Create a license with an invalid signature
|
||||
const invalidSignatureKey = createTestLicense(licenseData, false);
|
||||
|
||||
// Test - no mocks, real validation
|
||||
const result = validateLicenseKey(invalidSignatureKey);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
test("validateLicenseKey handles JSON parsing errors gracefully", () => {
|
||||
// Create a base64 string that decodes to valid JSON but lacks required fields
|
||||
const invalidStructureKey = Buffer.from(
|
||||
JSON.stringify({
|
||||
notTheRightField: "wrong structure",
|
||||
}),
|
||||
).toString("base64");
|
||||
|
||||
// Test - no mocks, real validation
|
||||
const result = validateLicenseKey(invalidStructureKey);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
210
core/control-plane/mdm/mdm.test.ts
Normal file
210
core/control-plane/mdm/mdm.test.ts
Normal file
|
|
@ -0,0 +1,210 @@
|
|||
import * as crypto from "crypto";
|
||||
import { LicenseKeyData, validateLicenseKey } from "./mdm";
|
||||
|
||||
// We'll create a real key pair once for all tests
|
||||
const testKeyPair = crypto.generateKeyPairSync("rsa", {
|
||||
modulusLength: 2048,
|
||||
publicKeyEncoding: {
|
||||
type: "spki",
|
||||
format: "pem",
|
||||
},
|
||||
privateKeyEncoding: {
|
||||
type: "pkcs8",
|
||||
format: "pem",
|
||||
},
|
||||
});
|
||||
|
||||
// Custom function to create test licenses with the new structure including unsignedData
|
||||
function createTestLicense(
|
||||
licenseData: LicenseKeyData,
|
||||
apiUrl: string = "https://api.continue.dev",
|
||||
useValidSignature: boolean = true,
|
||||
): string {
|
||||
// Convert license data to a string
|
||||
const licenseDataStr = JSON.stringify(licenseData);
|
||||
|
||||
// Create a signature with our generated private key
|
||||
const sign = crypto.createSign("SHA256");
|
||||
sign.update(licenseDataStr);
|
||||
sign.end();
|
||||
|
||||
let signature: string;
|
||||
if (useValidSignature) {
|
||||
signature = sign.sign(testKeyPair.privateKey, "base64");
|
||||
} else {
|
||||
// For invalid tests, create an intentionally wrong signature by signing different data
|
||||
const wrongSign = crypto.createSign("SHA256");
|
||||
wrongSign.update(licenseDataStr + "tampered");
|
||||
wrongSign.end();
|
||||
signature = wrongSign.sign(testKeyPair.privateKey, "base64");
|
||||
}
|
||||
|
||||
// Combine data, signature, and unsigned data into a license key
|
||||
const licenseKeyObj = {
|
||||
data: licenseDataStr,
|
||||
signature: signature,
|
||||
unsignedData: {
|
||||
apiUrl: apiUrl,
|
||||
},
|
||||
};
|
||||
|
||||
return Buffer.from(JSON.stringify(licenseKeyObj)).toString("base64");
|
||||
}
|
||||
|
||||
// We need to test the actual implementation - which we can't mock with ESM
|
||||
// Instead, we'll have tests that bypass validation or are expected to fail
|
||||
// depending on what we're testing
|
||||
|
||||
test("validateLicenseKey returns false for malformed license key", () => {
|
||||
// Test with a completely invalid license key
|
||||
const invalidLicenseKey = "not-a-valid-license-key";
|
||||
|
||||
// Test - no mocks, real validation
|
||||
const result = validateLicenseKey(invalidLicenseKey);
|
||||
|
||||
// Assert
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.licenseKeyData).toBeUndefined();
|
||||
});
|
||||
|
||||
test("validateLicenseKey returns false for invalid JSON in license key", () => {
|
||||
// Create a malformed but base64-encoded string
|
||||
const malformedLicenseKey = Buffer.from("this is not valid JSON").toString(
|
||||
"base64",
|
||||
);
|
||||
|
||||
// Test - no mocks, real validation
|
||||
const result = validateLicenseKey(malformedLicenseKey);
|
||||
|
||||
// Assert
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.licenseKeyData).toBeUndefined();
|
||||
});
|
||||
|
||||
test("validateLicenseKey returns false for expired license", () => {
|
||||
// Without mocking, we expect this to fail signature verification
|
||||
// We're testing the date logic by itself
|
||||
const licenseData: LicenseKeyData = {
|
||||
customerId: "customer123",
|
||||
createdAt: new Date(Date.now() - 2000 * 60 * 60 * 24).toISOString(), // Created 2 days ago
|
||||
expiresAt: new Date(Date.now() - 1000 * 60 * 60 * 24).toISOString(), // Expired 1 day ago
|
||||
};
|
||||
|
||||
// Create a license key with apiUrl in unsignedData - will fail verification but test logic still works
|
||||
const expiredLicenseKey = createTestLicense(
|
||||
licenseData,
|
||||
"https://api.continue.dev",
|
||||
);
|
||||
|
||||
// Test - expect false, either due to signature or expiration - both are valid test cases
|
||||
const result = validateLicenseKey(expiredLicenseKey);
|
||||
|
||||
// Assert
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.licenseKeyData).toBeUndefined();
|
||||
});
|
||||
|
||||
test("validateLicenseKey returns false for invalid signature", () => {
|
||||
// Create license data with valid dates
|
||||
const licenseData: LicenseKeyData = {
|
||||
customerId: "customer123",
|
||||
createdAt: new Date().toISOString(),
|
||||
expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(), // Valid for 1 day
|
||||
};
|
||||
|
||||
// Create a license with an invalid signature but valid unsignedData structure
|
||||
const invalidSignatureKey = createTestLicense(
|
||||
licenseData,
|
||||
"https://api.continue.dev",
|
||||
false,
|
||||
);
|
||||
|
||||
// Test - no mocks, real validation
|
||||
const result = validateLicenseKey(invalidSignatureKey);
|
||||
|
||||
// Assert
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.licenseKeyData).toBeUndefined();
|
||||
});
|
||||
|
||||
test("validateLicenseKey handles JSON parsing errors gracefully", () => {
|
||||
// Create a base64 string that decodes to valid JSON but lacks required fields
|
||||
const invalidStructureKey = Buffer.from(
|
||||
JSON.stringify({
|
||||
notTheRightField: "wrong structure",
|
||||
}),
|
||||
).toString("base64");
|
||||
|
||||
// Test - no mocks, real validation
|
||||
const result = validateLicenseKey(invalidStructureKey);
|
||||
|
||||
// Assert
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.licenseKeyData).toBeUndefined();
|
||||
});
|
||||
|
||||
test("validateLicenseKey handles missing unsignedData gracefully", () => {
|
||||
// Create a license key structure without unsignedData field
|
||||
const licenseData: LicenseKeyData = {
|
||||
customerId: "customer123",
|
||||
createdAt: new Date().toISOString(),
|
||||
expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(),
|
||||
};
|
||||
|
||||
const licenseDataStr = JSON.stringify(licenseData);
|
||||
const sign = crypto.createSign("SHA256");
|
||||
sign.update(licenseDataStr);
|
||||
sign.end();
|
||||
const signature = sign.sign(testKeyPair.privateKey, "base64");
|
||||
|
||||
// Create license key without unsignedData
|
||||
const licenseKeyObj = {
|
||||
data: licenseDataStr,
|
||||
signature: signature,
|
||||
// Missing unsignedData field
|
||||
};
|
||||
|
||||
const licenseKey = Buffer.from(JSON.stringify(licenseKeyObj)).toString(
|
||||
"base64",
|
||||
);
|
||||
|
||||
// Test - no mocks, real validation
|
||||
const result = validateLicenseKey(licenseKey);
|
||||
|
||||
// Assert - should fail due to signature verification with wrong public key
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.licenseKeyData).toBeUndefined();
|
||||
});
|
||||
|
||||
test("validateLicenseKey handles invalid unsignedData structure", () => {
|
||||
// Create license data with valid dates
|
||||
const licenseData: LicenseKeyData = {
|
||||
customerId: "customer123",
|
||||
createdAt: new Date().toISOString(),
|
||||
expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(),
|
||||
};
|
||||
|
||||
const licenseDataStr = JSON.stringify(licenseData);
|
||||
const sign = crypto.createSign("SHA256");
|
||||
sign.update(licenseDataStr);
|
||||
sign.end();
|
||||
const signature = sign.sign(testKeyPair.privateKey, "base64");
|
||||
|
||||
// Create license key with invalid unsignedData structure
|
||||
const licenseKeyObj = {
|
||||
data: licenseDataStr,
|
||||
signature: signature,
|
||||
unsignedData: "not an object", // Should be an object with apiUrl
|
||||
};
|
||||
|
||||
const licenseKey = Buffer.from(JSON.stringify(licenseKeyObj)).toString(
|
||||
"base64",
|
||||
);
|
||||
|
||||
// Test - no mocks, real validation
|
||||
const result = validateLicenseKey(licenseKey);
|
||||
|
||||
// Assert - should fail due to signature verification with wrong public key
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.licenseKeyData).toBeUndefined();
|
||||
});
|
||||
|
|
@ -6,7 +6,6 @@ import * as plist from "plist";
|
|||
|
||||
export interface MdmKeys {
|
||||
licenseKey: string;
|
||||
apiUrl: string;
|
||||
}
|
||||
|
||||
const CONTINUE_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
|
||||
|
|
@ -19,17 +18,30 @@ LXSsjLbeWHifRrQ18wj/PC990E33QaFGNFp0NcBXMPbq5eKYKEzKZ0GsxtLoGxar
|
|||
FQIDAQAB
|
||||
-----END PUBLIC KEY-----`;
|
||||
|
||||
export interface LicenseData {
|
||||
interface LicenseKeyUnsignedData {
|
||||
apiUrl: string;
|
||||
}
|
||||
|
||||
export interface LicenseKey {
|
||||
signature: string;
|
||||
data: string;
|
||||
unsignedData: LicenseKeyUnsignedData;
|
||||
}
|
||||
|
||||
export interface LicenseKeyData {
|
||||
customerId: string;
|
||||
createdAt: string;
|
||||
expiresAt: string;
|
||||
}
|
||||
|
||||
export function validateLicenseKey(licenseKey: string): boolean {
|
||||
export function validateLicenseKey(licenseKey: string): {
|
||||
isValid: boolean;
|
||||
licenseKeyData?: LicenseKey;
|
||||
} {
|
||||
try {
|
||||
// Decode the base64 license key
|
||||
const decodedString = Buffer.from(licenseKey, "base64").toString("utf8");
|
||||
const { data, signature } = JSON.parse(decodedString);
|
||||
const { data, signature, unsignedData } = JSON.parse(decodedString);
|
||||
|
||||
// Verify the signature
|
||||
const verify = crypto.createVerify("SHA256");
|
||||
|
|
@ -38,36 +50,31 @@ export function validateLicenseKey(licenseKey: string): boolean {
|
|||
|
||||
const isValid = verify.verify(CONTINUE_PUBLIC_KEY, signature, "base64");
|
||||
|
||||
if (!isValid) return false;
|
||||
if (!isValid) return { isValid: false };
|
||||
|
||||
// Check license expiration
|
||||
const licenseData: LicenseData = JSON.parse(data);
|
||||
const licenseData: LicenseKeyData = JSON.parse(data);
|
||||
const expirationDate = new Date(licenseData.expiresAt);
|
||||
const now = new Date();
|
||||
|
||||
return expirationDate > now;
|
||||
const isNotExpired = expirationDate > now;
|
||||
|
||||
if (!isNotExpired) return { isValid: false };
|
||||
|
||||
// Return both validation result and license key data
|
||||
const licenseKeyData: LicenseKey = {
|
||||
signature,
|
||||
data,
|
||||
unsignedData,
|
||||
};
|
||||
|
||||
return { isValid: true, licenseKeyData };
|
||||
} catch (error) {
|
||||
console.error("License validation error:", error);
|
||||
return false;
|
||||
return { isValid: false };
|
||||
}
|
||||
}
|
||||
|
||||
function extractConfigFromArray(config: any[]): Record<string, string> {
|
||||
const configObj: Record<string, string> = {};
|
||||
|
||||
for (let i = 0; i < config.length; i += 2) {
|
||||
if (i + 1 < config.length) {
|
||||
const key = config[i];
|
||||
const value = config[i + 1];
|
||||
if (typeof key === "string") {
|
||||
configObj[key] = value as string;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return configObj;
|
||||
}
|
||||
|
||||
const MACOS_MDM_PATHS = [
|
||||
// Organization-specific MDM plist
|
||||
"/Library/Managed Preferences/dev.continue.app.plist",
|
||||
|
|
@ -88,20 +95,15 @@ function readMdmKeysMacOS(): MdmKeys | undefined {
|
|||
|
||||
try {
|
||||
// Parse the plist file using the plist package
|
||||
const config = plist.parse(fileContent);
|
||||
const config = plist.parse(fileContent) as
|
||||
| { licenseKey: string | undefined }
|
||||
| undefined;
|
||||
|
||||
// Extract the relevant fields from the config
|
||||
// Config is an array of alternating keys and values
|
||||
if (Array.isArray(config)) {
|
||||
const configObj = extractConfigFromArray(config);
|
||||
|
||||
// Check if required keys are present
|
||||
if (configObj.licenseKey && configObj.apiUrl) {
|
||||
return {
|
||||
licenseKey: configObj.licenseKey,
|
||||
apiUrl: configObj.apiUrl,
|
||||
};
|
||||
}
|
||||
if (config && config?.licenseKey) {
|
||||
// Extract the license key from the configuration
|
||||
return { licenseKey: config?.licenseKey };
|
||||
} else {
|
||||
console.error("Invalid MDM configuration format");
|
||||
}
|
||||
} catch (parseError) {
|
||||
console.error(`Error parsing MDM configuration: ${parseError}`);
|
||||
|
|
@ -130,17 +132,11 @@ function readMdmKeysWindows(): MdmKeys | undefined {
|
|||
try {
|
||||
// Use REG QUERY command to read registry values
|
||||
const licenseKeyCmd = `reg query "${regPath}" /v licenseKey`;
|
||||
const apiUrlCmd = `reg query "${regPath}" /v apiUrl`;
|
||||
|
||||
const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" });
|
||||
const apiUrlOutput = execSync(apiUrlCmd, { encoding: "utf8" });
|
||||
|
||||
// Extract values from command output
|
||||
const licenseKey = extractRegValue(licenseKeyOutput);
|
||||
const apiUrl = extractRegValue(apiUrlOutput);
|
||||
|
||||
if (licenseKey && apiUrl) {
|
||||
return { licenseKey, apiUrl };
|
||||
if (licenseKey) {
|
||||
return { licenseKey };
|
||||
}
|
||||
} catch (error) {
|
||||
// Registry key might not exist, fallback to HKEY_CURRENT_USER
|
||||
|
|
@ -149,17 +145,11 @@ function readMdmKeysWindows(): MdmKeys | undefined {
|
|||
// Try HKEY_CURRENT_USER if not found in HKEY_LOCAL_MACHINE
|
||||
try {
|
||||
const licenseKeyCmd = `reg query "${userRegPath}" /v licenseKey`;
|
||||
const apiUrlCmd = `reg query "${userRegPath}" /v apiUrl`;
|
||||
|
||||
const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" });
|
||||
const apiUrlOutput = execSync(apiUrlCmd, { encoding: "utf8" });
|
||||
|
||||
// Extract values from command output
|
||||
const licenseKey = extractRegValue(licenseKeyOutput);
|
||||
const apiUrl = extractRegValue(apiUrlOutput);
|
||||
|
||||
if (licenseKey && apiUrl) {
|
||||
return { licenseKey, apiUrl };
|
||||
if (licenseKey) {
|
||||
return { licenseKey };
|
||||
}
|
||||
} catch (error) {
|
||||
// Registry key might not exist in HKCU either
|
||||
|
|
@ -199,11 +189,10 @@ function readMdmKeysLinux(): MdmKeys | undefined {
|
|||
// Parse the JSON configuration file
|
||||
const config = JSON.parse(fileContent);
|
||||
|
||||
// Check if required keys are present
|
||||
if (config.licenseKey && config.apiUrl) {
|
||||
// Check if required key is present
|
||||
if (config.licenseKey) {
|
||||
return {
|
||||
licenseKey: config.licenseKey,
|
||||
apiUrl: config.apiUrl,
|
||||
};
|
||||
}
|
||||
} catch (parseError) {
|
||||
|
|
@ -241,17 +230,20 @@ function readMdmKeys(): MdmKeys | undefined {
|
|||
/**
|
||||
* Read and validate MDM keys from the operating system's configuration files or registry.
|
||||
*/
|
||||
export function getMdmKeys(): MdmKeys | undefined {
|
||||
export function getLicenseKeyData(): LicenseKey | undefined {
|
||||
try {
|
||||
const mdmKeys = readMdmKeys();
|
||||
|
||||
if (mdmKeys) {
|
||||
if (!validateLicenseKey(mdmKeys.licenseKey)) {
|
||||
const { isValid, licenseKeyData } = validateLicenseKey(
|
||||
mdmKeys.licenseKey,
|
||||
);
|
||||
if (!isValid) {
|
||||
console.error("Invalid license key found: ", mdmKeys.licenseKey);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return mdmKeys;
|
||||
return licenseKeyData;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
|
|
@ -260,3 +252,113 @@ export function getMdmKeys(): MdmKeys | undefined {
|
|||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function writeMdmKeysMacOS(licenseKey: string): boolean {
|
||||
try {
|
||||
// Write to user-specific MDM plist
|
||||
const userMdmPath = path.join(
|
||||
os.homedir(),
|
||||
"Library/Managed Preferences/dev.continue.app.plist",
|
||||
);
|
||||
|
||||
const config = {
|
||||
licenseKey,
|
||||
};
|
||||
|
||||
// Ensure directory exists
|
||||
fs.mkdirSync(path.dirname(userMdmPath), { recursive: true });
|
||||
|
||||
// Write the plist file
|
||||
const plistContent = plist.build(config);
|
||||
fs.writeFileSync(userMdmPath, plistContent, "utf8");
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Error writing macOS MDM keys:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function writeMdmKeysWindows(licenseKey: string): boolean {
|
||||
try {
|
||||
const { execSync } = require("child_process");
|
||||
|
||||
// Use HKEY_CURRENT_USER to avoid needing admin privileges
|
||||
const userRegPath = "HKCU\\Software\\Continue\\MDM";
|
||||
|
||||
// Create the registry key if it doesn't exist
|
||||
try {
|
||||
execSync(`reg add "${userRegPath}" /f`);
|
||||
} catch (error) {
|
||||
// Key might already exist
|
||||
}
|
||||
|
||||
// Set the license key and API URL
|
||||
execSync(
|
||||
`reg add "${userRegPath}" /v licenseKey /t REG_SZ /d "${licenseKey}" /f`,
|
||||
);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Error writing Windows MDM keys:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function writeMdmKeysLinux(licenseKey: string): boolean {
|
||||
try {
|
||||
// Write to user-specific configuration
|
||||
const userMdmPath = path.join(os.homedir(), ".config/continue/mdm.json");
|
||||
|
||||
const config = {
|
||||
licenseKey,
|
||||
};
|
||||
|
||||
// Ensure directory exists
|
||||
fs.mkdirSync(path.dirname(userMdmPath), { recursive: true });
|
||||
|
||||
// Write the JSON configuration file
|
||||
fs.writeFileSync(userMdmPath, JSON.stringify(config, null, 2), "utf8");
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Error writing Linux MDM keys:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Store the license key in the appropriate OS-specific location.
|
||||
* For now, we'll use a default API URL since it's not provided in the command.
|
||||
*/
|
||||
export function setMdmLicenseKey(licenseKey: string): boolean {
|
||||
try {
|
||||
// Validate the license key first
|
||||
const { isValid } = validateLicenseKey(licenseKey);
|
||||
if (!isValid) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const platform = os.platform();
|
||||
|
||||
switch (platform) {
|
||||
case "darwin":
|
||||
return writeMdmKeysMacOS(licenseKey);
|
||||
|
||||
case "win32":
|
||||
return writeMdmKeysWindows(licenseKey);
|
||||
|
||||
case "linux":
|
||||
return writeMdmKeysLinux(licenseKey);
|
||||
|
||||
default:
|
||||
console.error(
|
||||
`Setting MDM keys not supported on platform: ${platform}`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error setting MDM license key:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
177
core/core.ts
177
core/core.ts
|
|
@ -14,7 +14,7 @@ import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
|
|||
import { getControlPlaneEnv } from "./control-plane/env";
|
||||
import { DevDataSqliteDb } from "./data/devdataSqlite";
|
||||
import { DataLogger } from "./data/log";
|
||||
import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer";
|
||||
import { CodebaseIndexer } from "./indexing/CodebaseIndexer";
|
||||
import DocsService from "./indexing/docs/DocsService";
|
||||
import { countTokens } from "./llm/countTokens";
|
||||
import Ollama from "./llm/llms/Ollama";
|
||||
|
|
@ -41,7 +41,6 @@ import {
|
|||
type ContextItem,
|
||||
type ContextItemId,
|
||||
type IDE,
|
||||
type IndexingProgressUpdate,
|
||||
} from ".";
|
||||
|
||||
import { ConfigYaml } from "@continuedev/config-yaml";
|
||||
|
|
@ -54,10 +53,10 @@ import {
|
|||
} from "./config/onboarding";
|
||||
import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks";
|
||||
import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton";
|
||||
import { setMdmLicenseKey } from "./control-plane/mdm/mdm";
|
||||
import { streamDiffLines } from "./edit/streamDiffLines";
|
||||
import { shouldIgnore } from "./indexing/shouldIgnore";
|
||||
import { walkDirCache } from "./indexing/walkDir";
|
||||
import { LLMError } from "./llm";
|
||||
import { LLMLogger } from "./llm/logger";
|
||||
import { llmStreamChat } from "./llm/streamChat";
|
||||
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
|
||||
|
|
@ -66,18 +65,12 @@ import { StreamAbortManager } from "./util/abortManager";
|
|||
|
||||
export class Core {
|
||||
configHandler: ConfigHandler;
|
||||
codebaseIndexerPromise: Promise<CodebaseIndexer>;
|
||||
codeBaseIndexer: CodebaseIndexer;
|
||||
completionProvider: CompletionProvider;
|
||||
continueServerClientPromise: Promise<ContinueServerClient>;
|
||||
codebaseIndexingState: IndexingProgressUpdate;
|
||||
private docsService: DocsService;
|
||||
private globalContext = new GlobalContext();
|
||||
llmLogger = new LLMLogger();
|
||||
|
||||
private readonly indexingPauseToken = new PauseToken(
|
||||
this.globalContext.get("indexingPaused") === true,
|
||||
);
|
||||
|
||||
private messageAbortControllers = new Map<string, AbortController>();
|
||||
private addMessageAbortController(id: string): AbortController {
|
||||
const controller = new AbortController();
|
||||
|
|
@ -115,12 +108,6 @@ export class Core {
|
|||
// Ensure .continue directory is created
|
||||
migrateV1DevDataFiles();
|
||||
|
||||
this.codebaseIndexingState = {
|
||||
status: "loading",
|
||||
desc: "loading",
|
||||
progress: 0,
|
||||
};
|
||||
|
||||
const ideInfoPromise = messenger.request("getIdeInfo", undefined);
|
||||
const ideSettingsPromise = messenger.request("getIdeSettings", undefined);
|
||||
const sessionInfoPromise = messenger.request("getControlPlaneSessionInfo", {
|
||||
|
|
@ -145,6 +132,13 @@ export class Core {
|
|||
await this.configHandler.reloadConfig();
|
||||
};
|
||||
|
||||
this.codeBaseIndexer = new CodebaseIndexer(
|
||||
this.configHandler,
|
||||
this.ide,
|
||||
this.messenger,
|
||||
this.globalContext.get("indexingPaused"),
|
||||
);
|
||||
|
||||
this.configHandler.onConfigUpdate(async (result) => {
|
||||
const serializedResult = await this.configHandler.getSerializedConfig();
|
||||
this.messenger.send("configUpdate", {
|
||||
|
|
@ -171,38 +165,17 @@ export class Core {
|
|||
dataLogger.ideInfoPromise = ideInfoPromise;
|
||||
dataLogger.ideSettingsPromise = ideSettingsPromise;
|
||||
|
||||
// Codebase Indexer and ContinueServerClient depend on IdeSettings
|
||||
let codebaseIndexerResolve: (_: any) => void | undefined;
|
||||
this.codebaseIndexerPromise = new Promise(
|
||||
async (resolve) => (codebaseIndexerResolve = resolve),
|
||||
);
|
||||
|
||||
let continueServerClientResolve: (_: any) => void | undefined;
|
||||
this.continueServerClientPromise = new Promise(
|
||||
(resolve) => (continueServerClientResolve = resolve),
|
||||
);
|
||||
|
||||
void ideSettingsPromise.then((ideSettings) => {
|
||||
const continueServerClient = new ContinueServerClient(
|
||||
ideSettings.remoteConfigServerUrl,
|
||||
ideSettings.userToken,
|
||||
);
|
||||
continueServerClientResolve(continueServerClient);
|
||||
|
||||
codebaseIndexerResolve(
|
||||
new CodebaseIndexer(
|
||||
this.configHandler,
|
||||
this.ide,
|
||||
this.indexingPauseToken,
|
||||
continueServerClient,
|
||||
),
|
||||
);
|
||||
|
||||
// Index on initialization
|
||||
void this.ide.getWorkspaceDirs().then(async (dirs) => {
|
||||
// Respect pauseCodebaseIndexOnStart user settings
|
||||
if (ideSettings.pauseCodebaseIndexOnStart) {
|
||||
this.indexingPauseToken.paused = true;
|
||||
this.codeBaseIndexer.paused = true;
|
||||
void this.messenger.request("indexProgress", {
|
||||
progress: 0,
|
||||
desc: "Initial Indexing Skipped",
|
||||
|
|
@ -211,7 +184,7 @@ export class Core {
|
|||
return;
|
||||
}
|
||||
|
||||
void this.refreshCodebaseIndex(dirs);
|
||||
await this.codeBaseIndexer.refreshCodebaseIndex(dirs);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -363,6 +336,10 @@ export class Core {
|
|||
await this.messenger.request("openUrl", url);
|
||||
});
|
||||
|
||||
on("controlPlane/getFreeTrialStatus", async (msg) => {
|
||||
return this.configHandler.controlPlaneClient.getFreeTrialStatus();
|
||||
});
|
||||
|
||||
on("mcp/reloadServer", async (msg) => {
|
||||
await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
|
||||
});
|
||||
|
|
@ -552,25 +529,24 @@ export class Core {
|
|||
}
|
||||
walkDirCache.invalidate();
|
||||
if (data?.shouldClearIndexes) {
|
||||
const codebaseIndexer = await this.codebaseIndexerPromise;
|
||||
await codebaseIndexer.clearIndexes();
|
||||
await this.codeBaseIndexer.clearIndexes();
|
||||
}
|
||||
|
||||
const dirs = data?.dirs ?? (await this.ide.getWorkspaceDirs());
|
||||
await this.refreshCodebaseIndex(dirs);
|
||||
await this.codeBaseIndexer.refreshCodebaseIndex(dirs);
|
||||
});
|
||||
on("index/setPaused", (msg) => {
|
||||
this.globalContext.update("indexingPaused", msg.data);
|
||||
this.indexingPauseToken.paused = msg.data;
|
||||
// Update using the new setter instead of token
|
||||
this.codeBaseIndexer.paused = msg.data;
|
||||
});
|
||||
on("index/indexingProgressBarInitialized", async (msg) => {
|
||||
// Triggered when progress bar is initialized.
|
||||
// If a non-default state has been stored, update the indexing display to that state
|
||||
if (this.codebaseIndexingState.status !== "loading") {
|
||||
void this.messenger.request(
|
||||
"indexProgress",
|
||||
this.codebaseIndexingState,
|
||||
);
|
||||
const currentState = this.codeBaseIndexer.currentIndexingState;
|
||||
|
||||
if (currentState.status !== "loading") {
|
||||
void this.messenger.request("indexProgress", currentState);
|
||||
}
|
||||
});
|
||||
|
||||
|
|
@ -590,7 +566,7 @@ export class Core {
|
|||
});
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
if (config && !config.disableIndexing) {
|
||||
await this.refreshCodebaseIndexFiles(toRefresh);
|
||||
await this.codeBaseIndexer.refreshCodebaseIndexFiles(toRefresh);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
|
@ -751,6 +727,11 @@ export class Core {
|
|||
return isBackgrounded; // Return true to indicate the message was handled successfully
|
||||
},
|
||||
);
|
||||
|
||||
on("mdm/setLicenseKey", ({ data: { licenseKey } }) => {
|
||||
const isValid = setMdmLicenseKey(licenseKey);
|
||||
return isValid;
|
||||
});
|
||||
}
|
||||
|
||||
private async isItemTooBig(item: ContextItemWithId) {
|
||||
|
|
@ -856,7 +837,7 @@ export class Core {
|
|||
// Reindex the file
|
||||
const ignore = await shouldIgnore(uri, this.ide);
|
||||
if (!ignore) {
|
||||
await this.refreshCodebaseIndexFiles([uri]);
|
||||
await this.codeBaseIndexer.refreshCodebaseIndexFiles([uri]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1027,100 +1008,4 @@ export class Core {
|
|||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
private indexingCancellationController: AbortController | undefined;
|
||||
private async sendIndexingErrorTelemetry(update: IndexingProgressUpdate) {
|
||||
console.debug(
|
||||
"Indexing failed with error: ",
|
||||
update.desc,
|
||||
update.debugInfo,
|
||||
);
|
||||
void Telemetry.capture(
|
||||
"indexing_error",
|
||||
{
|
||||
error: update.desc,
|
||||
stack: update.debugInfo,
|
||||
},
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
private async refreshCodebaseIndex(paths: string[]) {
|
||||
if (this.indexingCancellationController) {
|
||||
this.indexingCancellationController.abort();
|
||||
}
|
||||
this.indexingCancellationController = new AbortController();
|
||||
try {
|
||||
for await (const update of (
|
||||
await this.codebaseIndexerPromise
|
||||
).refreshDirs(paths, this.indexingCancellationController.signal)) {
|
||||
let updateToSend = { ...update };
|
||||
|
||||
void this.messenger.request("indexProgress", updateToSend);
|
||||
this.codebaseIndexingState = updateToSend;
|
||||
|
||||
if (update.status === "failed") {
|
||||
void this.sendIndexingErrorTelemetry(update);
|
||||
}
|
||||
}
|
||||
} catch (e: any) {
|
||||
console.log(`Failed refreshing codebase index directories : ${e}`);
|
||||
this.handleIndexingError(e);
|
||||
}
|
||||
|
||||
this.messenger.send("refreshSubmenuItems", {
|
||||
providers: "dependsOnIndexing",
|
||||
});
|
||||
this.indexingCancellationController = undefined;
|
||||
}
|
||||
|
||||
private async refreshCodebaseIndexFiles(files: string[]) {
|
||||
// Can be cancelled by codebase index but not vice versa
|
||||
if (
|
||||
this.indexingCancellationController &&
|
||||
!this.indexingCancellationController.signal.aborted
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this.indexingCancellationController = new AbortController();
|
||||
try {
|
||||
for await (const update of (
|
||||
await this.codebaseIndexerPromise
|
||||
).refreshFiles(files)) {
|
||||
let updateToSend = { ...update };
|
||||
|
||||
void this.messenger.request("indexProgress", updateToSend);
|
||||
this.codebaseIndexingState = updateToSend;
|
||||
|
||||
if (update.status === "failed") {
|
||||
void this.sendIndexingErrorTelemetry(update);
|
||||
}
|
||||
}
|
||||
} catch (e: any) {
|
||||
console.log(`Failed refreshing codebase index files : ${e}`);
|
||||
this.handleIndexingError(e);
|
||||
}
|
||||
|
||||
this.messenger.send("refreshSubmenuItems", {
|
||||
providers: "dependsOnIndexing",
|
||||
});
|
||||
this.indexingCancellationController = undefined;
|
||||
}
|
||||
|
||||
// private
|
||||
handleIndexingError(e: any) {
|
||||
if (e instanceof LLMError) {
|
||||
// Need to report this specific error to the IDE for special handling
|
||||
void this.messenger.request("reportError", e);
|
||||
}
|
||||
// broadcast indexing error
|
||||
let updateToSend: IndexingProgressUpdate = {
|
||||
progress: 0,
|
||||
status: "failed",
|
||||
desc: e.message,
|
||||
};
|
||||
void this.messenger.request("indexProgress", updateToSend);
|
||||
this.codebaseIndexingState = updateToSend;
|
||||
void this.sendIndexingErrorTelemetry(updateToSend);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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];
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import { execSync } from "node:child_process";
|
|||
import fs from "node:fs";
|
||||
import path from "path";
|
||||
|
||||
import { ContinueServerClient } from "../continueServer/stubs/client.js";
|
||||
import { LLMError } from "../llm/index.js";
|
||||
import { testConfigHandler, testIde } from "../test/fixtures.js";
|
||||
import {
|
||||
addToTestDir,
|
||||
|
|
@ -59,16 +59,34 @@ class TestCodebaseIndexer extends CodebaseIndexer {
|
|||
}
|
||||
}
|
||||
|
||||
// Create a mock messenger type that doesn't require actual protocol imports
|
||||
type MockMessengerType = {
|
||||
send: jest.Mock;
|
||||
request: jest.Mock;
|
||||
invoke: jest.Mock;
|
||||
on: jest.Mock;
|
||||
onError: jest.Mock;
|
||||
};
|
||||
|
||||
// These are more like integration tests, whereas we should separately test
|
||||
// the individual CodebaseIndex classes
|
||||
describe("CodebaseIndexer", () => {
|
||||
const pauseToken = new PauseToken(false);
|
||||
const continueServerClient = new ContinueServerClient(undefined, undefined);
|
||||
|
||||
// Replace mockProgressReporter with mockMessenger
|
||||
const mockMessenger: MockMessengerType = {
|
||||
send: jest.fn(),
|
||||
request: jest.fn(async () => {}),
|
||||
invoke: jest.fn(),
|
||||
on: jest.fn(),
|
||||
onError: jest.fn(),
|
||||
};
|
||||
|
||||
const codebaseIndexer = new TestCodebaseIndexer(
|
||||
testConfigHandler,
|
||||
testIde,
|
||||
pauseToken,
|
||||
continueServerClient,
|
||||
mockMessenger as any,
|
||||
false,
|
||||
);
|
||||
const testIndex = new TestCodebaseIndex();
|
||||
|
||||
|
|
@ -89,6 +107,7 @@ describe("CodebaseIndexer", () => {
|
|||
|
||||
afterEach(() => {
|
||||
walkDirCache.invalidate();
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
async function refreshIndex() {
|
||||
|
|
@ -241,4 +260,155 @@ describe("CodebaseIndexer", () => {
|
|||
execSync(`cd ${TEST_DIR_PATH} && git checkout main`);
|
||||
await expectPlan(0, 0, 0, 0);
|
||||
});
|
||||
|
||||
// New tests for the methods added from Core.ts
|
||||
describe("New methods from Core.ts", () => {
|
||||
// Simplified tests to focus on behavior, not implementation details
|
||||
test("should call messenger with progress updates when refreshing codebase index", async () => {
|
||||
jest
|
||||
.spyOn(codebaseIndexer as any, "refreshDirs")
|
||||
.mockImplementation(async function* () {
|
||||
yield { status: "done", progress: 1, desc: "Completed" };
|
||||
});
|
||||
|
||||
await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
|
||||
|
||||
expect(mockMessenger.request).toHaveBeenCalledWith(
|
||||
"indexProgress",
|
||||
expect.anything(),
|
||||
);
|
||||
expect(mockMessenger.send).toHaveBeenCalledWith("refreshSubmenuItems", {
|
||||
providers: "dependsOnIndexing",
|
||||
});
|
||||
});
|
||||
|
||||
test("should call messenger with progress updates when refreshing specific files", async () => {
|
||||
jest
|
||||
.spyOn(codebaseIndexer as any, "refreshFiles")
|
||||
.mockImplementation(async function* () {
|
||||
yield { status: "done", progress: 1, desc: "Completed" };
|
||||
});
|
||||
|
||||
await codebaseIndexer.refreshCodebaseIndexFiles(["/test/file.ts"]);
|
||||
|
||||
expect(mockMessenger.request).toHaveBeenCalledWith(
|
||||
"indexProgress",
|
||||
expect.anything(),
|
||||
);
|
||||
expect(mockMessenger.send).toHaveBeenCalledWith("refreshSubmenuItems", {
|
||||
providers: "all",
|
||||
});
|
||||
});
|
||||
|
||||
test("should abort previous indexing when starting a new one", async () => {
|
||||
// Set up a situation where indexingCancellationController exists
|
||||
const mockAbort = jest.fn();
|
||||
const controller = { abort: mockAbort, signal: { aborted: false } };
|
||||
|
||||
// Access the private property in a type-safe way for testing
|
||||
(codebaseIndexer as any).indexingCancellationController = controller;
|
||||
|
||||
// Mock refreshDirs to return immediately
|
||||
jest
|
||||
.spyOn(codebaseIndexer as any, "refreshDirs")
|
||||
.mockImplementation(async function* () {
|
||||
yield { status: "done", progress: 1, desc: "Completed" };
|
||||
});
|
||||
|
||||
// Start indexing - this should call abort on the existing controller
|
||||
await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
|
||||
|
||||
// Verify abort was called
|
||||
expect(mockAbort).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("should handle errors properly during indexing", async () => {
|
||||
const testError = new Error("Test indexing error");
|
||||
|
||||
// Mock console.log to avoid printing errors
|
||||
const consoleLogSpy = jest
|
||||
.spyOn(console, "log")
|
||||
.mockImplementation(() => {});
|
||||
|
||||
// Mock refreshDirs to throw an error
|
||||
jest
|
||||
.spyOn(codebaseIndexer as any, "refreshDirs")
|
||||
.mockImplementation(() => {
|
||||
throw testError;
|
||||
});
|
||||
|
||||
// We don't need to mock AbortController because we're mocking the entire refreshDirs call
|
||||
await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
|
||||
|
||||
// Use the first argument only for the assertion since the second argument doesn't match exactly
|
||||
expect(consoleLogSpy).toHaveBeenCalledWith(
|
||||
`Failed refreshing codebase index directories: Error: ${testError.message}`,
|
||||
);
|
||||
expect(mockMessenger.request).toHaveBeenCalledWith(
|
||||
"indexProgress",
|
||||
expect.objectContaining({
|
||||
status: "failed",
|
||||
}),
|
||||
);
|
||||
|
||||
consoleLogSpy.mockRestore();
|
||||
});
|
||||
|
||||
test("should handle LLMError specially during indexing", async () => {
|
||||
// Create a mock LLM
|
||||
const mockLlm: any = {
|
||||
providerName: "test-provider",
|
||||
model: "test-model",
|
||||
};
|
||||
|
||||
// Create a real LLMError
|
||||
const llmError = new LLMError("Test LLM error", mockLlm);
|
||||
|
||||
// Mock console.log to avoid printing errors
|
||||
jest.spyOn(console, "log").mockImplementation(() => {});
|
||||
|
||||
// Mock refreshDirs to throw an LLMError
|
||||
jest
|
||||
.spyOn(codebaseIndexer as any, "refreshDirs")
|
||||
.mockImplementation(() => {
|
||||
throw llmError;
|
||||
});
|
||||
|
||||
// We don't need to mock AbortController because we're mocking the entire refreshDirs call
|
||||
await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
|
||||
|
||||
expect(mockMessenger.request).toHaveBeenCalledWith(
|
||||
"reportError",
|
||||
llmError,
|
||||
);
|
||||
expect(mockMessenger.request).toHaveBeenCalledWith(
|
||||
"indexProgress",
|
||||
expect.objectContaining({
|
||||
status: "failed",
|
||||
desc: "Test LLM error",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
test("should provide access to current indexing state", async () => {
|
||||
const testState = {
|
||||
progress: 0.5,
|
||||
status: "indexing" as const,
|
||||
desc: "Test state",
|
||||
};
|
||||
|
||||
// Mock refreshDirs to set a specific state
|
||||
jest
|
||||
.spyOn(codebaseIndexer as any, "refreshDirs")
|
||||
.mockImplementation(async function* () {
|
||||
yield testState;
|
||||
});
|
||||
|
||||
// We don't need to mock AbortController because we're mocking the entire refreshDirs call
|
||||
await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
|
||||
|
||||
// Check that the state was updated
|
||||
expect(codebaseIndexer.currentIndexingState).toEqual(testState);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -3,10 +3,14 @@ import * as fs from "fs/promises";
|
|||
import { ConfigHandler } from "../config/ConfigHandler.js";
|
||||
import { IContinueServerClient } from "../continueServer/interface.js";
|
||||
import { IDE, IndexingProgressUpdate, IndexTag } from "../index.js";
|
||||
import type { FromCoreProtocol, ToCoreProtocol } from "../protocol";
|
||||
import type { IMessenger } from "../protocol/messenger";
|
||||
import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js";
|
||||
import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js";
|
||||
import { Telemetry } from "../util/posthog.js";
|
||||
import { findUriInDirs, getUriPathBasename } from "../util/uri.js";
|
||||
|
||||
import { ContinueServerClient } from "../continueServer/stubs/client";
|
||||
import { LLMError } from "../llm/index.js";
|
||||
import { getRootCause } from "../util/errors.js";
|
||||
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
|
||||
|
|
@ -41,6 +45,9 @@ export class CodebaseIndexer {
|
|||
* - To make as few requests as possible to the embeddings providers
|
||||
*/
|
||||
filesPerBatch = 500;
|
||||
private indexingCancellationController: AbortController | undefined;
|
||||
private codebaseIndexingState: IndexingProgressUpdate;
|
||||
private readonly pauseToken: PauseToken;
|
||||
|
||||
// Note that we exclude certain Sqlite errors that we do not want to clear the indexes on,
|
||||
// e.g. a `SQLITE_BUSY` error.
|
||||
|
|
@ -56,9 +63,32 @@ export class CodebaseIndexer {
|
|||
constructor(
|
||||
private readonly configHandler: ConfigHandler,
|
||||
protected readonly ide: IDE,
|
||||
private readonly pauseToken: PauseToken,
|
||||
private readonly continueServerClient: IContinueServerClient,
|
||||
) {}
|
||||
private readonly messenger?: IMessenger<ToCoreProtocol, FromCoreProtocol>,
|
||||
initialPaused: boolean = false,
|
||||
) {
|
||||
this.codebaseIndexingState = {
|
||||
status: "loading",
|
||||
desc: "loading",
|
||||
progress: 0,
|
||||
};
|
||||
|
||||
// Initialize pause token
|
||||
this.pauseToken = new PauseToken(initialPaused);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the paused state of the indexer
|
||||
*/
|
||||
set paused(value: boolean) {
|
||||
this.pauseToken.paused = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current paused state of the indexer
|
||||
*/
|
||||
get paused(): boolean {
|
||||
return this.pauseToken.paused;
|
||||
}
|
||||
|
||||
async clearIndexes() {
|
||||
const sqliteFilepath = getIndexSqlitePath();
|
||||
|
|
@ -88,10 +118,22 @@ export class CodebaseIndexer {
|
|||
return [];
|
||||
}
|
||||
|
||||
const ideSettings = await this.ide.getIdeSettings();
|
||||
if (!ideSettings) {
|
||||
return [];
|
||||
}
|
||||
const continueServerClient = new ContinueServerClient(
|
||||
ideSettings.remoteConfigServerUrl,
|
||||
ideSettings.userToken,
|
||||
);
|
||||
if (!continueServerClient) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const indexes: CodebaseIndex[] = [
|
||||
new ChunkCodebaseIndex(
|
||||
this.ide.readFile.bind(this.ide),
|
||||
this.continueServerClient,
|
||||
continueServerClient,
|
||||
embeddingsModel.maxEmbeddingChunkSize,
|
||||
), // Chunking must come first
|
||||
];
|
||||
|
|
@ -504,4 +546,109 @@ export class CodebaseIndexer {
|
|||
completedIndexCount += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// New methods using messenger directly
|
||||
|
||||
private async updateProgress(update: IndexingProgressUpdate) {
|
||||
this.codebaseIndexingState = update;
|
||||
if (this.messenger) {
|
||||
await this.messenger.request("indexProgress", update);
|
||||
}
|
||||
}
|
||||
|
||||
private async sendIndexingErrorTelemetry(update: IndexingProgressUpdate) {
|
||||
console.debug(
|
||||
"Indexing failed with error: ",
|
||||
update.desc,
|
||||
update.debugInfo,
|
||||
);
|
||||
void Telemetry.capture(
|
||||
"indexing_error",
|
||||
{
|
||||
error: update.desc,
|
||||
stack: update.debugInfo,
|
||||
},
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
public async refreshCodebaseIndex(paths: string[]) {
|
||||
if (this.indexingCancellationController) {
|
||||
this.indexingCancellationController.abort();
|
||||
}
|
||||
this.indexingCancellationController = new AbortController();
|
||||
try {
|
||||
for await (const update of this.refreshDirs(
|
||||
paths,
|
||||
this.indexingCancellationController.signal,
|
||||
)) {
|
||||
await this.updateProgress(update);
|
||||
|
||||
if (update.status === "failed") {
|
||||
await this.sendIndexingErrorTelemetry(update);
|
||||
}
|
||||
}
|
||||
} catch (e: any) {
|
||||
console.log(`Failed refreshing codebase index directories: ${e}`);
|
||||
await this.handleIndexingError(e);
|
||||
}
|
||||
|
||||
// Directly refresh submenu items
|
||||
if (this.messenger) {
|
||||
this.messenger.send("refreshSubmenuItems", {
|
||||
providers: "dependsOnIndexing",
|
||||
});
|
||||
}
|
||||
this.indexingCancellationController = undefined;
|
||||
}
|
||||
|
||||
public async refreshCodebaseIndexFiles(files: string[]) {
|
||||
// Can be cancelled by codebase index but not vice versa
|
||||
if (
|
||||
this.indexingCancellationController &&
|
||||
!this.indexingCancellationController.signal.aborted
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this.indexingCancellationController = new AbortController();
|
||||
try {
|
||||
for await (const update of this.refreshFiles(files)) {
|
||||
await this.updateProgress(update);
|
||||
|
||||
if (update.status === "failed") {
|
||||
await this.sendIndexingErrorTelemetry(update);
|
||||
}
|
||||
}
|
||||
} catch (e: any) {
|
||||
console.log(`Failed refreshing codebase index files: ${e}`);
|
||||
await this.handleIndexingError(e);
|
||||
}
|
||||
|
||||
// Directly refresh submenu items
|
||||
if (this.messenger) {
|
||||
this.messenger.send("refreshSubmenuItems", { providers: "all" });
|
||||
}
|
||||
this.indexingCancellationController = undefined;
|
||||
}
|
||||
|
||||
public async handleIndexingError(e: any) {
|
||||
if (e instanceof LLMError && this.messenger) {
|
||||
// Need to report this specific error to the IDE for special handling
|
||||
await this.messenger.request("reportError", e);
|
||||
}
|
||||
|
||||
// broadcast indexing error
|
||||
const updateToSend: IndexingProgressUpdate = {
|
||||
progress: 0,
|
||||
status: "failed",
|
||||
desc: e.message,
|
||||
};
|
||||
|
||||
await this.updateProgress(updateToSend);
|
||||
void this.sendIndexingErrorTelemetry(updateToSend);
|
||||
}
|
||||
|
||||
public get currentIndexingState(): IndexingProgressUpdate {
|
||||
return this.codebaseIndexingState;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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!"');
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -480,5 +480,5 @@ export {
|
|||
pruneLinesFromTop,
|
||||
pruneRawPromptFromTop,
|
||||
pruneStringFromBottom,
|
||||
pruneStringFromTop
|
||||
pruneStringFromTop,
|
||||
};
|
||||
|
|
|
|||
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;
|
||||
|
|
|
|||
|
|
@ -342,13 +342,13 @@ class Gemini extends BaseLLM {
|
|||
throw new Error(data.error.message);
|
||||
}
|
||||
|
||||
// Check for existence of each level before accessing the final 'text' property
|
||||
const content = data?.candidates?.[0]?.content;
|
||||
if (content) {
|
||||
// In case of max tokens reached, gemini will sometimes return content with no parts, even though that doesn't match the API spec
|
||||
const contentParts = data?.candidates?.[0]?.content?.parts;
|
||||
if (contentParts) {
|
||||
const textParts: MessagePart[] = [];
|
||||
const toolCalls: ToolCallDelta[] = [];
|
||||
|
||||
for (const part of content.parts) {
|
||||
for (const part of contentParts) {
|
||||
if ("text" in part) {
|
||||
textParts.push({ type: "text", text: part.text });
|
||||
} else if ("functionCall" in part) {
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -85,6 +85,12 @@ class ContinueProxy extends OpenAI {
|
|||
}
|
||||
|
||||
supportsCompletions(): boolean {
|
||||
// This was a hotfix and contains duplicate logic from class-specific completion support methods
|
||||
if (this.underlyingProviderName === "vllm") {
|
||||
return true;
|
||||
}
|
||||
// other providers that don't support completions include groq, mistral, nvidia, deepseek, etc.
|
||||
// For now disabling all except vllm
|
||||
return false;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
/* eslint-disable max-lines-per-function */
|
||||
import { ContextItemWithId, RuleWithSource, UserChatMessage } from "../..";
|
||||
import { getSystemMessageWithRules, shouldApplyRule } from "./getSystemMessageWithRules";
|
||||
import {
|
||||
getSystemMessageWithRules,
|
||||
shouldApplyRule,
|
||||
} from "./getSystemMessageWithRules";
|
||||
|
||||
describe("getSystemMessageWithRules", () => {
|
||||
const baseSystemMessage = "Base system message";
|
||||
|
|
@ -450,7 +453,8 @@ describe("getSystemMessageWithRules", () => {
|
|||
it("should include rules with alwaysApply: false when globs match", () => {
|
||||
const userMessage: UserChatMessage = {
|
||||
role: "user",
|
||||
content: "```tsx Component.tsx\nexport const Component = () => <div>Hello</div>;\n```",
|
||||
content:
|
||||
"```tsx Component.tsx\nexport const Component = () => <div>Hello</div>;\n```",
|
||||
};
|
||||
|
||||
const result = getSystemMessageWithRules({
|
||||
|
|
@ -701,14 +705,18 @@ describe("shouldApplyRule", () => {
|
|||
it("should return true when alwaysApply is true, regardless of file paths", () => {
|
||||
expect(shouldApplyRule(ruleAlwaysApplyTrue, [])).toBe(true);
|
||||
expect(shouldApplyRule(ruleAlwaysApplyTrue, ["src/main.js"])).toBe(true);
|
||||
expect(shouldApplyRule(ruleAlwaysApplyTrue, ["Component.tsx"])).toBe(true);
|
||||
expect(shouldApplyRule(ruleAlwaysApplyTrue, ["Component.tsx"])).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("should use glob matching when alwaysApply is false", () => {
|
||||
// Should apply when globs match
|
||||
expect(shouldApplyRule(ruleAlwaysApplyFalse, ["src/main.ts"])).toBe(true);
|
||||
expect(shouldApplyRule(ruleAlwaysApplyFalse, ["Component.tsx"])).toBe(true);
|
||||
|
||||
expect(shouldApplyRule(ruleAlwaysApplyFalse, ["Component.tsx"])).toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
// Should not apply when globs don't match
|
||||
expect(shouldApplyRule(ruleAlwaysApplyFalse, ["script.py"])).toBe(false);
|
||||
expect(shouldApplyRule(ruleAlwaysApplyFalse, [])).toBe(false);
|
||||
|
|
@ -716,7 +724,9 @@ describe("shouldApplyRule", () => {
|
|||
|
||||
it("should return false when alwaysApply is false and no globs specified", () => {
|
||||
expect(shouldApplyRule(ruleAlwaysApplyFalseNoGlobs, [])).toBe(false);
|
||||
expect(shouldApplyRule(ruleAlwaysApplyFalseNoGlobs, ["any-file.js"])).toBe(false);
|
||||
expect(
|
||||
shouldApplyRule(ruleAlwaysApplyFalseNoGlobs, ["any-file.js"]),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -724,7 +734,9 @@ describe("shouldApplyRule", () => {
|
|||
it("should return true for rules without globs regardless of file paths", () => {
|
||||
expect(shouldApplyRule(ruleWithoutGlobs, [])).toBe(true);
|
||||
expect(shouldApplyRule(ruleWithoutGlobs, ["src/main.js"])).toBe(true);
|
||||
expect(shouldApplyRule(ruleWithoutGlobs, ["Component.tsx", "utils.py"])).toBe(true);
|
||||
expect(
|
||||
shouldApplyRule(ruleWithoutGlobs, ["Component.tsx", "utils.py"]),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false for rules with globs when no file paths are provided", () => {
|
||||
|
|
@ -734,12 +746,16 @@ describe("shouldApplyRule", () => {
|
|||
it("should return true for rules with globs when matching file paths are provided", () => {
|
||||
expect(shouldApplyRule(ruleWithGlobs, ["Component.tsx"])).toBe(true);
|
||||
expect(shouldApplyRule(ruleWithGlobs, ["src/main.ts"])).toBe(true);
|
||||
expect(shouldApplyRule(ruleWithGlobs, ["utils.js", "Component.tsx"])).toBe(true);
|
||||
expect(
|
||||
shouldApplyRule(ruleWithGlobs, ["utils.js", "Component.tsx"]),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false for rules with globs when no matching file paths are provided", () => {
|
||||
expect(shouldApplyRule(ruleWithGlobs, ["utils.py"])).toBe(false);
|
||||
expect(shouldApplyRule(ruleWithGlobs, ["main.js", "script.rb"])).toBe(false);
|
||||
expect(shouldApplyRule(ruleWithGlobs, ["main.js", "script.rb"])).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -760,19 +776,39 @@ describe("shouldApplyRule", () => {
|
|||
|
||||
it("should handle array of glob patterns", () => {
|
||||
expect(shouldApplyRule(ruleWithArrayGlobs, ["src/main.ts"])).toBe(true);
|
||||
expect(shouldApplyRule(ruleWithArrayGlobs, ["tests/unit.test.js"])).toBe(true);
|
||||
expect(shouldApplyRule(ruleWithArrayGlobs, ["config/settings.json"])).toBe(false);
|
||||
expect(shouldApplyRule(ruleWithArrayGlobs, ["tests/unit.test.js"])).toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
shouldApplyRule(ruleWithArrayGlobs, ["config/settings.json"]),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should handle string glob patterns", () => {
|
||||
expect(shouldApplyRule(ruleWithSpecificPattern, ["utils.py"])).toBe(true);
|
||||
expect(shouldApplyRule(ruleWithSpecificPattern, ["src/models/user.py"])).toBe(true);
|
||||
expect(shouldApplyRule(ruleWithSpecificPattern, ["utils.js"])).toBe(false);
|
||||
expect(
|
||||
shouldApplyRule(ruleWithSpecificPattern, ["src/models/user.py"]),
|
||||
).toBe(true);
|
||||
expect(shouldApplyRule(ruleWithSpecificPattern, ["utils.js"])).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("should return true if any file path matches when multiple paths provided", () => {
|
||||
expect(shouldApplyRule(ruleWithSpecificPattern, ["utils.js", "models.py", "config.json"])).toBe(true);
|
||||
expect(shouldApplyRule(ruleWithGlobs, ["utils.py", "Component.tsx", "script.rb"])).toBe(true);
|
||||
expect(
|
||||
shouldApplyRule(ruleWithSpecificPattern, [
|
||||
"utils.js",
|
||||
"models.py",
|
||||
"config.json",
|
||||
]),
|
||||
).toBe(true);
|
||||
expect(
|
||||
shouldApplyRule(ruleWithGlobs, [
|
||||
"utils.py",
|
||||
"Component.tsx",
|
||||
"script.rb",
|
||||
]),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -784,7 +820,7 @@ describe("shouldApplyRule", () => {
|
|||
globs: [],
|
||||
source: "rules-block",
|
||||
};
|
||||
|
||||
|
||||
// Empty array should be treated as "no globs" (truthy check fails)
|
||||
expect(shouldApplyRule(ruleWithEmptyGlobs, ["any-file.js"])).toBe(false);
|
||||
});
|
||||
|
|
@ -796,7 +832,7 @@ describe("shouldApplyRule", () => {
|
|||
globs: undefined,
|
||||
source: "rules-block",
|
||||
};
|
||||
|
||||
|
||||
expect(shouldApplyRule(ruleUndefinedGlobs, ["any-file.js"])).toBe(true);
|
||||
expect(shouldApplyRule(ruleUndefinedGlobs, [])).toBe(true);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
import { ConfigHandler } from "../config/ConfigHandler.js";
|
||||
import { TRIAL_FIM_MODEL } from "../config/onboarding.js";
|
||||
import { IDE, ILLM } from "../index.js";
|
||||
import OpenAI from "../llm/llms/OpenAI.js";
|
||||
import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js";
|
||||
|
|
@ -18,7 +17,10 @@ import { AutocompleteDebouncer } from "../autocomplete/util/AutocompleteDebounce
|
|||
import { AutocompleteLoggingService } from "../autocomplete/util/AutocompleteLoggingService.js";
|
||||
import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js";
|
||||
import { HelperVars } from "../autocomplete/util/HelperVars.js";
|
||||
import { AutocompleteInput, AutocompleteOutcome } from "../autocomplete/util/types.js";
|
||||
import {
|
||||
AutocompleteInput,
|
||||
AutocompleteOutcome,
|
||||
} from "../autocomplete/util/types.js";
|
||||
|
||||
const autocompleteCache = AutocompleteLruCache.get();
|
||||
|
||||
|
|
@ -75,12 +77,14 @@ export class NextEditProvider {
|
|||
|
||||
if (llm instanceof OpenAI) {
|
||||
llm.useLegacyCompletionsEndpoint = true;
|
||||
} else if (
|
||||
llm.providerName === "free-trial" &&
|
||||
llm.model !== TRIAL_FIM_MODEL
|
||||
) {
|
||||
llm.model = TRIAL_FIM_MODEL;
|
||||
}
|
||||
// TODO: Resolve import error with TRIAL_FIM_MODEL
|
||||
// else if (
|
||||
// llm.providerName === "free-trial" &&
|
||||
// llm.model !== TRIAL_FIM_MODEL
|
||||
// ) {
|
||||
// llm.model = TRIAL_FIM_MODEL;
|
||||
// }
|
||||
|
||||
return llm;
|
||||
}
|
||||
|
|
@ -224,11 +228,11 @@ export class NextEditProvider {
|
|||
|
||||
const processedCompletion = helper.options.transform
|
||||
? postprocessCompletion({
|
||||
completion,
|
||||
prefix: helper.prunedPrefix,
|
||||
suffix: helper.prunedSuffix,
|
||||
llm,
|
||||
})
|
||||
completion,
|
||||
prefix: helper.prunedPrefix,
|
||||
suffix: helper.prunedSuffix,
|
||||
llm,
|
||||
})
|
||||
: completion;
|
||||
|
||||
completion = processedCompletion;
|
||||
|
|
|
|||
21
core/package-lock.json
generated
21
core/package-lock.json
generated
|
|
@ -14,7 +14,7 @@
|
|||
"@aws-sdk/credential-providers": "^3.778.0",
|
||||
"@continuedev/config-types": "^1.0.13",
|
||||
"@continuedev/config-yaml": "file:../packages/config-yaml",
|
||||
"@continuedev/fetch": "^1.0.10",
|
||||
"@continuedev/fetch": "^1.0.13",
|
||||
"@continuedev/llm-info": "^1.0.8",
|
||||
"@continuedev/openai-adapters": "^1.0.25",
|
||||
"@modelcontextprotocol/sdk": "^1.12.0",
|
||||
|
|
@ -2928,10 +2928,9 @@
|
|||
"link": true
|
||||
},
|
||||
"node_modules/@continuedev/fetch": {
|
||||
"version": "1.0.10",
|
||||
"resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.10.tgz",
|
||||
"integrity": "sha512-RBUXtm/VDz+9Itgw+CxrHXwVXoHCAedGzPOgA7gS5HZ9lObaeCJgEfzmfbln1ocFsfqSFmn5X5wSE7DHgfxpVA==",
|
||||
"license": "Apache-2.0",
|
||||
"version": "1.0.13",
|
||||
"resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.13.tgz",
|
||||
"integrity": "sha512-7vwsefFBozsutv355zD7mEhFfl6UT4KXRH1QXRzjdbCaYneiRdFLe6UAwV2wGnH71Lj76gOLnTlcGoTV357OZg==",
|
||||
"dependencies": {
|
||||
"@continuedev/config-types": "^1.0.5",
|
||||
"follow-redirects": "^1.15.6",
|
||||
|
|
@ -14808,9 +14807,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/prebuild-install/node_modules/tar-fs": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.2.tgz",
|
||||
"integrity": "sha512-EsaAXwxmx8UB7FRKqeozqEPop69DXcmYwTQwXvyAPF352HJsPdkVhvTaDPYqfNgruveJIJy3TA2l+2zj8LJIJA==",
|
||||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.3.tgz",
|
||||
"integrity": "sha512-090nwYJDmlhwFwEW3QQl+vaNnxsO2yVsd45eTKRBzSzu+hlb1w2K9inVq5b0ngXuLVqQ4ApvsUHHnu/zQNkWAg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"chownr": "^1.1.1",
|
||||
|
|
@ -16641,9 +16640,9 @@
|
|||
}
|
||||
},
|
||||
"node_modules/tar-fs": {
|
||||
"version": "3.0.8",
|
||||
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.0.8.tgz",
|
||||
"integrity": "sha512-ZoROL70jptorGAlgAYiLoBLItEKw/fUxg9BSYK/dF/GAGYFJOJJJMvjPAKDJraCXFwadD456FCuvLWgfhMsPwg==",
|
||||
"version": "3.0.9",
|
||||
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.0.9.tgz",
|
||||
"integrity": "sha512-XF4w9Xp+ZQgifKakjZYmFdkLoSWd34VGKcsTCwlNWM7QG3ZbaxnTsaBwnjFZqHRf/rROxaR8rXnbtwdvaDI+lA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"pump": "^3.0.0",
|
||||
|
|
|
|||
|
|
@ -51,7 +51,7 @@
|
|||
"@aws-sdk/credential-providers": "^3.778.0",
|
||||
"@continuedev/config-types": "^1.0.13",
|
||||
"@continuedev/config-yaml": "file:../packages/config-yaml",
|
||||
"@continuedev/fetch": "^1.0.10",
|
||||
"@continuedev/fetch": "^1.0.13",
|
||||
"@continuedev/llm-info": "^1.0.8",
|
||||
"@continuedev/openai-adapters": "^1.0.25",
|
||||
"@modelcontextprotocol/sdk": "^1.12.0",
|
||||
|
|
|
|||
|
|
@ -13,13 +13,6 @@ export function extractName(preamble: { name?: string }, path: string): string {
|
|||
return preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0];
|
||||
}
|
||||
|
||||
export function extractUserInput(input: string, commandName: string): string {
|
||||
if (input.startsWith(`/${commandName}`)) {
|
||||
return input.slice(commandName.length + 1).trimStart();
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
||||
async function renderPromptV1(
|
||||
prompt: string,
|
||||
context: ContinueSDK,
|
||||
|
|
@ -66,10 +59,9 @@ export function slashCommandFromPromptFileV1(
|
|||
prompt,
|
||||
promptFile: path,
|
||||
run: async function* (context) {
|
||||
const userInput = extractUserInput(context.input, name);
|
||||
const [_, renderedPrompt] = await renderPromptFileV2(prompt, {
|
||||
config: context.config,
|
||||
fullInput: userInput,
|
||||
fullInput: context.input,
|
||||
embeddingsProvider: context.config.modelsByRole.embed[0],
|
||||
reranker: context.config.modelsByRole.rerank[0],
|
||||
llm: context.llm,
|
||||
|
|
@ -85,18 +77,6 @@ export function slashCommandFromPromptFileV1(
|
|||
systemMessage,
|
||||
);
|
||||
|
||||
if (systemMessage) {
|
||||
const currentSystemMsg = messages.find((msg) => msg.role === "system");
|
||||
if (currentSystemMsg) {
|
||||
currentSystemMsg.content = systemMessage;
|
||||
} else {
|
||||
messages.unshift({
|
||||
role: "system",
|
||||
content: systemMessage,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for await (const chunk of context.llm.streamChat(
|
||||
messages,
|
||||
new AbortController().signal,
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { ContextItem, ContextProviderExtras } from "../..";
|
||||
import { contextProviderClassFromName } from "../../context/providers";
|
||||
import URLContextProvider from "../../context/providers/URLContextProvider";
|
||||
import { getUrlContextItems } from "../../context/providers/URLContextProvider";
|
||||
import { resolveRelativePathInDir } from "../../util/ideUtils";
|
||||
import { getUriPathBasename } from "../../util/uri";
|
||||
|
||||
|
|
@ -33,7 +33,7 @@ async function resolveAttachment(
|
|||
if (name.endsWith(".prompt")) {
|
||||
// Recurse
|
||||
const [items, _] = await renderPromptFileV2(
|
||||
await extras.ide.readFile(name),
|
||||
await extras.ide.readFile(resolvedFileUri),
|
||||
extras,
|
||||
);
|
||||
subItems.push(...items);
|
||||
|
|
@ -52,10 +52,7 @@ async function resolveAttachment(
|
|||
|
||||
// URLs
|
||||
if (name.startsWith("http")) {
|
||||
const items = await new URLContextProvider({}).getContextItems(
|
||||
name,
|
||||
extras,
|
||||
);
|
||||
const items = getUrlContextItems(name, extras.fetch);
|
||||
return items;
|
||||
}
|
||||
|
||||
|
|
@ -75,10 +72,13 @@ export async function renderPromptFileV2(
|
|||
});
|
||||
|
||||
const contextItems = (await Promise.all(contextItemsPromises)).flat();
|
||||
const renderedPrompt =
|
||||
contextItems.map((item) => item.content).join("\n\n") +
|
||||
"\n\n" +
|
||||
renderedBody;
|
||||
const renderedPrompt = [
|
||||
...contextItems.map((item) => item.content),
|
||||
renderedBody,
|
||||
extras.fullInput,
|
||||
]
|
||||
.join("\n\n")
|
||||
.trim();
|
||||
|
||||
return [contextItems, renderedPrompt];
|
||||
}
|
||||
|
|
|
|||
175
core/promptFiles/v2/renderPromptFile.vitest.ts
Normal file
175
core/promptFiles/v2/renderPromptFile.vitest.ts
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
import { ContextProviderExtras, ILLM, RangeInFile } from "../..";
|
||||
import { testConfigHandler, testIde } from "../../test/fixtures";
|
||||
import {
|
||||
addToTestDir,
|
||||
setUpTestDir,
|
||||
tearDownTestDir,
|
||||
} from "../../test/testDir";
|
||||
import { renderPromptFileV2 } from "./renderPromptFile";
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock(
|
||||
import("../../context/providers/URLContextProvider"),
|
||||
async (importOriginal) => {
|
||||
const actual = await importOriginal();
|
||||
return {
|
||||
...actual,
|
||||
getUrlContextItems: vi.fn().mockResolvedValue([
|
||||
{
|
||||
description: "https://example.com",
|
||||
content: "Example Content",
|
||||
name: "Example site",
|
||||
uri: {
|
||||
type: "url",
|
||||
value: "https://example.com",
|
||||
},
|
||||
},
|
||||
]),
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
describe("renderPromptFileV2", () => {
|
||||
let extras: ContextProviderExtras;
|
||||
const mockGetContextItems = vi.fn().mockResolvedValue([
|
||||
{
|
||||
name: "custom",
|
||||
content: "Custom provider content",
|
||||
description: "Custom provider",
|
||||
},
|
||||
]);
|
||||
beforeEach(async () => {
|
||||
const { config } = await testConfigHandler.loadConfig();
|
||||
|
||||
// Setup mock extras
|
||||
extras = {
|
||||
config: {
|
||||
...config!,
|
||||
contextProviders: [
|
||||
{
|
||||
description: {
|
||||
type: "normal",
|
||||
title: "CustomProvider",
|
||||
displayTitle: "Custom Provider",
|
||||
description: "A custom context provider",
|
||||
},
|
||||
loadSubmenuItems: vi.fn().mockResolvedValue([]),
|
||||
getContextItems: mockGetContextItems,
|
||||
},
|
||||
],
|
||||
},
|
||||
fullInput: "User input",
|
||||
embeddingsProvider: null,
|
||||
reranker: null,
|
||||
llm: {} as ILLM,
|
||||
ide: testIde,
|
||||
selectedCode: [] as RangeInFile[],
|
||||
fetch: vi.fn(),
|
||||
};
|
||||
|
||||
// Clear all mocks
|
||||
vi.clearAllMocks();
|
||||
setUpTestDir();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
tearDownTestDir();
|
||||
});
|
||||
|
||||
it("should render a prompt file with no attachments", async () => {
|
||||
const rawContent = "Simple prompt with no attachments";
|
||||
const [contextItems, renderedPrompt] = await renderPromptFileV2(
|
||||
rawContent,
|
||||
extras,
|
||||
);
|
||||
|
||||
expect(contextItems).toHaveLength(0);
|
||||
expect(renderedPrompt).toBe(
|
||||
"Simple prompt with no attachments\n\nUser input",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle URL attachments", async () => {
|
||||
const rawContent = "Content with URL @https://example.com";
|
||||
|
||||
const [contextItems, renderedPrompt] = await renderPromptFileV2(
|
||||
rawContent,
|
||||
extras,
|
||||
);
|
||||
|
||||
expect(contextItems).toHaveLength(1);
|
||||
expect(renderedPrompt).toContain("Example Content");
|
||||
});
|
||||
|
||||
it("should resolve file attachments", async () => {
|
||||
const rawContent = "Content with file attachment @test.txt";
|
||||
|
||||
addToTestDir([["test.txt", "File content"]]);
|
||||
|
||||
const [contextItems, renderedPrompt] = await renderPromptFileV2(
|
||||
rawContent,
|
||||
extras,
|
||||
);
|
||||
|
||||
expect(contextItems).toHaveLength(1);
|
||||
expect(renderedPrompt).toContain("```test.txt\nFile content\n```");
|
||||
expect(renderedPrompt).toContain("Content with file attachment @test.txt");
|
||||
});
|
||||
|
||||
it("should handle nested prompt files", async () => {
|
||||
const rawContent = "Main prompt with nested @nested.prompt";
|
||||
addToTestDir([
|
||||
["nested.prompt", "Nested prompt content with @CustomProvider"],
|
||||
]);
|
||||
|
||||
const [contextItems, renderedPrompt] = await renderPromptFileV2(
|
||||
rawContent,
|
||||
extras,
|
||||
);
|
||||
|
||||
expect(renderedPrompt).toContain("Custom provider content");
|
||||
});
|
||||
|
||||
it("should handle custom context providers", async () => {
|
||||
const rawContent = "Content with custom provider @CustomProvider";
|
||||
|
||||
const [contextItems, renderedPrompt] = await renderPromptFileV2(
|
||||
rawContent,
|
||||
extras,
|
||||
);
|
||||
|
||||
expect(contextItems).toHaveLength(1);
|
||||
expect(renderedPrompt).toContain("Custom provider content");
|
||||
expect(mockGetContextItems).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle multiple attachments", async () => {
|
||||
const rawContent = "Content with @file1.txt and @file2.txt";
|
||||
addToTestDir([
|
||||
["file1.txt", "Content 1"],
|
||||
["file2.txt", "Content 2"],
|
||||
]);
|
||||
|
||||
const [contextItems, renderedPrompt] = await renderPromptFileV2(
|
||||
rawContent,
|
||||
extras,
|
||||
);
|
||||
|
||||
expect(contextItems).toHaveLength(2);
|
||||
expect(renderedPrompt).toContain("```file1.txt\nContent 1\n```");
|
||||
expect(renderedPrompt).toContain("```file2.txt\nContent 2\n```");
|
||||
});
|
||||
|
||||
it("should handle failed attachment resolutions gracefully", async () => {
|
||||
const rawContent = "Content with @nonexistent";
|
||||
|
||||
const [contextItems, renderedPrompt] = await renderPromptFileV2(
|
||||
rawContent,
|
||||
extras,
|
||||
);
|
||||
|
||||
expect(contextItems).toHaveLength(0);
|
||||
expect(renderedPrompt).toBe("Content with @nonexistent\n\nUser input");
|
||||
});
|
||||
});
|
||||
|
|
@ -34,6 +34,7 @@ import {
|
|||
} from "../";
|
||||
import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager";
|
||||
import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes";
|
||||
import { FreeTrialStatus } from "../control-plane/client";
|
||||
|
||||
export type OnboardingModes = "Local" | "Best" | "Custom" | "Quickstart";
|
||||
|
||||
|
|
@ -198,6 +199,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
];
|
||||
"clipboardCache/add": [{ content: string }, void];
|
||||
"controlPlane/openUrl": [{ path: string; orgSlug: string | undefined }, void];
|
||||
"controlPlane/getFreeTrialStatus": [undefined, FreeTrialStatus | null];
|
||||
isItemTooBig: [{ item: ContextItemWithId }, boolean];
|
||||
didChangeControlPlaneSessionInfo: [
|
||||
{ sessionInfo: ControlPlaneSessionInfo | undefined },
|
||||
|
|
@ -205,4 +207,5 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
];
|
||||
"process/markAsBackgrounded": [{ toolCallId: string }, void];
|
||||
"process/isBackgrounded": [{ toolCallId: string }, boolean];
|
||||
"mdm/setLicenseKey": [{ licenseKey: string }, boolean];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { Tool } from "../..";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
|
||||
import os from 'os';
|
||||
import os from "os";
|
||||
|
||||
/**
|
||||
* Get the preferred shell for the current platform
|
||||
|
|
@ -10,17 +10,17 @@ import os from 'os';
|
|||
export function getPreferredShell(): string {
|
||||
const platform = os.platform();
|
||||
|
||||
if (platform === 'win32') {
|
||||
return process.env.COMSPEC || 'cmd.exe';
|
||||
} else if (platform === 'darwin') {
|
||||
return process.env.SHELL || '/bin/zsh';
|
||||
if (platform === "win32") {
|
||||
return process.env.COMSPEC || "cmd.exe";
|
||||
} else if (platform === "darwin") {
|
||||
return process.env.SHELL || "/bin/zsh";
|
||||
} else {
|
||||
// Linux and other Unix-like systems
|
||||
return process.env.SHELL || '/bin/bash';
|
||||
return process.env.SHELL || "/bin/bash";
|
||||
}
|
||||
}
|
||||
|
||||
export const PLATFORM_INFO = `Choose terminal commands and scripts optimized for ${os.platform} and ${os.arch} and shell ${getPreferredShell()}.`
|
||||
export const PLATFORM_INFO = `Choose terminal commands and scripts optimized for ${os.platform} and ${os.arch} and shell ${getPreferredShell()}.`;
|
||||
|
||||
export const runTerminalCommandTool: Tool = {
|
||||
type: "function",
|
||||
|
|
@ -32,28 +32,27 @@ export const runTerminalCommandTool: Tool = {
|
|||
group: BUILT_IN_GROUP_NAME,
|
||||
function: {
|
||||
name: BuiltInToolNames.RunTerminalCommand,
|
||||
description:
|
||||
`Run a terminal command in the current directory.\
|
||||
description: `Run a terminal command in the current directory.\
|
||||
The shell is not stateful and will not remember any previous commands.\
|
||||
When a command is run in the background ALWAYS suggest using shell commands to stop it; NEVER suggest using Ctrl+C.\
|
||||
When suggesting subsequent shell commands ALWAYS format them in shell command blocks.\
|
||||
Do NOT perform actions requiring special/admin privileges.\
|
||||
${PLATFORM_INFO}`,
|
||||
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,17 +3,22 @@ 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);
|
||||
|
||||
const ENABLED_FOR_REMOTES = ["","local","wsl","dev-container","devcontainer","ssh-remote","attached-container","codespaces","tunnel"];
|
||||
|
||||
export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
||||
// Default to waiting for completion if not specified
|
||||
const waitForCompletion = args.waitForCompletion !== false;
|
||||
const ideInfo = await extras.ide.getIdeInfo();
|
||||
const toolCallId = extras.toolCallId || "";
|
||||
|
||||
if (ideInfo.remoteName === "local" || ideInfo.remoteName === "") {
|
||||
if (ENABLED_FOR_REMOTES.includes(ideInfo.remoteName)) {
|
||||
// For streaming output
|
||||
if (extras.onPartialOutput) {
|
||||
return new Promise((resolve, reject) => {
|
||||
|
|
@ -56,7 +61,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 +123,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 +148,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
name: "Terminal",
|
||||
description: "Terminal command output",
|
||||
content: terminalOutput,
|
||||
status: status
|
||||
status: status,
|
||||
},
|
||||
]);
|
||||
} else {
|
||||
|
|
@ -149,9 +157,8 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
{
|
||||
name: "Terminal",
|
||||
description: "Terminal command output",
|
||||
content:
|
||||
terminalOutput,
|
||||
status: status,
|
||||
content: terminalOutput,
|
||||
status: status,
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
|
@ -191,7 +198,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 +232,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
|
|||
name: "Terminal",
|
||||
description: "Terminal command output",
|
||||
content: status,
|
||||
status: status
|
||||
status: status,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
|
@ -269,4 +276,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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
6
core/vendor/modules/.package-lock.json
generated
vendored
6
core/vendor/modules/.package-lock.json
generated
vendored
|
|
@ -383,11 +383,7 @@
|
|||
"resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.14.0.tgz",
|
||||
"integrity": "sha512-5ba7TWomIV/9b6NH/1x/8QEeowsb+jBEvFzU6z0T4mNsFwdPqXeFUM7uxC6QeSRkEbWu3qEB0VMjrvzN/0S9+w==",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32",
|
||||
"darwin",
|
||||
"linux"
|
||||
],
|
||||
"os": ["win32", "darwin", "linux"],
|
||||
"dependencies": {
|
||||
"onnxruntime-common": "~1.14.0"
|
||||
}
|
||||
|
|
|
|||
186
core/vendor/modules/@xenova/transformers/README.md
vendored
186
core/vendor/modules/@xenova/transformers/README.md
vendored
|
|
@ -1,5 +1,3 @@
|
|||
|
||||
|
||||
<p align="center">
|
||||
<br/>
|
||||
<picture>
|
||||
|
|
@ -28,23 +26,21 @@
|
|||
</a>
|
||||
</p>
|
||||
|
||||
|
||||
State-of-the-art Machine Learning for the web. Run 🤗 Transformers directly in your browser, with no need for a server!
|
||||
|
||||
Transformers.js is designed to be functionally equivalent to Hugging Face's [transformers](https://github.com/huggingface/transformers) python library, meaning you can run the same pretrained models using a very similar API. These models support common tasks in different modalities, such as:
|
||||
- 📝 **Natural Language Processing**: text classification, named entity recognition, question answering, language modeling, summarization, translation, multiple choice, and text generation.
|
||||
- 🖼️ **Computer Vision**: image classification, object detection, and segmentation.
|
||||
- 🗣️ **Audio**: automatic speech recognition and audio classification.
|
||||
- 🐙 **Multimodal**: zero-shot image classification.
|
||||
|
||||
Transformers.js uses [ONNX Runtime](https://onnxruntime.ai/) to run models in the browser. The best part about it, is that you can easily [convert](#convert-your-models-to-onnx) your pretrained PyTorch, TensorFlow, or JAX models to ONNX using [🤗 Optimum](https://github.com/huggingface/optimum#onnx--onnx-runtime).
|
||||
- 📝 **Natural Language Processing**: text classification, named entity recognition, question answering, language modeling, summarization, translation, multiple choice, and text generation.
|
||||
- 🖼️ **Computer Vision**: image classification, object detection, and segmentation.
|
||||
- 🗣️ **Audio**: automatic speech recognition and audio classification.
|
||||
- 🐙 **Multimodal**: zero-shot image classification.
|
||||
|
||||
Transformers.js uses [ONNX Runtime](https://onnxruntime.ai/) to run models in the browser. The best part about it, is that you can easily [convert](#convert-your-models-to-onnx) your pretrained PyTorch, TensorFlow, or JAX models to ONNX using [🤗 Optimum](https://github.com/huggingface/optimum#onnx--onnx-runtime).
|
||||
|
||||
For more information, check out the full [documentation](https://huggingface.co/docs/transformers.js).
|
||||
|
||||
|
||||
## Quick tour
|
||||
|
||||
|
||||
It's super simple to translate from existing code! Just like the python library, we support the `pipeline` API. Pipelines group together a pretrained model with preprocessing of inputs and postprocessing of outputs, making it the easiest way to run models with the library.
|
||||
|
||||
<table>
|
||||
|
|
@ -69,12 +65,12 @@ out = pipe('I love transformers!')
|
|||
<td>
|
||||
|
||||
```javascript
|
||||
import { pipeline } from '@xenova/transformers';
|
||||
import { pipeline } from "@xenova/transformers";
|
||||
|
||||
// Allocate a pipeline for sentiment-analysis
|
||||
let pipe = await pipeline('sentiment-analysis');
|
||||
let pipe = await pipeline("sentiment-analysis");
|
||||
|
||||
let out = await pipe('I love transformers!');
|
||||
let out = await pipe("I love transformers!");
|
||||
// [{'label': 'POSITIVE', 'score': 0.999817686}]
|
||||
```
|
||||
|
||||
|
|
@ -82,74 +78,72 @@ let out = await pipe('I love transformers!');
|
|||
</tr>
|
||||
</table>
|
||||
|
||||
|
||||
You can also use a different model by specifying the model id or path as the second argument to the `pipeline` function. For example:
|
||||
|
||||
```javascript
|
||||
// Use a different model for sentiment-analysis
|
||||
let pipe = await pipeline('sentiment-analysis', 'Xenova/bert-base-multilingual-uncased-sentiment');
|
||||
let pipe = await pipeline(
|
||||
"sentiment-analysis",
|
||||
"Xenova/bert-base-multilingual-uncased-sentiment",
|
||||
);
|
||||
```
|
||||
|
||||
|
||||
## Installation
|
||||
|
||||
|
||||
To install via [NPM](https://www.npmjs.com/package/@xenova/transformers), run:
|
||||
|
||||
```bash
|
||||
npm i @xenova/transformers
|
||||
```
|
||||
|
||||
Alternatively, you can use it in vanilla JS, without any bundler, by using a CDN or static hosting. For example, using [ES Modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules), you can import the library with:
|
||||
|
||||
```html
|
||||
<script type="module">
|
||||
import { pipeline } from 'https://cdn.jsdelivr.net/npm/@xenova/transformers@2.14.0';
|
||||
import { pipeline } from "https://cdn.jsdelivr.net/npm/@xenova/transformers@2.14.0";
|
||||
</script>
|
||||
```
|
||||
|
||||
|
||||
## Examples
|
||||
|
||||
Want to jump straight in? Get started with one of our sample applications/templates:
|
||||
|
||||
| Name | Description | Links |
|
||||
|-------------------|----------------------------------|-------------------------------|
|
||||
| Whisper Web | Speech recognition w/ Whisper | [code](https://github.com/xenova/whisper-web), [demo](https://huggingface.co/spaces/Xenova/whisper-web) |
|
||||
| Doodle Dash | Real-time sketch-recognition game | [blog](https://huggingface.co/blog/ml-web-games), [code](https://github.com/xenova/doodle-dash), [demo](https://huggingface.co/spaces/Xenova/doodle-dash) |
|
||||
| Code Playground | In-browser code completion website | [code](./examples/code-completion/), [demo](https://huggingface.co/spaces/Xenova/ai-code-playground) |
|
||||
| Semantic Image Search (client-side) | Search for images with text | [code](./examples/semantic-image-search-client/), [demo](https://huggingface.co/spaces/Xenova/semantic-image-search-client) |
|
||||
| Semantic Image Search (server-side) | Search for images with text (Supabase) | [code](./examples/semantic-image-search/), [demo](https://huggingface.co/spaces/Xenova/semantic-image-search) |
|
||||
| Vanilla JavaScript | In-browser object detection | [video](https://scrimba.com/scrim/cKm9bDAg), [code](./examples/vanilla-js/), [demo](https://huggingface.co/spaces/Scrimba/vanilla-js-object-detector) |
|
||||
| React | Multilingual translation website | [code](./examples/react-translator/), [demo](https://huggingface.co/spaces/Xenova/react-translator) |
|
||||
| Text to speech (client-side) | In-browser speech synthesis | [code](./examples/text-to-speech-client/), [demo](https://huggingface.co/spaces/Xenova/text-to-speech-client) |
|
||||
| Browser extension | Text classification extension | [code](./examples/extension/) |
|
||||
| Electron | Text classification application | [code](./examples/electron/) |
|
||||
| Next.js (client-side) | Sentiment analysis (in-browser inference) | [code](./examples/next-client/), [demo](https://huggingface.co/spaces/Xenova/next-example-app) |
|
||||
| Next.js (server-side) | Sentiment analysis (Node.js inference) | [code](./examples/next-server/), [demo](https://huggingface.co/spaces/Xenova/next-server-example-app) |
|
||||
| Node.js | Sentiment analysis API | [code](./examples/node/) |
|
||||
| Demo site | A collection of demos | [code](./examples/demo-site/), [demo](https://xenova.github.io/transformers.js/) |
|
||||
| Name | Description | Links |
|
||||
| ----------------------------------- | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Whisper Web | Speech recognition w/ Whisper | [code](https://github.com/xenova/whisper-web), [demo](https://huggingface.co/spaces/Xenova/whisper-web) |
|
||||
| Doodle Dash | Real-time sketch-recognition game | [blog](https://huggingface.co/blog/ml-web-games), [code](https://github.com/xenova/doodle-dash), [demo](https://huggingface.co/spaces/Xenova/doodle-dash) |
|
||||
| Code Playground | In-browser code completion website | [code](./examples/code-completion/), [demo](https://huggingface.co/spaces/Xenova/ai-code-playground) |
|
||||
| Semantic Image Search (client-side) | Search for images with text | [code](./examples/semantic-image-search-client/), [demo](https://huggingface.co/spaces/Xenova/semantic-image-search-client) |
|
||||
| Semantic Image Search (server-side) | Search for images with text (Supabase) | [code](./examples/semantic-image-search/), [demo](https://huggingface.co/spaces/Xenova/semantic-image-search) |
|
||||
| Vanilla JavaScript | In-browser object detection | [video](https://scrimba.com/scrim/cKm9bDAg), [code](./examples/vanilla-js/), [demo](https://huggingface.co/spaces/Scrimba/vanilla-js-object-detector) |
|
||||
| React | Multilingual translation website | [code](./examples/react-translator/), [demo](https://huggingface.co/spaces/Xenova/react-translator) |
|
||||
| Text to speech (client-side) | In-browser speech synthesis | [code](./examples/text-to-speech-client/), [demo](https://huggingface.co/spaces/Xenova/text-to-speech-client) |
|
||||
| Browser extension | Text classification extension | [code](./examples/extension/) |
|
||||
| Electron | Text classification application | [code](./examples/electron/) |
|
||||
| Next.js (client-side) | Sentiment analysis (in-browser inference) | [code](./examples/next-client/), [demo](https://huggingface.co/spaces/Xenova/next-example-app) |
|
||||
| Next.js (server-side) | Sentiment analysis (Node.js inference) | [code](./examples/next-server/), [demo](https://huggingface.co/spaces/Xenova/next-server-example-app) |
|
||||
| Node.js | Sentiment analysis API | [code](./examples/node/) |
|
||||
| Demo site | A collection of demos | [code](./examples/demo-site/), [demo](https://xenova.github.io/transformers.js/) |
|
||||
|
||||
Check out the Transformers.js [template](https://huggingface.co/new-space?template=static-templates%2Ftransformers.js) on Hugging Face to get started in one click!
|
||||
|
||||
|
||||
## Custom usage
|
||||
|
||||
|
||||
|
||||
By default, Transformers.js uses [hosted pretrained models](https://huggingface.co/models?library=transformers.js) and [precompiled WASM binaries](https://cdn.jsdelivr.net/npm/@xenova/transformers@2.14.0/dist/), which should work out-of-the-box. You can customize this as follows:
|
||||
|
||||
|
||||
### Settings
|
||||
|
||||
```javascript
|
||||
import { env } from '@xenova/transformers';
|
||||
import { env } from "@xenova/transformers";
|
||||
|
||||
// Specify a custom location for models (defaults to '/models/').
|
||||
env.localModelPath = '/path/to/models/';
|
||||
env.localModelPath = "/path/to/models/";
|
||||
|
||||
// Disable the loading of remote models from the Hugging Face Hub:
|
||||
env.allowRemoteModels = false;
|
||||
|
||||
// Set location of .wasm files. Defaults to use a CDN.
|
||||
env.backends.onnx.wasm.wasmPaths = '/path/to/files/';
|
||||
env.backends.onnx.wasm.wasmPaths = "/path/to/files/";
|
||||
```
|
||||
|
||||
For a full list of available settings, check out the [API Reference](https://huggingface.co/docs/transformers.js/api/env).
|
||||
|
|
@ -163,6 +157,7 @@ python -m scripts.convert --quantize --model_id <model_name_or_path>
|
|||
```
|
||||
|
||||
For example, convert and quantize [bert-base-uncased](https://huggingface.co/bert-base-uncased) using:
|
||||
|
||||
```bash
|
||||
python -m scripts.convert --quantize --model_id bert-base-uncased
|
||||
```
|
||||
|
|
@ -181,7 +176,6 @@ bert-base-uncased/
|
|||
|
||||
For the full list of supported architectures, see the [Optimum documentation](https://huggingface.co/docs/optimum/main/en/exporters/onnx/overview).
|
||||
|
||||
|
||||
## Supported tasks/models
|
||||
|
||||
Here is the list of all tasks and architectures currently supported by Transformers.js.
|
||||
|
|
@ -191,78 +185,72 @@ to open up a feature request [here](https://github.com/xenova/transformers.js/is
|
|||
To find compatible models on the Hub, select the "transformers.js" library tag in the filter menu (or visit [this link](https://huggingface.co/models?library=transformers.js)).
|
||||
You can refine your search by selecting the task you're interested in (e.g., [text-classification](https://huggingface.co/models?pipeline_tag=text-classification&library=transformers.js)).
|
||||
|
||||
|
||||
### Tasks
|
||||
|
||||
#### Natural Language Processing
|
||||
|
||||
| Task | ID | Description | Supported? |
|
||||
|--------------------------|----|-------------|------------|
|
||||
| [Conversational](https://huggingface.co/tasks/conversational) | `conversational` | Generating conversational text that is relevant, coherent and knowledgable given a prompt. | ❌ |
|
||||
| [Fill-Mask](https://huggingface.co/tasks/fill-mask) | `fill-mask` | Masking some of the words in a sentence and predicting which words should replace those masks. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.FillMaskPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=fill-mask&library=transformers.js) |
|
||||
| [Question Answering](https://huggingface.co/tasks/question-answering) | `question-answering` | Retrieve the answer to a question from a given text. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.QuestionAnsweringPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=question-answering&library=transformers.js) |
|
||||
| [Sentence Similarity](https://huggingface.co/tasks/sentence-similarity) | `sentence-similarity` | Determining how similar two texts are. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.FeatureExtractionPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=feature-extraction&library=transformers.js) |
|
||||
| [Summarization](https://huggingface.co/tasks/summarization) | `summarization` | Producing a shorter version of a document while preserving its important information. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.SummarizationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=summarization&library=transformers.js) |
|
||||
| [Table Question Answering](https://huggingface.co/tasks/table-question-answering) | `table-question-answering` | Answering a question about information from a given table. | ❌ |
|
||||
| [Text Classification](https://huggingface.co/tasks/text-classification) | `text-classification` or `sentiment-analysis` | Assigning a label or class to a given text. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TextClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=text-classification&library=transformers.js) |
|
||||
| [Text Generation](https://huggingface.co/tasks/text-generation#completion-generation-models) | `text-generation` | Producing new text by predicting the next word in a sequence. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TextGenerationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=text-generation&library=transformers.js) |
|
||||
| [Text-to-text Generation](https://huggingface.co/tasks/text-generation#text-to-text-generation-models) | `text2text-generation` | Converting one text sequence into another text sequence. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.Text2TextGenerationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=text2text-generation&library=transformers.js) |
|
||||
| [Token Classification](https://huggingface.co/tasks/token-classification) | `token-classification` or `ner` | Assigning a label to each token in a text. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TokenClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=token-classification&library=transformers.js) |
|
||||
| [Translation](https://huggingface.co/tasks/translation) | `translation` | Converting text from one language to another. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TranslationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=translation&library=transformers.js) |
|
||||
| [Zero-Shot Classification](https://huggingface.co/tasks/zero-shot-classification) | `zero-shot-classification` | Classifying text into classes that are unseen during training. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ZeroShotClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=zero-shot-classification&library=transformers.js) |
|
||||
| Task | ID | Description | Supported? |
|
||||
| ------------------------------------------------------------------------------------------------------ | --------------------------------------------- | ---------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| [Conversational](https://huggingface.co/tasks/conversational) | `conversational` | Generating conversational text that is relevant, coherent and knowledgable given a prompt. | ❌ |
|
||||
| [Fill-Mask](https://huggingface.co/tasks/fill-mask) | `fill-mask` | Masking some of the words in a sentence and predicting which words should replace those masks. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.FillMaskPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=fill-mask&library=transformers.js) |
|
||||
| [Question Answering](https://huggingface.co/tasks/question-answering) | `question-answering` | Retrieve the answer to a question from a given text. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.QuestionAnsweringPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=question-answering&library=transformers.js) |
|
||||
| [Sentence Similarity](https://huggingface.co/tasks/sentence-similarity) | `sentence-similarity` | Determining how similar two texts are. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.FeatureExtractionPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=feature-extraction&library=transformers.js) |
|
||||
| [Summarization](https://huggingface.co/tasks/summarization) | `summarization` | Producing a shorter version of a document while preserving its important information. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.SummarizationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=summarization&library=transformers.js) |
|
||||
| [Table Question Answering](https://huggingface.co/tasks/table-question-answering) | `table-question-answering` | Answering a question about information from a given table. | ❌ |
|
||||
| [Text Classification](https://huggingface.co/tasks/text-classification) | `text-classification` or `sentiment-analysis` | Assigning a label or class to a given text. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TextClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=text-classification&library=transformers.js) |
|
||||
| [Text Generation](https://huggingface.co/tasks/text-generation#completion-generation-models) | `text-generation` | Producing new text by predicting the next word in a sequence. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TextGenerationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=text-generation&library=transformers.js) |
|
||||
| [Text-to-text Generation](https://huggingface.co/tasks/text-generation#text-to-text-generation-models) | `text2text-generation` | Converting one text sequence into another text sequence. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.Text2TextGenerationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=text2text-generation&library=transformers.js) |
|
||||
| [Token Classification](https://huggingface.co/tasks/token-classification) | `token-classification` or `ner` | Assigning a label to each token in a text. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TokenClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=token-classification&library=transformers.js) |
|
||||
| [Translation](https://huggingface.co/tasks/translation) | `translation` | Converting text from one language to another. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TranslationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=translation&library=transformers.js) |
|
||||
| [Zero-Shot Classification](https://huggingface.co/tasks/zero-shot-classification) | `zero-shot-classification` | Classifying text into classes that are unseen during training. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ZeroShotClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=zero-shot-classification&library=transformers.js) |
|
||||
|
||||
#### Vision
|
||||
|
||||
| Task | ID | Description | Supported? |
|
||||
|--------------------------|----|-------------|------------|
|
||||
| [Depth Estimation](https://huggingface.co/tasks/depth-estimation) | `depth-estimation` | Predicting the depth of objects present in an image. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.DepthEstimationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=depth-estimation&library=transformers.js) |
|
||||
| [Image Classification](https://huggingface.co/tasks/image-classification) | `image-classification` | Assigning a label or class to an entire image. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ImageClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=image-classification&library=transformers.js) |
|
||||
| [Image Segmentation](https://huggingface.co/tasks/image-segmentation) | `image-segmentation` | Divides an image into segments where each pixel is mapped to an object. This task has multiple variants such as instance segmentation, panoptic segmentation and semantic segmentation. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ImageSegmentationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=image-segmentation&library=transformers.js) |
|
||||
| [Image-to-Image](https://huggingface.co/tasks/image-to-image) | `image-to-image` | Transforming a source image to match the characteristics of a target image or a target image domain. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ImageToImagePipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=image-to-image&library=transformers.js) |
|
||||
| [Mask Generation](https://huggingface.co/tasks/mask-generation) | `mask-generation` | Generate masks for the objects in an image. | ❌ |
|
||||
| [Object Detection](https://huggingface.co/tasks/object-detection) | `object-detection` | Identify objects of certain defined classes within an image. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ObjectDetectionPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=object-detection&library=transformers.js) |
|
||||
| [Video Classification](https://huggingface.co/tasks/video-classification) | n/a | Assigning a label or class to an entire video. | ❌ |
|
||||
| [Unconditional Image Generation](https://huggingface.co/tasks/unconditional-image-generation) | n/a | Generating images with no condition in any context (like a prompt text or another image). | ❌ |
|
||||
| Task | ID | Description | Supported? |
|
||||
| --------------------------------------------------------------------------------------------- | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| [Depth Estimation](https://huggingface.co/tasks/depth-estimation) | `depth-estimation` | Predicting the depth of objects present in an image. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.DepthEstimationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=depth-estimation&library=transformers.js) |
|
||||
| [Image Classification](https://huggingface.co/tasks/image-classification) | `image-classification` | Assigning a label or class to an entire image. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ImageClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=image-classification&library=transformers.js) |
|
||||
| [Image Segmentation](https://huggingface.co/tasks/image-segmentation) | `image-segmentation` | Divides an image into segments where each pixel is mapped to an object. This task has multiple variants such as instance segmentation, panoptic segmentation and semantic segmentation. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ImageSegmentationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=image-segmentation&library=transformers.js) |
|
||||
| [Image-to-Image](https://huggingface.co/tasks/image-to-image) | `image-to-image` | Transforming a source image to match the characteristics of a target image or a target image domain. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ImageToImagePipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=image-to-image&library=transformers.js) |
|
||||
| [Mask Generation](https://huggingface.co/tasks/mask-generation) | `mask-generation` | Generate masks for the objects in an image. | ❌ |
|
||||
| [Object Detection](https://huggingface.co/tasks/object-detection) | `object-detection` | Identify objects of certain defined classes within an image. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ObjectDetectionPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=object-detection&library=transformers.js) |
|
||||
| [Video Classification](https://huggingface.co/tasks/video-classification) | n/a | Assigning a label or class to an entire video. | ❌ |
|
||||
| [Unconditional Image Generation](https://huggingface.co/tasks/unconditional-image-generation) | n/a | Generating images with no condition in any context (like a prompt text or another image). | ❌ |
|
||||
|
||||
#### Audio
|
||||
|
||||
| Task | ID | Description | Supported? |
|
||||
|--------------------------|----|-------------|------------|
|
||||
| [Audio Classification](https://huggingface.co/tasks/audio-classification) | `audio-classification` | Assigning a label or class to a given audio. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.AudioClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=audio-classification&library=transformers.js) |
|
||||
| [Audio-to-Audio](https://huggingface.co/tasks/audio-to-audio) | n/a | Generating audio from an input audio source. | ❌ |
|
||||
| [Automatic Speech Recognition](https://huggingface.co/tasks/automatic-speech-recognition) | `automatic-speech-recognition` | Transcribing a given audio into text. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.AutomaticSpeechRecognitionPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=automatic-speech-recognition&library=transformers.js) |
|
||||
| [Text-to-Speech](https://huggingface.co/tasks/text-to-speech) | `text-to-speech` or `text-to-audio` | Generating natural-sounding speech given text input. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TextToAudioPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=text-to-audio&library=transformers.js) |
|
||||
|
||||
| Task | ID | Description | Supported? |
|
||||
| ----------------------------------------------------------------------------------------- | ----------------------------------- | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| [Audio Classification](https://huggingface.co/tasks/audio-classification) | `audio-classification` | Assigning a label or class to a given audio. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.AudioClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=audio-classification&library=transformers.js) |
|
||||
| [Audio-to-Audio](https://huggingface.co/tasks/audio-to-audio) | n/a | Generating audio from an input audio source. | ❌ |
|
||||
| [Automatic Speech Recognition](https://huggingface.co/tasks/automatic-speech-recognition) | `automatic-speech-recognition` | Transcribing a given audio into text. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.AutomaticSpeechRecognitionPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=automatic-speech-recognition&library=transformers.js) |
|
||||
| [Text-to-Speech](https://huggingface.co/tasks/text-to-speech) | `text-to-speech` or `text-to-audio` | Generating natural-sounding speech given text input. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.TextToAudioPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=text-to-audio&library=transformers.js) |
|
||||
|
||||
#### Tabular
|
||||
|
||||
| Task | ID | Description | Supported? |
|
||||
|--------------------------|----|-------------|------------|
|
||||
| [Tabular Classification](https://huggingface.co/tasks/tabular-classification) | n/a | Classifying a target category (a group) based on set of attributes. | ❌ |
|
||||
| [Tabular Regression](https://huggingface.co/tasks/tabular-regression) | n/a | Predicting a numerical value given a set of attributes. | ❌ |
|
||||
|
||||
| Task | ID | Description | Supported? |
|
||||
| ----------------------------------------------------------------------------- | --- | ------------------------------------------------------------------- | ---------- |
|
||||
| [Tabular Classification](https://huggingface.co/tasks/tabular-classification) | n/a | Classifying a target category (a group) based on set of attributes. | ❌ |
|
||||
| [Tabular Regression](https://huggingface.co/tasks/tabular-regression) | n/a | Predicting a numerical value given a set of attributes. | ❌ |
|
||||
|
||||
#### Multimodal
|
||||
|
||||
| Task | ID | Description | Supported? |
|
||||
|--------------------------|----|-------------|------------|
|
||||
| [Document Question Answering](https://huggingface.co/tasks/document-question-answering) | `document-question-answering` | Answering questions on document images. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.DocumentQuestionAnsweringPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=document-question-answering&library=transformers.js) |
|
||||
| [Feature Extraction](https://huggingface.co/tasks/feature-extraction) | `feature-extraction` | Transforming raw data into numerical features that can be processed while preserving the information in the original dataset. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.FeatureExtractionPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=feature-extraction&library=transformers.js) |
|
||||
| [Image-to-Text](https://huggingface.co/tasks/image-to-text) | `image-to-text` | Output text from a given image. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ImageToTextPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=image-to-text&library=transformers.js) |
|
||||
| [Text-to-Image](https://huggingface.co/tasks/text-to-image) | `text-to-image` | Generates images from input text. | ❌ |
|
||||
| [Visual Question Answering](https://huggingface.co/tasks/visual-question-answering) | `visual-question-answering` | Answering open-ended questions based on an image. | ❌ |
|
||||
| [Zero-Shot Audio Classification](https://huggingface.co/learn/audio-course/chapter4/classification_models#zero-shot-audio-classification) | `zero-shot-audio-classification` | Classifying audios into classes that are unseen during training. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ZeroShotAudioClassificationPipeline)<br>[(models)](https://huggingface.co/models?other=zero-shot-audio-classification&library=transformers.js) |
|
||||
| [Zero-Shot Image Classification](https://huggingface.co/tasks/zero-shot-image-classification) | `zero-shot-image-classification` | Classifying images into classes that are unseen during training. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ZeroShotImageClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=zero-shot-image-classification&library=transformers.js) |
|
||||
| [Zero-Shot Object Detection](https://huggingface.co/tasks/zero-shot-object-detection) | `zero-shot-object-detection` | Identify objects of classes that are unseen during training. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ZeroShotObjectDetectionPipeline)<br>[(models)](https://huggingface.co/models?other=zero-shot-object-detection&library=transformers.js) |
|
||||
|
||||
| Task | ID | Description | Supported? |
|
||||
| ----------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| [Document Question Answering](https://huggingface.co/tasks/document-question-answering) | `document-question-answering` | Answering questions on document images. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.DocumentQuestionAnsweringPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=document-question-answering&library=transformers.js) |
|
||||
| [Feature Extraction](https://huggingface.co/tasks/feature-extraction) | `feature-extraction` | Transforming raw data into numerical features that can be processed while preserving the information in the original dataset. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.FeatureExtractionPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=feature-extraction&library=transformers.js) |
|
||||
| [Image-to-Text](https://huggingface.co/tasks/image-to-text) | `image-to-text` | Output text from a given image. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ImageToTextPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=image-to-text&library=transformers.js) |
|
||||
| [Text-to-Image](https://huggingface.co/tasks/text-to-image) | `text-to-image` | Generates images from input text. | ❌ |
|
||||
| [Visual Question Answering](https://huggingface.co/tasks/visual-question-answering) | `visual-question-answering` | Answering open-ended questions based on an image. | ❌ |
|
||||
| [Zero-Shot Audio Classification](https://huggingface.co/learn/audio-course/chapter4/classification_models#zero-shot-audio-classification) | `zero-shot-audio-classification` | Classifying audios into classes that are unseen during training. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ZeroShotAudioClassificationPipeline)<br>[(models)](https://huggingface.co/models?other=zero-shot-audio-classification&library=transformers.js) |
|
||||
| [Zero-Shot Image Classification](https://huggingface.co/tasks/zero-shot-image-classification) | `zero-shot-image-classification` | Classifying images into classes that are unseen during training. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ZeroShotImageClassificationPipeline)<br>[(models)](https://huggingface.co/models?pipeline_tag=zero-shot-image-classification&library=transformers.js) |
|
||||
| [Zero-Shot Object Detection](https://huggingface.co/tasks/zero-shot-object-detection) | `zero-shot-object-detection` | Identify objects of classes that are unseen during training. | ✅ [(docs)](https://huggingface.co/docs/transformers.js/api/pipelines#module_pipelines.ZeroShotObjectDetectionPipeline)<br>[(models)](https://huggingface.co/models?other=zero-shot-object-detection&library=transformers.js) |
|
||||
|
||||
#### Reinforcement Learning
|
||||
|
||||
| Task | ID | Description | Supported? |
|
||||
|--------------------------|----|-------------|------------|
|
||||
| [Reinforcement Learning](https://huggingface.co/tasks/reinforcement-learning) | n/a | Learning from actions by interacting with an environment through trial and error and receiving rewards (negative or positive) as feedback. | ❌ |
|
||||
|
||||
|
||||
| Task | ID | Description | Supported? |
|
||||
| ----------------------------------------------------------------------------- | --- | ------------------------------------------------------------------------------------------------------------------------------------------ | ---------- |
|
||||
| [Reinforcement Learning](https://huggingface.co/tasks/reinforcement-learning) | n/a | Learning from actions by interacting with an environment through trial and error and receiving rewards (negative or positive) as feedback. | ❌ |
|
||||
|
||||
### Models
|
||||
|
||||
|
|
@ -274,7 +262,7 @@ You can refine your search by selecting the task you're interested in (e.g., [te
|
|||
1. **[Blenderbot](https://huggingface.co/docs/transformers/model_doc/blenderbot)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/2004.13637) by Stephen Roller, Emily Dinan, Naman Goyal, Da Ju, Mary Williamson, Yinhan Liu, Jing Xu, Myle Ott, Kurt Shuster, Eric M. Smith, Y-Lan Boureau, Jason Weston.
|
||||
1. **[BlenderbotSmall](https://huggingface.co/docs/transformers/model_doc/blenderbot-small)** (from Facebook) released with the paper [Recipes for building an open-domain chatbot](https://arxiv.org/abs/2004.13637) by Stephen Roller, Emily Dinan, Naman Goyal, Da Ju, Mary Williamson, Yinhan Liu, Jing Xu, Myle Ott, Kurt Shuster, Eric M. Smith, Y-Lan Boureau, Jason Weston.
|
||||
1. **[BLOOM](https://huggingface.co/docs/transformers/model_doc/bloom)** (from BigScience workshop) released by the [BigScience Workshop](https://bigscience.huggingface.co/).
|
||||
1. **[CamemBERT](https://huggingface.co/docs/transformers/model_doc/camembert)** (from Inria/Facebook/Sorbonne) released with the paper [CamemBERT: a Tasty French Language Model](https://arxiv.org/abs/1911.03894) by Louis Martin*, Benjamin Muller*, Pedro Javier Ortiz Suárez*, Yoann Dupont, Laurent Romary, Éric Villemonte de la Clergerie, Djamé Seddah and Benoît Sagot.
|
||||
1. **[CamemBERT](https://huggingface.co/docs/transformers/model_doc/camembert)** (from Inria/Facebook/Sorbonne) released with the paper [CamemBERT: a Tasty French Language Model](https://arxiv.org/abs/1911.03894) by Louis Martin*, Benjamin Muller*, Pedro Javier Ortiz Suárez\*, Yoann Dupont, Laurent Romary, Éric Villemonte de la Clergerie, Djamé Seddah and Benoît Sagot.
|
||||
1. **[Chinese-CLIP](https://huggingface.co/docs/transformers/model_doc/chinese_clip)** (from OFA-Sys) released with the paper [Chinese CLIP: Contrastive Vision-Language Pretraining in Chinese](https://arxiv.org/abs/2211.01335) by An Yang, Junshu Pan, Junyang Lin, Rui Men, Yichang Zhang, Jingren Zhou, Chang Zhou.
|
||||
1. **[CLAP](https://huggingface.co/docs/transformers/model_doc/clap)** (from LAION-AI) released with the paper [Large-scale Contrastive Language-Audio Pretraining with Feature Fusion and Keyword-to-Caption Augmentation](https://arxiv.org/abs/2211.06687) by Yusong Wu, Ke Chen, Tianyu Zhang, Yuchen Hui, Taylor Berg-Kirkpatrick, Shlomo Dubnov.
|
||||
1. **[CLIP](https://huggingface.co/docs/transformers/model_doc/clip)** (from OpenAI) released with the paper [Learning Transferable Visual Models From Natural Language Supervision](https://arxiv.org/abs/2103.00020) by Alec Radford, Jong Wook Kim, Chris Hallacy, Aditya Ramesh, Gabriel Goh, Sandhini Agarwal, Girish Sastry, Amanda Askell, Pamela Mishkin, Jack Clark, Gretchen Krueger, Ilya Sutskever.
|
||||
|
|
@ -294,7 +282,7 @@ You can refine your search by selecting the task you're interested in (e.g., [te
|
|||
1. **[Donut](https://huggingface.co/docs/transformers/model_doc/donut)** (from NAVER), released together with the paper [OCR-free Document Understanding Transformer](https://arxiv.org/abs/2111.15664) by Geewook Kim, Teakgyu Hong, Moonbin Yim, Jeongyeon Nam, Jinyoung Park, Jinyeong Yim, Wonseok Hwang, Sangdoo Yun, Dongyoon Han, Seunghyun Park.
|
||||
1. **[DPT](https://huggingface.co/docs/transformers/master/model_doc/dpt)** (from Intel Labs) released with the paper [Vision Transformers for Dense Prediction](https://arxiv.org/abs/2103.13413) by René Ranftl, Alexey Bochkovskiy, Vladlen Koltun.
|
||||
1. **[ELECTRA](https://huggingface.co/docs/transformers/model_doc/electra)** (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang Luong, Quoc V. Le, Christopher D. Manning.
|
||||
1. **[ESM](https://huggingface.co/docs/transformers/model_doc/esm)** (from Meta AI) are transformer protein language models. **ESM-1b** was released with the paper [Biological structure and function emerge from scaling unsupervised learning to 250 million protein sequences](https://www.pnas.org/content/118/15/e2016239118) by Alexander Rives, Joshua Meier, Tom Sercu, Siddharth Goyal, Zeming Lin, Jason Liu, Demi Guo, Myle Ott, C. Lawrence Zitnick, Jerry Ma, and Rob Fergus. **ESM-1v** was released with the paper [Language models enable zero-shot prediction of the effects of mutations on protein function](https://doi.org/10.1101/2021.07.09.450648) by Joshua Meier, Roshan Rao, Robert Verkuil, Jason Liu, Tom Sercu and Alexander Rives. **ESM-2 and ESMFold** were released with the paper [Language models of protein sequences at the scale of evolution enable accurate structure prediction](https://doi.org/10.1101/2022.07.20.500902) by Zeming Lin, Halil Akin, Roshan Rao, Brian Hie, Zhongkai Zhu, Wenting Lu, Allan dos Santos Costa, Maryam Fazel-Zarandi, Tom Sercu, Sal Candido, Alexander Rives.
|
||||
1. **[ESM](https://huggingface.co/docs/transformers/model_doc/esm)** (from Meta AI) are transformer protein language models. **ESM-1b** was released with the paper [Biological structure and function emerge from scaling unsupervised learning to 250 million protein sequences](https://www.pnas.org/content/118/15/e2016239118) by Alexander Rives, Joshua Meier, Tom Sercu, Siddharth Goyal, Zeming Lin, Jason Liu, Demi Guo, Myle Ott, C. Lawrence Zitnick, Jerry Ma, and Rob Fergus. **ESM-1v** was released with the paper [Language models enable zero-shot prediction of the effects of mutations on protein function](https://doi.org/10.1101/2021.07.09.450648) by Joshua Meier, Roshan Rao, Robert Verkuil, Jason Liu, Tom Sercu and Alexander Rives. **ESM-2 and ESMFold** were released with the paper [Language models of protein sequences at the scale of evolution enable accurate structure prediction](https://doi.org/10.1101/2022.07.20.500902) by Zeming Lin, Halil Akin, Roshan Rao, Brian Hie, Zhongkai Zhu, Wenting Lu, Allan dos Santos Costa, Maryam Fazel-Zarandi, Tom Sercu, Sal Candido, Alexander Rives.
|
||||
1. **[Falcon](https://huggingface.co/docs/transformers/model_doc/falcon)** (from Technology Innovation Institute) by Almazrouei, Ebtesam and Alobeidli, Hamza and Alshamsi, Abdulaziz and Cappelli, Alessandro and Cojocaru, Ruxandra and Debbah, Merouane and Goffinet, Etienne and Heslow, Daniel and Launay, Julien and Malartic, Quentin and Noune, Badreddine and Pannier, Baptiste and Penedo, Guilherme.
|
||||
1. **[FLAN-T5](https://huggingface.co/docs/transformers/model_doc/flan-t5)** (from Google AI) released in the repository [google-research/t5x](https://github.com/google-research/t5x/blob/main/docs/models.md#flan-t5-checkpoints) by Hyung Won Chung, Le Hou, Shayne Longpre, Barret Zoph, Yi Tay, William Fedus, Eric Li, Xuezhi Wang, Mostafa Dehghani, Siddhartha Brahma, Albert Webson, Shixiang Shane Gu, Zhuyun Dai, Mirac Suzgun, Xinyun Chen, Aakanksha Chowdhery, Sharan Narang, Gaurav Mishra, Adams Yu, Vincent Zhao, Yanping Huang, Andrew Dai, Hongkun Yu, Slav Petrov, Ed H. Chi, Jeff Dean, Jacob Devlin, Adam Roberts, Denny Zhou, Quoc V. Le, and Jason Wei
|
||||
1. **[GLPN](https://huggingface.co/docs/transformers/model_doc/glpn)** (from KAIST) released with the paper [Global-Local Path Networks for Monocular Depth Estimation with Vertical CutDepth](https://arxiv.org/abs/2201.07436) by Doyeon Kim, Woonghyun Ga, Pyungwhan Ahn, Donggyu Joo, Sehwan Chun, Junmo Kim.
|
||||
|
|
@ -347,5 +335,3 @@ You can refine your search by selecting the task you're interested in (e.g., [te
|
|||
1. **[XLM](https://huggingface.co/docs/transformers/model_doc/xlm)** (from Facebook) released together with the paper [Cross-lingual Language Model Pretraining](https://arxiv.org/abs/1901.07291) by Guillaume Lample and Alexis Conneau.
|
||||
1. **[XLM-RoBERTa](https://huggingface.co/docs/transformers/model_doc/xlm-roberta)** (from Facebook AI), released together with the paper [Unsupervised Cross-lingual Representation Learning at Scale](https://arxiv.org/abs/1911.02116) by Alexis Conneau*, Kartikay Khandelwal*, Naman Goyal, Vishrav Chaudhary, Guillaume Wenzek, Francisco Guzmán, Edouard Grave, Myle Ott, Luke Zettlemoyer and Veselin Stoyanov.
|
||||
1. **[YOLOS](https://huggingface.co/docs/transformers/model_doc/yolos)** (from Huazhong University of Science & Technology) released with the paper [You Only Look at One Sequence: Rethinking Transformer in Vision through Object Detection](https://arxiv.org/abs/2106.00666) by Yuxin Fang, Bencheng Liao, Xinggang Wang, Jiemin Fang, Jiyang Qi, Rui Wu, Jianwei Niu, Wenyu Liu.
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -6,45 +6,46 @@
|
|||
* So, we just import both packages, and use the appropriate one based on the environment:
|
||||
* - When running in node, we use `onnxruntime-node`.
|
||||
* - When running in the browser, we use `onnxruntime-web` (`onnxruntime-node` is not bundled).
|
||||
*
|
||||
*
|
||||
* This module is not directly exported, but can be accessed through the environment variables:
|
||||
* ```javascript
|
||||
* import { env } from '@xenova/transformers';
|
||||
* console.log(env.backends.onnx);
|
||||
* ```
|
||||
*
|
||||
*
|
||||
* @module backends/onnx
|
||||
*/
|
||||
|
||||
// NOTE: Import order matters here. We need to import `onnxruntime-node` before `onnxruntime-web`.
|
||||
// In either case, we select the default export if it exists, otherwise we use the named export.
|
||||
import * as ONNX_NODE from 'onnxruntime-node';
|
||||
import * as ONNX_WEB from 'onnxruntime-web';
|
||||
import * as ONNX_NODE from "onnxruntime-node";
|
||||
import * as ONNX_WEB from "onnxruntime-web";
|
||||
|
||||
/** @type {import('onnxruntime-web')} The ONNX runtime module. */
|
||||
export let ONNX;
|
||||
|
||||
export const executionProviders = [
|
||||
// 'webgpu',
|
||||
'wasm'
|
||||
// 'webgpu',
|
||||
"wasm",
|
||||
];
|
||||
|
||||
if (typeof process !== 'undefined' && process?.release?.name === 'node') {
|
||||
// Running in a node-like environment.
|
||||
ONNX = ONNX_NODE.default ?? ONNX_NODE;
|
||||
|
||||
// Add `cpu` execution provider, with higher precedence that `wasm`.
|
||||
executionProviders.unshift('cpu');
|
||||
if (typeof process !== "undefined" && process?.release?.name === "node") {
|
||||
// Running in a node-like environment.
|
||||
ONNX = ONNX_NODE.default ?? ONNX_NODE;
|
||||
|
||||
// Add `cpu` execution provider, with higher precedence that `wasm`.
|
||||
executionProviders.unshift("cpu");
|
||||
} else {
|
||||
// Running in a browser-environment
|
||||
ONNX = ONNX_WEB.default ?? ONNX_WEB;
|
||||
// Running in a browser-environment
|
||||
ONNX = ONNX_WEB.default ?? ONNX_WEB;
|
||||
|
||||
// SIMD for WebAssembly does not operate correctly in some recent versions of iOS (16.4.x).
|
||||
// As a temporary fix, we disable it for now.
|
||||
// For more information, see: https://github.com/microsoft/onnxruntime/issues/15644
|
||||
const isIOS = typeof navigator !== 'undefined' && /iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent);
|
||||
if (isIOS) {
|
||||
ONNX.env.wasm.simd = false;
|
||||
}
|
||||
// SIMD for WebAssembly does not operate correctly in some recent versions of iOS (16.4.x).
|
||||
// As a temporary fix, we disable it for now.
|
||||
// For more information, see: https://github.com/microsoft/onnxruntime/issues/15644
|
||||
const isIOS =
|
||||
typeof navigator !== "undefined" &&
|
||||
/iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent);
|
||||
if (isIOS) {
|
||||
ONNX.env.wasm.simd = false;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,9 @@
|
|||
|
||||
/**
|
||||
* @file Helper module for using model configs. For more information, see the corresponding
|
||||
* [Python documentation](https://huggingface.co/docs/transformers/main/en/model_doc/auto#transformers.AutoConfig).
|
||||
*
|
||||
*
|
||||
* **Example:** Load an `AutoConfig`.
|
||||
*
|
||||
*
|
||||
* ```javascript
|
||||
* import { AutoConfig } from '@xenova/transformers';
|
||||
* let config = await AutoConfig.from_pretrained('bert-base-uncased');
|
||||
|
|
@ -23,19 +22,16 @@
|
|||
* // ...
|
||||
* // }
|
||||
* ```
|
||||
*
|
||||
*
|
||||
* @module configs
|
||||
*/
|
||||
|
||||
import {
|
||||
getModelJSON,
|
||||
} from './utils/hub.js';
|
||||
import { getModelJSON } from "./utils/hub.js";
|
||||
|
||||
/**
|
||||
* @typedef {import('./utils/hub.js').PretrainedOptions} PretrainedOptions
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Loads a config from the specified path.
|
||||
* @param {string} pretrained_model_name_or_path The path to the config directory.
|
||||
|
|
@ -43,8 +39,13 @@ import {
|
|||
* @returns {Promise<Array>} A promise that resolves with information about the loaded config.
|
||||
*/
|
||||
async function loadConfig(pretrained_model_name_or_path, options) {
|
||||
let info = await getModelJSON(pretrained_model_name_or_path, 'config.json', true, options);
|
||||
return info;
|
||||
let info = await getModelJSON(
|
||||
pretrained_model_name_or_path,
|
||||
"config.json",
|
||||
true,
|
||||
options,
|
||||
);
|
||||
return info;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -52,56 +53,60 @@ async function loadConfig(pretrained_model_name_or_path, options) {
|
|||
* [Python documentation](https://huggingface.co/docs/transformers/main/en/main_classes/configuration#transformers.PretrainedConfig).
|
||||
*/
|
||||
export class PretrainedConfig {
|
||||
// NOTE: Typo in original
|
||||
// NOTE: Typo in original
|
||||
|
||||
/**
|
||||
* Create a new PreTrainedTokenizer instance.
|
||||
* @param {Object} configJSON The JSON of the config.
|
||||
*/
|
||||
constructor(configJSON) {
|
||||
this.model_type = null;
|
||||
this.is_encoder_decoder = false;
|
||||
/**
|
||||
* Create a new PreTrainedTokenizer instance.
|
||||
* @param {Object} configJSON The JSON of the config.
|
||||
*/
|
||||
constructor(configJSON) {
|
||||
this.model_type = null;
|
||||
this.is_encoder_decoder = false;
|
||||
|
||||
Object.assign(this, configJSON);
|
||||
}
|
||||
Object.assign(this, configJSON);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a pre-trained config from the given `pretrained_model_name_or_path`.
|
||||
*
|
||||
* @param {string} pretrained_model_name_or_path The path to the pre-trained config.
|
||||
* @param {PretrainedOptions} options Additional options for loading the config.
|
||||
* @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`.
|
||||
*
|
||||
* @returns {Promise<PretrainedConfig>} A new instance of the `PretrainedConfig` class.
|
||||
*/
|
||||
static async from_pretrained(pretrained_model_name_or_path, {
|
||||
progress_callback = null,
|
||||
config = null,
|
||||
cache_dir = null,
|
||||
local_files_only = false,
|
||||
revision = 'main',
|
||||
} = {}) {
|
||||
|
||||
let data = config ?? await loadConfig(pretrained_model_name_or_path, {
|
||||
progress_callback,
|
||||
config,
|
||||
cache_dir,
|
||||
local_files_only,
|
||||
revision,
|
||||
})
|
||||
return new this(data);
|
||||
}
|
||||
/**
|
||||
* Loads a pre-trained config from the given `pretrained_model_name_or_path`.
|
||||
*
|
||||
* @param {string} pretrained_model_name_or_path The path to the pre-trained config.
|
||||
* @param {PretrainedOptions} options Additional options for loading the config.
|
||||
* @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`.
|
||||
*
|
||||
* @returns {Promise<PretrainedConfig>} A new instance of the `PretrainedConfig` class.
|
||||
*/
|
||||
static async from_pretrained(
|
||||
pretrained_model_name_or_path,
|
||||
{
|
||||
progress_callback = null,
|
||||
config = null,
|
||||
cache_dir = null,
|
||||
local_files_only = false,
|
||||
revision = "main",
|
||||
} = {},
|
||||
) {
|
||||
let data =
|
||||
config ??
|
||||
(await loadConfig(pretrained_model_name_or_path, {
|
||||
progress_callback,
|
||||
config,
|
||||
cache_dir,
|
||||
local_files_only,
|
||||
revision,
|
||||
}));
|
||||
return new this(data);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper class which is used to instantiate pretrained configs with the `from_pretrained` function.
|
||||
*
|
||||
*
|
||||
* @example
|
||||
* let config = await AutoConfig.from_pretrained('bert-base-uncased');
|
||||
* let config = await AutoConfig.from_pretrained('bert-base-uncased');
|
||||
*/
|
||||
export class AutoConfig {
|
||||
/** @type {PretrainedConfig.from_pretrained} */
|
||||
static async from_pretrained(...args) {
|
||||
return PretrainedConfig.from_pretrained(...args);
|
||||
}
|
||||
/** @type {PretrainedConfig.from_pretrained} */
|
||||
static async from_pretrained(...args) {
|
||||
return PretrainedConfig.from_pretrained(...args);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,37 +1,37 @@
|
|||
/**
|
||||
* @file Module used to configure Transformers.js.
|
||||
*
|
||||
*
|
||||
* **Example:** Disable remote models.
|
||||
* ```javascript
|
||||
* import { env } from '@xenova/transformers';
|
||||
* env.allowRemoteModels = false;
|
||||
* ```
|
||||
*
|
||||
*
|
||||
* **Example:** Set local model path.
|
||||
* ```javascript
|
||||
* import { env } from '@xenova/transformers';
|
||||
* env.localModelPath = '/path/to/local/models/';
|
||||
* ```
|
||||
*
|
||||
*
|
||||
* **Example:** Set cache directory.
|
||||
* ```javascript
|
||||
* import { env } from '@xenova/transformers';
|
||||
* env.cacheDir = '/path/to/cache/directory/';
|
||||
* ```
|
||||
*
|
||||
*
|
||||
* @module env
|
||||
*/
|
||||
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
import { ONNX } from './backends/onnx.js';
|
||||
import { ONNX } from "./backends/onnx.js";
|
||||
const { env: onnx_env } = ONNX;
|
||||
|
||||
const VERSION = '2.14.0';
|
||||
const VERSION = "2.14.0";
|
||||
|
||||
// Check if various APIs are available (depends on environment)
|
||||
const WEB_CACHE_AVAILABLE = typeof self !== 'undefined' && 'caches' in self;
|
||||
const WEB_CACHE_AVAILABLE = typeof self !== "undefined" && "caches" in self;
|
||||
const FS_AVAILABLE = !isEmpty(fs); // check if file system is available
|
||||
const PATH_AVAILABLE = !isEmpty(path); // check if path is available
|
||||
|
||||
|
|
@ -43,23 +43,22 @@ const RUNNING_LOCALLY = FS_AVAILABLE && PATH_AVAILABLE;
|
|||
|
||||
// Only used for environments with access to file system
|
||||
const DEFAULT_CACHE_DIR = RUNNING_LOCALLY
|
||||
? path.join(__dirname, '/.cache/')
|
||||
: null;
|
||||
? path.join(__dirname, "/.cache/")
|
||||
: null;
|
||||
|
||||
// Set local model path, based on available APIs
|
||||
const DEFAULT_LOCAL_MODEL_PATH = '/models/';
|
||||
const DEFAULT_LOCAL_MODEL_PATH = "/models/";
|
||||
const localModelPath = RUNNING_LOCALLY
|
||||
? path.join(__dirname, DEFAULT_LOCAL_MODEL_PATH)
|
||||
: DEFAULT_LOCAL_MODEL_PATH;
|
||||
? path.join(__dirname, DEFAULT_LOCAL_MODEL_PATH)
|
||||
: DEFAULT_LOCAL_MODEL_PATH;
|
||||
|
||||
// Set path to wasm files. This is needed when running in a web worker.
|
||||
// https://onnxruntime.ai/docs/api/js/interfaces/Env.WebAssemblyFlags.html#wasmPaths
|
||||
// We use remote wasm files by default to make it easier for newer users.
|
||||
// In practice, users should probably self-host the necessary .wasm files.
|
||||
onnx_env.wasm.wasmPaths = RUNNING_LOCALLY
|
||||
? path.join(__dirname, '/dist/')
|
||||
: `https://cdn.jsdelivr.net/npm/@xenova/transformers@${VERSION}/dist/`;
|
||||
|
||||
? path.join(__dirname, "/dist/")
|
||||
: `https://cdn.jsdelivr.net/npm/@xenova/transformers@${VERSION}/dist/`;
|
||||
|
||||
/**
|
||||
* Global variable used to control execution. This provides users a simple way to configure Transformers.js.
|
||||
|
|
@ -83,44 +82,42 @@ onnx_env.wasm.wasmPaths = RUNNING_LOCALLY
|
|||
* implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache
|
||||
*/
|
||||
export const env = {
|
||||
/////////////////// Backends settings ///////////////////
|
||||
backends: {
|
||||
// onnxruntime-web/onnxruntime-node
|
||||
onnx: onnx_env,
|
||||
/////////////////// Backends settings ///////////////////
|
||||
backends: {
|
||||
// onnxruntime-web/onnxruntime-node
|
||||
onnx: onnx_env,
|
||||
|
||||
// TensorFlow.js
|
||||
tfjs: {},
|
||||
},
|
||||
// TensorFlow.js
|
||||
tfjs: {},
|
||||
},
|
||||
|
||||
__dirname,
|
||||
version: VERSION,
|
||||
__dirname,
|
||||
version: VERSION,
|
||||
|
||||
/////////////////// Model settings ///////////////////
|
||||
allowRemoteModels: true,
|
||||
remoteHost: 'https://huggingface.co/',
|
||||
remotePathTemplate: '{model}/resolve/{revision}/',
|
||||
/////////////////// Model settings ///////////////////
|
||||
allowRemoteModels: true,
|
||||
remoteHost: "https://huggingface.co/",
|
||||
remotePathTemplate: "{model}/resolve/{revision}/",
|
||||
|
||||
allowLocalModels: true,
|
||||
localModelPath: localModelPath,
|
||||
useFS: FS_AVAILABLE,
|
||||
allowLocalModels: true,
|
||||
localModelPath: localModelPath,
|
||||
useFS: FS_AVAILABLE,
|
||||
|
||||
/////////////////// Cache settings ///////////////////
|
||||
useBrowserCache: WEB_CACHE_AVAILABLE,
|
||||
/////////////////// Cache settings ///////////////////
|
||||
useBrowserCache: WEB_CACHE_AVAILABLE,
|
||||
|
||||
useFSCache: FS_AVAILABLE,
|
||||
cacheDir: DEFAULT_CACHE_DIR,
|
||||
|
||||
useCustomCache: false,
|
||||
customCache: null,
|
||||
//////////////////////////////////////////////////////
|
||||
}
|
||||
useFSCache: FS_AVAILABLE,
|
||||
cacheDir: DEFAULT_CACHE_DIR,
|
||||
|
||||
useCustomCache: false,
|
||||
customCache: null,
|
||||
//////////////////////////////////////////////////////
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {Object} obj
|
||||
* @private
|
||||
*/
|
||||
function isEmpty(obj) {
|
||||
return Object.keys(obj).length === 0;
|
||||
return Object.keys(obj).length === 0;
|
||||
}
|
||||
|
||||
|
|
|
|||
7197
core/vendor/modules/@xenova/transformers/src/models.js
vendored
7197
core/vendor/modules/@xenova/transformers/src/models.js
vendored
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -1,18 +1,18 @@
|
|||
/**
|
||||
* @file Entry point for the Transformers.js library. Only the exports from this file
|
||||
* are available to the end user, and are grouped as follows:
|
||||
*
|
||||
*
|
||||
* 1. [Pipelines](./pipelines)
|
||||
* 2. [Environment variables](./env)
|
||||
* 3. [Models](./models)
|
||||
* 4. [Tokenizers](./tokenizers)
|
||||
* 5. [Processors](./processors)
|
||||
*
|
||||
*
|
||||
* @module transformers
|
||||
*/
|
||||
|
||||
export * from './env.js';
|
||||
export * from './pipelines.js';
|
||||
export * from "./env.js";
|
||||
export * from "./pipelines.js";
|
||||
// export * from './models.js';
|
||||
// export * from './tokenizers.js';
|
||||
// export * from './processors.js';
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -1,10 +1,9 @@
|
|||
|
||||
/**
|
||||
* @file Core utility functions/classes for Transformers.js.
|
||||
*
|
||||
*
|
||||
* These are only used internally, meaning an end-user shouldn't
|
||||
* need to access anything here.
|
||||
*
|
||||
*
|
||||
* @module utils/core
|
||||
*/
|
||||
|
||||
|
|
@ -17,7 +16,7 @@
|
|||
* @private
|
||||
*/
|
||||
export function dispatchCallback(progress_callback, data) {
|
||||
if (progress_callback) progress_callback(data);
|
||||
if (progress_callback) progress_callback(data);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -28,8 +27,10 @@ export function dispatchCallback(progress_callback, data) {
|
|||
* @see https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript
|
||||
*/
|
||||
export function reverseDictionary(data) {
|
||||
// https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript
|
||||
return Object.fromEntries(Object.entries(data).map(([key, value]) => [value, key]));
|
||||
// https://ultimatecourses.com/blog/reverse-object-keys-and-values-in-javascript
|
||||
return Object.fromEntries(
|
||||
Object.entries(data).map(([key, value]) => [value, key]),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -39,29 +40,30 @@ export function reverseDictionary(data) {
|
|||
* @returns {string} The escaped string.
|
||||
*/
|
||||
export function escapeRegExp(string) {
|
||||
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
|
||||
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
|
||||
}
|
||||
|
||||
/**
|
||||
* A base class for creating callable objects.
|
||||
*
|
||||
*
|
||||
* @type {new () => {(...args: any[]): any, _call(...args: any[]): any}}
|
||||
*/
|
||||
export const Callable = /** @type {any} */ (class {
|
||||
export const Callable = /** @type {any} */ (
|
||||
class {
|
||||
/**
|
||||
* Creates a new instance of the Callable class.
|
||||
*/
|
||||
* Creates a new instance of the Callable class.
|
||||
*/
|
||||
constructor() {
|
||||
/**
|
||||
* Creates a closure that delegates to a private method '_call' with the given arguments.
|
||||
* @type {any}
|
||||
* @param {...any} args Zero or more arguments to pass to the '_call' method.
|
||||
* @returns {*} The result of calling the '_call' method.
|
||||
*/
|
||||
let closure = function (...args) {
|
||||
return closure._call(...args)
|
||||
}
|
||||
return Object.setPrototypeOf(closure, new.target.prototype)
|
||||
/**
|
||||
* Creates a closure that delegates to a private method '_call' with the given arguments.
|
||||
* @type {any}
|
||||
* @param {...any} args Zero or more arguments to pass to the '_call' method.
|
||||
* @returns {*} The result of calling the '_call' method.
|
||||
*/
|
||||
let closure = function (...args) {
|
||||
return closure._call(...args);
|
||||
};
|
||||
return Object.setPrototypeOf(closure, new.target.prototype);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -72,29 +74,29 @@ export const Callable = /** @type {any} */ (class {
|
|||
* @throws {Error} If the subclass does not implement the `_call` method.
|
||||
*/
|
||||
_call(...args) {
|
||||
throw Error('Must implement _call method in subclass')
|
||||
throw Error("Must implement _call method in subclass");
|
||||
}
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* Check if a value is a typed array.
|
||||
* @param {*} val The value to check.
|
||||
* @returns {boolean} True if the value is a `TypedArray`, false otherwise.
|
||||
*
|
||||
*
|
||||
* Adapted from https://stackoverflow.com/a/71091338/13989043
|
||||
*/
|
||||
export function isTypedArray(val) {
|
||||
return val?.prototype?.__proto__?.constructor?.name === 'TypedArray';
|
||||
return val?.prototype?.__proto__?.constructor?.name === "TypedArray";
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Check if a value is an integer.
|
||||
* @param {*} x The value to check.
|
||||
* @returns {boolean} True if the value is a string, false otherwise.
|
||||
*/
|
||||
export function isIntegralNumber(x) {
|
||||
return Number.isInteger(x) || typeof x === 'bigint'
|
||||
return Number.isInteger(x) || typeof x === "bigint";
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -103,7 +105,7 @@ export function isIntegralNumber(x) {
|
|||
* @returns {boolean} True if the value exists, false otherwise.
|
||||
*/
|
||||
export function exists(x) {
|
||||
return x !== undefined && x !== null;
|
||||
return x !== undefined && x !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -113,13 +115,13 @@ export function exists(x) {
|
|||
* @returns {number[]} An array containing the dimensions of the input array.
|
||||
*/
|
||||
export function calculateDimensions(arr) {
|
||||
const dimensions = [];
|
||||
let current = arr;
|
||||
while (Array.isArray(current)) {
|
||||
dimensions.push(current.length);
|
||||
current = current[0];
|
||||
}
|
||||
return dimensions;
|
||||
const dimensions = [];
|
||||
let current = arr;
|
||||
while (Array.isArray(current)) {
|
||||
dimensions.push(current.length);
|
||||
current = current[0];
|
||||
}
|
||||
return dimensions;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -131,15 +133,15 @@ export function calculateDimensions(arr) {
|
|||
* @throws {Error} If the key does not exist and no default value is provided.
|
||||
*/
|
||||
export function pop(obj, key, defaultValue = undefined) {
|
||||
const value = obj[key];
|
||||
if (value !== undefined) {
|
||||
delete obj[key];
|
||||
return value;
|
||||
}
|
||||
if (defaultValue === undefined) {
|
||||
throw Error(`Key ${key} does not exist in object.`)
|
||||
}
|
||||
return defaultValue;
|
||||
const value = obj[key];
|
||||
if (value !== undefined) {
|
||||
delete obj[key];
|
||||
return value;
|
||||
}
|
||||
if (defaultValue === undefined) {
|
||||
throw Error(`Key ${key} does not exist in object.`);
|
||||
}
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -149,7 +151,7 @@ export function pop(obj, key, defaultValue = undefined) {
|
|||
* @returns {Array} The merged array.
|
||||
*/
|
||||
export function mergeArrays(...arrs) {
|
||||
return Array.prototype.concat.apply([], arrs);
|
||||
return Array.prototype.concat.apply([], arrs);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -159,9 +161,9 @@ export function mergeArrays(...arrs) {
|
|||
* @private
|
||||
*/
|
||||
export function product(...a) {
|
||||
// Cartesian product of items
|
||||
// Adapted from https://stackoverflow.com/a/43053803
|
||||
return a.reduce((a, b) => a.flatMap(d => b.map(e => [d, e])));
|
||||
// Cartesian product of items
|
||||
// Adapted from https://stackoverflow.com/a/43053803
|
||||
return a.reduce((a, b) => a.flatMap((d) => b.map((e) => [d, e])));
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -171,5 +173,5 @@ export function product(...a) {
|
|||
* @returns {number} The index offset.
|
||||
*/
|
||||
export function calculateReflectOffset(i, w) {
|
||||
return Math.abs((i + w) % (2 * w) - w);
|
||||
return Math.abs(((i + w) % (2 * w)) - w);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,415 +1,420 @@
|
|||
|
||||
/**
|
||||
* @file Custom data structures.
|
||||
*
|
||||
*
|
||||
* These are only used internally, meaning an end-user shouldn't
|
||||
* need to access anything here.
|
||||
*
|
||||
*
|
||||
* @module utils/data-structures
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Efficient Heap-based Implementation of a Priority Queue.
|
||||
* It uses an array-based binary heap, where the root is at index `0`, and the
|
||||
* children of node `i` are located at indices `2i + 1` and `2i + 2`, respectively.
|
||||
*
|
||||
*
|
||||
* Adapted from the following sources:
|
||||
* - https://stackoverflow.com/a/42919752/13989043 (original)
|
||||
* - https://github.com/belladoreai/llama-tokenizer-js (minor improvements)
|
||||
*/
|
||||
export class PriorityQueue {
|
||||
/**
|
||||
* Create a new PriorityQueue.
|
||||
* @param {Function} comparator Comparator function to determine priority. Defaults to a MaxHeap.
|
||||
*/
|
||||
constructor(comparator = (a, b) => a > b) {
|
||||
this._heap = [];
|
||||
this._comparator = comparator;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new PriorityQueue.
|
||||
* @param {Function} comparator Comparator function to determine priority. Defaults to a MaxHeap.
|
||||
*/
|
||||
constructor(comparator = (a, b) => a > b) {
|
||||
this._heap = [];
|
||||
this._comparator = comparator;
|
||||
}
|
||||
/**
|
||||
* The size of the queue
|
||||
*/
|
||||
get size() {
|
||||
return this._heap.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* The size of the queue
|
||||
*/
|
||||
get size() {
|
||||
return this._heap.length;
|
||||
}
|
||||
/**
|
||||
* Check if the queue is empty.
|
||||
* @returns {boolean} `true` if the queue is empty, `false` otherwise.
|
||||
*/
|
||||
isEmpty() {
|
||||
return this.size === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the queue is empty.
|
||||
* @returns {boolean} `true` if the queue is empty, `false` otherwise.
|
||||
*/
|
||||
isEmpty() {
|
||||
return this.size === 0;
|
||||
}
|
||||
/**
|
||||
* Return the element with the highest priority in the queue.
|
||||
* @returns {any} The highest priority element in the queue.
|
||||
*/
|
||||
peek() {
|
||||
return this._heap[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the element with the highest priority in the queue.
|
||||
* @returns {any} The highest priority element in the queue.
|
||||
*/
|
||||
peek() {
|
||||
return this._heap[0];
|
||||
}
|
||||
/**
|
||||
* Add one or more elements to the queue.
|
||||
* @param {...any} values The values to push into the queue.
|
||||
* @returns {number} The new size of the queue.
|
||||
*/
|
||||
push(...values) {
|
||||
return this.extend(values);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add one or more elements to the queue.
|
||||
* @param {...any} values The values to push into the queue.
|
||||
* @returns {number} The new size of the queue.
|
||||
*/
|
||||
push(...values) {
|
||||
return this.extend(values);
|
||||
/**
|
||||
* Add multiple elements to the queue.
|
||||
* @param {any[]} values The values to push into the queue.
|
||||
* @returns {number} The new size of the queue.
|
||||
*/
|
||||
extend(values) {
|
||||
for (const value of values) {
|
||||
this._heap.push(value);
|
||||
this._siftUp();
|
||||
}
|
||||
return this.size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add multiple elements to the queue.
|
||||
* @param {any[]} values The values to push into the queue.
|
||||
* @returns {number} The new size of the queue.
|
||||
*/
|
||||
extend(values) {
|
||||
for (const value of values) {
|
||||
this._heap.push(value);
|
||||
this._siftUp();
|
||||
}
|
||||
return this.size;
|
||||
/**
|
||||
* Remove and return the element with the highest priority in the queue.
|
||||
* @returns {any} The element with the highest priority in the queue.
|
||||
*/
|
||||
pop() {
|
||||
const poppedValue = this.peek();
|
||||
const bottom = this.size - 1;
|
||||
if (bottom > 0) {
|
||||
this._swap(0, bottom);
|
||||
}
|
||||
this._heap.pop();
|
||||
this._siftDown();
|
||||
return poppedValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove and return the element with the highest priority in the queue.
|
||||
* @returns {any} The element with the highest priority in the queue.
|
||||
*/
|
||||
pop() {
|
||||
const poppedValue = this.peek();
|
||||
const bottom = this.size - 1;
|
||||
if (bottom > 0) {
|
||||
this._swap(0, bottom);
|
||||
}
|
||||
this._heap.pop();
|
||||
this._siftDown();
|
||||
return poppedValue;
|
||||
}
|
||||
/**
|
||||
* Replace the element with the highest priority in the queue with a new value.
|
||||
* @param {*} value The new value.
|
||||
* @returns {*} The replaced value.
|
||||
*/
|
||||
replace(value) {
|
||||
const replacedValue = this.peek();
|
||||
this._heap[0] = value;
|
||||
this._siftDown();
|
||||
return replacedValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the element with the highest priority in the queue with a new value.
|
||||
* @param {*} value The new value.
|
||||
* @returns {*} The replaced value.
|
||||
*/
|
||||
replace(value) {
|
||||
const replacedValue = this.peek();
|
||||
this._heap[0] = value;
|
||||
this._siftDown();
|
||||
return replacedValue;
|
||||
}
|
||||
/**
|
||||
* Compute the index for the parent of the node at index `i`.
|
||||
* @param {number} i The index of the node to get the parent of.
|
||||
* @returns {number} The index of the parent node.
|
||||
* @private
|
||||
*/
|
||||
_parent(i) {
|
||||
return ((i + 1) >>> 1) - 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the index for the parent of the node at index `i`.
|
||||
* @param {number} i The index of the node to get the parent of.
|
||||
* @returns {number} The index of the parent node.
|
||||
* @private
|
||||
*/
|
||||
_parent(i) {
|
||||
return ((i + 1) >>> 1) - 1;
|
||||
}
|
||||
/**
|
||||
* Compute the index for the left child of the node at index `i`.
|
||||
* @param {number} i The index of the node to get the left child of.
|
||||
* @returns {number} The index of the left child.
|
||||
* @private
|
||||
*/
|
||||
_left(i) {
|
||||
return (i << 1) + 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the index for the left child of the node at index `i`.
|
||||
* @param {number} i The index of the node to get the left child of.
|
||||
* @returns {number} The index of the left child.
|
||||
* @private
|
||||
*/
|
||||
_left(i) {
|
||||
return (i << 1) + 1;
|
||||
}
|
||||
/**
|
||||
* Compute the index for the right child of the node at index `i`.
|
||||
* @param {number} i The index of the node to get the right child of.
|
||||
* @returns {number} The index of the right child.
|
||||
* @private
|
||||
*/
|
||||
_right(i) {
|
||||
return (i + 1) << 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the index for the right child of the node at index `i`.
|
||||
* @param {number} i The index of the node to get the right child of.
|
||||
* @returns {number} The index of the right child.
|
||||
* @private
|
||||
*/
|
||||
_right(i) {
|
||||
return (i + 1) << 1;
|
||||
}
|
||||
/**
|
||||
* Check if the element at index `i` is greater than the element at index `j`.
|
||||
* @param {number} i The index of the first element to compare.
|
||||
* @param {number} j The index of the second element to compare.
|
||||
* @returns {boolean} `true` if the element at index `i` is greater than the element at index `j`, `false` otherwise.
|
||||
* @private
|
||||
*/
|
||||
_greater(i, j) {
|
||||
return this._comparator(this._heap[i], this._heap[j]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the element at index `i` is greater than the element at index `j`.
|
||||
* @param {number} i The index of the first element to compare.
|
||||
* @param {number} j The index of the second element to compare.
|
||||
* @returns {boolean} `true` if the element at index `i` is greater than the element at index `j`, `false` otherwise.
|
||||
* @private
|
||||
*/
|
||||
_greater(i, j) {
|
||||
return this._comparator(this._heap[i], this._heap[j]);
|
||||
}
|
||||
/**
|
||||
* Swap the elements at indices `i` and `j`.
|
||||
* @param {number} i The index of the first element to swap.
|
||||
* @param {number} j The index of the second element to swap.
|
||||
* @private
|
||||
*/
|
||||
_swap(i, j) {
|
||||
const temp = this._heap[i];
|
||||
this._heap[i] = this._heap[j];
|
||||
this._heap[j] = temp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Swap the elements at indices `i` and `j`.
|
||||
* @param {number} i The index of the first element to swap.
|
||||
* @param {number} j The index of the second element to swap.
|
||||
* @private
|
||||
*/
|
||||
_swap(i, j) {
|
||||
const temp = this._heap[i];
|
||||
this._heap[i] = this._heap[j];
|
||||
this._heap[j] = temp;
|
||||
/**
|
||||
* Maintain the heap property by updating positions in the heap,
|
||||
* starting at the last element and moving up the heap.
|
||||
* @private
|
||||
*/
|
||||
_siftUp() {
|
||||
let node = this.size - 1;
|
||||
while (node > 0 && this._greater(node, this._parent(node))) {
|
||||
this._swap(node, this._parent(node));
|
||||
node = this._parent(node);
|
||||
}
|
||||
|
||||
/**
|
||||
* Maintain the heap property by updating positions in the heap,
|
||||
* starting at the last element and moving up the heap.
|
||||
* @private
|
||||
*/
|
||||
_siftUp() {
|
||||
let node = this.size - 1;
|
||||
while (node > 0 && this._greater(node, this._parent(node))) {
|
||||
this._swap(node, this._parent(node));
|
||||
node = this._parent(node);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Maintain the heap property by updating positions in the heap,
|
||||
* starting at the first element and moving down the heap.
|
||||
* @private
|
||||
*/
|
||||
_siftDown() {
|
||||
let node = 0;
|
||||
while (
|
||||
(this._left(node) < this.size && this._greater(this._left(node), node)) ||
|
||||
(this._right(node) < this.size && this._greater(this._right(node), node))
|
||||
) {
|
||||
const maxChild = (this._right(node) < this.size && this._greater(this._right(node), this._left(node)))
|
||||
? this._right(node)
|
||||
: this._left(node);
|
||||
this._swap(node, maxChild);
|
||||
node = maxChild;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Maintain the heap property by updating positions in the heap,
|
||||
* starting at the first element and moving down the heap.
|
||||
* @private
|
||||
*/
|
||||
_siftDown() {
|
||||
let node = 0;
|
||||
while (
|
||||
(this._left(node) < this.size && this._greater(this._left(node), node)) ||
|
||||
(this._right(node) < this.size && this._greater(this._right(node), node))
|
||||
) {
|
||||
const maxChild =
|
||||
this._right(node) < this.size &&
|
||||
this._greater(this._right(node), this._left(node))
|
||||
? this._right(node)
|
||||
: this._left(node);
|
||||
this._swap(node, maxChild);
|
||||
node = maxChild;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A trie structure to efficiently store and search for strings.
|
||||
*/
|
||||
export class CharTrie {
|
||||
constructor() {
|
||||
this.root = CharTrieNode.default();
|
||||
}
|
||||
constructor() {
|
||||
this.root = CharTrieNode.default();
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds one or more `texts` to the trie.
|
||||
* @param {string[]} texts The strings to add to the trie.
|
||||
*/
|
||||
extend(texts) {
|
||||
for (let text of texts) {
|
||||
this.push(text);
|
||||
}
|
||||
/**
|
||||
* Adds one or more `texts` to the trie.
|
||||
* @param {string[]} texts The strings to add to the trie.
|
||||
*/
|
||||
extend(texts) {
|
||||
for (let text of texts) {
|
||||
this.push(text);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds text to the trie.
|
||||
* @param {string} text The string to add to the trie.
|
||||
*/
|
||||
push(text) {
|
||||
let node = this.root;
|
||||
for (let ch of text) {
|
||||
let child = node.children.get(ch);
|
||||
if (child === undefined) {
|
||||
child = CharTrieNode.default();
|
||||
node.children.set(ch, child);
|
||||
}
|
||||
node = child;
|
||||
}
|
||||
node.isLeaf = true;
|
||||
/**
|
||||
* Adds text to the trie.
|
||||
* @param {string} text The string to add to the trie.
|
||||
*/
|
||||
push(text) {
|
||||
let node = this.root;
|
||||
for (let ch of text) {
|
||||
let child = node.children.get(ch);
|
||||
if (child === undefined) {
|
||||
child = CharTrieNode.default();
|
||||
node.children.set(ch, child);
|
||||
}
|
||||
node = child;
|
||||
}
|
||||
node.isLeaf = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches the trie for all strings with a common prefix of `text`.
|
||||
* @param {string} text The common prefix to search for.
|
||||
* @yields {string} Each string in the trie that has `text` as a prefix.
|
||||
*/
|
||||
*commonPrefixSearch(text) {
|
||||
let node = this.root;
|
||||
let prefix = "";
|
||||
for (let i = 0; i < text.length && node !== undefined; ++i) {
|
||||
const ch = text[i];
|
||||
prefix += ch;
|
||||
node = node.children.get(ch);
|
||||
if (node !== undefined && node.isLeaf) {
|
||||
yield prefix;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Searches the trie for all strings with a common prefix of `text`.
|
||||
* @param {string} text The common prefix to search for.
|
||||
* @yields {string} Each string in the trie that has `text` as a prefix.
|
||||
*/
|
||||
*commonPrefixSearch(text) {
|
||||
let node = this.root;
|
||||
let prefix = "";
|
||||
for (let i = 0; i < text.length && node !== undefined; ++i) {
|
||||
const ch = text[i];
|
||||
prefix += ch;
|
||||
node = node.children.get(ch);
|
||||
if (node !== undefined && node.isLeaf) {
|
||||
yield prefix;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a node in a character trie.
|
||||
*/
|
||||
class CharTrieNode {
|
||||
/**
|
||||
* Create a new CharTrieNode.
|
||||
* @param {boolean} isLeaf Whether the node is a leaf node or not.
|
||||
* @param {Map<string, CharTrieNode>} children A map containing the node's children, where the key is a character and the value is a `CharTrieNode`.
|
||||
*/
|
||||
constructor(isLeaf, children) {
|
||||
this.isLeaf = isLeaf;
|
||||
this.children = children;
|
||||
}
|
||||
/**
|
||||
* Create a new CharTrieNode.
|
||||
* @param {boolean} isLeaf Whether the node is a leaf node or not.
|
||||
* @param {Map<string, CharTrieNode>} children A map containing the node's children, where the key is a character and the value is a `CharTrieNode`.
|
||||
*/
|
||||
constructor(isLeaf, children) {
|
||||
this.isLeaf = isLeaf;
|
||||
this.children = children;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a new `CharTrieNode` instance with default values.
|
||||
* @returns {CharTrieNode} A new `CharTrieNode` instance with `isLeaf` set to `false` and an empty `children` map.
|
||||
*/
|
||||
static default() {
|
||||
return new CharTrieNode(false, new Map());
|
||||
}
|
||||
/**
|
||||
* Returns a new `CharTrieNode` instance with default values.
|
||||
* @returns {CharTrieNode} A new `CharTrieNode` instance with `isLeaf` set to `false` and an empty `children` map.
|
||||
*/
|
||||
static default() {
|
||||
return new CharTrieNode(false, new Map());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A lattice data structure to be used for tokenization.
|
||||
*/
|
||||
export class TokenLattice {
|
||||
/**
|
||||
* Creates a new TokenLattice instance.
|
||||
*
|
||||
* @param {string} sentence The input sentence to be tokenized.
|
||||
* @param {number} bosTokenId The beginning-of-sequence token ID.
|
||||
* @param {number} eosTokenId The end-of-sequence token ID.
|
||||
*/
|
||||
constructor(sentence, bosTokenId, eosTokenId) {
|
||||
this.sentence = sentence;
|
||||
this.len = sentence.length;
|
||||
this.bosTokenId = bosTokenId;
|
||||
this.eosTokenId = eosTokenId;
|
||||
this.nodes = [];
|
||||
this.beginNodes = Array.from({ length: this.len + 1 }, () => []);
|
||||
this.endNodes = Array.from({ length: this.len + 1 }, () => []);
|
||||
/**
|
||||
* Creates a new TokenLattice instance.
|
||||
*
|
||||
* @param {string} sentence The input sentence to be tokenized.
|
||||
* @param {number} bosTokenId The beginning-of-sequence token ID.
|
||||
* @param {number} eosTokenId The end-of-sequence token ID.
|
||||
*/
|
||||
constructor(sentence, bosTokenId, eosTokenId) {
|
||||
this.sentence = sentence;
|
||||
this.len = sentence.length;
|
||||
this.bosTokenId = bosTokenId;
|
||||
this.eosTokenId = eosTokenId;
|
||||
this.nodes = [];
|
||||
this.beginNodes = Array.from({ length: this.len + 1 }, () => []);
|
||||
this.endNodes = Array.from({ length: this.len + 1 }, () => []);
|
||||
|
||||
const bos = new TokenLatticeNode(this.bosTokenId, 0, 0, 0, 0.0);
|
||||
const eos = new TokenLatticeNode(this.eosTokenId, 1, this.len, 0, 0.0);
|
||||
this.nodes.push(bos.clone());
|
||||
this.nodes.push(eos.clone());
|
||||
this.beginNodes[this.len].push(eos);
|
||||
this.endNodes[0].push(bos);
|
||||
}
|
||||
const bos = new TokenLatticeNode(this.bosTokenId, 0, 0, 0, 0.0);
|
||||
const eos = new TokenLatticeNode(this.eosTokenId, 1, this.len, 0, 0.0);
|
||||
this.nodes.push(bos.clone());
|
||||
this.nodes.push(eos.clone());
|
||||
this.beginNodes[this.len].push(eos);
|
||||
this.endNodes[0].push(bos);
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts a new token node into the token lattice.
|
||||
*
|
||||
* @param {number} pos The starting position of the token.
|
||||
* @param {number} length The length of the token.
|
||||
* @param {number} score The score of the token.
|
||||
* @param {number} tokenId The token ID of the token.
|
||||
*/
|
||||
insert(pos, length, score, tokenId) {
|
||||
const nodeId = this.nodes.length;
|
||||
const node = new TokenLatticeNode(tokenId, nodeId, pos, length, score);
|
||||
this.beginNodes[pos].push(node);
|
||||
this.endNodes[pos + length].push(node);
|
||||
this.nodes.push(node);
|
||||
}
|
||||
/**
|
||||
* Inserts a new token node into the token lattice.
|
||||
*
|
||||
* @param {number} pos The starting position of the token.
|
||||
* @param {number} length The length of the token.
|
||||
* @param {number} score The score of the token.
|
||||
* @param {number} tokenId The token ID of the token.
|
||||
*/
|
||||
insert(pos, length, score, tokenId) {
|
||||
const nodeId = this.nodes.length;
|
||||
const node = new TokenLatticeNode(tokenId, nodeId, pos, length, score);
|
||||
this.beginNodes[pos].push(node);
|
||||
this.endNodes[pos + length].push(node);
|
||||
this.nodes.push(node);
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements the Viterbi algorithm to compute the most likely sequence of tokens.
|
||||
*
|
||||
* @returns {TokenLatticeNode[]} The array of nodes representing the most likely sequence of tokens.
|
||||
*/
|
||||
viterbi() {
|
||||
const len = this.len;
|
||||
let pos = 0;
|
||||
while (pos <= len) {
|
||||
if (this.beginNodes[pos].length == 0) {
|
||||
return [];
|
||||
}
|
||||
for (let rnode of this.beginNodes[pos]) {
|
||||
rnode.prev = null;
|
||||
let bestScore = 0.0;
|
||||
let bestNode = null;
|
||||
for (let lnode of this.endNodes[pos]) {
|
||||
const score = lnode.backtraceScore + rnode.score;
|
||||
if (bestNode === null || score > bestScore) {
|
||||
bestNode = lnode.clone();
|
||||
bestScore = score;
|
||||
}
|
||||
}
|
||||
|
||||
if (bestNode !== null) {
|
||||
rnode.prev = bestNode;
|
||||
rnode.backtraceScore = bestScore;
|
||||
} else {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
++pos;
|
||||
/**
|
||||
* Implements the Viterbi algorithm to compute the most likely sequence of tokens.
|
||||
*
|
||||
* @returns {TokenLatticeNode[]} The array of nodes representing the most likely sequence of tokens.
|
||||
*/
|
||||
viterbi() {
|
||||
const len = this.len;
|
||||
let pos = 0;
|
||||
while (pos <= len) {
|
||||
if (this.beginNodes[pos].length == 0) {
|
||||
return [];
|
||||
}
|
||||
for (let rnode of this.beginNodes[pos]) {
|
||||
rnode.prev = null;
|
||||
let bestScore = 0.0;
|
||||
let bestNode = null;
|
||||
for (let lnode of this.endNodes[pos]) {
|
||||
const score = lnode.backtraceScore + rnode.score;
|
||||
if (bestNode === null || score > bestScore) {
|
||||
bestNode = lnode.clone();
|
||||
bestScore = score;
|
||||
}
|
||||
}
|
||||
|
||||
const results = [];
|
||||
const root = this.beginNodes[len][0];
|
||||
const prev = root.prev;
|
||||
if (prev === null) {
|
||||
return [];
|
||||
if (bestNode !== null) {
|
||||
rnode.prev = bestNode;
|
||||
rnode.backtraceScore = bestScore;
|
||||
} else {
|
||||
return [];
|
||||
}
|
||||
|
||||
let node = prev.clone();
|
||||
while (node.prev !== null) {
|
||||
results.push(node.clone());
|
||||
const n = node.clone();
|
||||
node = n.prev.clone();
|
||||
}
|
||||
|
||||
results.reverse();
|
||||
return results;
|
||||
}
|
||||
++pos;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {TokenLatticeNode} node
|
||||
* @returns {string} The array of nodes representing the most likely sequence of tokens.
|
||||
*/
|
||||
piece(node) {
|
||||
return this.sentence.slice(node.pos, node.pos + node.length);
|
||||
const results = [];
|
||||
const root = this.beginNodes[len][0];
|
||||
const prev = root.prev;
|
||||
if (prev === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {Array} The array of nodes representing the most likely sequence of tokens.
|
||||
*/
|
||||
tokens() {
|
||||
const nodes = this.viterbi();
|
||||
return nodes.map(x => this.piece(x));
|
||||
let node = prev.clone();
|
||||
while (node.prev !== null) {
|
||||
results.push(node.clone());
|
||||
const n = node.clone();
|
||||
node = n.prev.clone();
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {Array} The array of nodes representing the most likely sequence of tokens.
|
||||
*/
|
||||
tokenIds() {
|
||||
const nodes = this.viterbi();
|
||||
return nodes.map(x => x.tokenId);
|
||||
}
|
||||
results.reverse();
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {TokenLatticeNode} node
|
||||
* @returns {string} The array of nodes representing the most likely sequence of tokens.
|
||||
*/
|
||||
piece(node) {
|
||||
return this.sentence.slice(node.pos, node.pos + node.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {Array} The array of nodes representing the most likely sequence of tokens.
|
||||
*/
|
||||
tokens() {
|
||||
const nodes = this.viterbi();
|
||||
return nodes.map((x) => this.piece(x));
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {Array} The array of nodes representing the most likely sequence of tokens.
|
||||
*/
|
||||
tokenIds() {
|
||||
const nodes = this.viterbi();
|
||||
return nodes.map((x) => x.tokenId);
|
||||
}
|
||||
}
|
||||
class TokenLatticeNode {
|
||||
/**
|
||||
* Represents a node in a token lattice for a given sentence.
|
||||
* @param {number} tokenId The ID of the token associated with this node.
|
||||
* @param {number} nodeId The ID of this node.
|
||||
* @param {number} pos The starting position of the token in the sentence.
|
||||
* @param {number} length The length of the token.
|
||||
* @param {number} score The score associated with the token.
|
||||
*/
|
||||
constructor(tokenId, nodeId, pos, length, score) {
|
||||
this.tokenId = tokenId;
|
||||
this.nodeId = nodeId;
|
||||
this.pos = pos;
|
||||
this.length = length;
|
||||
this.score = score;
|
||||
this.prev = null;
|
||||
this.backtraceScore = 0.0;
|
||||
}
|
||||
/**
|
||||
* Represents a node in a token lattice for a given sentence.
|
||||
* @param {number} tokenId The ID of the token associated with this node.
|
||||
* @param {number} nodeId The ID of this node.
|
||||
* @param {number} pos The starting position of the token in the sentence.
|
||||
* @param {number} length The length of the token.
|
||||
* @param {number} score The score associated with the token.
|
||||
*/
|
||||
constructor(tokenId, nodeId, pos, length, score) {
|
||||
this.tokenId = tokenId;
|
||||
this.nodeId = nodeId;
|
||||
this.pos = pos;
|
||||
this.length = length;
|
||||
this.score = score;
|
||||
this.prev = null;
|
||||
this.backtraceScore = 0.0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a clone of this node.
|
||||
* @returns {TokenLatticeNode} A clone of this node.
|
||||
*/
|
||||
clone() {
|
||||
const n = new TokenLatticeNode(this.tokenId, this.nodeId, this.pos, this.length, this.score);
|
||||
n.prev = this.prev;
|
||||
n.backtraceScore = this.backtraceScore;
|
||||
return n;
|
||||
}
|
||||
/**
|
||||
* Returns a clone of this node.
|
||||
* @returns {TokenLatticeNode} A clone of this node.
|
||||
*/
|
||||
clone() {
|
||||
const n = new TokenLatticeNode(
|
||||
this.tokenId,
|
||||
this.nodeId,
|
||||
this.pos,
|
||||
this.length,
|
||||
this.score,
|
||||
);
|
||||
n.prev = this.prev;
|
||||
n.backtraceScore = this.backtraceScore;
|
||||
return n;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -1,5 +1,5 @@
|
|||
/** @type {import('onnxruntime-web')} The ONNX runtime module. */
|
||||
export let ONNX: typeof ONNX_WEB;
|
||||
export const executionProviders: string[];
|
||||
import * as ONNX_WEB from 'onnxruntime-web';
|
||||
//# sourceMappingURL=onnx.d.ts.map
|
||||
import * as ONNX_WEB from "onnxruntime-web";
|
||||
//# sourceMappingURL=onnx.d.ts.map
|
||||
|
|
|
|||
|
|
@ -3,23 +3,32 @@
|
|||
* [Python documentation](https://huggingface.co/docs/transformers/main/en/main_classes/configuration#transformers.PretrainedConfig).
|
||||
*/
|
||||
export class PretrainedConfig {
|
||||
/**
|
||||
* Loads a pre-trained config from the given `pretrained_model_name_or_path`.
|
||||
*
|
||||
* @param {string} pretrained_model_name_or_path The path to the pre-trained config.
|
||||
* @param {PretrainedOptions} options Additional options for loading the config.
|
||||
* @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`.
|
||||
*
|
||||
* @returns {Promise<PretrainedConfig>} A new instance of the `PretrainedConfig` class.
|
||||
*/
|
||||
static from_pretrained(pretrained_model_name_or_path: string, { progress_callback, config, cache_dir, local_files_only, revision, }?: PretrainedOptions): Promise<PretrainedConfig>;
|
||||
/**
|
||||
* Create a new PreTrainedTokenizer instance.
|
||||
* @param {Object} configJSON The JSON of the config.
|
||||
*/
|
||||
constructor(configJSON: any);
|
||||
model_type: any;
|
||||
is_encoder_decoder: boolean;
|
||||
/**
|
||||
* Loads a pre-trained config from the given `pretrained_model_name_or_path`.
|
||||
*
|
||||
* @param {string} pretrained_model_name_or_path The path to the pre-trained config.
|
||||
* @param {PretrainedOptions} options Additional options for loading the config.
|
||||
* @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`.
|
||||
*
|
||||
* @returns {Promise<PretrainedConfig>} A new instance of the `PretrainedConfig` class.
|
||||
*/
|
||||
static from_pretrained(
|
||||
pretrained_model_name_or_path: string,
|
||||
{
|
||||
progress_callback,
|
||||
config,
|
||||
cache_dir,
|
||||
local_files_only,
|
||||
revision,
|
||||
}?: PretrainedOptions,
|
||||
): Promise<PretrainedConfig>;
|
||||
/**
|
||||
* Create a new PreTrainedTokenizer instance.
|
||||
* @param {Object} configJSON The JSON of the config.
|
||||
*/
|
||||
constructor(configJSON: any);
|
||||
model_type: any;
|
||||
is_encoder_decoder: boolean;
|
||||
}
|
||||
/**
|
||||
* Helper class which is used to instantiate pretrained configs with the `from_pretrained` function.
|
||||
|
|
@ -28,16 +37,25 @@ export class PretrainedConfig {
|
|||
* let config = await AutoConfig.from_pretrained('bert-base-uncased');
|
||||
*/
|
||||
export class AutoConfig {
|
||||
/**
|
||||
* Loads a pre-trained config from the given `pretrained_model_name_or_path`.
|
||||
*
|
||||
* @param {string} pretrained_model_name_or_path The path to the pre-trained config.
|
||||
* @param {PretrainedOptions} options Additional options for loading the config.
|
||||
* @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`.
|
||||
*
|
||||
* @returns {Promise<PretrainedConfig>} A new instance of the `PretrainedConfig` class.
|
||||
*/
|
||||
static from_pretrained(pretrained_model_name_or_path: string, { progress_callback, config, cache_dir, local_files_only, revision, }?: import("./utils/hub.js").PretrainedOptions): Promise<PretrainedConfig>;
|
||||
/**
|
||||
* Loads a pre-trained config from the given `pretrained_model_name_or_path`.
|
||||
*
|
||||
* @param {string} pretrained_model_name_or_path The path to the pre-trained config.
|
||||
* @param {PretrainedOptions} options Additional options for loading the config.
|
||||
* @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`.
|
||||
*
|
||||
* @returns {Promise<PretrainedConfig>} A new instance of the `PretrainedConfig` class.
|
||||
*/
|
||||
static from_pretrained(
|
||||
pretrained_model_name_or_path: string,
|
||||
{
|
||||
progress_callback,
|
||||
config,
|
||||
cache_dir,
|
||||
local_files_only,
|
||||
revision,
|
||||
}?: import("./utils/hub.js").PretrainedOptions,
|
||||
): Promise<PretrainedConfig>;
|
||||
}
|
||||
export type PretrainedOptions = import('./utils/hub.js').PretrainedOptions;
|
||||
//# sourceMappingURL=configs.d.ts.map
|
||||
export type PretrainedOptions = import("./utils/hub.js").PretrainedOptions;
|
||||
//# sourceMappingURL=configs.d.ts.map
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue