Merge branch 'main' into winarm64

This commit is contained in:
Nate 2025-07-21 19:53:45 -07:00
commit 4ea4c7ba40
332 changed files with 24257 additions and 5207 deletions

View file

@ -1,11 +0,0 @@
name: Continue Documentation MCP
version: 0.0.1
schema: v1
mcpServers:
- name: Continue Docs Search
type: stdio
command: npx
args:
- mint-mcp
- add
- continue-docs

View file

@ -0,0 +1,25 @@
---
globs: ["gui/**/*", "core/**/*"]
description: Provides test running instructions for GUI and core folders
alwaysApply: false
---
When working with test files, use the following commands to run tests:
GUI folder tests:
- Run all tests: `cd gui && npm test`
Core folder tests:
- Run Jest tests: `cd core && npm test`
- Run Vitest tests: `cd core && npm run vitest`
Test file patterns:
- GUI: _.test.ts or_.test.tsx files use Vitest
- Core: _.test.ts files use Jest,_.vitest.ts files use Vitest
Best practices:
- We are transitioning to vitest, so use that when creating new tests

View file

@ -8,9 +8,9 @@
- [] The relevant docs, if any, have been updated or created
- [] The relevant tests, if any, have been updated or created
## Screenshots
## Screen recording or screenshot
[ For visual changes, include screenshots. Screen recordings are particularly helpful, and appreciated! ]
[ When applicable, please include a short screen recording or screenshot - this makes it much easier for us as contributors to review and understand your changes. See [this PR](https://github.com/continuedev/continue/pull/6455) as a good example. ]
## Tests

View file

@ -24,7 +24,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
path-to-signatures: "signatures/version1/cla.json"
path-to-document: "https://github.com/continuedev/continue/blob/main/docs/docs/CLA.md"
path-to-document: "https://github.com/continuedev/continue/blob/main/CLA.md"
branch: cla-signatures
# Bots and CLAs signed outside of GitHub
allowlist: dependabot[bot],fbricon,panyamkeerthana,Jazzcort,owtaylor,halfline

View file

@ -31,6 +31,8 @@ jobs:
uses: wagoid/commitlint-github-action@v6
with:
configFile: .commitlintrc.warning.json
# Only check the last commit instead of all commits in the PR
commitDepth: 1
continue-on-error: true
- name: Add commit message guidance comment
@ -57,7 +59,7 @@ jobs:
body: [
"## ⚠️ Conventional Commit Format",
"",
"Your commit messages don't follow the conventional commit format, but **this won't block your PR from being merged**. We recommend downloading [this extension](https://marketplace.visualstudio.com/items?itemName=vivaxy.vscode-conventional-commits) if you are using VS Code.",
"Your latest commit message doesn't follow the conventional commit format, but **this won't block your PR from being merged**. We recommend downloading [this extension](https://marketplace.visualstudio.com/items?itemName=vivaxy.vscode-conventional-commits) if you are using VS Code.",
"",
"### Expected Format:",
"```",

View file

@ -50,7 +50,7 @@ jobs:
echo "metrics_content=$content" >> "$GITHUB_OUTPUT"
- name: Post a message in a channel
uses: slackapi/slack-github-action@v2.1.0
uses: slackapi/slack-github-action@v2.1.1
with:
webhook: ${{ secrets.ISSUE_PR_METRICS_SLACK_WEBHOOK_URL }}
webhook-type: incoming-webhook

View file

@ -572,6 +572,43 @@ jobs:
cd packages/config-yaml
npm test
openai-adapters-tests:
needs: install-openai-adapters
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') }}
- uses: actions/cache@v4
id: openai-adapters-cache
with:
path: packages/openai-adapters/node_modules
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
- name: Run openai-adapters tests
run: |
cd packages/openai-adapters
npm test
env:
IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
vscode-get-test-file-matrix:
runs-on: ubuntu-latest
needs: [install-root, install-vscode, install-config-yaml]
@ -613,6 +650,9 @@ jobs:
echo "test_file_matrix<<EOF" >> $GITHUB_OUTPUT
echo "$FILES" >> $GITHUB_OUTPUT
echo "EOF" >> $GITHUB_OUTPUT
env:
# https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333
GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }}
- name: Debug Outputs
run: |
@ -1068,6 +1108,7 @@ jobs:
- config-yaml-checks
- install-config-yaml
- install-openai-adapters
- openai-adapters-tests
steps:
- name: Decide whether the needed jobs succeeded or failed

View file

@ -6,6 +6,13 @@ on:
- main
paths:
- "packages/config-yaml/**"
- ".github/workflows/release-config-yaml.yml"
- ".github/workflows/reusable-release.yml"
permissions:
contents: write
issues: write
pull-requests: write
jobs:
release:
@ -16,3 +23,12 @@ jobs:
secrets:
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}

View file

@ -6,6 +6,13 @@ on:
- main
paths:
- "packages/fetch/**"
- ".github/workflows/release-fetch.yml"
- ".github/workflows/reusable-release.yml"
permissions:
contents: write
issues: write
pull-requests: write
jobs:
release:
@ -16,3 +23,12 @@ jobs:
secrets:
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}

View file

@ -16,3 +16,11 @@ jobs:
secrets:
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}

View file

@ -6,6 +6,13 @@ on:
- main
paths:
- "packages/openai-adapters/**"
- ".github/workflows/release-openai-adapters.yml"
- ".github/workflows/reusable-release.yml"
permissions:
contents: write
issues: write
pull-requests: write
jobs:
release:
@ -16,3 +23,12 @@ jobs:
secrets:
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}

View file

@ -14,6 +14,24 @@ on:
required: true
SEMANTIC_RELEASE_NPM_TOKEN:
required: true
OPENAI_API_KEY:
required: false
ANTHROPIC_API_KEY:
required: false
GEMINI_API_KEY:
required: false
MISTRAL_API_KEY:
required: false
AZURE_OPENAI_API_KEY:
required: false
AZURE_FOUNDRY_CODESTRAL_API_KEY:
required: false
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY:
required: false
AZURE_OPENAI_GPT41_API_KEY:
required: false
VOYAGE_API_KEY:
required: false
permissions:
contents: write
@ -46,10 +64,20 @@ jobs:
- name: Run tests
run: npm test
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }}
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }}
- name: Release
env:
GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
NODE_AUTH_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
run: npx semantic-release
run: npx semantic-release

3
.gitignore vendored
View file

@ -67,8 +67,9 @@ instance/
# Scrapy stuff:
.scrapy
# Sphinx documentation
# docusaurus
docs/_build/
docs/.docusaurus
# PyBuilder
target/

48
CLA.md Normal file
View file

@ -0,0 +1,48 @@
# Individual Contributor License Agreement (v1.0, Continue)
_Based on the Apache Software Foundation Individual CLA v 2.2._
By commenting **“I have read the CLA Document and I hereby sign the CLA”**
on a Pull Request, **you (“Contributor”) agree to the following terms** for any
past and future “Contributions” submitted to **Continue (the “Project”)**.
---
## 1. Definitions
- **“Contribution”** – any original work of authorship submitted to the Project
(code, documentation, designs, etc.).
- **“You” / “Your”** – the individual (or legal entity) posting the acceptance
comment.
## 2. Copyright License
You grant **Continue Dev, Inc.** and all recipients of software distributed by the
Project a perpetual, worldwide, non‑exclusive, royalty‑free, irrevocable
license to reproduce, prepare derivative works of, publicly display, publicly
perform, sublicense, and distribute Your Contributions and derivative works.
## 3. Patent License
You grant **Continue Dev, Inc.** and all recipients of the Project a perpetual,
worldwide, non‑exclusive, royalty‑free, irrevocable (except as below) patent
license to make, have made, use, sell, offer to sell, import, and otherwise
transfer Your Contributions alone or in combination with the Project.
If any entity brings patent litigation alleging that the Project or a
Contribution infringes a patent, the patent licenses granted by You to that
entity under this CLA terminate.
## 4. Representations
1. You are legally entitled to grant the licenses above.
2. Each Contribution is either Your original creation or You have authority to
submit it under this CLA.
3. Your Contributions are provided **“AS IS”** without warranties of any kind.
4. You will notify the Project if any statement above becomes inaccurate.
## 5. Miscellany
This Agreement is governed by the laws of the **State of California**, USA,
excluding its conflict‑of‑laws rules. If any provision is held unenforceable,
the remaining provisions remain in force.

View file

@ -192,6 +192,7 @@ To keep the Continue codebase clean and maintainable, we expect the following fr
- Keep changes focused. Multiple unrelated fixes should be opened as separate PRs
- Write or update tests for new functionality
- Update relevant documentation in the `docs` folder
- **For new features**: Include a short screen recording or screenshot demonstrating the new functionality. This makes it much easier for us as contributors to review and understand your changes. See [this PR](https://github.com/continuedev/continue/pull/6455) as a good example
- Open a PR against the `main` branch. Make sure to fill in the PR template
### Formatting

View file

@ -36,27 +36,27 @@ and [hub of models, rules, prompts, docs, and other building blocks](https://hub
[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
![agent](docs/static/img/agent.gif)
![agent](docs/images/agent.gif)
## Chat
[Chat](https://continue.dev/docs/chat/how-to-use-it) makes it easy to ask for help from an LLM without needing to leave
the IDE
![chat](docs/static/img/chat.gif)
![chat](docs/images/chat.gif)
## Autocomplete
[Autocomplete](https://continue.dev/docs/autocomplete/how-to-use-it) provides inline code suggestions as you type
![autocomplete](docs/static/img/autocomplete.gif)
![autocomplete](docs/images/autocomplete.gif)
## Edit
[Edit](https://continue.dev/docs/edit/how-to-use-it) is a convenient way to modify code without leaving your current
file
![edit](docs/static/img/edit.gif)
![edit](docs/images/edit.gif)
</div>

View file

@ -19,5 +19,13 @@
"max-depth": ["error", { "max": 6 }],
"max-nested-callbacks": ["error", { "max": 4 }],
"max-params": ["error", { "max": 8 }]
}
},
"overrides": [
{
"files": ["**/*.vitest.ts"],
"rules": {
"max-lines-per-function": "off"
}
}
]
}

View file

@ -103,6 +103,16 @@ export function postprocessCompletion({
}
}
if (llm.model.includes("qwen3")) {
// Qwen3 always starts from special thinking markers, and we don't want them to output these contents
// Remove all content from "
completion = completion.replace(/<think>.*?<\/think>/s, "");
completion = completion.replace(/<\/think>/, "");
// Remove any number of newline characters at the beginning and end
completion = completion.replace(/^\n+|\n+$/g, "");
}
if (llm.model.includes("mercury") || llm.model.includes("granite")) {
// Granite tends to repeat the start of the line in the completion output
let prefixEnd = prefix.split("\n").pop();

View file

@ -9,9 +9,7 @@
* creating a render of it.
*/
import {
transformerMetaHighlight,
transformerNotationDiff,
transformerNotationFocus,
transformerNotationHighlight,
} from "@shikijs/transformers";
import { JSDOM } from "jsdom";
@ -21,6 +19,7 @@ import {
getSingletonHighlighter,
Highlighter,
} from "shiki";
import { DiffLine } from "..";
import { escapeForSVG, kebabOfStr } from "../util/text";
interface CodeRendererOptions {
@ -37,6 +36,10 @@ interface HTMLOptions {
interface ConversionOptions extends HTMLOptions {
transparent?: boolean;
imageType: "svg";
fontSize: number;
fontFamily: string;
dimensions: Dimensions;
lineHeight: number;
}
interface Dimensions {
@ -166,83 +169,102 @@ export class CodeRenderer {
code: string,
language: string = "javascript",
currLineOffsetFromTop: number,
newDiffLines: DiffLine[],
): Promise<string> {
const annotatedCode = code
.split("\n")
.map((line, i) =>
i === currLineOffsetFromTop
? line + " \/\/ \[\!code highlight\]"
: line,
)
.join("\n");
const lines = code.split("\n");
const newDiffLineMap = new Set();
if (newDiffLines) {
newDiffLines.forEach((diffLine) => {
if (diffLine.type === "new") {
newDiffLineMap.add(diffLine.line);
}
});
}
const annotatedLines = [];
// NOTE: Shiki's preprocessor deletes transformer annotations when applied to an empty line.
// If you are transforming an empty line, make sure that
// the transformation is applied to a non-empty line first.
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// Add highlight comment before target line.
if (i + 1 === currLineOffsetFromTop && currLineOffsetFromTop >= 0) {
annotatedLines.push("// [!code highlight:1]");
}
// Handle diff lines
if (newDiffLineMap.has(line)) {
if (line.trim() === "") {
// For empty lines, add the magic comment on a separate line before.
annotatedLines.push("// [!code ++]");
annotatedLines.push(line); // The empty line itself.
} else {
// For non-empty lines, append the magic comment.
annotatedLines.push(line + "// [!code ++]");
}
newDiffLineMap.delete(line);
} else {
annotatedLines.push(line);
}
}
const annotatedCode = annotatedLines.join("\n");
await this.highlighter!.loadLanguage(language as BundledLanguage);
return this.highlighter!.codeToHtml(annotatedCode, {
lang: language,
theme: this.currentTheme,
transformers: [
// transformerColorizedBrackets(),
transformerMetaHighlight(),
transformerNotationHighlight(),
transformerNotationDiff(),
transformerNotationFocus(),
],
transformers: [transformerNotationHighlight(), transformerNotationDiff()],
});
}
async convertToSVG(
code: string,
language: string = "javascript",
fontSize: number,
fontFamily: string,
dimensions: Dimensions,
lineHeight: number,
options: ConversionOptions,
currLineOffsetFromTop: number,
newDiffLines: DiffLine[],
): Promise<Buffer> {
const strokeWidth = 1;
const highlightedCodeHtml = await this.highlightCode(
code,
language,
currLineOffsetFromTop,
newDiffLines,
);
// console.log(highlightedCodeHtml);
const { guts, lineBackgrounds } = this.convertShikiHtmlToSvgGut(
highlightedCodeHtml,
fontSize,
fontFamily,
lineHeight,
dimensions,
options,
);
const backgroundColor = this.getBackgroundColor(highlightedCodeHtml);
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${dimensions.width}" height="${dimensions.height}" shape-rendering="crispEdges">
<style>
:root {
--purple: rgb(112, 114, 209);
--green: rgb(136, 194, 163);
--blue: rgb(107, 166, 205);
}
</style>
<g>
<rect x="0" y="0" rx="10" ry="10" width="${dimensions.width}" height="${dimensions.height}" fill="${this.editorBackground}" shape-rendering="crispEdges" />
${lineBackgrounds}
${guts}
</g>
</svg>`;
console.log(svg);
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${options.dimensions.width}" height="${options.dimensions.height}" shape-rendering="crispEdges">
<style>
:root {
--purple: rgb(112, 114, 209);
--green: rgb(136, 194, 163);
--blue: rgb(107, 166, 205);
}
</style>
<g>
<rect x="0" y="0" rx="10" ry="10" width="${options.dimensions.width}" height="${options.dimensions.height}" fill="${this.editorBackground}" shape-rendering="crispEdges" />
${lineBackgrounds}
${guts}
</g>
</svg>`;
// console.log(svg);
return Buffer.from(svg, "utf8");
}
convertShikiHtmlToSvgGut(
shikiHtml: string,
fontSize: number,
fontFamily: string,
lineHeight: number,
dimensions: Dimensions,
options: ConversionOptions,
): { guts: string; lineBackgrounds: string } {
const dom = new JSDOM(shikiHtml);
const document = dom.window.document;
@ -263,6 +285,7 @@ export class CodeRenderer {
if (classes.includes("highlighted")) {
fill = ` fill="${this.editorLineHighlight}"`;
}
const content = el.textContent || "";
return `<tspan xml:space="preserve"${fill}>${escapeForSVG(content)}</tspan>`;
})
@ -278,8 +301,8 @@ export class CodeRenderer {
// The first step is to add lineHeight / 2 to move the axis down.
// The second step is to add 'dominant-baseline="central"' to vertically center the text.
// Note that we choose "central" over "middle". "middle" will center the text too perfectly, which is actually undesirable!
const y = index * lineHeight + lineHeight / 2;
return `<text x="0" y="${y}" font-family="${fontFamily}" font-size="${fontSize.toString()}" xml:space="preserve" dominant-baseline="central" shape-rendering="crispEdges">${spans}</text>`;
const y = index * options.lineHeight + options.lineHeight / 2;
return `<text x="0" y="${y}" font-family="${options.fontFamily}" font-size="${options.fontSize.toString()}" xml:space="preserve" dominant-baseline="central" shape-rendering="crispEdges">${spans}</text>`;
});
const lineBackgrounds = lines
@ -287,8 +310,11 @@ export class CodeRenderer {
const classes = line?.getAttribute("class") || "";
const bgColor = classes.includes("highlighted")
? this.editorLineHighlight
: this.editorBackground;
const y = index * lineHeight;
: classes.includes("diff add")
? "rgba(255, 255, 0, 0.2)"
: this.editorBackground;
const y = index * options.lineHeight;
const isFirst = index === 0;
const isLast = index === lines.length - 1;
const radius = 10;
@ -297,24 +323,24 @@ export class CodeRenderer {
// This is undesirable in our case because pixel-perfect alignment of these rectangles will introduce thin gaps.
// Turning it off with 'shape-rendering="crispEdges"' solves the issue.
return isFirst
? `<path d="M ${0} ${y + lineHeight}
L ${0} ${y + radius}
Q ${0} ${y} ${radius} ${y}
L ${dimensions.width - radius} ${y}
Q ${dimensions.width} ${y} ${dimensions.width} ${y + radius}
L ${dimensions.width} ${y + lineHeight}
Z"
fill="${bgColor}" />`
? `<path d="M ${0} ${y + options.lineHeight}
L ${0} ${y + radius}
Q ${0} ${y} ${radius} ${y}
L ${options.dimensions.width - radius} ${y}
Q ${options.dimensions.width} ${y} ${options.dimensions.width} ${y + radius}
L ${options.dimensions.width} ${y + options.lineHeight}
Z"
fill="${bgColor}" />`
: isLast
? `<path d="M ${0} ${y}
L ${0} ${y + lineHeight - radius}
Q ${0} ${y + lineHeight} ${radius} ${y + lineHeight}
L ${dimensions.width - radius} ${y + lineHeight}
Q ${dimensions.width} ${y + lineHeight} ${dimensions.width} ${y + lineHeight - 10}
L ${dimensions.width} ${y}
Z"
fill="${bgColor}" />`
: `<rect x="0" y="${y}" rx="${radius}" ry="${radius}" width="100%" height="${lineHeight}" fill="${bgColor}" shape-rendering="crispEdges" />`;
? `<path d="M ${0} ${y}
L ${0} ${y + options.lineHeight - radius}
Q ${0} ${y + options.lineHeight} ${radius} ${y + options.lineHeight}
L ${options.dimensions.width - radius} ${y + options.lineHeight}
Q ${options.dimensions.width} ${y + options.lineHeight} ${options.dimensions.width} ${y + options.lineHeight - 10}
L ${options.dimensions.width} ${y}
Z"
fill="${bgColor}" />`
: `<rect x="0" y="${y}" width="100%" height="${options.lineHeight}" fill="${bgColor}" shape-rendering="crispEdges" />`;
})
.join("\n");
@ -344,12 +370,9 @@ export class CodeRenderer {
async getDataUri(
code: string,
language: string = "javascript",
fontSize: number,
fontFamily: string,
dimensions: Dimensions,
lineHeight: number,
options: ConversionOptions,
currLineOffsetFromTop: number,
newDiffLines: DiffLine[],
): Promise<DataUri> {
switch (options.imageType) {
// case "png":
@ -366,12 +389,9 @@ export class CodeRenderer {
const svgBuffer = await this.convertToSVG(
code,
language,
fontSize,
fontFamily,
dimensions,
lineHeight,
options,
currLineOffsetFromTop,
newDiffLines,
);
return `data:image/svg+xml;base64,${svgBuffer.toString("base64")}`;
}

View file

@ -11,12 +11,14 @@ import {
} from "../index.js";
import { GlobalContext } from "../util/GlobalContext.js";
import EventEmitter from "node:events";
import {
AuthType,
ControlPlaneSessionInfo,
} from "../control-plane/AuthTypes.js";
import { getControlPlaneEnv } from "../control-plane/env.js";
import { logger } from "../util/logger.js";
import { Telemetry } from "../util/posthog.js";
import {
ASSISTANTS,
getAllDotContinueDefinitionFiles,
@ -44,6 +46,16 @@ export class ConfigHandler {
private organizations: OrgWithProfiles[] = [];
currentProfile: ProfileLifecycleManager | null;
currentOrg: OrgWithProfiles;
totalConfigLoads: number = 0;
public isInitialized: Promise<void>;
private initter: EventEmitter;
cascadeAbortController: AbortController;
private abortCascade() {
this.cascadeAbortController.abort();
this.cascadeAbortController = new AbortController();
}
constructor(
private readonly ide: IDE,
@ -53,9 +65,11 @@ export class ConfigHandler {
) {
this.ide = ide;
this.ideSettingsPromise = ideSettingsPromise;
this.controlPlaneClient = new ControlPlaneClient(
sessionInfoPromise,
ideSettingsPromise,
this.ide.getIdeInfo(),
);
// This profile manager will always be available
@ -80,7 +94,13 @@ export class ConfigHandler {
this.currentOrg = personalOrg;
this.organizations = [personalOrg];
void this.cascadeInit();
this.initter = new EventEmitter();
this.isInitialized = new Promise((resolve) => {
this.initter.on("init", resolve);
});
this.cascadeAbortController = new AbortController();
void this.cascadeInit("Config handler initialization");
}
private workspaceDirs: string[] | null = null;
@ -96,54 +116,71 @@ export class ConfigHandler {
return `${workspaceId}:::${orgId}`;
}
private async cascadeInit() {
private async cascadeInit(reason: string) {
const signal = this.cascadeAbortController.signal;
this.workspaceDirs = null; // forces workspace dirs reload
const orgs = await this.getOrgs();
try {
const orgs = await this.getOrgs();
// Figure out selected org
const workspaceId = await this.getWorkspaceId();
const selectedOrgs =
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
const currentSelection = selectedOrgs[workspaceId];
// Figure out selected org
const workspaceId = await this.getWorkspaceId();
const selectedOrgs =
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
const currentSelection = selectedOrgs[workspaceId];
const firstNonPersonal = orgs.find(
(org) => org.id !== this.PERSONAL_ORG_DESC.id,
);
const fallback = firstNonPersonal ?? orgs[0];
// note, ignoring case of zero orgs since should never happen
const firstNonPersonal = orgs.find(
(org) => org.id !== this.PERSONAL_ORG_DESC.id,
);
const fallback = firstNonPersonal ?? orgs[0];
// note, ignoring case of zero orgs since should never happen
let selectedOrg: OrgWithProfiles;
if (!currentSelection) {
selectedOrg = fallback;
} else {
const match = orgs.find((org) => org.id === currentSelection);
if (match) {
selectedOrg = match;
} else {
let selectedOrg: OrgWithProfiles;
if (!currentSelection) {
selectedOrg = fallback;
} else {
const match = orgs.find((org) => org.id === currentSelection);
if (match) {
selectedOrg = match;
} else {
selectedOrg = fallback;
}
}
if (signal.aborted) {
return; // local only case, no`fetch to throw abort error
}
this.initter.emit("init");
this.globalContext.update("lastSelectedOrgIdForWorkspace", {
...selectedOrgs,
[workspaceId]: selectedOrg.id,
});
this.organizations = orgs;
this.currentOrg = selectedOrg;
this.currentProfile = selectedOrg.currentProfile;
await this.reloadConfig(reason);
} catch (e) {
if (e instanceof Error && e.message.includes("AbortError")) {
return;
} else {
this.initter.emit("init"); // Error case counts for initialization
throw e;
}
}
this.globalContext.update("lastSelectedOrgIdForWorkspace", {
...selectedOrgs,
[workspaceId]: selectedOrg.id,
});
this.organizations = orgs;
this.currentOrg = selectedOrg;
this.currentProfile = selectedOrg.currentProfile;
await this.reloadConfig();
}
private async getOrgs(): Promise<OrgWithProfiles[]> {
if (await this.controlPlaneClient.isSignedIn()) {
const isSignedIn = await this.controlPlaneClient.isSignedIn();
if (isSignedIn) {
const orgDescs = await this.controlPlaneClient.listOrganizations();
const personalHubOrg = await this.getPersonalHubOrg();
const hubOrgs = await Promise.all(
orgDescs.map((org) => this.getNonPersonalHubOrg(org)),
);
return [...hubOrgs, personalHubOrg];
const orgs = await Promise.all([
this.getPersonalHubOrg(),
...orgDescs.map((org) => this.getNonPersonalHubOrg(org)),
]);
return orgs;
} else {
return [await this.getLocalOrg()];
}
@ -312,13 +349,14 @@ export class ConfigHandler {
// Should not be used internally
//////////////////
async refreshAll() {
await this.cascadeInit();
await this.cascadeInit("External refresh all");
}
// Ide settings change: refresh session and cascade refresh from the top
async updateIdeSettings(ideSettings: IdeSettings) {
this.ideSettingsPromise = Promise.resolve(ideSettings);
await this.cascadeInit();
this.abortCascade();
await this.cascadeInit("IDE settings update");
}
// Session change: refresh session and cascade refresh from the top
@ -328,8 +366,10 @@ export class ConfigHandler {
this.controlPlaneClient = new ControlPlaneClient(
Promise.resolve(sessionInfo),
this.ideSettingsPromise,
this.ide.getIdeInfo(),
);
await this.cascadeInit();
this.abortCascade();
await this.cascadeInit("Control plane session info update");
}
// Org id: check id validity, save selection, switch and reload
@ -356,7 +396,7 @@ export class ConfigHandler {
await this.setSelectedProfileId(profileId);
} else {
this.currentProfile = org.currentProfile;
await this.reloadConfig();
await this.reloadConfig("Selected org changed");
}
}
@ -384,14 +424,17 @@ export class ConfigHandler {
});
this.currentProfile = profile;
await this.reloadConfig();
await this.reloadConfig("Selected profile changed");
}
// Bottom level of cascade: refresh the current profile
// IMPORTANT - must always refresh when switching profiles
// Because of e.g. MCP singleton and docs service using things from config
// Could improve this
async reloadConfig() {
async reloadConfig(reason: string) {
const startTime = performance.now();
this.totalConfigLoads += 1;
// console.log(`Reloading config (#${this.totalConfigLoads}): ${reason}`); // Uncomment to see config loading logs
if (!this.currentProfile) {
return {
config: undefined,
@ -415,6 +458,17 @@ export class ConfigHandler {
await this.currentProfile.reloadConfig(this.additionalContextProviders);
this.notifyConfigListeners({ config, errors, configLoadInterrupted });
// Track config loading telemetry
const endTime = performance.now();
const duration = endTime - startTime;
void Telemetry.capture("config_reload", {
duration,
reason,
totalConfigLoads: this.totalConfigLoads,
configLoadInterrupted,
});
return { config, errors, configLoadInterrupted };
}
@ -457,6 +511,7 @@ export class ConfigHandler {
configLoadInterrupted: true,
};
}
await this.isInitialized;
const config = await this.currentProfile.loadConfig(
this.additionalContextProviders,
);
@ -487,7 +542,7 @@ export class ConfigHandler {
private additionalContextProviders: IContextProvider[] = [];
registerCustomContextProvider(contextProvider: IContextProvider) {
this.additionalContextProviders.push(contextProvider);
void this.reloadConfig();
void this.reloadConfig("Custom context provider registered");
}
/**
* Retrieves the titles of additional context providers that are of type "submenu".

View file

@ -32,7 +32,7 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => {
}`;
fs.writeFileSync(getConfigTsPath(), configTs);
await new Promise((resolve) => setTimeout(resolve, 1000));
const config = await testConfigHandler.reloadConfig();
const config = await testConfigHandler.reloadConfig("test");
/**
* @ts-ignore is applied because this test is skipped
*/
@ -45,7 +45,7 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => {
path.join(TEST_DIR, ".continuerc.json"),
JSON.stringify({ systemMessage: "SYSTEM2" }),
);
const config = await testConfigHandler.reloadConfig();
const config = await testConfigHandler.reloadConfig("test");
/**
* @ts-ignore is applied because this test is skipped
*/

View file

@ -7,6 +7,43 @@ import { walkDirs } from "../../indexing/walkDir";
import { RULES_MARKDOWN_FILENAME } from "../../llm/rules/constants";
import { getUriPathBasename } from "../../util/uri";
export class CodebaseRulesCache {
private static instance: CodebaseRulesCache | null = null;
private constructor() {}
public static getInstance(): CodebaseRulesCache {
if (CodebaseRulesCache.instance === null) {
CodebaseRulesCache.instance = new CodebaseRulesCache();
}
return CodebaseRulesCache.instance;
}
rules: RuleWithSource[] = [];
errors: ConfigValidationError[] = [];
async refresh(ide: IDE) {
const { rules, errors } = await loadCodebaseRules(ide);
this.rules = rules;
this.errors = errors;
}
async update(ide: IDE, uri: string) {
const content = await ide.readFile(uri);
const rule = markdownToRule(content, { uriType: "file", filePath: uri });
const ruleWithSource: RuleWithSource = {
...rule,
source: "colocated-markdown",
ruleFile: uri,
};
const matchIdx = this.rules.findIndex((r) => r.ruleFile === uri);
if (matchIdx === -1) {
this.rules.push(ruleWithSource);
} else {
this.rules[matchIdx] = ruleWithSource;
}
}
remove(uri: string) {
this.rules = this.rules.filter((r) => r.ruleFile !== uri);
}
}
/**
* Loads rules from rules.md files colocated in the codebase
*/
@ -33,7 +70,11 @@ export async function loadCodebaseRules(ide: IDE): Promise<{
const content = await ide.readFile(filePath);
const rule = markdownToRule(content, { uriType: "file", filePath });
rules.push({ ...rule, source: "rules-block", ruleFile: filePath });
rules.push({
...rule,
source: "colocated-markdown",
ruleFile: filePath,
});
} catch (e) {
errors.push({
fatal: false,

View file

@ -45,27 +45,27 @@ describe("loadCodebaseRules", () => {
"src/rules.md": {
name: "General Rules",
rule: "Follow coding standards",
source: "rules-block",
source: "colocated-markdown",
ruleFile: "src/rules.md",
},
"src/redux/rules.md": {
name: "Redux Rules",
rule: "Use Redux Toolkit",
globs: "**/*.{ts,tsx}",
source: "rules-block",
source: "colocated-markdown",
ruleFile: "src/redux/rules.md",
},
"src/components/rules.md": {
name: "Component Rules",
rule: "Use functional components",
globs: ["**/*.tsx", "**/*.jsx"],
source: "rules-block",
source: "colocated-markdown",
ruleFile: "src/components/rules.md",
},
".continue/rules.md": {
name: "Global Rules",
rule: "Follow project guidelines",
source: "rules-block",
source: "colocated-markdown",
ruleFile: ".continue/rules.md",
},
};

View file

@ -16,7 +16,7 @@ describe("Rule Colocation Application", () => {
{
name: "Root Rule",
rule: "Follow project standards",
source: "rules-block",
source: "colocated-markdown",
ruleFile: ".continue/rules.md",
},
@ -24,7 +24,7 @@ describe("Rule Colocation Application", () => {
{
name: "React Components Rule",
rule: "Use functional components with hooks",
source: "rules-block",
source: "colocated-markdown",
ruleFile: "src/components/rules.md",
// No explicit globs - should implicitly only apply to files in that directory
},
@ -34,7 +34,7 @@ describe("Rule Colocation Application", () => {
name: "Redux Rule",
rule: "Use Redux Toolkit for state management",
globs: "src/redux/**/*.{ts,tsx}",
source: "rules-block",
source: "colocated-markdown",
ruleFile: "src/redux/rules.md",
},
@ -43,7 +43,7 @@ describe("Rule Colocation Application", () => {
name: "TypeScript Components Rule",
rule: "Use TypeScript with React components",
globs: "**/*.tsx", // Only apply to .tsx files
source: "rules-block",
source: "colocated-markdown",
ruleFile: "src/components/rules.md",
},
@ -52,7 +52,7 @@ describe("Rule Colocation Application", () => {
name: "API Utils Rule",
rule: "Follow API utility conventions",
globs: "**/*.ts", // Only TypeScript files in this directory
source: "rules-block",
source: "colocated-markdown",
ruleFile: "src/utils/api/rules.md",
},
];
@ -183,7 +183,7 @@ describe("Rule Colocation Application", () => {
const impliedComponentRule: RuleWithSource = {
name: "Implied Components Rule",
rule: "Use React component best practices",
source: "rules-block",
source: "colocated-markdown",
ruleFile: "src/components/rules.md",
// No explicit globs - should infer from directory
};
@ -233,7 +233,7 @@ describe("Rule Colocation Application", () => {
name: "TypeScript Component Rule",
rule: "Use TypeScript with React components",
globs: "**/*.tsx", // Only apply to .tsx files
source: "rules-block",
source: "colocated-markdown",
ruleFile: "src/components/rules.md",
};
@ -280,7 +280,7 @@ describe("Rule Colocation Application", () => {
name: "API Utils Rule",
rule: "Follow API utility conventions",
globs: "**/*.ts", // Only TypeScript files in this directory
source: "rules-block",
source: "colocated-markdown",
ruleFile: "src/utils/api/rules.md",
};
@ -323,7 +323,7 @@ describe("Rule Colocation Application", () => {
return {
name: `Inferred Rule for ${directory}`,
rule: `Follow standards for ${directory}`,
source: "rules-block",
source: "colocated-markdown",
ruleFile: ruleFilePath,
// In a fixed implementation, these globs would be automatically inferred
// globs: expectedGlob,

View file

@ -20,6 +20,7 @@ import {
Tool,
} from "../../";
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
import CurrentFileContextProvider from "../../context/providers/CurrentFileContextProvider";
import MCPContextProvider from "../../context/providers/MCPContextProvider";
import RulesContextProvider from "../../context/providers/RulesContextProvider";
import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
@ -36,7 +37,7 @@ import { Telemetry } from "../../util/posthog";
import { TTS } from "../../util/tts";
import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles";
import { loadContinueConfigFromJson } from "../load";
import { loadCodebaseRules } from "../markdown/loadCodebaseRules";
import { CodebaseRulesCache } from "../markdown/loadCodebaseRules";
import { loadMarkdownRules } from "../markdown/loadMarkdownRules";
import { migrateJsonSharedConfig } from "../migrateSharedConfig";
import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
@ -152,11 +153,21 @@ export default async function doLoadConfig(options: {
newConfig.rules.unshift(...rules);
newConfig.contextProviders.push(new RulesContextProvider({}));
// Add current file as context if setting is enabled
if (
newConfig.experimental?.useCurrentFileAsContext === true &&
!newConfig.contextProviders.find(
(c) =>
c.description.title === CurrentFileContextProvider.description.title,
)
) {
newConfig.contextProviders.push(new CurrentFileContextProvider({}));
}
// Add rules from colocated rules.md files in the codebase
const { rules: codebaseRules, errors: codebaseRulesErrors } =
await loadCodebaseRules(ide);
newConfig.rules.unshift(...codebaseRules);
errors.push(...codebaseRulesErrors);
const codebaseRulesCache = CodebaseRulesCache.getInstance();
newConfig.rules.unshift(...codebaseRulesCache.rules);
errors.push(...codebaseRulesCache.errors);
// Rectify model selections for each role
newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);

View file

@ -19,7 +19,6 @@ export const sharedConfigSchema = z
readResponseTTS: z.boolean(),
promptPath: z.string(),
useCurrentFileAsContext: z.boolean(),
logEditingData: z.boolean(),
optInNextEditFeature: z.boolean(),
enableExperimentalTools: z.boolean(),
codebaseToolCallingOnly: z.boolean(),
@ -181,9 +180,6 @@ export function modifyAnyConfigWithSharedConfig<
configCopy.experimental.useCurrentFileAsContext =
sharedConfig.useCurrentFileAsContext;
}
if (sharedConfig.logEditingData !== undefined) {
configCopy.experimental.logEditingData = sharedConfig.logEditingData;
}
if (sharedConfig.optInNextEditFeature !== undefined) {
configCopy.experimental.optInNextEditFeature =
sharedConfig.optInNextEditFeature;

View file

@ -235,6 +235,8 @@ async function configYamlToContinueConfig(options: {
startUrl: doc.startUrl,
rootUrl: doc.rootUrl,
faviconUrl: doc.faviconUrl,
maxDepth: doc.maxDepth,
useLocalCrawling: doc.useLocalCrawling,
}));
config.mcpServers?.forEach((mcpServer) => {

View file

@ -19,7 +19,7 @@ import { BuiltInToolNames } from "../../../tools/builtIn";
import { callBuiltInTool } from "../../../tools/callTool";
import { globSearchTool } from "../../../tools/definitions/globSearch";
import { grepSearchTool } from "../../../tools/definitions/grepSearch";
import { lsTool } from "../../../tools/definitions/lsTool";
import { lsTool } from "../../../tools/definitions/ls";
import { readFileTool } from "../../../tools/definitions/readFile";
import { viewRepoMapTool } from "../../../tools/definitions/viewRepoMap";
import { viewSubdirectoryTool } from "../../../tools/definitions/viewSubdirectory";
@ -60,12 +60,13 @@ export interface IRetrievalPipeline {
export default class BaseRetrievalPipeline implements IRetrievalPipeline {
private ftsIndex = new FullTextSearchCodebaseIndex();
private lanceDbIndex: LanceDbIndex | null = null;
private lanceDbInitPromise: Promise<void> | null = null;
constructor(protected readonly options: RetrievalPipelineOptions) {
void this.initLanceDb();
}
private async initLanceDb() {
protected async initLanceDb() {
const embedModel = this.options.config.selectedModelByRole.embed;
if (!embedModel) {
@ -77,6 +78,23 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
);
}
protected async ensureLanceDbInitialized(): Promise<boolean> {
if (this.lanceDbIndex) {
return true;
}
if (this.lanceDbInitPromise) {
await this.lanceDbInitPromise;
return this.lanceDbIndex !== null;
}
this.lanceDbInitPromise = this.initLanceDb();
await this.lanceDbInitPromise;
this.lanceDbInitPromise = null; // clear after init
return this.lanceDbIndex !== null;
}
private getCleanedTrigrams(
query: RetrievalPipelineRunArguments["query"],
): string[] {
@ -163,7 +181,9 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
input: string,
n: number,
): Promise<Chunk[]> {
if (!this.lanceDbIndex) {
const initialized = await this.ensureLanceDbInitialized();
if (!initialized || !this.lanceDbIndex) {
console.warn(
"LanceDB index not available, skipping embeddings retrieval",
);

View file

@ -10,7 +10,7 @@ import {
import fetch, { RequestInit, Response } from "node-fetch";
import { OrganizationDescription } from "../config/ProfileLifecycleManager.js";
import { IdeSettings, ModelDescription } from "../index.js";
import { IdeInfo, IdeSettings, ModelDescription } from "../index.js";
import { ControlPlaneSessionInfo, isOnPremSession } from "./AuthTypes.js";
import { getControlPlaneEnv } from "./env.js";
@ -40,6 +40,7 @@ export class ControlPlaneClient {
ControlPlaneSessionInfo | undefined
>,
private readonly ideSettingsPromise: Promise<IdeSettings>,
private readonly ideInfoPromise: Promise<IdeInfo>,
) {}
async resolveFQSNs(
@ -86,11 +87,17 @@ export class ControlPlaneClient {
const env = await getControlPlaneEnv(this.ideSettingsPromise);
const url = new URL(path, env.CONTROL_PLANE_URL).toString();
const ideInfo = await this.ideInfoPromise;
const resp = await fetch(url, {
...init,
headers: {
...init.headers,
Authorization: `Bearer ${accessToken}`,
...{
"x-extension-version": ideInfo.extensionVersion,
"x-is-prerelease": String(ideInfo.isPrerelease),
},
},
});

View file

@ -132,7 +132,10 @@ function readMdmKeysWindows(): MdmKeys | undefined {
try {
// Use REG QUERY command to read registry values
const licenseKeyCmd = `reg query "${regPath}" /v licenseKey`;
const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" });
const licenseKeyOutput = execSync(licenseKeyCmd, {
encoding: "utf8",
stdio: ["pipe", "pipe", "pipe"],
});
// Extract values from command output
const licenseKey = extractRegValue(licenseKeyOutput);
if (licenseKey) {
@ -145,7 +148,10 @@ function readMdmKeysWindows(): MdmKeys | undefined {
// Try HKEY_CURRENT_USER if not found in HKEY_LOCAL_MACHINE
try {
const licenseKeyCmd = `reg query "${userRegPath}" /v licenseKey`;
const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" });
const licenseKeyOutput = execSync(licenseKeyCmd, {
encoding: "utf8",
stdio: ["pipe", "pipe", "pipe"],
});
// Extract values from command output
const licenseKey = extractRegValue(licenseKeyOutput);
if (licenseKey) {

View file

@ -11,7 +11,6 @@ import { ConfigHandler } from "./config/ConfigHandler";
import { SYSTEM_PROMPT_DOT_FILE } from "./config/getWorkspaceContinueRuleDotFiles";
import { addModel, deleteModel } from "./config/util";
import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider";
import { ContinueServerClient } from "./continueServer/stubs/client";
import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
import { getControlPlaneEnv } from "./control-plane/env";
import { DevDataSqliteDb } from "./data/devdataSqlite";
@ -25,6 +24,7 @@ import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile";
import { callTool } from "./tools/callTool";
import { ChatDescriber } from "./util/chatDescriber";
import { clipboardCache } from "./util/clipboardCache";
import { compactConversation } from "./util/conversationCompaction";
import { GlobalContext } from "./util/GlobalContext";
import historyManager from "./util/history";
import { editConfigFile, migrateV1DevDataFiles } from "./util/paths";
@ -53,6 +53,7 @@ import { BLOCK_TYPES, ConfigYaml } from "@continuedev/config-yaml";
import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache";
import { stringifyMcpPrompt } from "./commands/slash/mcpSlashCommand";
import { isLocalDefinitionFile } from "./config/loadLocalAssistants";
import { CodebaseRulesCache } from "./config/markdown/loadCodebaseRules";
import {
setupLocalConfig,
setupProviderConfig,
@ -70,6 +71,7 @@ import { RULES_MARKDOWN_FILENAME } from "./llm/rules/constants";
import { llmStreamChat } from "./llm/streamChat";
import { BeforeAfterDiff } from "./nextEdit/context/diffFormatting";
import { processSmallEdit } from "./nextEdit/context/processSmallEdit";
import { NextEditProvider } from "./nextEdit/NextEditProvider";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import { OnboardingModes } from "./protocol/core";
import type { IMessenger, Message } from "./protocol/messenger";
@ -89,6 +91,7 @@ export class Core {
configHandler: ConfigHandler;
codeBaseIndexer: CodebaseIndexer;
completionProvider: CompletionProvider;
nextEditProvider: NextEditProvider;
private docsService: DocsService;
private globalContext = new GlobalContext();
llmLogger = new LLMLogger();
@ -151,7 +154,7 @@ export class Core {
);
MCPManagerSingleton.getInstance().onConnectionsRefreshed = () => {
void this.configHandler.reloadConfig();
void this.configHandler.reloadConfig("MCP Connections refreshed");
// Refresh @mention dropdown submenu items for MCP providers
const mcpManager = MCPManagerSingleton.getInstance();
@ -202,11 +205,6 @@ export class Core {
dataLogger.ideSettingsPromise = ideSettingsPromise;
void ideSettingsPromise.then((ideSettings) => {
const continueServerClient = new ContinueServerClient(
ideSettings.remoteConfigServerUrl,
ideSettings.userToken,
);
// Index on initialization
void this.ide.getWorkspaceDirs().then(async (dirs) => {
// Respect pauseCodebaseIndexOnStart user settings
@ -239,6 +237,24 @@ export class Core {
(..._) => Promise.resolve([]),
);
const codebaseRulesCache = CodebaseRulesCache.getInstance();
void codebaseRulesCache
.refresh(ide)
.catch((e) => console.error("Failed to initialize colocated rules cache"))
.then(() => {
void this.configHandler.reloadConfig(
"Initial codebase rules post-walkdir/load reload",
);
});
this.nextEditProvider = NextEditProvider.initialize(
this.configHandler,
ide,
getLlm,
(e) => {},
(..._) => Promise.resolve([]),
"fineTuned",
);
this.registerMessageHandlers(ideSettingsPromise);
}
@ -305,23 +321,31 @@ export class Core {
on("config/addModel", (msg) => {
const model = msg.data.model;
addModel(model, msg.data.role);
void this.configHandler.reloadConfig();
void this.configHandler.reloadConfig(
"Model added (config/addModel message)",
);
});
on("config/deleteModel", (msg) => {
deleteModel(msg.data.title);
void this.configHandler.reloadConfig();
void this.configHandler.reloadConfig(
"Model removed (config/deleteModel message)",
);
});
on("config/newPromptFile", async (msg) => {
const { config } = await this.configHandler.loadConfig();
await createNewPromptFileV2(this.ide, config?.experimental?.promptPath);
await this.configHandler.reloadConfig();
await this.configHandler.reloadConfig(
"Prompt file created (config/newPromptFile message)",
);
});
on("config/addLocalWorkspaceBlock", async (msg) => {
await createNewWorkspaceBlockFile(this.ide, msg.data.blockType);
await this.configHandler.reloadConfig();
await this.configHandler.reloadConfig(
"Local block created (config/addLocalWorkspaceBlock message)",
);
});
on("config/openProfile", async (msg) => {
@ -329,8 +353,12 @@ export class Core {
});
on("config/reload", async (msg) => {
void this.configHandler.reloadConfig();
return await this.configHandler.getSerializedConfig();
// User force reloading will retrigger colocated rules
const codebaseRulesCache = CodebaseRulesCache.getInstance();
await codebaseRulesCache.refresh(this.ide);
void this.configHandler.reloadConfig(
"Force reloaded (config/reload message)",
);
});
on("config/ideSettingsUpdate", async (msg) => {
@ -349,7 +377,9 @@ export class Core {
on("config/updateSharedConfig", async (msg) => {
const newSharedConfig = this.globalContext.updateSharedConfig(msg.data);
await this.configHandler.reloadConfig();
await this.configHandler.reloadConfig(
"Shared config update (config/updateSharedConfig message)",
);
return newSharedConfig;
});
@ -359,7 +389,9 @@ export class Core {
msg.data.role,
msg.data.title,
);
await this.configHandler.reloadConfig();
await this.configHandler.reloadConfig(
"Selected model update (config/updateSelectedModel message)",
);
return newSelectedModels;
});
@ -487,6 +519,18 @@ export class Core {
});
on("llm/listModels", this.handleListModels.bind(this));
on("llm/compileChat", async (msg) => {
const { messages, options } = msg.data;
const model = (await this.configHandler.loadConfig()).config
?.selectedModelByRole.chat;
if (!model) {
throw new Error("No chat model selected");
}
return model.compileChatMessages(messages, options);
});
// Provide messenger to utils so they can interact with GUI + state
TTS.messenger = this.messenger;
ChatDescriber.messenger = this.messenger;
@ -506,6 +550,28 @@ export class Core {
return await ChatDescriber.describe(currentModel, {}, msg.data.text);
});
on("conversation/compact", async (msg) => {
const currentModel = (await this.configHandler.loadConfig()).config
?.selectedModelByRole.chat;
if (!currentModel) {
throw new Error("No chat model selected");
}
try {
await compactConversation({
sessionId: msg.data.sessionId,
index: msg.data.index,
historyManager,
currentModel,
});
return undefined;
} catch (error) {
console.error("Error compacting conversation:", error);
return undefined;
}
});
// Autocomplete
on("autocomplete/complete", async (msg) => {
const outcome =
@ -522,6 +588,21 @@ export class Core {
this.completionProvider.cancel();
});
// Next Edit
on("nextEdit/predict", async (msg) => {
const outcome = await this.nextEditProvider.provideInlineCompletionItems(
msg.data,
undefined,
);
return outcome ? [outcome.completion, outcome.originalEditableRange] : [];
});
on("nextEdit/accept", async (msg) => {
this.nextEditProvider.accept(msg.data.completionId);
});
on("nextEdit/reject", async (msg) => {
this.nextEditProvider.reject(msg.data.completionId);
});
on("streamDiffLines", async (msg) => {
const { config } = await this.configHandler.loadConfig();
if (!config) {
@ -636,9 +717,12 @@ export class Core {
void refreshIfNotIgnored(data.uris);
if (hasRulesFiles(data.uris)) {
await this.configHandler.reloadConfig();
const rulesCache = CodebaseRulesCache.getInstance();
await Promise.all(
data.uris.map((uri) => rulesCache.update(this.ide, uri)),
);
await this.configHandler.reloadConfig("Rules file created");
}
// If it's a local assistant being created, we want to reload all assistants so it shows up in the list
let localAssistantCreated = false;
for (const uri of data.uris) {
@ -658,7 +742,9 @@ export class Core {
void refreshIfNotIgnored(data.uris);
if (hasRulesFiles(data.uris)) {
await this.configHandler.reloadConfig();
const rulesCache = CodebaseRulesCache.getInstance();
data.uris.forEach((uri) => rulesCache.remove(uri));
await this.configHandler.reloadConfig("Codebase rule file deleted");
}
}
});
@ -934,7 +1020,7 @@ export class Core {
],
}),
);
void this.configHandler.reloadConfig();
void this.configHandler.reloadConfig("Autocomplete model added");
}
private async handleFilesChanged({
@ -964,7 +1050,9 @@ export class Core {
this.globalContext.update("showConfigUpdateToast", false);
}
}
await this.configHandler.reloadConfig();
await this.configHandler.reloadConfig(
"Current profile config file updated",
);
continue;
}
@ -972,15 +1060,24 @@ export class Core {
uri.endsWith(".continuerc.json") ||
uri.endsWith(".prompt") ||
uri.endsWith(SYSTEM_PROMPT_DOT_FILE) ||
(uri.includes(".continue") && uri.endsWith(".yaml")) ||
uri.endsWith(RULES_MARKDOWN_FILENAME) ||
BLOCK_TYPES.some(
(blockType) =>
uri.includes(`.continue/${blockType}`) ||
uri.includes(`.continue\\${blockType}`),
(uri.includes(".continue") &&
(uri.endsWith(".yaml") || uri.endsWith("yml"))) ||
BLOCK_TYPES.some((blockType) =>
uri.includes(`.continue/${blockType}`),
)
) {
await this.configHandler.reloadConfig();
await this.configHandler.reloadConfig(
"Config-related file updated: continuerc, prompt, local block, etc",
);
} else if (uri.endsWith(RULES_MARKDOWN_FILENAME)) {
try {
const codebaseRulesCache = CodebaseRulesCache.getInstance();
void codebaseRulesCache.update(this.ide, uri).then(() => {
void this.configHandler.reloadConfig("Codebase rule update");
});
} catch (e) {
console.error("Failed to update codebase rule", e);
}
} else if (
uri.endsWith(".continueignore") ||
uri.endsWith(".gitignore")
@ -1062,7 +1159,7 @@ export class Core {
editConfigFile((c) => c, editConfigYamlCallback);
void this.configHandler.reloadConfig();
void this.configHandler.reloadConfig("Onboarding completed");
}
private getContextItems = async (

View file

@ -1,6 +1,6 @@
import { diffLines, type Change } from "diff";
import { diffChars, diffLines, type Change } from "diff";
import { DiffLine } from "..";
import { DiffChar, DiffLine } from "..";
export function convertMyersChangeToDiffLines(change: Change): DiffLine[] {
const type: DiffLine["type"] = change.added
@ -55,3 +55,157 @@ export function myersDiff(oldContent: string, newContent: string): DiffLine[] {
return ourFormat;
}
export function myersCharDiff(
oldContent: string,
newContent: string,
): DiffChar[] {
// Process the content character by character.
// We will handle newlines separately,
// because diffChars does not have an option to ignore eol newlines.
const theirFormat = diffChars(oldContent, newContent);
// Track indices as we process the diff.
let oldIndex = 0;
let newIndex = 0;
let oldLineIndex = 0;
let newLineIndex = 0;
let oldCharIndexInLine = 0;
let newCharIndexInLine = 0;
const result: DiffChar[] = [];
for (const change of theirFormat) {
// Split the change value by newlines to handle them separately.
if (change.value.includes("\n")) {
const parts = change.value.split(/(\n)/g); // This keeps the newlines as separate entries.
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (part === "") continue;
if (part === "\n") {
// Handle newline.
if (change.added) {
result.push({
type: "new",
char: part,
newIndex: newIndex,
newLineIndex: newLineIndex,
newCharIndexInLine: newCharIndexInLine,
});
newIndex += part.length;
newLineIndex++;
newCharIndexInLine = 0; // Reset when moving to a new line.
} else if (change.removed) {
result.push({
type: "old",
char: part,
oldIndex: oldIndex,
oldLineIndex: oldLineIndex,
oldCharIndexInLine: oldCharIndexInLine,
});
oldIndex += part.length;
oldLineIndex++;
oldCharIndexInLine = 0; // Reset when moving to a new line.
} else {
result.push({
type: "same",
char: part,
oldIndex: oldIndex,
newIndex: newIndex,
oldLineIndex: oldLineIndex,
newLineIndex: newLineIndex,
oldCharIndexInLine: oldCharIndexInLine,
newCharIndexInLine: newCharIndexInLine,
});
oldIndex += part.length;
newIndex += part.length;
oldLineIndex++;
newLineIndex++;
oldCharIndexInLine = 0;
newCharIndexInLine = 0;
}
} else {
// Handle regular text.
if (change.added) {
result.push({
type: "new",
char: part,
newIndex: newIndex,
newLineIndex: newLineIndex,
newCharIndexInLine: newCharIndexInLine,
});
newIndex += part.length;
newCharIndexInLine += part.length;
} else if (change.removed) {
result.push({
type: "old",
char: part,
oldIndex: oldIndex,
oldLineIndex: oldLineIndex,
oldCharIndexInLine: oldCharIndexInLine,
});
oldIndex += part.length;
oldCharIndexInLine += part.length;
} else {
result.push({
type: "same",
char: part,
oldIndex: oldIndex,
newIndex: newIndex,
oldLineIndex: oldLineIndex,
newLineIndex: newLineIndex,
oldCharIndexInLine: oldCharIndexInLine,
newCharIndexInLine: newCharIndexInLine,
});
oldIndex += part.length;
newIndex += part.length;
oldCharIndexInLine += part.length;
newCharIndexInLine += part.length;
}
}
}
} else {
// No newlines, handle as a simple change.
if (change.added) {
result.push({
type: "new",
char: change.value,
newIndex: newIndex,
newLineIndex: newLineIndex,
newCharIndexInLine: newCharIndexInLine,
});
newIndex += change.value.length;
newCharIndexInLine += change.value.length;
} else if (change.removed) {
result.push({
type: "old",
char: change.value,
oldIndex: oldIndex,
oldLineIndex: oldLineIndex,
oldCharIndexInLine: oldCharIndexInLine,
});
oldIndex += change.value.length;
oldCharIndexInLine += change.value.length;
} else {
result.push({
type: "same",
char: change.value,
oldIndex: oldIndex,
newIndex: newIndex,
oldLineIndex: oldLineIndex,
newLineIndex: newLineIndex,
oldCharIndexInLine: oldCharIndexInLine,
newCharIndexInLine: newCharIndexInLine,
});
oldIndex += change.value.length;
newIndex += change.value.length;
oldCharIndexInLine += change.value.length;
newCharIndexInLine += change.value.length;
}
}
}
return result;
}

View file

@ -2,7 +2,7 @@ import { describe, expect, test } from "vitest";
import { dedent } from "../util";
import { myersDiff } from "./myers";
import { myersCharDiff, myersDiff } from "./myers";
describe("Test myers diff function", () => {
test("should ...", () => {
@ -56,3 +56,589 @@ describe("Test myers diff function", () => {
]);
});
});
describe("Test myersCharDiff function on the same line", () => {
test("should differentiate character changes", () => {
const oldContent = "hello world";
const newContent = "hello earth";
const diffChars = myersCharDiff(oldContent, newContent);
expect(diffChars).toEqual([
{
type: "same",
char: "hello ",
oldIndex: 0,
newIndex: 0,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "old",
char: "wo",
oldIndex: 6,
oldCharIndexInLine: 6,
oldLineIndex: 0,
},
{
type: "new",
char: "ea",
newIndex: 6,
newCharIndexInLine: 6,
newLineIndex: 0,
},
{
type: "same",
char: "r",
oldIndex: 8,
newIndex: 8,
oldCharIndexInLine: 8,
newCharIndexInLine: 8,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "old",
char: "ld",
oldIndex: 9,
oldCharIndexInLine: 9,
oldLineIndex: 0,
},
{
type: "new",
char: "th",
newIndex: 9,
newCharIndexInLine: 9,
newLineIndex: 0,
},
]);
});
test("should handle insertions", () => {
const oldContent = "abc";
const newContent = "abxyzc";
const diffChars = myersCharDiff(oldContent, newContent);
expect(diffChars).toEqual([
{
type: "same",
char: "ab",
oldIndex: 0,
newIndex: 0,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "new",
char: "xyz",
newIndex: 2,
newCharIndexInLine: 2,
newLineIndex: 0,
},
{
type: "same",
char: "c",
oldIndex: 2,
newIndex: 5,
oldCharIndexInLine: 2,
newCharIndexInLine: 5,
oldLineIndex: 0,
newLineIndex: 0,
},
]);
});
test("should handle deletions", () => {
const oldContent = "abxyzc";
const newContent = "abc";
const diffChars = myersCharDiff(oldContent, newContent);
expect(diffChars).toEqual([
{
type: "same",
char: "ab",
oldIndex: 0,
newIndex: 0,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "old",
char: "xyz",
oldIndex: 2,
oldCharIndexInLine: 2,
oldLineIndex: 0,
},
{
type: "same",
char: "c",
oldIndex: 5,
newIndex: 2,
oldCharIndexInLine: 5,
newCharIndexInLine: 2,
oldLineIndex: 0,
newLineIndex: 0,
},
]);
});
test("should handle empty strings", () => {
const oldContent = "";
const newContent = "abc";
const diffChars = myersCharDiff(oldContent, newContent);
expect(diffChars).toEqual([
{
type: "new",
char: "abc",
newIndex: 0,
newCharIndexInLine: 0,
newLineIndex: 0,
},
]);
});
test("should handle identical strings", () => {
const content = "no changes here";
const diffChars = myersCharDiff(content, content);
expect(diffChars).toEqual([
{
type: "same",
char: "no changes here",
oldIndex: 0,
newIndex: 0,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 0,
newLineIndex: 0,
},
]);
});
test("should handle whitespace changes", () => {
const oldContent = "hello world";
const newContent = "hello world";
const diffChars = myersCharDiff(oldContent, newContent);
expect(diffChars).toEqual([
{
type: "same",
char: "hello ",
oldIndex: 0,
newIndex: 0,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "new",
char: " ",
newIndex: 6,
newCharIndexInLine: 6,
newLineIndex: 0,
},
{
type: "same",
char: "world",
oldIndex: 6,
newIndex: 7,
oldCharIndexInLine: 6,
newCharIndexInLine: 7,
oldLineIndex: 0,
newLineIndex: 0,
},
]);
});
test("should handle complex changes", () => {
const oldContent = "The quick brown fox jumps over the lazy dog";
const newContent = "The fast brown fox leaps over the sleeping dog";
const diffChars = myersCharDiff(oldContent, newContent);
expect(diffChars).toEqual([
{
type: "same",
char: "The ",
oldIndex: 0,
newIndex: 0,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "old",
char: "quick",
oldIndex: 4,
oldCharIndexInLine: 4,
oldLineIndex: 0,
},
{
type: "new",
char: "fast",
newIndex: 4,
newCharIndexInLine: 4,
newLineIndex: 0,
},
{
type: "same",
char: " brown fox ",
oldIndex: 9,
newIndex: 8,
oldCharIndexInLine: 9,
newCharIndexInLine: 8,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "old",
char: "jum",
oldIndex: 20,
oldCharIndexInLine: 20,
oldLineIndex: 0,
},
{
type: "new",
char: "lea",
newIndex: 19,
newCharIndexInLine: 19,
newLineIndex: 0,
},
{
type: "same",
char: "ps over the ",
oldIndex: 23,
newIndex: 22,
oldCharIndexInLine: 23,
newCharIndexInLine: 22,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "new",
char: "s",
newIndex: 34,
newCharIndexInLine: 34,
newLineIndex: 0,
},
{
type: "same",
char: "l",
oldIndex: 35,
newIndex: 35,
oldCharIndexInLine: 35,
newCharIndexInLine: 35,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "old",
char: "azy",
oldIndex: 36,
oldCharIndexInLine: 36,
oldLineIndex: 0,
},
{
type: "new",
char: "eeping",
newIndex: 36,
newCharIndexInLine: 36,
newLineIndex: 0,
},
{
type: "same",
char: " dog",
oldIndex: 39,
newIndex: 42,
oldCharIndexInLine: 39,
newCharIndexInLine: 42,
oldLineIndex: 0,
newLineIndex: 0,
},
]);
});
});
describe("Test myersCharDiff function on different lines", () => {
test("should track line indices for multi-line changes", () => {
const oldContent = ["Line one", "Line two", "Line three"].join("\n");
const newContent = ["Line one", "Modified line", "Line three"].join("\n");
const diffChars = myersCharDiff(oldContent, newContent);
expect(diffChars).toEqual([
{
type: "same",
char: "Line one",
oldIndex: 0,
newIndex: 0,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "same",
char: "\n",
oldIndex: 8,
newIndex: 8,
oldCharIndexInLine: 8,
newCharIndexInLine: 8,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "old",
char: "L",
oldIndex: 9,
oldCharIndexInLine: 0,
oldLineIndex: 1,
},
{
type: "new",
char: "Mod",
newIndex: 9,
newCharIndexInLine: 0,
newLineIndex: 1,
},
{
char: "i",
newCharIndexInLine: 3,
newIndex: 12,
newLineIndex: 1,
oldCharIndexInLine: 1,
oldIndex: 10,
oldLineIndex: 1,
type: "same",
},
{
char: "n",
oldCharIndexInLine: 2,
oldIndex: 11,
oldLineIndex: 1,
type: "old",
},
{
char: "fi",
newCharIndexInLine: 4,
newIndex: 13,
newLineIndex: 1,
type: "new",
},
{
char: "e",
newCharIndexInLine: 6,
newIndex: 15,
newLineIndex: 1,
oldCharIndexInLine: 3,
oldIndex: 12,
oldLineIndex: 1,
type: "same",
},
{
char: "d",
newCharIndexInLine: 7,
newIndex: 16,
newLineIndex: 1,
type: "new",
},
{
char: " ",
newCharIndexInLine: 8,
newIndex: 17,
newLineIndex: 1,
oldCharIndexInLine: 4,
oldIndex: 13,
oldLineIndex: 1,
type: "same",
},
{
type: "old",
char: "two",
oldCharIndexInLine: 5,
oldIndex: 14,
oldLineIndex: 1,
},
{
type: "new",
char: "line",
newCharIndexInLine: 9,
newIndex: 18,
newLineIndex: 1,
},
{
type: "same",
char: "\n",
oldIndex: 17,
oldCharIndexInLine: 8,
oldLineIndex: 1,
newIndex: 22,
newCharIndexInLine: 13,
newLineIndex: 1,
},
{
type: "same",
char: "Line three",
oldIndex: 18,
newIndex: 23,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 2,
newLineIndex: 2,
},
]);
});
test("should track line indices when adding new lines", () => {
const oldContent = ["First line", "Last line"].join("\n");
const newContent = [
"First line",
"Middle line",
"Another middle",
"Last line",
].join("\n");
const diffChars = myersCharDiff(oldContent, newContent);
expect(diffChars).toEqual([
{
type: "same",
char: "First line",
oldIndex: 0,
newIndex: 0,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "same",
char: "\n",
oldIndex: 10,
newIndex: 10,
oldCharIndexInLine: 10,
newCharIndexInLine: 10,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "new",
char: "Middle line",
newIndex: 11,
newCharIndexInLine: 0,
newLineIndex: 1,
},
{
type: "new",
char: "\n",
newIndex: 22,
newCharIndexInLine: 11,
newLineIndex: 1,
},
{
type: "new",
char: "Another middle",
newCharIndexInLine: 0,
newIndex: 23,
newLineIndex: 2,
},
{
type: "new",
char: "\n",
newCharIndexInLine: 14,
newIndex: 37,
newLineIndex: 2,
},
{
type: "same",
char: "Last line",
oldIndex: 11,
oldCharIndexInLine: 0,
oldLineIndex: 1,
newIndex: 38,
newCharIndexInLine: 0,
newLineIndex: 3,
},
]);
});
test("should track line indices when removing lines", () => {
const oldContent = [
"Start",
"Line to remove",
"Another to remove",
"End",
].join("\n");
const newContent = ["Start", "End"].join("\n");
const diffChars = myersCharDiff(oldContent, newContent);
expect(diffChars).toEqual([
{
type: "same",
char: "Start",
oldIndex: 0,
newIndex: 0,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "same",
char: "\n",
oldIndex: 5,
newIndex: 5,
oldCharIndexInLine: 5,
newCharIndexInLine: 5,
oldLineIndex: 0,
newLineIndex: 0,
},
{
type: "old",
char: "Line to remove",
oldIndex: 6,
oldCharIndexInLine: 0,
oldLineIndex: 1,
},
{
type: "old",
char: "\n",
oldCharIndexInLine: 14,
oldIndex: 20,
oldLineIndex: 1,
},
{
type: "old",
char: "Another to remove",
oldCharIndexInLine: 0,
oldIndex: 21,
oldLineIndex: 2,
},
{
type: "old",
char: "\n",
oldCharIndexInLine: 17,
oldIndex: 38,
oldLineIndex: 2,
},
{
type: "same",
char: "End",
oldIndex: 39,
newIndex: 6,
oldCharIndexInLine: 0,
newCharIndexInLine: 0,
oldLineIndex: 3,
newLineIndex: 1,
},
]);
});
});

View file

@ -1,4 +1,4 @@
import { DiffLine, DiffLineType } from "../index.js";
import { DiffLine, DiffType } from "../index.js";
import { LineStream, matchLine } from "./util.js";
@ -33,7 +33,7 @@ export async function* streamDiff(
seenIndentationMistake = true;
}
let type: DiffLineType;
let type: DiffType;
const isNewLine = matchIndex === -1;

View file

@ -6,11 +6,11 @@ import { describe, expect, test } from "vitest";
// @ts-ignore no typings available
import { changed, diff as myersDiff } from "myers-diff";
import { streamDiff } from "../diff/streamDiff.js";
import { DiffLine, DiffLineType } from "../index.js";
import { DiffLine, DiffType } from "../index.js";
import { generateLines } from "./util.js";
// "modification" is an extra type used to represent an "old" + "new" diff line
type MyersDiffTypes = Extract<DiffLineType, "new" | "old"> | "modification";
type MyersDiffTypes = Extract<DiffType, "new" | "old"> | "modification";
const UNIFIED_DIFF_SYMBOLS = {
same: "",

85
core/index.d.ts vendored
View file

@ -50,6 +50,7 @@ export interface IndexingProgressUpdate {
shouldClearIndexes?: boolean;
status:
| "loading"
| "waiting"
| "indexing"
| "done"
| "failed"
@ -121,6 +122,7 @@ export interface ILLM
messages: ChatMessage[],
signal: AbortSignal,
options?: LLMFullCompletionOptions,
messageOptions?: MessageOption,
): AsyncGenerator<ChatMessage, PromptLog>;
chat(
@ -129,6 +131,11 @@ export interface ILLM
options?: LLMFullCompletionOptions,
): Promise<ChatMessage>;
compileChatMessages(
messages: ChatMessage[],
options: LLMFullCompletionOpeions,
): CompiledChatMessagesReport;
embed(chunks: string[]): Promise<number[][]>;
rerank(query: string, chunks: Chunk[]): Promise<number[]>;
@ -362,10 +369,32 @@ export interface ThinkingChatMessage {
toolCalls?: ToolCallDelta[];
}
/**
* This is meant to be equivalent to the OpenAI [usage object](https://platform.openai.com/docs/api-reference/chat/object#chat/object-usage)
* but potentially with additional information that is needed for other providers.
*/
export interface Usage {
completionTokens: number;
promptTokens: number;
promptTokensDetails?: {
cachedTokens?: number;
/** This an Anthropic-specific property */
cacheWriteTokens?: number;
audioTokens?: number;
};
completionTokensDetails?: {
acceptedPredictionTokens?: number;
reasoningTokens?: number;
rejectedPredictionTokens?: number;
audioTokens?: number;
};
}
export interface AssistantChatMessage {
role: "assistant";
content: MessageContent;
toolCalls?: ToolCallDelta[];
usage?: Usage;
}
export interface SystemChatMessage {
@ -431,12 +460,12 @@ export interface PromptLog {
export type MessageModes = "chat" | "agent" | "plan";
export type ToolStatus =
| "generating"
| "generated"
| "calling"
| "errored"
| "done"
| "canceled";
| "generating" // Tool call arguments are being streamed from the LLM
| "generated" // Tool call is complete and ready for execution (awaiting approval)
| "calling" // Tool is actively being executed
| "errored" // Tool execution failed with an error
| "done" // Tool execution completed successfully
| "canceled"; // Tool call was canceled by user or system
// Will exist only on "assistant" messages with tool calls
interface ToolCallState {
@ -461,10 +490,11 @@ export interface ChatHistoryItem {
editorState?: any;
modifiers?: InputModifiers;
promptLogs?: PromptLog[];
toolCallState?: ToolCallState;
toolCallStates?: ToolCallState[];
isGatheringContext?: boolean;
reasoning?: Reasoning;
appliedRules?: RuleWithSource[];
conversationSummary?: string;
}
export interface LLMFullCompletionOptions extends BaseCompletionOptions {
@ -483,12 +513,14 @@ export interface LLMInteractionStartChat extends LLMInteractionBase {
kind: "startChat";
messages: ChatMessage[];
options: CompletionOptions;
provider: string;
}
export interface LLMInteractionStartComplete extends LLMInteractionBase {
kind: "startComplete";
prompt: string;
options: CompletionOptions;
provider: string;
}
export interface LLMInteractionStartFim extends LLMInteractionBase {
@ -496,6 +528,7 @@ export interface LLMInteractionStartFim extends LLMInteractionBase {
prefix: string;
suffix: string;
options: CompletionOptions;
provider: string;
}
export interface LLMInteractionChunk extends LLMInteractionBase {
@ -512,6 +545,7 @@ export interface LLMInteractionEnd extends LLMInteractionBase {
promptTokens: number;
generatedTokens: number;
thinkingTokens: number;
usage: Usage | undefined;
}
export interface LLMInteractionSuccess extends LLMInteractionEnd {
@ -665,13 +699,26 @@ export type CustomLLM = RequireAtLeastOne<
// IDE
export type DiffLineType = "new" | "old" | "same";
export type DiffType = "new" | "old" | "same";
export interface DiffLine {
type: DiffLineType;
export interface DiffObject {
type: DiffType;
}
export interface DiffLine extends DiffObject {
line: string;
}
interface DiffChar extends DiffObject {
char: string;
oldIndex?: number; // Character index assuming a flattened line string.
newIndex?: number;
oldCharIndexInLine?: number; // Character index assuming new lines reset the character index to 0.
newCharIndexInLine?: number;
oldLineIndex?: number;
newLineIndex?: number;
}
export interface Problem {
filepath: string;
range: Range;
@ -691,6 +738,7 @@ export interface IdeInfo {
version: string;
remoteName: string;
extensionVersion: string;
isPrerelease: boolean;
}
export interface BranchAndDir {
@ -1268,7 +1316,6 @@ export interface ContinueUIConfig {
codeWrap?: boolean;
showSessionTabs?: boolean;
autoAcceptEditToolDiffs?: boolean;
logEditingData?: boolean;
}
export interface ContextMenuConfig {
@ -1421,11 +1468,6 @@ export interface ExperimentalConfig {
*/
useCurrentFileAsContext?: boolean;
/**
* If enabled, will save data on the user's editing processes
*/
logEditingData?: boolean;
/**
* If enabled, will enable next edit in place of autocomplete
*/
@ -1649,6 +1691,7 @@ export type RuleSource =
| "model-options-plan"
| "model-options-agent"
| "rules-block"
| "colocated-markdown"
| "json-systemMessage"
| ".continuerules";
@ -1668,3 +1711,13 @@ export interface CompleteOnboardingPayload {
provider?: string;
apiKey?: string;
}
export interface CompiledMessagesResult {
compiledChatMessages: ChatMessage[];
didPrune: boolean;
contextPercentage: number;
}
export interface MessageOption {
precompiled: boolean;
}

View file

@ -1,3 +1,5 @@
/* eslint-disable max-lines-per-function */
/* lint is not useful for test classes */
import { jest } from "@jest/globals";
import { execSync } from "node:child_process";
import fs from "node:fs";
@ -14,8 +16,11 @@ import {
} from "../test/testDir.js";
import { getIndexSqlitePath } from "../util/paths.js";
import { ConfigResult } from "@continuedev/config-yaml";
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider.js";
import { ContinueConfig } from "../index.js";
import { localPathToUri } from "../util/pathToUri.js";
import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js";
import { CodebaseIndexer } from "./CodebaseIndexer.js";
import { getComputeDeleteAddRemove } from "./refreshIndex.js";
import { TestCodebaseIndex } from "./TestCodebaseIndex.js";
import { CodebaseIndex } from "./types.js";
@ -57,6 +62,17 @@ class TestCodebaseIndexer extends CodebaseIndexer {
protected async getIndexesToBuild(): Promise<CodebaseIndex[]> {
return [new TestCodebaseIndex()];
}
// Add public methods to test private methods
public testHasCodebaseContextProvider() {
return (this as any).hasCodebaseContextProvider();
}
public async testHandleConfigUpdate(
configResult: ConfigResult<ContinueConfig>,
) {
return (this as any).handleConfigUpdate({ config: configResult.config });
}
}
// Create a mock messenger type that doesn't require actual protocol imports
@ -71,8 +87,6 @@ type MockMessengerType = {
// These are more like integration tests, whereas we should separately test
// the individual CodebaseIndex classes
describe("CodebaseIndexer", () => {
const pauseToken = new PauseToken(false);
// Replace mockProgressReporter with mockMessenger
const mockMessenger: MockMessengerType = {
send: jest.fn(),
@ -82,13 +96,8 @@ describe("CodebaseIndexer", () => {
onError: jest.fn(),
};
const codebaseIndexer = new TestCodebaseIndexer(
testConfigHandler,
testIde,
mockMessenger as any,
false,
);
const testIndex = new TestCodebaseIndex();
let codebaseIndexer: TestCodebaseIndexer;
let testIndex: TestCodebaseIndex;
beforeAll(async () => {
tearDownTestDir();
@ -99,6 +108,15 @@ describe("CodebaseIndexer", () => {
cwd: TEST_DIR_PATH,
});
execSync('git config user.name "Test"', { cwd: TEST_DIR_PATH });
codebaseIndexer = new TestCodebaseIndexer(
testConfigHandler,
testIde,
mockMessenger as any,
false,
);
await codebaseIndexer.initPromise;
testIndex = new TestCodebaseIndex();
});
afterAll(async () => {
@ -161,6 +179,7 @@ describe("CodebaseIndexer", () => {
}
test("should index test folder without problem", async () => {
walkDirCache.invalidate();
addToTestDir([
["test.ts", TEST_TS],
["py/main.py", TEST_PY],
@ -403,4 +422,270 @@ describe("CodebaseIndexer", () => {
expect(codebaseIndexer.currentIndexingState).toEqual(testState);
});
});
// New describe block for testing handleConfigUpdate functionality
describe("handleConfigUpdate functionality", () => {
let testIndexer: TestCodebaseIndexer;
let mockRefreshCodebaseIndex: jest.MockedFunction<any>;
let mockGetWorkspaceDirs: jest.MockedFunction<any>;
beforeEach(() => {
testIndexer = new TestCodebaseIndexer(
testConfigHandler,
testIde,
mockMessenger as any,
false,
);
// Mock the refreshCodebaseIndex method to avoid actual indexing
mockRefreshCodebaseIndex = jest
.spyOn(testIndexer, "refreshCodebaseIndex")
.mockImplementation(async () => {});
// Mock getWorkspaceDirs to return test directories
mockGetWorkspaceDirs = jest
.spyOn(testIde, "getWorkspaceDirs")
.mockResolvedValue(["/test/workspace"]);
});
afterEach(() => {
jest.clearAllMocks();
});
describe("hasCodebaseContextProvider", () => {
test("should return true when codebase context provider is present", () => {
// Set up config with codebase context provider
(testIndexer as any).config = {
contextProviders: [
{
description: {
title: CodebaseContextProvider.description.title,
},
},
],
};
const result = testIndexer.testHasCodebaseContextProvider();
expect(result).toBe(true);
});
test("should return false when no context providers are configured", () => {
(testIndexer as any).config = {
contextProviders: undefined,
};
const result = testIndexer.testHasCodebaseContextProvider();
expect(result).toBe(false);
});
test("should return false when context providers exist but no codebase provider", () => {
(testIndexer as any).config = {
contextProviders: [
{
description: {
title: "SomeOtherProvider",
},
},
],
};
const result = testIndexer.testHasCodebaseContextProvider();
expect(result).toBe(false);
});
test("should return false when context providers is empty array", () => {
(testIndexer as any).config = {
contextProviders: [],
};
const result = testIndexer.testHasCodebaseContextProvider();
expect(result).toBe(false);
});
});
describe("handleConfigUpdate", () => {
test("should return early when newConfig is null", async () => {
const configResult: ConfigResult<ContinueConfig> = {
config: null as any,
errors: [],
configLoadInterrupted: false,
};
await testIndexer.testHandleConfigUpdate(configResult);
// These get called once on init, so we want them to not get called again
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
});
test("should return early when newConfig is undefined", async () => {
const configResult: ConfigResult<ContinueConfig> = {
config: undefined as any,
errors: [],
configLoadInterrupted: false,
};
await testIndexer.testHandleConfigUpdate(configResult);
// These get called once on init, so we want them to not get called again
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
});
test("should return early when no codebase context provider is present", async () => {
const configResult: ConfigResult<ContinueConfig> = {
config: {
contextProviders: [
{
description: {
title: "SomeOtherProvider",
},
},
],
selectedModelByRole: {
embed: {
model: "test-model",
provider: "test-provider",
},
},
} as unknown as ContinueConfig,
errors: [],
configLoadInterrupted: false,
};
await testIndexer.testHandleConfigUpdate(configResult);
// These get called once on init, so we want them to not get called again
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
});
test("should return early when no embed model is configured", async () => {
const configResult: ConfigResult<ContinueConfig> = {
config: {
contextProviders: [
{
description: {
title: CodebaseContextProvider.description.title,
},
},
],
selectedModelByRole: {
embed: undefined,
},
} as unknown as ContinueConfig,
errors: [],
configLoadInterrupted: false,
};
await testIndexer.testHandleConfigUpdate(configResult);
// These get called once on init, so we want them to not get called again
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
});
test("should call refreshCodebaseIndex when all conditions are met", async () => {
const configResult: ConfigResult<ContinueConfig> = {
config: {
contextProviders: [
{
description: {
title: CodebaseContextProvider.description.title,
},
},
],
selectedModelByRole: {
embed: {
model: "test-model",
provider: "test-provider",
},
},
} as unknown as ContinueConfig,
errors: [],
configLoadInterrupted: false,
};
await testIndexer.testHandleConfigUpdate(configResult);
// These get called once on init, and we want them to get called again
expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(2);
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2);
expect(mockRefreshCodebaseIndex).toHaveBeenCalledWith([
"/test/workspace",
]);
});
test("should set config property before checking conditions", async () => {
const testConfig = {
contextProviders: [
{
description: {
title: CodebaseContextProvider.description.title,
},
},
],
selectedModelByRole: {
embed: {
model: "test-model",
provider: "test-provider",
},
},
} as unknown as ContinueConfig;
const configResult: ConfigResult<ContinueConfig> = {
config: testConfig,
errors: [],
configLoadInterrupted: false,
};
await testIndexer.testHandleConfigUpdate(configResult);
// Verify that the config was set
expect((testIndexer as any).config).toBe(testConfig);
// These get called once on init, and we want them to get called again
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2);
});
test("should handle multiple context providers correctly", async () => {
const configResult: ConfigResult<ContinueConfig> = {
config: {
contextProviders: [
{
description: {
title: "SomeOtherProvider",
},
},
{
description: {
title: CodebaseContextProvider.description.title,
},
},
{
description: {
title: "AnotherProvider",
},
},
],
selectedModelByRole: {
embed: {
model: "test-model",
provider: "test-provider",
},
},
} as unknown as ContinueConfig,
errors: [],
configLoadInterrupted: false,
};
await testIndexer.testHandleConfigUpdate(configResult);
// These get called once on init, and we want them to get called again
expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2);
expect(mockRefreshCodebaseIndex).toHaveBeenCalledWith([
"/test/workspace",
]);
});
});
});
});

View file

@ -1,7 +1,12 @@
import * as fs from "fs/promises";
import { ConfigHandler } from "../config/ConfigHandler.js";
import { IDE, IndexingProgressUpdate, IndexTag } from "../index.js";
import {
ContinueConfig,
IDE,
IndexingProgressUpdate,
IndexTag,
} from "../index.js";
import type { FromCoreProtocol, ToCoreProtocol } from "../protocol";
import type { IMessenger } from "../protocol/messenger";
import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js";
@ -9,14 +14,17 @@ import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js";
import { Telemetry } from "../util/posthog.js";
import { findUriInDirs, getUriPathBasename } from "../util/uri.js";
import { ConfigResult } from "@continuedev/config-yaml";
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider.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";
import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js";
import { embedModelsAreEqual } from "./docs/DocsService.js";
import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js";
import { LanceDbIndex } from "./LanceDbIndex.js";
import { getComputeDeleteAddRemove } from "./refreshIndex.js";
import { getComputeDeleteAddRemove, IndexLock } from "./refreshIndex.js";
import {
CodebaseIndex,
IndexResultType,
@ -44,6 +52,10 @@ export class CodebaseIndexer {
* - To make as few requests as possible to the embeddings providers
*/
filesPerBatch = 200;
// We normally allow this to run in the background,
// and only need to `await` it for tests.
public initPromise: Promise<void>;
private config!: ContinueConfig;
private indexingCancellationController: AbortController | undefined;
private codebaseIndexingState: IndexingProgressUpdate;
private readonly pauseToken: PauseToken;
@ -83,6 +95,17 @@ export class CodebaseIndexer {
// Initialize pause token
this.pauseToken = new PauseToken(initialPaused);
this.initPromise = this.init(configHandler);
}
// Initialization - load config and attach config listener
private async init(configHandler: ConfigHandler) {
const result = await configHandler.loadConfig();
await this.handleConfigUpdate(result);
configHandler.onConfigUpdate(
this.handleConfigUpdate.bind(this) as (arg: any) => void,
);
}
set paused(value: boolean) {
@ -192,7 +215,7 @@ export class CodebaseIndexer {
workspaceDirs: string[],
): Promise<void> {
if (this.pauseToken.paused) {
// NOTE: by returning here, there is a chance that while paused a file is modified and
// FIXME: by returning here, there is a chance that while paused a file is modified and
// then after unpausing the file is not reindexed
return;
}
@ -643,11 +666,47 @@ export class CodebaseIndexer {
);
}
/**
* We want to prevent sqlite concurrent write errors
* when there are 2 indexing happening from different windows.
* We want the other window to wait until the first window's indexing finishes.
* Incase the first window closes before indexing is finished,
* we want to unlock the IndexLock by checking the last timestamp.
*/
private async *waitForDBIndex(): AsyncGenerator<IndexingProgressUpdate> {
let foundLock = await IndexLock.isLocked();
while (foundLock?.locked) {
if ((Date.now() - foundLock.timestamp) / 1000 > 10) {
console.log(`${foundLock.dirs} is not being indexed... unlocking`);
await IndexLock.unlock();
break;
}
console.log(`indexing ${foundLock.dirs}`);
yield {
progress: 0,
desc: "",
status: "waiting",
};
await new Promise((resolve) => setTimeout(resolve, 1000));
foundLock = await IndexLock.isLocked();
}
}
public async refreshCodebaseIndex(paths: string[]) {
if (this.indexingCancellationController) {
this.indexingCancellationController.abort();
}
this.indexingCancellationController = new AbortController();
for await (const update of this.waitForDBIndex()) {
this.updateProgress(update);
}
await IndexLock.lock(paths.join(", ")); // acquire the index lock to prevent multiple windows to begin indexing
const indexLockTimestampUpdateInterval = setInterval(
() => void IndexLock.updateTimestamp(),
5_000,
);
try {
for await (const update of this.refreshDirs(
paths,
@ -664,6 +723,9 @@ export class CodebaseIndexer {
await this.handleIndexingError(e);
}
clearInterval(indexLockTimestampUpdateInterval); // interval will also be cleared when window closes before indexing is finished
await IndexLock.unlock();
// Directly refresh submenu items
if (this.messenger) {
this.messenger.send("refreshSubmenuItems", {
@ -724,4 +786,49 @@ export class CodebaseIndexer {
public get currentIndexingState(): IndexingProgressUpdate {
return this.codebaseIndexingState;
}
private hasCodebaseContextProvider() {
return !!this.config.contextProviders?.some(
(provider) =>
provider.description.title ===
CodebaseContextProvider.description.title,
);
}
private isIndexingConfigSame(
config1: ContinueConfig | undefined,
config2: ContinueConfig,
) {
return embedModelsAreEqual(
config1?.selectedModelByRole.embed,
config2.selectedModelByRole.embed,
);
}
private async handleConfigUpdate({
config: newConfig,
}: ConfigResult<ContinueConfig>) {
if (newConfig) {
const needsReindex = !this.isIndexingConfigSame(this.config, newConfig);
this.config = newConfig; // IMPORTANT - need to set up top, other methods below use this without passing it in
// No point in indexing if no codebase context provider
const hasCodebaseContextProvider = this.hasCodebaseContextProvider();
if (!hasCodebaseContextProvider) {
return;
}
// Skip codebase indexing if not supported
// No warning message here because would show on ANY config update
if (!this.config.selectedModelByRole.embed) {
return;
}
if (needsReindex) {
const dirs = await this.ide.getWorkspaceDirs();
await this.refreshCodebaseIndex(dirs);
}
}
}
}

View file

@ -7,6 +7,15 @@ export interface SiteIndexingResults {
title: string;
}
/**
* Strip off the trailing forward slash from the given URL
* @param url The URL of the document
* @returns A sanitized URL without trailing forward slash
*/
const stripTrailingSlash = (url: string): string => {
return url.replace(/\/+$/, "");
};
export class DocsCache {
static readonly AWS_REGION: string = "us-west-1";
static readonly BUCKET_NAME: string = "continue-preindexed-docs";
@ -33,7 +42,8 @@ export class DocsCache {
url: string,
): string {
const normalizedEmbeddingId = DocsCache.normalizeEmbeddingId(embeddingId);
const normalizedUrl = encodeURIComponent(url.replace(/\//g, "_"));
const sanitizedUrl = stripTrailingSlash(url);
const normalizedUrl = encodeURIComponent(sanitizedUrl.replace(/\//g, "_"));
return normalizedEmbeddingId + "/" + normalizedUrl;
}

View file

@ -69,7 +69,7 @@ const markFailedInGlobalContext = (siteIndexingConfig: SiteIndexingConfig) => {
const globalContext = new GlobalContext();
const failedDocs = globalContext.get("failedDocs") ?? [];
const newFailedDocs = failedDocs.filter(
(d) => !siteIndexingConfigsAreEqual(siteIndexingConfig, d),
(d) => !docConfigsAreEqual(siteIndexingConfig, d),
);
newFailedDocs.push(siteIndexingConfig);
globalContext.update("failedDocs", newFailedDocs);
@ -81,7 +81,7 @@ const removeFromFailedGlobalContext = (
const globalContext = new GlobalContext();
const failedDocs = globalContext.get("failedDocs") ?? [];
const newFailedDocs = failedDocs.filter(
(d) => !siteIndexingConfigsAreEqual(siteIndexingConfig, d),
(d) => !docConfigsAreEqual(siteIndexingConfig, d),
);
globalContext.update("failedDocs", newFailedDocs);
};
@ -89,32 +89,69 @@ const removeFromFailedGlobalContext = (
const hasIndexingFailed = (siteIndexingConfig: SiteIndexingConfig) => {
const globalContext = new GlobalContext();
const failedDocs = globalContext.get("failedDocs") ?? [];
return failedDocs.find((d) =>
siteIndexingConfigsAreEqual(siteIndexingConfig, d),
return failedDocs.find((d) => docConfigsAreEqual(siteIndexingConfig, d));
};
export function embedModelsAreEqual(
llm1: ILLM | null | undefined,
llm2: ILLM | null | undefined,
): boolean {
return (
llm1?.underlyingProviderName === llm2?.underlyingProviderName &&
llm1?.title === llm2?.title &&
llm1?.maxEmbeddingChunkSize === llm2?.maxEmbeddingChunkSize
);
}
const docConfigsAreEqual = (
siteConfig1: SiteIndexingConfig,
siteConfig2: SiteIndexingConfig,
) => {
return (
siteConfig1.faviconUrl === siteConfig2.faviconUrl &&
siteConfig1.title === siteConfig2.title &&
docConfigsAreEqualExceptTitleAndFavicon(siteConfig1, siteConfig2)
);
};
const docConfigsAreEqualExceptTitleAndFavicon = (
siteConfig1: SiteIndexingConfig,
siteConfig2: SiteIndexingConfig,
) => {
return (
siteConfig1.startUrl === siteConfig2.startUrl &&
siteConfig1.maxDepth === siteConfig2.maxDepth &&
siteConfig1.useLocalCrawling === siteConfig2.useLocalCrawling
);
};
const siteIndexingConfigsAreEqual = (
config1: SiteIndexingConfig,
config2: SiteIndexingConfig,
siteConfig1: SiteIndexingConfig,
siteConfig2: SiteIndexingConfig,
contConfig1: ContinueConfig | undefined,
contConfig2: ContinueConfig,
) => {
return (
config1.startUrl === config2.startUrl &&
config1.faviconUrl === config2.faviconUrl &&
config1.title === config2.title &&
config1.maxDepth === config2.maxDepth &&
config1.useLocalCrawling === config2.useLocalCrawling
docConfigsAreEqual(siteConfig1, siteConfig2) &&
embedModelsAreEqual(
contConfig1?.selectedModelByRole.embed,
contConfig2.selectedModelByRole.embed,
)
);
};
const siteIndexingConfigsAreEqualExceptTitleAndFavicon = (
config1: SiteIndexingConfig,
config2: SiteIndexingConfig,
siteConfig1: SiteIndexingConfig,
siteConfig2: SiteIndexingConfig,
contConfig1: ContinueConfig | undefined,
contConfig2: ContinueConfig,
) => {
return (
config1.startUrl === config2.startUrl &&
config1.maxDepth === config2.maxDepth &&
config1.useLocalCrawling === config2.useLocalCrawling
docConfigsAreEqualExceptTitleAndFavicon(siteConfig1, siteConfig2) &&
embedModelsAreEqual(
contConfig1?.selectedModelByRole.embed,
contConfig2.selectedModelByRole.embed,
)
);
};
@ -968,7 +1005,6 @@ export default class DocsService {
await db.exec("PRAGMA busy_timeout = 3000;");
await runSqliteMigrations(db);
// First create the table if it doesn't exist
await db.exec(`CREATE TABLE IF NOT EXISTS ${DocsService.sqlitebTableName} (
id INTEGER PRIMARY KEY AUTOINCREMENT,
@ -978,6 +1014,8 @@ export default class DocsService {
embeddingsProviderId STRING
)`);
await runSqliteMigrations(db);
this.sqliteDb = db;
}
@ -1036,12 +1074,22 @@ export default class DocsService {
);
// TODO: Changes to the docs config made while Continue isn't running won't be caught
if (oldConfigDoc && !siteIndexingConfigsAreEqual(oldConfigDoc, doc)) {
if (
oldConfigDoc &&
!siteIndexingConfigsAreEqual(
oldConfigDoc,
doc,
oldConfig,
newConfig,
)
) {
// When only the title or faviconUrl changed, Update the sqlite metadate instead of reindexing
if (
siteIndexingConfigsAreEqualExceptTitleAndFavicon(
oldConfigDoc,
doc,
oldConfig,
newConfig,
)
) {
await this.updateMetadataInSqlite(doc);
@ -1261,7 +1309,7 @@ export default class DocsService {
// Handles the case where a user has manually added the doc to config.json
// so it already exists in the file
const doesEquivalentDocExist = this.config.docs?.some((doc) =>
siteIndexingConfigsAreEqual(doc, siteIndexingConfig),
docConfigsAreEqual(doc, siteIndexingConfig),
);
if (!doesEquivalentDocExist) {

View file

@ -53,7 +53,7 @@ describe("DocsCrawler", () => {
};
}
describe("GitHub Crawler", () => {
describe.skip("GitHub Crawler", () => {
const repoUrl =
"https://github.com/Patrick-Erichsen/test-github-repo-for-crawling";

View file

@ -45,6 +45,16 @@ export class SqliteDb {
artifactId STRING NOT NULL
)`,
);
await db.exec(
`CREATE TABLE IF NOT EXISTS indexing_lock (
id INTEGER PRIMARY KEY AUTOINCREMENT,
locked BOOLEAN NOT NULL,
timestamp INTEGER NOT NULL,
dirs STRING NOT NULL
)`,
);
// Delete duplicate rows from tag_catalog
await db.exec(`
DELETE FROM tag_catalog
@ -532,3 +542,47 @@ export function truncateToLastNBytes(input: string, maxBytes: number): string {
export function truncateSqliteLikePattern(input: string, safety: number = 100) {
return truncateToLastNBytes(input, SQLITE_MAX_LIKE_PATTERN_LENGTH - safety);
}
export class IndexLock {
private static getLockTableName() {
return "indexing_lock";
}
static async isLocked(): Promise<
{ locked: boolean; dirs: string; timestamp: number } | undefined | undefined
> {
const db = await SqliteDb.get();
const row = (await db.get(
`SELECT locked, dirs, timestamp FROM ${IndexLock.getLockTableName()} WHERE locked = ?`,
true,
)) as { locked: boolean; dirs: string; timestamp: number } | undefined;
return row;
}
static async lock(dirs: string) {
const db = await SqliteDb.get();
await db.run(
`INSERT INTO ${IndexLock.getLockTableName()} (locked, timestamp, dirs) VALUES (?, ?, ?)`,
true,
Date.now(),
dirs,
);
}
static async updateTimestamp() {
const db = await SqliteDb.get();
await db.run(
`UPDATE ${IndexLock.getLockTableName()} SET timestamp = ? where locked = ?`,
Date.now(),
true,
);
}
static async unlock() {
const db = await SqliteDb.get();
await db.run(
`DELETE FROM ${IndexLock.getLockTableName()} WHERE locked = ?`,
true,
);
}
}

View file

@ -3,7 +3,17 @@ import { fileURLToPath } from "url";
export default {
transform: {
"^.+\\.(ts|js)$": ["ts-jest", { useESM: true, useIsolatedModules: true }],
"^.+\\.(ts|js)$": [
"ts-jest",
{
useESM: true,
useIsolatedModules: true,
tsconfig: {
experimentalDecorators: true,
emitDecoratorMetadata: true,
},
},
],
},
moduleNameMapper: {
"^(\\.{1,2}/.*)\\.js$": "$1",

View file

@ -1,10 +1,11 @@
// @ts-nocheck
// Generated by continue
import { ChatMessage, MessagePart } from "../index.js";
import { ChatMessage, MessagePart, ToolCall } from "../index.js";
import {
compileChatMessages,
countTokens,
countTokensAsync,
extractToolSequence,
pruneLinesFromBottom,
pruneLinesFromTop,
pruneRawPromptFromTop,
@ -174,3 +175,188 @@ describe.skip("compileChatMessages", () => {
expect(compiled.length).toBe(1);
});
});
describe("extractToolSequence", () => {
// Helper function to create mock messages
const createUserMessage = (content: string): ChatMessage => ({
role: "user",
content,
});
const createAssistantMessage = (
content: string,
toolCalls?: ToolCall[],
): ChatMessage => ({
role: "assistant",
content,
toolCalls,
});
const createToolMessage = (
content: string,
toolCallId: string,
): ChatMessage => ({
role: "tool",
content,
toolCallId,
});
const createToolCall = (
id: string,
name: string,
args: object,
): ToolCall => ({
id,
type: "function",
function: {
name,
arguments: JSON.stringify(args),
},
});
test("extractToolSequence should handle a single user message", () => {
const messages: ChatMessage[] = [createUserMessage("Hello world!")];
const sequence = extractToolSequence(messages);
expect(sequence).toHaveLength(1);
expect(sequence[0].role).toBe("user");
expect(sequence[0].content).toBe("Hello world!");
expect(messages).toHaveLength(0); // Original array should be modified
});
test("extractToolSequence should handle a single tool message with assistant", () => {
const toolCall = createToolCall("tc_1", "read_file", { path: "test.txt" });
const messages: ChatMessage[] = [
createAssistantMessage("I'll read the file for you.", [toolCall]),
createToolMessage("File contents here", "tc_1"),
];
const sequence = extractToolSequence(messages);
expect(sequence).toHaveLength(2);
expect(sequence[0].role).toBe("assistant");
expect(sequence[1].role).toBe("tool");
expect(sequence[1].toolCallId).toBe("tc_1");
expect(messages).toHaveLength(0);
});
test("extractToolSequence should handle multiple consecutive tool messages", () => {
const toolCall1 = createToolCall("tc_1", "read_file", { path: "test.txt" });
const toolCall2 = createToolCall("tc_2", "write_file", {
path: "output.txt",
content: "data",
});
const messages: ChatMessage[] = [
createAssistantMessage("I'll read and write files.", [
toolCall1,
toolCall2,
]),
createToolMessage("File contents 1", "tc_1"),
createToolMessage("File written successfully", "tc_2"),
];
const sequence = extractToolSequence(messages);
expect(sequence).toHaveLength(3);
expect(sequence[0].role).toBe("assistant");
expect(sequence[1].role).toBe("tool");
expect(sequence[1].toolCallId).toBe("tc_1");
expect(sequence[2].role).toBe("tool");
expect(sequence[2].toolCallId).toBe("tc_2");
expect(messages).toHaveLength(0);
});
test("extractToolSequence should handle tool sequence with previous context", () => {
const toolCall = createToolCall("tc_1", "search", { query: "test" });
const messages: ChatMessage[] = [
createUserMessage("What's in the codebase?"),
createAssistantMessage("Let me search for you.", [toolCall]),
createToolMessage("Search results here", "tc_1"),
];
const sequence = extractToolSequence(messages);
expect(sequence).toHaveLength(2);
expect(sequence[0].role).toBe("assistant");
expect(sequence[1].role).toBe("tool");
expect(messages).toHaveLength(1); // User message should remain
expect(messages[0].role).toBe("user");
});
test("extractToolSequence should throw error when tool message has no matching tool call", () => {
const toolCall = createToolCall("tc_1", "read_file", { path: "test.txt" });
const messages: ChatMessage[] = [
createAssistantMessage("I'll read the file for you.", [toolCall]),
createToolMessage("File contents here", "tc_2"), // Wrong tool call ID
];
expect(() => extractToolSequence(messages)).toThrow(
'Error parsing chat history: no tool call found to match tool output for id "tc_2"',
);
});
test("extractToolSequence should throw error when last message is not user or tool", () => {
const messages: ChatMessage[] = [
createUserMessage("Hello"),
createAssistantMessage("Hi there!"),
];
expect(() => extractToolSequence(messages)).toThrow(
"Error parsing chat history: no user/tool message found",
);
});
test("extractToolSequence should throw error when messages array is empty", () => {
const messages: ChatMessage[] = [];
expect(() => extractToolSequence(messages)).toThrow(
"Error parsing chat history: no user/tool message found",
);
});
test("extractToolSequence should handle tool sequence without assistant message", () => {
const messages: ChatMessage[] = [
createToolMessage("Orphaned tool message", "tc_1"),
];
const sequence = extractToolSequence(messages);
expect(sequence).toHaveLength(1);
expect(sequence[0].role).toBe("tool");
expect(sequence[0].toolCallId).toBe("tc_1");
expect(messages).toHaveLength(0);
});
test("extractToolSequence should handle complex tool sequence with multiple tool calls", () => {
const toolCall1 = createToolCall("tc_1", "read_file", {
path: "file1.txt",
});
const toolCall2 = createToolCall("tc_2", "read_file", {
path: "file2.txt",
});
const toolCall3 = createToolCall("tc_3", "write_file", {
path: "output.txt",
content: "merged",
});
const messages: ChatMessage[] = [
createUserMessage("Merge these files"),
createAssistantMessage("I'll read both files and merge them.", [
toolCall1,
toolCall2,
toolCall3,
]),
createToolMessage("Contents of file1", "tc_1"),
createToolMessage("Contents of file2", "tc_2"),
createToolMessage("Files merged successfully", "tc_3"),
];
const sequence = extractToolSequence(messages);
expect(sequence).toHaveLength(4);
expect(sequence[0].role).toBe("assistant");
expect(sequence[1].role).toBe("tool");
expect(sequence[1].toolCallId).toBe("tc_1");
expect(sequence[2].role).toBe("tool");
expect(sequence[2].toolCallId).toBe("tc_2");
expect(sequence[3].role).toBe("tool");
expect(sequence[3].toolCallId).toBe("tc_3");
expect(messages).toHaveLength(1); // User message should remain
});
});

View file

@ -1,22 +1,23 @@
import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken";
import { ChatMessage, MessageContent, MessagePart, Tool } from "../index.js";
import { renderChatMessage } from "../util/messageContent.js";
import {
AsyncEncoder,
GPTAsyncEncoder,
LlamaAsyncEncoder,
} from "./asyncEncoder.js";
ChatMessage,
CompiledMessagesResult,
MessageContent,
MessagePart,
Tool,
} from "../index.js";
import { autodetectTemplateType } from "./autodetect.js";
import llamaTokenizer from "./llamaTokenizer.js";
import {
addSpaceToAnyEmptyMessages,
chatMessageIsEmpty,
flattenMessages,
isUserOrToolMsg,
messageHasToolCallId,
} from "./messages.js";
import { renderChatMessage } from "../util/messageContent.js";
import { AsyncEncoder, LlamaAsyncEncoder } from "./asyncEncoder.js";
import llamaTokenizer from "./llamaTokenizer.js";
interface Encoding {
encode: Tiktoken["encode"];
decode: Tiktoken["decode"];
@ -47,7 +48,6 @@ class NonWorkerAsyncEncoder implements AsyncEncoder {
}
let gptEncoding: Encoding | null = null;
const gptAsyncEncoder = new GPTAsyncEncoder();
const llamaEncoding = new LlamaEncoding();
const llamaAsyncEncoder = new LlamaAsyncEncoder();
@ -213,6 +213,59 @@ function countChatMessageTokens(
return tokens;
}
/**
* Extracts and validates the tool call sequence from the end of a message array.
* Tool sequences consist of: [assistant_with_tool_calls, tool_response_1, tool_response_2, ...]
* or just a single user message.
*
* @param messages - Array of chat messages (will be modified by popping messages)
* @returns Array of messages that form the tool sequence
*/
function extractToolSequence(messages: ChatMessage[]): ChatMessage[] {
const lastMsg = messages.pop();
if (!lastMsg || !isUserOrToolMsg(lastMsg)) {
throw new Error("Error parsing chat history: no user/tool message found");
}
const toolSequence: ChatMessage[] = [];
if (lastMsg.role === "tool") {
toolSequence.push(lastMsg);
// Collect all consecutive tool messages from the end
while (
messages.length > 0 &&
messages[messages.length - 1].role === "tool"
) {
toolSequence.unshift(messages.pop()!);
}
// Get the assistant message with tool calls
const assistantMsg = messages.pop();
if (assistantMsg) {
toolSequence.unshift(assistantMsg);
// Validate that all tool messages have matching tool call IDs
for (const toolMsg of toolSequence.slice(1)) {
// Skip assistant message
if (
toolMsg.role === "tool" &&
!messageHasToolCallId(assistantMsg, toolMsg.toolCallId)
) {
throw new Error(
`Error parsing chat history: no tool call found to match tool output for id "${toolMsg.toolCallId}"`,
);
}
}
}
} else {
// Single user message
toolSequence.push(lastMsg);
}
return toolSequence;
}
function pruneLinesFromTop(
prompt: string,
maxTokens: number,
@ -309,9 +362,6 @@ function getTokenCountingBufferSafety(contextLength: number) {
}
const MIN_RESPONSE_TOKENS = 1000;
function getMinResponseTokens(maxTokens: number) {
return Math.min(MIN_RESPONSE_TOKENS, maxTokens);
}
function pruneRawPromptFromTop(
modelName: string,
@ -326,13 +376,36 @@ function pruneRawPromptFromTop(
return pruneStringFromTop(modelName, maxTokens, prompt);
}
/*
Goal: reconcile chat messages with available context length
Guidelines:
- Always keep last user message, system message, and tools
- Never allow tool output without the corresponding tool call
- Remove older messages first
*/
/**
* Reconciles chat messages with available context length by intelligently pruning older messages
* while preserving critical conversation elements.
*
* Core Guidelines:
* - Always preserve the last user/tool message sequence (including any associated assistant message with tool calls)
* - Always preserve the system message and tools
* - Never allow orphaned tool responses without their corresponding tool calls
* - Remove older messages first when pruning is necessary
* - Maintain conversation coherence by flattening adjacent similar messages
*
* Process:
* 1. Handle image content conversion for models that don't support images
* 2. Extract and preserve system message
* 3. Filter out empty messages and trailing non-user/tool messages
* 4. Extract the complete tool sequence from the end (user message or assistant + tool responses)
* 5. Calculate token requirements for non-negotiable elements (system, tools, last sequence)
* 6. Prune older messages until within available token budget
* 7. Reassemble with proper ordering and flatten adjacent similar messages
*
* @param params - Configuration object containing:
* - modelName: LLM model name for token counting
* - msgs: Array of chat messages to process
* - contextLength: Maximum context length supported by the model
* - maxTokens: Maximum tokens to reserve for the response
* - supportsImages: Whether the model supports image content
* - tools: Optional array of available tools
* @returns Processed array of chat messages that fit within context constraints
* @throws Error if non-negotiable elements exceed available context
*/
function compileChatMessages({
modelName,
msgs,
@ -347,7 +420,9 @@ function compileChatMessages({
maxTokens: number;
supportsImages: boolean;
tools?: Tool[];
}): ChatMessage[] {
}): CompiledMessagesResult {
let didPrune = false;
let msgsCopy: ChatMessage[] = msgs.map((m) => ({ ...m }));
// If images not supported, convert MessagePart[] to string
@ -369,31 +444,13 @@ function compileChatMessages({
msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy);
while (msgsCopy.length > 1) {
if (isUserOrToolMsg(msgsCopy.at(-1))) {
break;
}
msgsCopy.pop();
}
// Extract the tool sequence from the end of the message array
const toolSequence = extractToolSequence(msgsCopy);
const lastUserOrToolMsg = msgsCopy.pop();
if (!lastUserOrToolMsg || !isUserOrToolMsg(lastUserOrToolMsg)) {
throw new Error("Error parsing chat history: no user/tool message found"); // should never happen
}
let lastToolCallsMsg: ChatMessage | undefined = undefined;
if (lastUserOrToolMsg.role === "tool") {
lastToolCallsMsg = msgsCopy.pop();
if (!messageHasToolCallId(lastToolCallsMsg, lastUserOrToolMsg.toolCallId)) {
throw new Error(
`Error parsing chat history: no tool call found to match tool output for id "${lastUserOrToolMsg.toolCallId}"`,
);
}
}
let lastMessagesTokens = countChatMessageTokens(modelName, lastUserOrToolMsg);
if (lastToolCallsMsg) {
lastMessagesTokens += countChatMessageTokens(modelName, lastToolCallsMsg);
// Count tokens for all messages in the tool sequence
let lastMessagesTokens = 0;
for (const msg of toolSequence) {
lastMessagesTokens += countChatMessageTokens(modelName, msg);
}
// System message
@ -409,7 +466,7 @@ function compileChatMessages({
}
const countingSafetyBuffer = getTokenCountingBufferSafety(contextLength);
const minOutputTokens = getMinResponseTokens(maxTokens);
const minOutputTokens = Math.min(MIN_RESPONSE_TOKENS, maxTokens);
let inputTokensAvailable = contextLength;
@ -426,14 +483,13 @@ function compileChatMessages({
if (inputTokensAvailable < 0) {
throw new Error(
`Not enough context available to include the system message, last user message, and tools.
There must be at least ${minOutputTokens} tokens remaining for output.
Request had the following token counts:
- contextLength: ${contextLength}
- counting safety buffer: ${countingSafetyBuffer}
- tools: ~${toolTokens}
- system message: ~${systemMsgTokens}
- last user or tool + tool call message tokens: ~${lastMessagesTokens}
- max output tokens: ${maxTokens}`,
There must be at least ${minOutputTokens} tokens remaining for output.
Request had the following token counts:
- contextLength: ${contextLength}
- counting safety buffer: ${countingSafetyBuffer}
- tools: ~${toolTokens}
- system message: ~${systemMsgTokens}
- max output tokens: ${maxTokens}`,
);
}
@ -451,6 +507,7 @@ function compileChatMessages({
while (historyWithTokens.length > 0 && currentTotal > inputTokensAvailable) {
const message = historyWithTokens.shift()!;
currentTotal -= message.tokens;
didPrune = true;
// At this point make sure no latent tool response without corresponding call
while (historyWithTokens[0]?.role === "tool") {
@ -465,20 +522,25 @@ function compileChatMessages({
reassembled.push(systemMsg);
}
reassembled.push(...historyWithTokens.map(({ tokens, ...rest }) => rest));
if (lastToolCallsMsg) {
reassembled.push(lastToolCallsMsg);
}
reassembled.push(lastUserOrToolMsg);
reassembled.push(...toolSequence);
// Flatten the messages (combines adjacent similar messages)
const flattenedHistory = flattenMessages(reassembled);
return flattenedHistory;
const inputTokens =
currentTotal + systemMsgTokens + toolTokens + lastMessagesTokens;
const availableTokens =
contextLength - countingSafetyBuffer - minOutputTokens;
const contextPercentage = inputTokens / availableTokens;
return {
compiledChatMessages: reassembled,
didPrune,
contextPercentage,
};
}
export {
compileChatMessages,
countTokens,
countTokensAsync,
extractToolSequence,
pruneLinesFromBottom,
pruneLinesFromTop,
pruneRawPromptFromTop,

View file

@ -20,6 +20,7 @@ import {
ILLMLogger,
LLMFullCompletionOptions,
LLMOptions,
MessageOption,
ModelCapability,
ModelInstaller,
PromptLog,
@ -27,6 +28,7 @@ import {
RequestOptions,
TabAutocompleteOptions,
TemplateType,
Usage,
} from "../index.js";
import mergeJson from "../util/merge.js";
import { renderChatMessage } from "../util/messageContent.js";
@ -326,6 +328,7 @@ export abstract class BaseLLM implements ILLM {
completion: string,
thinking: string | undefined,
interaction: ILLMInteractionLog | undefined,
usage: Usage | undefined,
error?: any,
): InteractionStatus {
let promptTokens = this.countTokens(prompt);
@ -367,6 +370,7 @@ export abstract class BaseLLM implements ILLM {
promptTokens,
generatedTokens,
thinkingTokens,
usage,
});
return "cancelled";
} else {
@ -378,6 +382,7 @@ export abstract class BaseLLM implements ILLM {
promptTokens,
generatedTokens,
thinkingTokens,
usage,
});
return "error";
}
@ -387,6 +392,7 @@ export abstract class BaseLLM implements ILLM {
promptTokens,
generatedTokens,
thinkingTokens,
usage,
});
return "success";
}
@ -573,6 +579,7 @@ export abstract class BaseLLM implements ILLM {
prefix,
suffix,
options: completionOptions,
provider: this.providerName,
});
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, fimLog);
@ -621,6 +628,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
undefined,
);
} catch (e) {
status = this._logEnd(
@ -629,6 +637,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
undefined,
e,
);
throw e;
@ -640,6 +649,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
undefined,
"cancel",
);
}
@ -680,6 +690,7 @@ export abstract class BaseLLM implements ILLM {
kind: "startComplete",
prompt,
options: completionOptions,
provider: this.providerName,
});
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, prompt);
@ -735,6 +746,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
undefined,
);
} catch (e) {
status = this._logEnd(
@ -743,6 +755,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
undefined,
e,
);
throw e;
@ -754,6 +767,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
undefined,
"cancel",
);
}
@ -795,6 +809,7 @@ export abstract class BaseLLM implements ILLM {
kind: "startComplete",
prompt: prompt,
options: completionOptions,
provider: this.providerName,
});
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, prompt);
@ -828,6 +843,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
undefined,
);
} catch (e) {
status = this._logEnd(
@ -836,6 +852,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
undefined,
e,
);
throw e;
@ -847,6 +864,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
undefined,
"cancel",
);
}
@ -867,6 +885,23 @@ export abstract class BaseLLM implements ILLM {
return { role: "assistant" as const, content: completion };
}
compileChatMessages(
message: ChatMessage[],
options: LLMFullCompletionOptions,
) {
let { completionOptions } = this._parseCompletionOptions(options);
completionOptions = this._modifyCompletionOptions(completionOptions);
return compileChatMessages({
modelName: completionOptions.model,
msgs: message,
contextLength: this.contextLength,
maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
supportsImages: this.supportsImages(),
tools: options.tools,
});
}
protected modifyChatBody(
body: ChatCompletionCreateParams,
): ChatCompletionCreateParams {
@ -891,6 +926,7 @@ export abstract class BaseLLM implements ILLM {
_messages: ChatMessage[],
signal: AbortSignal,
options: LLMFullCompletionOptions = {},
messageOptions?: MessageOption,
): AsyncGenerator<ChatMessage, PromptLog> {
let { completionOptions, logEnabled } =
this._parseCompletionOptions(options);
@ -901,14 +937,21 @@ export abstract class BaseLLM implements ILLM {
completionOptions = this._modifyCompletionOptions(completionOptions);
const messages = compileChatMessages({
modelName: completionOptions.model,
msgs: _messages,
contextLength: this.contextLength,
maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
supportsImages: this.supportsImages(),
tools: options.tools,
});
let messages = _messages;
// If not precompiled, compile the chat messages
if (!messageOptions?.precompiled) {
const { compiledChatMessages } = compileChatMessages({
modelName: completionOptions.model,
msgs: _messages,
contextLength: this.contextLength,
maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
supportsImages: this.supportsImages(),
tools: options.tools,
});
messages = compiledChatMessages;
}
const prompt = this.templateMessages
? this.templateMessages(messages)
@ -918,6 +961,7 @@ export abstract class BaseLLM implements ILLM {
kind: "startChat",
messages,
options: completionOptions,
provider: this.providerName,
});
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, prompt);
@ -926,6 +970,7 @@ export abstract class BaseLLM implements ILLM {
let thinking = "";
let completion = "";
let usage: Usage | undefined = undefined;
try {
if (this.templateMessages) {
@ -992,6 +1037,11 @@ export abstract class BaseLLM implements ILLM {
kind: "message",
message: chunk,
});
if (chunk.role === "assistant" && chunk.usage) {
usage = chunk.usage;
}
yield chunk;
}
}
@ -1002,6 +1052,7 @@ export abstract class BaseLLM implements ILLM {
completion,
thinking,
interaction,
usage,
);
} catch (e) {
status = this._logEnd(
@ -1010,6 +1061,7 @@ export abstract class BaseLLM implements ILLM {
completion,
thinking,
interaction,
usage,
e,
);
throw e;
@ -1021,6 +1073,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
usage,
"cancel",
);
}

View file

@ -1,5 +1,10 @@
import { streamSse } from "@continuedev/fetch";
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
import {
ChatMessage,
CompletionOptions,
LLMOptions,
Usage,
} from "../../index.js";
import { safeParseToolCallArgs } from "../../tools/parseArgs.js";
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
@ -234,15 +239,49 @@ class Anthropic extends BaseLLM {
if (options.stream === false) {
const data = await response.json();
yield { role: "assistant", content: data.content[0].text };
const cost = data.usage
? {
inputTokens: data.usage.input_tokens,
outputTokens: data.usage.output_tokens,
totalTokens: data.usage.input_tokens + data.usage.output_tokens,
}
: {};
yield {
role: "assistant",
content: data.content[0].text,
...(Object.keys(cost).length > 0 ? { cost } : {}),
};
return;
}
let lastToolUseId: string | undefined;
let lastToolUseName: string | undefined;
let usage: Usage = {
promptTokens: 0,
completionTokens: 0,
promptTokensDetails: {
cachedTokens: 0,
cacheWriteTokens: 0,
},
};
for await (const value of streamSse(response)) {
// https://docs.anthropic.com/en/api/messages-streaming#event-types
switch (value.type) {
case "message_start":
// Capture initial usage information
usage.promptTokens = value.message.usage.input_tokens;
usage.promptTokensDetails!.cachedTokens =
value.message.usage.cache_read_input_tokens;
usage.promptTokensDetails!.cacheWriteTokens =
value.message.usage.cache_creation_input_tokens;
break;
case "message_delta":
// Update usage information during streaming
if (value.usage) {
usage.completionTokens = value.usage.output_tokens;
}
break;
case "content_block_start":
if (value.content_block.type === "tool_use") {
lastToolUseId = value.content_block.id;
@ -250,7 +289,6 @@ class Anthropic extends BaseLLM {
}
// handle redacted thinking
if (value.content_block.type === "redacted_thinking") {
console.log("redacted thinking", value.content_block.data);
yield {
role: "thinking",
content: "",
@ -303,6 +341,12 @@ class Anthropic extends BaseLLM {
break;
}
}
yield {
role: "assistant",
content: "",
usage,
};
}
}

View file

@ -0,0 +1,495 @@
import { afterEach, describe, expect, test, vi } from "vitest";
import { ILLM } from "../../index.js";
import Anthropic from "./Anthropic.js";
interface LlmTestCase {
llm: ILLM;
methodToTest: keyof ILLM;
params: any[];
expectedRequest: {
url: string;
method: string;
headers?: Record<string, string>;
body?: Record<string, any>;
};
mockResponse?: any;
mockStream?: any[];
}
function createMockStream(mockStream: any[]) {
const encoder = new TextEncoder();
return new ReadableStream({
start(controller) {
for (const chunk of mockStream) {
controller.enqueue(
encoder.encode(
`data: ${
typeof chunk === "string" ? chunk : JSON.stringify(chunk)
}\n\n`,
),
);
}
controller.close();
},
});
}
function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
const mockFetch = vi.fn();
if (mockStream) {
const stream = createMockStream(mockStream);
mockFetch.mockResolvedValue(
new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
},
}),
);
} else {
mockFetch.mockResolvedValue(
new Response(JSON.stringify(mockResponse), {
headers: { "Content-Type": "application/json" },
}),
);
}
return mockFetch;
}
function setupReadableStreamPolyfill() {
// This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
// @ts-ignore
const originalFrom = ReadableStream.from;
// @ts-ignore
ReadableStream.from = (body) => {
if (body?.source) {
return body;
}
return originalFrom(body);
};
}
async function executeLlmMethod(
llm: ILLM,
methodToTest: keyof ILLM,
params: any[],
) {
if (typeof (llm as any)[methodToTest] !== "function") {
throw new Error(
`Method ${String(methodToTest)} does not exist on the LLM instance.`,
);
}
const result = await (llm as any)[methodToTest](...params);
if (result?.next) {
for await (const _ of result) {
}
}
}
function assertFetchCall(mockFetch: any, expectedRequest: any) {
expect(mockFetch).toHaveBeenCalledTimes(1);
const [url, options] = mockFetch.mock.calls[0];
expect(url.toString()).toBe(expectedRequest.url);
expect(options.method).toBe(expectedRequest.method);
if (expectedRequest.headers) {
expect(options.headers).toEqual(
expect.objectContaining(expectedRequest.headers),
);
}
if (expectedRequest.body) {
const actualBody = JSON.parse(options.body as string);
expect(actualBody).toEqual(expectedRequest.body);
}
}
async function runLlmTest(testCase: LlmTestCase) {
const {
llm,
methodToTest,
params,
expectedRequest,
mockResponse,
mockStream,
} = testCase;
const mockFetch = setupMockFetch(mockResponse, mockStream);
setupReadableStreamPolyfill();
(llm as any).fetch = mockFetch;
await executeLlmMethod(llm, methodToTest, params);
assertFetchCall(mockFetch, expectedRequest);
}
describe("Anthropic", () => {
afterEach(() => {
vi.clearAllMocks();
});
test("streamChat should send a valid request", async () => {
const anthropic = new Anthropic({
apiKey: "test-api-key",
model: "claude-3-5-sonnet-latest",
apiBase: "https://api.anthropic.com/v1/",
});
await runLlmTest({
llm: anthropic,
methodToTest: "streamChat",
params: [
[{ role: "user", content: "hello" }],
new AbortController().signal,
],
expectedRequest: {
url: "https://api.anthropic.com/v1/messages",
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": "test-api-key",
},
body: {
model: "claude-3-5-sonnet-latest",
max_tokens: 8192,
stream: true,
messages: [
{
role: "user",
content: [{ type: "text", text: "hello" }],
},
],
system: "",
},
},
mockStream: [
'{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello! How can I help you today?"}}',
'{"type": "content_block_stop"}',
],
});
});
test("chat should send a valid request", async () => {
const anthropic = new Anthropic({
apiKey: "test-api-key",
model: "claude-3-5-sonnet-latest",
apiBase: "https://api.anthropic.com/v1/",
});
await runLlmTest({
llm: anthropic,
methodToTest: "chat",
params: [
[{ role: "user", content: "hello" }],
new AbortController().signal,
],
expectedRequest: {
url: "https://api.anthropic.com/v1/messages",
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": "test-api-key",
},
body: {
model: "claude-3-5-sonnet-latest",
max_tokens: 8192,
stream: true,
messages: [
{
role: "user",
content: [{ type: "text", text: "hello" }],
},
],
system: "",
},
},
mockStream: [
'{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello! How can I help you today?"}}',
'{"type": "content_block_stop"}',
],
});
});
test("streamComplete should send a valid request", async () => {
const anthropic = new Anthropic({
apiKey: "test-api-key",
model: "claude-3-5-sonnet-latest",
apiBase: "https://api.anthropic.com/v1/",
});
await runLlmTest({
llm: anthropic,
methodToTest: "streamComplete",
params: ["Complete this: Hello", new AbortController().signal],
expectedRequest: {
url: "https://api.anthropic.com/v1/messages",
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": "test-api-key",
},
body: {
model: "claude-3-5-sonnet-latest",
max_tokens: 8192,
stream: true,
messages: [
{
role: "user",
content: [{ type: "text", text: "Complete this: Hello" }],
},
],
system: "",
},
},
mockStream: [
'{"type": "content_block_delta", "delta": {"type": "text_delta", "text": " world!"}}',
'{"type": "content_block_stop"}',
],
});
});
test("complete should send a valid request", async () => {
const anthropic = new Anthropic({
apiKey: "test-api-key",
model: "claude-3-5-sonnet-latest",
apiBase: "https://api.anthropic.com/v1/",
});
await runLlmTest({
llm: anthropic,
methodToTest: "complete",
params: ["Complete this: Hello", new AbortController().signal],
expectedRequest: {
url: "https://api.anthropic.com/v1/messages",
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": "test-api-key",
},
body: {
model: "claude-3-5-sonnet-latest",
max_tokens: 8192,
stream: true,
messages: [
{
role: "user",
content: [{ type: "text", text: "Complete this: Hello" }],
},
],
system: "",
},
},
mockStream: [
'{"type": "content_block_delta", "delta": {"type": "text_delta", "text": " world!"}}',
'{"type": "content_block_stop"}',
],
});
});
describe("Different configurations", () => {
test("should handle system message", async () => {
const anthropic = new Anthropic({
apiKey: "test-api-key",
model: "claude-3-5-sonnet-latest",
apiBase: "https://api.anthropic.com/v1/",
});
await runLlmTest({
llm: anthropic,
methodToTest: "streamChat",
params: [
[
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Hello!" },
],
new AbortController().signal,
],
expectedRequest: {
url: "https://api.anthropic.com/v1/messages",
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": "test-api-key",
},
body: {
model: "claude-3-5-sonnet-latest",
max_tokens: 8192,
stream: true,
messages: [
{
role: "user",
content: [{ type: "text", text: "Hello!" }],
},
],
system: "You are a helpful assistant.",
},
},
mockStream: [
'{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello! How can I help you today?"}}',
'{"type": "content_block_stop"}',
],
});
});
test("should handle tool calls", async () => {
const anthropic = new Anthropic({
apiKey: "test-api-key",
model: "claude-3-5-sonnet-latest",
apiBase: "https://api.anthropic.com/v1/",
});
const tools = [
{
type: "function" as const,
function: {
name: "get_weather",
description: "Get the current weather",
parameters: {
type: "object",
properties: {
location: { type: "string" },
},
required: ["location"],
},
},
},
];
await runLlmTest({
llm: anthropic,
methodToTest: "streamChat",
params: [
[{ role: "user", content: "What's the weather in New York?" }],
new AbortController().signal,
{ tools },
],
expectedRequest: {
url: "https://api.anthropic.com/v1/messages",
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": "test-api-key",
},
body: {
model: "claude-3-5-sonnet-latest",
max_tokens: 8192,
stream: true,
messages: [
{
role: "user",
content: [
{ type: "text", text: "What's the weather in New York?" },
],
},
],
tools: [
{
name: "get_weather",
description: "Get the current weather",
input_schema: {
type: "object",
properties: {
location: { type: "string" },
},
required: ["location"],
},
},
],
system: "",
},
},
mockStream: [
'{"type": "content_block_start", "content_block": {"type": "tool_use", "id": "toolu_123", "name": "get_weather"}}',
'{"type": "content_block_delta", "delta": {"type": "input_json_delta", "partial_json": "{\\"location\\": \\"New York\\""}}',
'{"type": "content_block_stop"}',
],
});
});
test("should handle custom max tokens", async () => {
const anthropic = new Anthropic({
apiKey: "test-api-key",
model: "claude-3-5-sonnet-latest",
apiBase: "https://api.anthropic.com/v1/",
});
await runLlmTest({
llm: anthropic,
methodToTest: "streamChat",
params: [
[{ role: "user", content: "hello" }],
new AbortController().signal,
{ maxTokens: 1000 },
],
expectedRequest: {
url: "https://api.anthropic.com/v1/messages",
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": "test-api-key",
},
body: {
model: "claude-3-5-sonnet-latest",
max_tokens: 1000,
stream: true,
messages: [
{
role: "user",
content: [{ type: "text", text: "hello" }],
},
],
system: "",
},
},
mockStream: [
'{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello!"}}',
'{"type": "content_block_stop"}',
],
});
});
});
describe("Error handling", () => {
test("should throw error when API key is missing", async () => {
const anthropic = new Anthropic({
apiKey: "",
model: "claude-3-5-sonnet-latest",
apiBase: "https://api.anthropic.com/v1/",
});
await expect(
runLlmTest({
llm: anthropic,
methodToTest: "streamChat",
params: [
[{ role: "user", content: "hello" }],
new AbortController().signal,
],
expectedRequest: {
url: "https://api.anthropic.com/v1/messages",
method: "POST",
},
}),
).rejects.toThrow(
"Request not sent. You have an Anthropic model configured in your config.json, but the API key is not set.",
);
});
});
});

View file

@ -11,18 +11,14 @@ import {
} from "@aws-sdk/client-bedrock-runtime";
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
import {
ChatMessage,
Chunk,
CompletionOptions,
LLMOptions,
MessageContent,
} from "../../index.js";
import type { CompletionOptions } from "../../index.js";
import { ChatMessage, Chunk, LLMOptions, MessageContent } from "../../index.js";
import { safeParseToolCallArgs } from "../../tools/parseArgs.js";
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { PROVIDER_TOOL_SUPPORT } from "../toolSupport.js";
import { getSecureID } from "../utils/getSecureID.js";
import { withLLMRetry } from "../utils/retry.js";
interface ModelConfig {
formatPayload: (text: string) => any;
@ -89,6 +85,7 @@ class Bedrock extends BaseLLM {
}
}
@withLLMRetry()
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
@ -132,16 +129,9 @@ class Bedrock extends BaseLLM {
});
const command = new ConverseStreamCommand(input);
let response: ConverseStreamCommandOutput;
try {
response = (await client.send(command, {
abortSignal: signal,
})) as ConverseStreamCommandOutput;
} catch (error: unknown) {
console.error(error);
const message = error instanceof Error ? error.message : "Unknown error";
throw new Error(`Failed to communicate with Bedrock API: ${message}`);
}
const response = (await client.send(command, {
abortSignal: signal,
})) as ConverseStreamCommandOutput;
if (!response?.stream) {
throw new Error("No stream received from Bedrock API");
@ -259,19 +249,9 @@ class Bedrock extends BaseLLM {
}
}
} catch (error: unknown) {
// Clean up state and let the original error bubble up to the retry decorator
this._currentToolResponse = null;
if (error instanceof Error) {
if ("code" in error) {
// AWS SDK specific errors
throw new Error(
`AWS Bedrock stream error (${(error as any).code}): ${error.message}`,
);
}
throw new Error(`Error processing Bedrock stream: ${error.message}`);
}
throw new Error(
"Error processing Bedrock stream: Unknown error occurred",
);
throw error;
}
}

View file

@ -17,7 +17,7 @@ import OpenAI from "./OpenAI.js";
class Docker extends OpenAI implements ModelInstaller {
static providerName = "docker";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "http://localhost:12434/engines/v1",
apiBase: "http://localhost:12434/engines/v1/",
model: "gemma3-4B-F4", // Default model
};

View file

@ -5,7 +5,7 @@ import OpenAI from "./OpenAI.js";
class Fireworks extends OpenAI {
static providerName = "fireworks";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.fireworks.ai/inference/v1",
apiBase: "https://api.fireworks.ai/inference/v1/",
};
private static modelConversion: { [key: string]: string } = {

View file

@ -0,0 +1,12 @@
import Fireworks from "./Fireworks.js";
import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js";
createOpenAISubclassTests(Fireworks, {
providerName: "fireworks",
defaultApiBase: "https://api.fireworks.ai/inference/v1/",
modelConversions: {
"starcoder-7b": "accounts/fireworks/models/starcoder-7b",
},
modelConversionContent:
"<|im_start|>user\nhello<|im_end|>\n<|im_start|>assistant\n",
});

View file

@ -0,0 +1,12 @@
import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js";
import Groq from "./Groq.js";
createOpenAISubclassTests(Groq, {
providerName: "groq",
defaultApiBase: "https://api.groq.com/openai/v1/",
modelConversions: {
"mistral-8x7b": "mixtral-8x7b-32768",
"llama3-8b": "llama3-8b-8192",
"llama3-70b": "llama3-70b-8192",
},
});

View file

@ -5,7 +5,7 @@ import OpenAI from "./OpenAI";
class Kindo extends OpenAI {
static providerName = "kindo";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://llm.kindo.ai/v1",
apiBase: "https://llm.kindo.ai/v1/",
requestOptions: {
headers: {
"kindo-token-transaction-type": "CONTINUE",

View file

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

View file

@ -0,0 +1,294 @@
import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js";
// Import core OpenAI-compatible providers
import OpenAI from "./OpenAI.js";
import Groq from "./Groq.js";
import Fireworks from "./Fireworks.js";
import Together from "./Together.js";
import Deepseek from "./Deepseek.js";
import OpenRouter from "./OpenRouter.js";
import xAI from "./xAI.js";
import Mistral from "./Mistral.js";
import LMStudio from "./LMStudio.js";
import Cerebras from "./Cerebras.js";
import DeepInfra from "./DeepInfra.js";
import Nvidia from "./Nvidia.js";
// Base OpenAI tests
import { afterEach, describe, expect, test, vi } from "vitest";
import { ILLM } from "../../index.js";
interface LlmTestCase {
llm: ILLM;
methodToTest: keyof ILLM;
params: any[];
expectedRequest: {
url: string;
method: string;
headers?: Record<string, string>;
body?: Record<string, any>;
};
mockResponse?: any;
mockStream?: any[];
}
function createMockStream(mockStream: any[]) {
const encoder = new TextEncoder();
return new ReadableStream({
start(controller) {
for (const chunk of mockStream) {
controller.enqueue(
encoder.encode(
`data: ${
typeof chunk === "string" ? chunk : JSON.stringify(chunk)
}\n\n`,
),
);
}
controller.close();
},
});
}
function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
const mockFetch = vi.fn();
if (mockStream) {
const stream = createMockStream(mockStream);
mockFetch.mockResolvedValue(
new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
},
}),
);
} else {
mockFetch.mockResolvedValue(
new Response(JSON.stringify(mockResponse), {
headers: { "Content-Type": "application/json" },
}),
);
}
return mockFetch;
}
function setupReadableStreamPolyfill() {
// This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
// @ts-ignore
const originalFrom = ReadableStream.from;
// @ts-ignore
ReadableStream.from = (body) => {
if (body?.source) {
return body;
}
return originalFrom(body);
};
}
async function executeLlmMethod(
llm: ILLM,
methodToTest: keyof ILLM,
params: any[],
) {
if (typeof (llm as any)[methodToTest] !== "function") {
throw new Error(
`Method ${String(methodToTest)} does not exist on the LLM instance.`,
);
}
const result = await (llm as any)[methodToTest](...params);
if (result?.next) {
for await (const _ of result) {
}
}
}
function assertFetchCall(mockFetch: any, expectedRequest: any) {
expect(mockFetch).toHaveBeenCalledTimes(1);
const [url, options] = mockFetch.mock.calls[0];
expect(url.toString()).toBe(expectedRequest.url);
expect(options.method).toBe(expectedRequest.method);
if (expectedRequest.headers) {
expect(options.headers).toEqual(
expect.objectContaining(expectedRequest.headers),
);
}
if (expectedRequest.body) {
const actualBody = JSON.parse(options.body as string);
expect(actualBody).toEqual(expectedRequest.body);
}
}
async function runLlmTest(testCase: LlmTestCase) {
const {
llm,
methodToTest,
params,
expectedRequest,
mockResponse,
mockStream,
} = testCase;
const mockFetch = setupMockFetch(mockResponse, mockStream);
setupReadableStreamPolyfill();
(llm as any).fetch = mockFetch;
// Disable OpenAI adapter to use our custom fetch mock
(llm as any).useOpenAIAdapterFor = [];
await executeLlmMethod(llm, methodToTest, params);
assertFetchCall(mockFetch, expectedRequest);
}
describe("OpenAI", () => {
afterEach(() => {
vi.clearAllMocks();
});
test("streamChat should send a valid request", async () => {
const openai = new OpenAI({
apiKey: "test-api-key",
model: "gpt-4",
apiBase: "https://api.openai.com/v1/",
});
await runLlmTest({
llm: openai,
methodToTest: "streamChat",
params: [
[{ role: "user", content: "hello" }],
new AbortController().signal,
],
expectedRequest: {
url: "https://api.openai.com/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
model: "gpt-4",
messages: [{ role: "user", content: "hello" }],
stream: true,
max_tokens: 2048,
},
},
mockStream: [
{ choices: [{ delta: { content: "Hello" } }] },
{ choices: [{ delta: { content: " world" } }] },
],
});
});
});
// Core OpenAI-compatible providers
createOpenAISubclassTests(Groq, {
providerName: "groq",
defaultApiBase: "https://api.groq.com/openai/v1/",
modelConversions: {
"mistral-8x7b": "mistral-8x7b",
"llama3-8b": "llama3-8b-8192",
},
modelConversionContent: "[INST] hello [/INST]",
modelConversionMaxTokens: 4096,
});
createOpenAISubclassTests(Fireworks, {
providerName: "fireworks",
defaultApiBase: "https://api.fireworks.ai/inference/v1/",
modelConversions: {
"starcoder-7b": "starcoder-7b",
},
modelConversionContent:
"<|im_start|>user\nhello<|im_end|>\n<|im_start|>assistant\n",
});
createOpenAISubclassTests(Together, {
providerName: "together",
defaultApiBase: "https://api.together.xyz/v1/",
modelConversions: {
"codellama-7b": "codellama-7b",
"llama3-8b": "meta-llama/Llama-3-8b-chat-hf",
},
modelConversionContent: "hello",
customStreamCompleteEndpoint: "completions",
});
createOpenAISubclassTests(Deepseek, {
providerName: "deepseek",
defaultApiBase: "https://api.deepseek.com/",
});
createOpenAISubclassTests(OpenRouter, {
providerName: "openrouter",
defaultApiBase: "https://openrouter.ai/api/v1/",
});
createOpenAISubclassTests(xAI, {
providerName: "xAI",
defaultApiBase: "https://api.x.ai/v1/",
modelConversions: {
"grok-beta": "grok-beta",
},
modelConversionContent: "hello",
});
createOpenAISubclassTests(Mistral, {
providerName: "mistral",
defaultApiBase: "https://api.mistral.ai/v1/",
modelConversions: {
"mistral-7b": "mistral-7b",
"mistral-8x7b": "open-mixtral-8x7b",
},
modelConversionContent: "hello",
});
createOpenAISubclassTests(LMStudio, {
providerName: "lmstudio",
defaultApiBase: "http://localhost:1234/v1/",
});
createOpenAISubclassTests(Cerebras, {
providerName: "cerebras",
defaultApiBase: "https://api.cerebras.ai/v1/",
modelConversions: {
"llama3.1-8b": "llama3.1-8b",
"llama3.1-70b": "llama3.1-70b",
},
modelConversionContent:
"<|start_header_id|>user<|end_header_id|>\nhello<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n",
});
createOpenAISubclassTests(DeepInfra, {
providerName: "deepinfra",
defaultApiBase: "https://api.deepinfra.com/v1/openai/",
customEmbeddingsUrl:
"https://api.deepinfra.com/v1/inference/text-embedding-ada-002",
customEmbeddingsHeaders: {
Authorization: "bearer test-api-key",
},
customEmbeddingsBody: {
inputs: ["Hello", "World"],
},
});
createOpenAISubclassTests(Nvidia, {
providerName: "nvidia",
defaultApiBase: "https://integrate.api.nvidia.com/v1/",
customEmbeddingsHeaders: {
Authorization: "Bearer test-api-key",
"Content-Type": "application/json",
},
customEmbeddingsBody: {
input: ["Hello", "World"],
model: "text-embedding-ada-002",
input_type: "passage",
truncate: "END",
},
});

View file

@ -0,0 +1,453 @@
import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js";
// Import all OpenAI-compatible providers
import OpenAI from "./OpenAI.js";
import Groq from "./Groq.js";
import Fireworks from "./Fireworks.js";
import Together from "./Together.js";
import Deepseek from "./Deepseek.js";
import OpenRouter from "./OpenRouter.js";
import xAI from "./xAI.js";
import Mistral from "./Mistral.js";
import LMStudio from "./LMStudio.js";
import Cerebras from "./Cerebras.js";
import DeepInfra from "./DeepInfra.js";
import Nvidia from "./Nvidia.js";
import SambaNova from "./SambaNova.js";
import Scaleway from "./Scaleway.js";
import Venice from "./Venice.js";
import Moonshot from "./Moonshot.js";
import Novita from "./Novita.js";
import SiliconFlow from "./SiliconFlow.js";
import Kindo from "./Kindo.js";
import Azure from "./Azure.js";
import Inception from "./Inception.js";
import Docker from "./Docker.js";
import Voyage from "./Voyage.js";
import Vllm from "./Vllm.js";
import TextGenWebUI from "./TextGenWebUI.js";
// import Relace from "./Relace.js"; // Skip - causing import issues
import FunctionNetwork from "./FunctionNetwork.js";
import NCompass from "./NCompass.js";
import LlamaStack from "./LlamaStack.js";
import Nebius from "./Nebius.js";
import OVHcloud from "./OVHcloud.js";
// Base OpenAI tests
import { afterEach, describe, expect, test, vi } from "vitest";
import { ILLM } from "../../index.js";
interface LlmTestCase {
llm: ILLM;
methodToTest: keyof ILLM;
params: any[];
expectedRequest: {
url: string;
method: string;
headers?: Record<string, string>;
body?: Record<string, any>;
};
mockResponse?: any;
mockStream?: any[];
}
function createMockStream(mockStream: any[]) {
const encoder = new TextEncoder();
return new ReadableStream({
start(controller) {
for (const chunk of mockStream) {
controller.enqueue(
encoder.encode(
`data: ${
typeof chunk === "string" ? chunk : JSON.stringify(chunk)
}\n\n`,
),
);
}
controller.close();
},
});
}
function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
const mockFetch = vi.fn();
if (mockStream) {
const stream = createMockStream(mockStream);
mockFetch.mockResolvedValue(
new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
},
}),
);
} else {
mockFetch.mockResolvedValue(
new Response(JSON.stringify(mockResponse), {
headers: { "Content-Type": "application/json" },
}),
);
}
return mockFetch;
}
function setupReadableStreamPolyfill() {
// This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
// @ts-ignore
const originalFrom = ReadableStream.from;
// @ts-ignore
ReadableStream.from = (body) => {
if (body?.source) {
return body;
}
return originalFrom(body);
};
}
async function executeLlmMethod(
llm: ILLM,
methodToTest: keyof ILLM,
params: any[],
) {
if (typeof (llm as any)[methodToTest] !== "function") {
throw new Error(
`Method ${String(methodToTest)} does not exist on the LLM instance.`,
);
}
const result = await (llm as any)[methodToTest](...params);
if (result?.next) {
for await (const _ of result) {
}
}
}
function assertFetchCall(mockFetch: any, expectedRequest: any) {
expect(mockFetch).toHaveBeenCalledTimes(1);
const [url, options] = mockFetch.mock.calls[0];
expect(url.toString()).toBe(expectedRequest.url);
expect(options.method).toBe(expectedRequest.method);
if (expectedRequest.headers) {
expect(options.headers).toEqual(
expect.objectContaining(expectedRequest.headers),
);
}
if (expectedRequest.body) {
const actualBody = JSON.parse(options.body as string);
expect(actualBody).toEqual(expectedRequest.body);
}
}
async function runLlmTest(testCase: LlmTestCase) {
const {
llm,
methodToTest,
params,
expectedRequest,
mockResponse,
mockStream,
} = testCase;
const mockFetch = setupMockFetch(mockResponse, mockStream);
setupReadableStreamPolyfill();
(llm as any).fetch = mockFetch;
// Disable OpenAI adapter to use our custom fetch mock
(llm as any).useOpenAIAdapterFor = [];
await executeLlmMethod(llm, methodToTest, params);
assertFetchCall(mockFetch, expectedRequest);
}
describe("OpenAI", () => {
afterEach(() => {
vi.clearAllMocks();
});
test("streamChat should send a valid request", async () => {
const openai = new OpenAI({
apiKey: "test-api-key",
model: "gpt-4",
apiBase: "https://api.openai.com/v1/",
});
await runLlmTest({
llm: openai,
methodToTest: "streamChat",
params: [
[{ role: "user", content: "hello" }],
new AbortController().signal,
],
expectedRequest: {
url: "https://api.openai.com/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
model: "gpt-4",
messages: [{ role: "user", content: "hello" }],
stream: true,
max_tokens: 2048,
},
},
mockStream: [
{ choices: [{ delta: { content: "Hello" } }] },
{ choices: [{ delta: { content: " world" } }] },
],
});
});
test("should handle embeddings", async () => {
const openai = new OpenAI({
apiKey: "test-api-key",
model: "text-embedding-ada-002",
apiBase: "https://api.openai.com/v1/",
});
await runLlmTest({
llm: openai,
methodToTest: "embed",
params: [["Hello", "World"]],
expectedRequest: {
url: "https://api.openai.com/v1/embeddings",
method: "POST",
headers: {
Authorization: "Bearer test-api-key",
"Content-Type": "application/json",
"api-key": "test-api-key",
},
body: {
input: ["Hello", "World"],
model: "text-embedding-ada-002",
},
},
mockResponse: {
data: [{ embedding: [0.1, 0.2, 0.3] }, { embedding: [0.4, 0.5, 0.6] }],
},
});
});
});
// OpenAI-compatible providers
createOpenAISubclassTests(Groq, {
providerName: "groq",
defaultApiBase: "https://api.groq.com/openai/v1/",
modelConversions: {
"mistral-8x7b": "mixtral-8x7b-32768",
"llama3-8b": "llama3-8b-8192",
"llama3-70b": "llama3-70b-8192",
},
modelConversionContent: "[INST] hello [/INST]",
modelConversionMaxTokens: 4096,
});
createOpenAISubclassTests(Fireworks, {
providerName: "fireworks",
defaultApiBase: "https://api.fireworks.ai/inference/v1/",
modelConversions: {
"starcoder-7b": "accounts/fireworks/models/starcoder-7b",
},
modelConversionContent:
"<|im_start|>user\nhello<|im_end|>\n<|im_start|>assistant\n",
});
createOpenAISubclassTests(Together, {
providerName: "together",
defaultApiBase: "https://api.together.xyz/v1/",
modelConversions: {
"codellama-7b": "codellama-7b",
"llama3-8b": "meta-llama/Llama-3-8b-chat-hf",
"mistral-8x7b": "mistralai/Mixtral-8x7B-Instruct-v0.1",
},
modelConversionContent: "hello",
customStreamCompleteEndpoint: "completions",
});
createOpenAISubclassTests(Deepseek, {
providerName: "deepseek",
defaultApiBase: "https://api.deepseek.com/",
});
createOpenAISubclassTests(OpenRouter, {
providerName: "openrouter",
defaultApiBase: "https://openrouter.ai/api/v1/",
});
createOpenAISubclassTests(xAI, {
providerName: "xAI",
defaultApiBase: "https://api.x.ai/v1/",
modelConversions: {
"grok-beta": "grok-beta",
},
modelConversionContent: "hello",
});
createOpenAISubclassTests(Mistral, {
providerName: "mistral",
defaultApiBase: "https://api.mistral.ai/v1/",
modelConversions: {
"mistral-7b": "mistral-7b",
"mistral-8x7b": "open-mixtral-8x7b",
},
modelConversionContent: "hello",
});
createOpenAISubclassTests(LMStudio, {
providerName: "lmstudio",
defaultApiBase: "http://localhost:1234/v1/",
});
createOpenAISubclassTests(Cerebras, {
providerName: "cerebras",
defaultApiBase: "https://api.cerebras.ai/v1/",
modelConversions: {
"llama3.1-8b": "llama3.1-8b",
"llama3.1-70b": "llama3.1-70b",
},
modelConversionContent:
"<|start_header_id|>user<|end_header_id|>\nhello<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n",
});
createOpenAISubclassTests(DeepInfra, {
providerName: "deepinfra",
defaultApiBase: "https://api.deepinfra.com/v1/openai/",
customEmbeddingsUrl:
"https://api.deepinfra.com/v1/inference/text-embedding-ada-002",
customEmbeddingsHeaders: {
Authorization: "bearer test-api-key",
},
customEmbeddingsBody: {
inputs: ["Hello", "World"],
},
});
createOpenAISubclassTests(Nvidia, {
providerName: "nvidia",
defaultApiBase: "https://integrate.api.nvidia.com/v1/",
customEmbeddingsHeaders: {
Authorization: "Bearer test-api-key",
"Content-Type": "application/json",
},
customEmbeddingsBody: {
input: ["Hello", "World"],
model: "text-embedding-ada-002",
input_type: "passage",
truncate: "END",
},
});
createOpenAISubclassTests(SambaNova, {
providerName: "sambanova",
defaultApiBase: "https://api.sambanova.ai/v1/",
});
createOpenAISubclassTests(Scaleway, {
providerName: "scaleway",
defaultApiBase: "https://api.scaleway.ai/v1/",
});
createOpenAISubclassTests(Venice, {
providerName: "venice",
defaultApiBase: "https://api.venice.ai/api/v1/",
});
createOpenAISubclassTests(Moonshot, {
providerName: "moonshot",
defaultApiBase: "https://api.moonshot.cn/v1/",
});
createOpenAISubclassTests(Novita, {
providerName: "novita",
defaultApiBase: "https://api.novita.ai/v3/openai/",
customStreamCompleteEndpoint: "completions",
});
createOpenAISubclassTests(SiliconFlow, {
providerName: "siliconflow",
defaultApiBase: "https://api.siliconflow.cn/v1/",
});
createOpenAISubclassTests(Kindo, {
providerName: "kindo",
defaultApiBase: "https://llm.kindo.ai/v1/",
});
createOpenAISubclassTests(Azure, {
providerName: "azure",
});
createOpenAISubclassTests(Inception, {
providerName: "inception",
defaultApiBase: "https://api.inceptionlabs.ai/v1/",
customBodyOptions: {
temperature: 0.0,
presence_penalty: 1.5,
stop: ["<|endoftext|>"],
},
});
createOpenAISubclassTests(Docker, {
providerName: "docker",
defaultApiBase: "http://localhost:12434/engines/v1/",
});
createOpenAISubclassTests(Voyage, {
providerName: "voyage",
defaultApiBase: "https://api.voyageai.com/v1/",
});
createOpenAISubclassTests(Vllm, {
providerName: "vllm",
defaultApiBase: "https://api.openai.com/v1/",
});
createOpenAISubclassTests(TextGenWebUI, {
providerName: "text-gen-webui",
defaultApiBase: "http://localhost:5000/v1/",
});
createOpenAISubclassTests(FunctionNetwork, {
providerName: "function-network",
defaultApiBase: "https://api.function.network/v1/",
customEmbeddingsHeaders: {
Authorization: "Bearer test-api-key",
"Content-Type": "application/json",
},
});
createOpenAISubclassTests(NCompass, {
providerName: "ncompass",
defaultApiBase: "https://api.ncompass.tech/v1/",
customEmbeddingsUrl: "https://api.gcp.ncompass.tech/v1/embeddings",
customEmbeddingsHeaders: {
Authorization: "Bearer test-api-key",
"Content-Type": "application/json",
},
customEmbeddingsBody: {
input: ["Hello", "World"],
model: "text-embedding-ada-002",
},
});
createOpenAISubclassTests(LlamaStack, {
providerName: "llamastack",
defaultApiBase: "http://localhost:8321/v1/openai/v1/",
});
createOpenAISubclassTests(Nebius, {
providerName: "nebius",
defaultApiBase: "https://api.studio.nebius.ai/v1/",
});
createOpenAISubclassTests(OVHcloud, {
providerName: "ovhcloud",
defaultApiBase: "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1/",
});

View file

@ -0,0 +1,427 @@
import { afterEach, describe, expect, test, vi } from "vitest";
import { ILLM } from "../../index.js";
import OpenAI from "./OpenAI.js";
interface LlmTestCase {
llm: ILLM;
methodToTest: keyof ILLM;
params: any[];
expectedRequest: {
url: string;
method: string;
headers?: Record<string, string>;
body?: Record<string, any>;
};
mockResponse?: any;
mockStream?: any[];
}
function createMockStream(mockStream: any[]) {
const encoder = new TextEncoder();
return new ReadableStream({
start(controller) {
for (const chunk of mockStream) {
controller.enqueue(
encoder.encode(
`data: ${
typeof chunk === "string" ? chunk : JSON.stringify(chunk)
}\n\n`,
),
);
}
controller.close();
},
});
}
function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
const mockFetch = vi.fn();
if (mockStream) {
const stream = createMockStream(mockStream);
mockFetch.mockResolvedValue(
new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
},
}),
);
} else {
mockFetch.mockResolvedValue(
new Response(JSON.stringify(mockResponse), {
headers: { "Content-Type": "application/json" },
}),
);
}
return mockFetch;
}
function setupReadableStreamPolyfill() {
// This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
// @ts-ignore
const originalFrom = ReadableStream.from;
// @ts-ignore
ReadableStream.from = (body) => {
if (body?.source) {
return body;
}
return originalFrom(body);
};
}
async function executeLlmMethod(
llm: ILLM,
methodToTest: keyof ILLM,
params: any[],
) {
if (typeof (llm as any)[methodToTest] !== "function") {
throw new Error(
`Method ${String(methodToTest)} does not exist on the LLM instance.`,
);
}
const result = await (llm as any)[methodToTest](...params);
if (result?.next) {
for await (const _ of result) {
}
}
}
function assertFetchCall(mockFetch: any, expectedRequest: any) {
expect(mockFetch).toHaveBeenCalledTimes(1);
const [url, options] = mockFetch.mock.calls[0];
expect(url.toString()).toBe(expectedRequest.url);
expect(options.method).toBe(expectedRequest.method);
if (expectedRequest.headers) {
expect(options.headers).toEqual(
expect.objectContaining(expectedRequest.headers),
);
}
if (expectedRequest.body) {
const actualBody = JSON.parse(options.body as string);
expect(actualBody).toEqual(expectedRequest.body);
}
}
async function runLlmTest(testCase: LlmTestCase) {
const {
llm,
methodToTest,
params,
expectedRequest,
mockResponse,
mockStream,
} = testCase;
const mockFetch = setupMockFetch(mockResponse, mockStream);
setupReadableStreamPolyfill();
(llm as any).fetch = mockFetch;
// Disable OpenAI adapter to use our custom fetch mock
(llm as any).useOpenAIAdapterFor = [];
await executeLlmMethod(llm, methodToTest, params);
assertFetchCall(mockFetch, expectedRequest);
}
describe("OpenAI", () => {
afterEach(() => {
vi.clearAllMocks();
});
test("streamChat should send a valid request", async () => {
const openai = new OpenAI({
apiKey: "test-api-key",
model: "gpt-4",
apiBase: "https://api.openai.com/v1/",
});
await runLlmTest({
llm: openai,
methodToTest: "streamChat",
params: [
[{ role: "user", content: "hello" }],
new AbortController().signal,
],
expectedRequest: {
url: "https://api.openai.com/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
model: "gpt-4",
messages: [{ role: "user", content: "hello" }],
stream: true,
max_tokens: 2048,
},
},
mockStream: [
{ choices: [{ delta: { content: "Hello" } }] },
{ choices: [{ delta: { content: " world" } }] },
],
});
});
test("chat should send a valid request", async () => {
const openai = new OpenAI({
apiKey: "test-api-key",
model: "gpt-4",
apiBase: "https://api.openai.com/v1/",
});
await runLlmTest({
llm: openai,
methodToTest: "chat",
params: [
[{ role: "user", content: "hello" }],
new AbortController().signal,
],
expectedRequest: {
url: "https://api.openai.com/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
model: "gpt-4",
messages: [{ role: "user", content: "hello" }],
stream: true,
max_tokens: 2048,
},
},
mockStream: [
{ choices: [{ delta: { content: "Hello" } }] },
{ choices: [{ delta: { content: " world" } }] },
],
});
});
test("streamComplete should send a valid request", async () => {
const openai = new OpenAI({
apiKey: "test-api-key",
model: "gpt-4",
apiBase: "https://api.openai.com/v1/",
});
await runLlmTest({
llm: openai,
methodToTest: "streamComplete",
params: ["Hello", new AbortController().signal],
expectedRequest: {
url: "https://api.openai.com/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
model: "gpt-4",
messages: [{ role: "user", content: "Hello" }],
stream: true,
max_tokens: 2048,
},
},
mockStream: [
{ choices: [{ delta: { content: "Hello" } }] },
{ choices: [{ delta: { content: " world" } }] },
],
});
});
test("complete should send a valid request", async () => {
const openai = new OpenAI({
apiKey: "test-api-key",
model: "gpt-4",
apiBase: "https://api.openai.com/v1/",
});
await runLlmTest({
llm: openai,
methodToTest: "complete",
params: ["Hello", new AbortController().signal],
expectedRequest: {
url: "https://api.openai.com/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
model: "gpt-4",
messages: [{ role: "user", content: "Hello" }],
stream: true,
max_tokens: 2048,
},
},
mockStream: [
{ choices: [{ delta: { content: "Hello" } }] },
{ choices: [{ delta: { content: " world" } }] },
],
});
});
test("should handle O1 models correctly", async () => {
const openai = new OpenAI({
apiKey: "test-api-key",
model: "o1-preview",
apiBase: "https://api.openai.com/v1/",
});
await runLlmTest({
llm: openai,
methodToTest: "chat",
params: [
[{ role: "user", content: "hello" }],
new AbortController().signal,
{ maxTokens: 100 },
],
expectedRequest: {
url: "https://api.openai.com/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
model: "o1-preview",
messages: [{ role: "user", content: "hello" }],
stream: true,
max_completion_tokens: 100,
},
},
mockStream: [{ choices: [{ delta: { content: "Hello world" } }] }],
});
});
test("should handle tools", async () => {
const openai = new OpenAI({
apiKey: "test-api-key",
model: "gpt-4",
apiBase: "https://api.openai.com/v1/",
});
const tools = [
{
type: "function" as const,
function: {
name: "test_function",
description: "Test function",
parameters: { type: "object", properties: {} },
},
},
];
await runLlmTest({
llm: openai,
methodToTest: "chat",
params: [
[{ role: "user", content: "hello" }],
new AbortController().signal,
{ tools },
],
expectedRequest: {
url: "https://api.openai.com/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
model: "gpt-4",
messages: [{ role: "user", content: "hello" }],
stream: true,
max_tokens: 2048,
tools: [
{
type: "function",
function: {
name: "test_function",
description: "Test function",
parameters: { type: "object", properties: {} },
},
},
],
},
},
mockStream: [{ choices: [{ delta: { content: "I'll help you" } }] }],
});
});
test("should handle custom max tokens", async () => {
const openai = new OpenAI({
apiKey: "test-api-key",
model: "gpt-4",
apiBase: "https://api.openai.com/v1/",
});
await runLlmTest({
llm: openai,
methodToTest: "chat",
params: [
[{ role: "user", content: "hello" }],
new AbortController().signal,
{ maxTokens: 500 },
],
expectedRequest: {
url: "https://api.openai.com/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
model: "gpt-4",
messages: [{ role: "user", content: "hello" }],
stream: true,
max_tokens: 500,
},
},
mockStream: [{ choices: [{ delta: { content: "Hello" } }] }],
});
});
test("should handle embeddings", async () => {
const openai = new OpenAI({
apiKey: "test-api-key",
model: "text-embedding-ada-002",
apiBase: "https://api.openai.com/v1/",
});
await runLlmTest({
llm: openai,
methodToTest: "embed",
params: [["Hello", "World"]],
expectedRequest: {
url: "https://api.openai.com/v1/embeddings",
method: "POST",
headers: {
Authorization: "Bearer test-api-key",
"Content-Type": "application/json",
"api-key": "test-api-key",
},
body: {
input: ["Hello", "World"],
model: "text-embedding-ada-002",
},
},
mockResponse: {
data: [{ embedding: [0.1, 0.2, 0.3] }, { embedding: [0.4, 0.5, 0.6] }],
},
});
});
});

View file

@ -6,7 +6,7 @@ import OpenAI from "./OpenAI";
class Venice extends OpenAI {
static providerName = "venice";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.venice.ai/api/v1",
apiBase: "https://api.venice.ai/api/v1/",
};
protected _convertArgs(

View file

@ -1,9 +1,12 @@
import { streamResponse, streamSse } from "@continuedev/fetch";
import {
AssistantChatMessage,
ChatMessage,
Chunk,
CompletionOptions,
LLMOptions,
ToolCallDelta,
ToolResultChatMessage,
} from "../../index.js";
import { BaseLLM } from "../index.js";
import { fromChatCompletionChunk } from "../openaiTypeConverters.js";
@ -89,30 +92,24 @@ class WatsonX extends BaseLLM {
static providerName = "watsonx";
protected _convertMessage(message: ChatMessage) {
if (typeof message.content === "string") {
return message;
let message_ = message as any;
if (message_.role === "tool") {
message_.tool_call_id = (message as ToolResultChatMessage).toolCallId;
delete message_.toolCallId;
} else if (message.role === "assistant" && !!message.toolCalls) {
message_.tool_calls = message.toolCalls.map((t) => ({
...t,
type: "function",
}));
delete message_.toolCalls;
delete message_.content;
} else if (
message_.role === "user" &&
typeof message_.content === "string"
) {
message_.content = [{ type: "text", text: message_.content }];
}
if (message.role === "tool") {
return null;
}
const parts = message.content.map((part) => {
if (part.type === "imageUrl") {
return {
type: "image_url",
image_url: { ...part.imageUrl, detail: "low" },
};
}
return {
type: "text",
text: part.text,
};
});
return {
...message,
content: parts,
};
return message_;
}
protected _convertArgs(options: any, messages: ChatMessage[]) {
@ -257,11 +254,11 @@ class WatsonX extends BaseLLM {
const headers = this._getHeaders();
const payload: any = {
messages: messages,
messages: messages.map(this._convertMessage).filter(Boolean),
max_tokens: options.maxTokens ?? 1024,
stop: stopSequences,
frequency_penalty: options.frequencyPenalty || 1,
presence_penalty: options.presencePenalty || 1,
frequency_penalty: options.frequencyPenalty ?? 0,
presence_penalty: options.presencePenalty ?? 0,
};
if (!this.deploymentId) {
@ -291,10 +288,53 @@ class WatsonX extends BaseLLM {
signal,
});
let toolName;
let toolCallId = null;
let accumulatedArgs = "";
for await (const value of streamSse(response)) {
const chunk = fromChatCompletionChunk(value);
if (chunk) {
yield chunk;
const message = fromChatCompletionChunk(value);
if (!!message) {
if (
(message as AssistantChatMessage)?.toolCalls &&
(message as AssistantChatMessage).toolCalls?.length !== 0
) {
let chunk = message as AssistantChatMessage;
if (!!chunk.toolCalls?.[0]?.id) {
toolCallId = chunk.toolCalls?.[0]?.id;
}
if (!!chunk.toolCalls?.[0]?.function?.name) {
accumulatedArgs = "";
toolName = chunk.toolCalls[0].function.name;
continue;
}
if (!!toolName) {
if (value?.choices?.[0]?.finish_reason === "tool_calls") {
// If final assistant message has "tool_calls" as finish_reason
let args: string | undefined;
try {
accumulatedArgs += chunk.toolCalls?.[0]?.function?.arguments;
// Check if accumulated argument chunks are parsable
args = JSON.stringify(JSON.parse(accumulatedArgs));
} catch (e) {
// Otherwise use arguments from final assistant tool call message
args = chunk.toolCalls?.[0]?.function?.arguments;
}
const toolCall = {
function: { name: toolName, arguments: args },
id: toolCallId,
};
chunk.toolCalls = [toolCall as ToolCallDelta];
} else {
if (!!chunk.toolCalls?.[0]?.function?.arguments)
accumulatedArgs += chunk.toolCalls?.[0]?.function?.arguments;
continue;
}
}
yield chunk;
} else {
yield message;
}
}
}
}

View file

@ -0,0 +1,93 @@
import { expect, jest } from "@jest/globals";
import { ILLM } from "../../index.js";
export interface LlmTestCase {
llm: ILLM;
methodToTest: keyof ILLM;
params: any[];
expectedRequest: {
url: string;
method: string;
headers?: Record<string, string>;
body?: Record<string, any>;
};
mockResponse?: any;
mockStream?: string[]; // array of string chunks for SSE
}
export async function runLlmTest(testCase: LlmTestCase) {
const {
llm,
methodToTest,
params,
expectedRequest,
mockResponse,
mockStream,
} = testCase;
const mockFetch = jest.fn<any>();
if (mockStream) {
const encoder = new TextEncoder();
let streamIndex = 0;
mockFetch.mockResolvedValue(
new Response(
new ReadableStream({
start(controller) {
mockStream.forEach((chunk) => {
controller.enqueue(new TextEncoder().encode(chunk));
});
controller.close();
},
}),
{
headers: {
"Content-Type": "text/event-stream",
},
},
),
);
} else {
mockFetch.mockResolvedValue(
new Response(JSON.stringify(mockResponse), {
headers: {
"Content-Type": "application/json",
},
}),
);
}
// @ts-ignore
llm.fetch = mockFetch;
// @ts-ignore
if (typeof llm[methodToTest] !== "function") {
throw new Error(
`Method ${String(methodToTest)} does not exist on the LLM instance.`,
);
}
// @ts-ignore
const result = await llm[methodToTest](...params);
if (mockStream) {
// Consume the stream to ensure it's processed correctly
for await (const _ of result) {
}
}
expect(mockFetch).toHaveBeenCalledTimes(1);
const [url, options] = mockFetch.mock.calls[0] as [string, RequestInit];
expect(url.toString()).toBe(expectedRequest.url);
expect(options.method).toBe(expectedRequest.method);
if (expectedRequest.headers) {
expect(options.headers).toEqual(expectedRequest.headers);
}
if (expectedRequest.body) {
const actualBody = JSON.parse(options.body as string);
expect(actualBody).toEqual(expectedRequest.body);
}
}

View file

@ -11,6 +11,7 @@ import OpenAI from "../OpenAI.js";
import type { Chunk, LLMOptions } from "../../../index.js";
import { LLMConfigurationStatuses } from "../../constants.js";
import { LlmApiRequestType } from "../../openaiTypeConverters.js";
class ContinueProxy extends OpenAI {
set controlPlaneProxyInfo(value: ControlPlaneProxyInfo) {
@ -23,6 +24,8 @@ class ContinueProxy extends OpenAI {
}
}
protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = [];
// The apiKey and apiBase are set to the values for the proxy,
// but we need to keep track of the actual values that the proxy will use
// to call whatever LLM API is chosen

View file

@ -0,0 +1,758 @@
import { afterEach, describe, expect, test, vi } from "vitest";
import { ILLM } from "../../../index.js";
import ContinueProxy from "./ContinueProxy.js";
vi.mock("@continuedev/config-yaml", async (importOriginal) => {
const mod = (await importOriginal()) as any;
return {
...mod,
parseProxyModelName: vi.fn(() => ({
provider: "test-provider",
model: "test-model",
ownerSlug: "test-owner",
packageSlug: "test-package",
})),
};
});
interface LlmTestCase {
llm: ILLM;
methodToTest: keyof ILLM;
params: any[];
expectedRequest: {
url: string;
method: string;
headers?: Record<string, string>;
body?: Record<string, any>;
};
mockResponse?: any;
mockStream?: any[];
}
function createMockStream(mockStream: any[]) {
const encoder = new TextEncoder();
return new ReadableStream({
start(controller) {
for (const chunk of mockStream) {
controller.enqueue(
encoder.encode(
`data: ${
typeof chunk === "string" ? chunk : JSON.stringify(chunk)
}\n\n`,
),
);
}
controller.close();
},
});
}
function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
const mockFetch = vi.fn();
if (mockStream) {
const stream = createMockStream(mockStream);
mockFetch.mockResolvedValue(
new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
},
}),
);
} else {
mockFetch.mockResolvedValue(
new Response(JSON.stringify(mockResponse), {
headers: { "Content-Type": "application/json" },
}),
);
}
return mockFetch;
}
function setupReadableStreamPolyfill() {
// This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
// @ts-ignore
const originalFrom = ReadableStream.from;
// @ts-ignore
ReadableStream.from = (body) => {
if (body?.source) {
return body;
}
return originalFrom(body);
};
}
async function executeLlmMethod(
llm: ILLM,
methodToTest: keyof ILLM,
params: any[],
) {
if (typeof (llm as any)[methodToTest] !== "function") {
throw new Error(
`Method ${String(methodToTest)} does not exist on the LLM instance.`,
);
}
const result = await (llm as any)[methodToTest](...params);
if (result?.next) {
for await (const _ of result) {
}
}
}
function assertFetchCall(mockFetch: any, expectedRequest: any) {
expect(mockFetch).toHaveBeenCalledTimes(1);
const [url, options] = mockFetch.mock.calls[0];
expect(url.toString()).toBe(expectedRequest.url);
expect(options.method).toBe(expectedRequest.method);
if (expectedRequest.headers) {
expect(options.headers).toEqual(
expect.objectContaining(expectedRequest.headers),
);
}
if (expectedRequest.body) {
const actualBody = JSON.parse(options.body as string);
expect(actualBody).toEqual(expectedRequest.body);
}
}
async function runLlmTest(testCase: LlmTestCase) {
const {
llm,
methodToTest,
params,
expectedRequest,
mockResponse,
mockStream,
} = testCase;
const mockFetch = setupMockFetch(mockResponse, mockStream);
setupReadableStreamPolyfill();
(llm as any).fetch = mockFetch;
await executeLlmMethod(llm, methodToTest, params);
assertFetchCall(mockFetch, expectedRequest);
}
describe("ContinueProxy", () => {
afterEach(() => {
vi.clearAllMocks();
});
test("rerank should send a valid request", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "rerank",
params: [
"test query",
[{ content: "document1" }, { content: "document2" }],
],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/rerank",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
},
body: {
query: "test query",
documents: ["document1", "document2"],
model: "test-model",
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
orgScopeId: null,
},
},
},
mockResponse: {
data: [
{ index: 0, relevance_score: 0.9 },
{ index: 1, relevance_score: 0.1 },
],
},
});
});
test("streamChat should send a valid request", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "streamChat",
params: [[{ role: "user", content: "hello" }]],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
"x-continue-unique-id": "NOT_UNIQUE",
},
body: {
model: "test-model",
messages: [{ role: "user", content: "hello" }],
max_tokens: 4096,
stream: true,
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
orgScopeId: null,
},
},
},
mockStream: [
'{"choices": [{"delta": {"content": "response"}}]}',
"[DONE]",
],
});
});
test("chat should send a valid request", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "chat",
params: [[{ role: "user", content: "hello" }]],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
"x-continue-unique-id": "NOT_UNIQUE",
},
body: {
model: "test-model",
messages: [{ role: "user", content: "hello" }],
max_tokens: 4096,
stream: true,
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
orgScopeId: null,
},
},
},
mockStream: [
'{"choices": [{"delta": {"content": "Hello! How can I help you today?"}}]}',
"[DONE]",
],
});
});
test("streamComplete should send a valid request", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "streamComplete",
params: ["Complete this: Hello"],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
"x-continue-unique-id": "NOT_UNIQUE",
},
body: {
model: "test-model",
messages: [{ role: "user", content: "Complete this: Hello" }],
max_tokens: 4096,
stream: true,
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
orgScopeId: null,
},
},
},
mockStream: [
'{"choices": [{"delta": {"content": " world!"}}]}',
"[DONE]",
],
});
});
test("complete should send a valid request", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "complete",
params: ["Complete this: Hello"],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
"x-continue-unique-id": "NOT_UNIQUE",
},
body: {
model: "test-model",
messages: [{ role: "user", content: "Complete this: Hello" }],
max_tokens: 4096,
stream: true,
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
orgScopeId: null,
},
},
},
mockStream: [
'{"choices": [{"delta": {"content": " world!"}}]}',
"[DONE]",
],
});
});
test("streamFim should send a valid request", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "streamFim",
params: ["function test() {\n ", "\n}"],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/fim/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"x-api-key": "test-api-key",
Authorization: "Bearer test-api-key",
},
body: {
model: "test-model",
prompt: "function test() {\n ",
suffix: "\n}",
max_tokens: 4096,
stream: true,
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
orgScopeId: null,
},
},
},
mockStream: [
'{"choices": [{"delta": {"content": "console.log("Hello");"}}]}',
"[DONE]",
],
});
});
test("embed should send a valid request", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "embed",
params: [["text to embed", "another text"]],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/embeddings",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
input: ["text to embed", "another text"],
model: "test-model",
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
orgScopeId: null,
},
},
},
mockResponse: {
data: [{ embedding: [0.1, 0.2, 0.3] }, { embedding: [0.4, 0.5, 0.6] }],
},
});
});
test("listModels should send a valid request", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "listModels",
params: [],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/models",
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
},
mockResponse: {
data: [{ id: "gpt-4" }, { id: "gpt-3.5-turbo" }],
},
});
});
describe("Different provider configurations", () => {
test("should handle on-prem proxy URL", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
onPremProxyUrl: "https://my-proxy.company.com/",
});
await runLlmTest({
llm: proxy,
methodToTest: "rerank",
params: [
"test query",
[{ content: "document1" }, { content: "document2" }],
],
expectedRequest: {
url: "https://my-proxy.company.com/model-proxy/v1/rerank",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
},
body: {
query: "test query",
documents: ["document1", "document2"],
model: "test-model",
continueProperties: {
apiBase: undefined,
apiKeyLocation: undefined,
env: undefined,
envSecretLocations: undefined,
orgScopeId: null,
},
},
},
mockResponse: {
data: [
{ index: 0, relevance_score: 0.9 },
{ index: 1, relevance_score: 0.1 },
],
},
});
});
test("should handle environment variables", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
env: {
CUSTOM_VAR: "custom-value",
ANOTHER_VAR: "another-value",
},
});
await runLlmTest({
llm: proxy,
methodToTest: "streamChat",
params: [[{ role: "user", content: "hello" }]],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
"x-continue-unique-id": "NOT_UNIQUE",
},
body: {
model: "test-model",
messages: [{ role: "user", content: "hello" }],
max_tokens: 4096,
stream: true,
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
env: {
CUSTOM_VAR: "custom-value",
ANOTHER_VAR: "another-value",
},
orgScopeId: null,
},
},
},
mockStream: [
'{"choices": [{"delta": {"content": "response"}}]}',
"[DONE]",
],
});
});
test("should handle API key location", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
apiKeyLocation: "env:OPENAI_API_KEY",
});
await runLlmTest({
llm: proxy,
methodToTest: "embed",
params: [["test text"]],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/embeddings",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
input: ["test text"],
model: "test-model",
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
apiKeyLocation: "env:OPENAI_API_KEY",
env: undefined,
envSecretLocations: undefined,
orgScopeId: null,
},
},
},
mockResponse: {
data: [{ embedding: [0.1, 0.2, 0.3] }],
},
});
});
test("should handle env secret locations", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
envSecretLocations: {
AZURE_API_KEY: "env:AZURE_API_KEY",
AZURE_ENDPOINT: "env:AZURE_ENDPOINT",
},
});
await runLlmTest({
llm: proxy,
methodToTest: "streamFim",
params: ["const x = ", ";"],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/fim/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"x-api-key": "test-api-key",
Authorization: "Bearer test-api-key",
},
body: {
model: "test-model",
prompt: "const x = ",
suffix: ";",
max_tokens: 4096,
stream: true,
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
envSecretLocations: {
AZURE_API_KEY: "env:AZURE_API_KEY",
AZURE_ENDPOINT: "env:AZURE_ENDPOINT",
},
orgScopeId: null,
},
},
},
mockStream: ['{"choices": [{"delta": {"content": "42"}}]}', "[DONE]"],
});
});
test("should handle organization scope ID", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
orgScopeId: "org_12345",
});
await runLlmTest({
llm: proxy,
methodToTest: "listModels",
params: [],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/models",
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
},
mockResponse: {
data: [{ id: "gpt-4" }],
},
});
});
});
describe("Edge cases", () => {
test("should handle empty chunks array for rerank", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "rerank",
params: ["test query", []],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/rerank",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
},
body: {
query: "test query",
documents: [],
model: "test-model",
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
apiKeyLocation: undefined,
env: undefined,
envSecretLocations: undefined,
orgScopeId: null,
},
},
},
mockResponse: {
data: [],
},
});
});
test("should handle complex chat messages", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
const complexMessages = [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Hello!" },
{ role: "assistant", content: "Hi there! How can I help you today?" },
{ role: "user", content: "What's the weather like?" },
];
await runLlmTest({
llm: proxy,
methodToTest: "streamChat",
params: [complexMessages],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
"x-continue-unique-id": "NOT_UNIQUE",
},
body: {
model: "test-model",
messages: complexMessages,
max_tokens: 4096,
stream: true,
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
orgScopeId: null,
},
},
},
mockStream: [
'{"choices": [{"delta": {"content": "I don\'t have access to current weather data."}}]}',
"[DONE]",
],
});
});
test("should handle single embedding chunk", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "embed",
params: [["single text"]],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/embeddings",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
input: ["single text"],
model: "test-model",
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
apiKeyLocation: undefined,
env: undefined,
envSecretLocations: undefined,
orgScopeId: null,
},
},
},
mockResponse: {
data: [{ embedding: [0.1, 0.2, 0.3] }],
},
});
});
});
});

View file

@ -0,0 +1,375 @@
import { afterEach, describe, expect, test, vi } from "vitest";
import { ILLM } from "../../../index.js";
import OpenAI from "../OpenAI.js";
interface LlmTestCase {
llm: ILLM;
methodToTest: keyof ILLM;
params: any[];
expectedRequest: {
url: string;
method: string;
headers?: Record<string, string>;
body?: Record<string, any>;
};
mockResponse?: any;
mockStream?: any[];
}
function createMockStream(mockStream: any[]) {
const encoder = new TextEncoder();
return new ReadableStream({
start(controller) {
for (const chunk of mockStream) {
controller.enqueue(
encoder.encode(
`data: ${
typeof chunk === "string" ? chunk : JSON.stringify(chunk)
}\n\n`,
),
);
}
controller.close();
},
});
}
function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
const mockFetch = vi.fn();
if (mockStream) {
const stream = createMockStream(mockStream);
mockFetch.mockResolvedValue(
new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
},
}),
);
} else {
mockFetch.mockResolvedValue(
new Response(JSON.stringify(mockResponse), {
headers: { "Content-Type": "application/json" },
}),
);
}
return mockFetch;
}
function setupReadableStreamPolyfill() {
// This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
// @ts-ignore
const originalFrom = ReadableStream.from;
// @ts-ignore
ReadableStream.from = (body) => {
if (body?.source) {
return body;
}
return originalFrom(body);
};
}
async function executeLlmMethod(
llm: ILLM,
methodToTest: keyof ILLM,
params: any[],
) {
if (typeof (llm as any)[methodToTest] !== "function") {
throw new Error(
`Method ${String(methodToTest)} does not exist on the LLM instance.`,
);
}
const result = await (llm as any)[methodToTest](...params);
if (result?.next) {
for await (const _ of result) {
}
}
}
function assertFetchCall(mockFetch: any, expectedRequest: any) {
expect(mockFetch).toHaveBeenCalledTimes(1);
const [url, options] = mockFetch.mock.calls[0];
expect(url.toString()).toBe(expectedRequest.url);
expect(options.method).toBe(expectedRequest.method);
if (expectedRequest.headers) {
expect(options.headers).toEqual(
expect.objectContaining(expectedRequest.headers),
);
}
if (expectedRequest.body) {
const actualBody = JSON.parse(options.body as string);
expect(actualBody).toEqual(expectedRequest.body);
}
}
async function runLlmTest(testCase: LlmTestCase) {
const {
llm,
methodToTest,
params,
expectedRequest,
mockResponse,
mockStream,
} = testCase;
const mockFetch = setupMockFetch(mockResponse, mockStream);
setupReadableStreamPolyfill();
(llm as any).fetch = mockFetch;
// Disable OpenAI adapter to use our custom fetch mock
(llm as any).useOpenAIAdapterFor = [];
await executeLlmMethod(llm, methodToTest, params);
assertFetchCall(mockFetch, expectedRequest);
}
export interface OpenAISubclassConfig {
providerName: string;
defaultApiBase?: string;
modelConversions?: { [key: string]: string };
customOptions?: any;
modelConversionContent?: string;
modelConversionMaxTokens?: number;
customStreamCompleteEndpoint?: string;
customEmbeddingsUrl?: string;
customEmbeddingsHeaders?: { [key: string]: string };
customEmbeddingsBody?: any;
customBodyOptions?: any;
}
function getExpectedUrl(
config: OpenAISubclassConfig,
endpoint: string,
model: string = "gpt-4",
) {
let baseUrl = config.defaultApiBase || "https://api.openai.com/v1/";
if (config.providerName === "azure") {
return `${baseUrl}openai/deployments/${model}/${endpoint}?api-version=2023-07-01-preview`;
} else if (config.providerName === "ncompass") {
return `${baseUrl}${endpoint}`;
}
return `${baseUrl}${endpoint}`;
}
export const createOpenAISubclassTests = (
ProviderClass: typeof OpenAI,
config: OpenAISubclassConfig,
) => {
describe(config.providerName, () => {
afterEach(() => {
vi.clearAllMocks();
});
test("should have correct provider name", () => {
expect(ProviderClass.providerName).toBe(config.providerName);
});
if (config.defaultApiBase) {
test("should have correct default API base", () => {
expect(ProviderClass.defaultOptions?.apiBase).toBe(
config.defaultApiBase,
);
});
}
test("streamChat should send a valid request", async () => {
const provider = new ProviderClass({
apiKey: "test-api-key",
model: "gpt-4",
apiBase: config.defaultApiBase || "https://api.openai.com/v1/",
});
await runLlmTest({
llm: provider,
methodToTest: "streamChat",
params: [
[{ role: "user", content: "hello" }],
new AbortController().signal,
],
expectedRequest: {
url: getExpectedUrl(config, "chat/completions"),
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
model: "gpt-4",
messages: [{ role: "user", content: "hello" }],
stream: true,
max_tokens: 2048,
...config.customBodyOptions,
},
},
mockStream: [
{ choices: [{ delta: { content: "Hello" } }] },
{ choices: [{ delta: { content: " world" } }] },
],
});
});
test("chat should send a valid request", async () => {
const provider = new ProviderClass({
apiKey: "test-api-key",
model: "gpt-4",
apiBase: config.defaultApiBase || "https://api.openai.com/v1/",
});
await runLlmTest({
llm: provider,
methodToTest: "chat",
params: [
[{ role: "user", content: "hello" }],
new AbortController().signal,
],
expectedRequest: {
url: getExpectedUrl(config, "chat/completions"),
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
model: "gpt-4",
messages: [{ role: "user", content: "hello" }],
stream: true,
max_tokens: 2048,
...config.customBodyOptions,
},
},
mockStream: [
{ choices: [{ delta: { content: "Hello" } }] },
{ choices: [{ delta: { content: " world" } }] },
],
});
});
test("streamComplete should send a valid request", async () => {
const provider = new ProviderClass({
apiKey: "test-api-key",
model: "gpt-4",
apiBase: config.defaultApiBase || "https://api.openai.com/v1/",
});
await runLlmTest({
llm: provider,
methodToTest: "streamComplete",
params: ["Hello", new AbortController().signal],
expectedRequest: {
url: getExpectedUrl(
config,
config.customStreamCompleteEndpoint || "chat/completions",
),
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body:
config.customStreamCompleteEndpoint === "completions"
? {
model: "gpt-4",
prompt: "Hello",
stream: true,
max_tokens: 2048,
...config.customBodyOptions,
}
: {
model: "gpt-4",
messages: [{ role: "user", content: "Hello" }],
stream: true,
max_tokens: 2048,
...config.customBodyOptions,
},
},
mockStream: [
{ choices: [{ delta: { content: "Hello" } }] },
{ choices: [{ delta: { content: " world" } }] },
],
});
});
test("complete should send a valid request", async () => {
const provider = new ProviderClass({
apiKey: "test-api-key",
model: "gpt-4",
apiBase: config.defaultApiBase || "https://api.openai.com/v1/",
});
await runLlmTest({
llm: provider,
methodToTest: "complete",
params: ["Hello", new AbortController().signal],
expectedRequest: {
url: getExpectedUrl(config, "chat/completions"),
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
model: "gpt-4",
messages: [{ role: "user", content: "Hello" }],
stream: true,
max_tokens: 2048,
...config.customBodyOptions,
},
},
mockStream: [
{ choices: [{ delta: { content: "Hello" } }] },
{ choices: [{ delta: { content: " world" } }] },
],
});
});
test("should handle embeddings", async () => {
const provider = new ProviderClass({
apiKey: "test-api-key",
model: "text-embedding-ada-002",
apiBase: config.defaultApiBase || "https://api.openai.com/v1/",
});
// Skip test if provider doesn't support embeddings (e.g., ncompass with undefined endpoint)
if (config.providerName === "ncompass" && !config.customEmbeddingsUrl) {
return;
}
await runLlmTest({
llm: provider,
methodToTest: "embed",
params: [["Hello", "World"]],
expectedRequest: {
url:
config.customEmbeddingsUrl ||
`${config.defaultApiBase || "https://api.openai.com/v1/"}embeddings`,
method: "POST",
headers: config.customEmbeddingsHeaders || {
Authorization: "Bearer test-api-key",
"Content-Type": "application/json",
"api-key": "test-api-key",
},
body: config.customEmbeddingsBody || {
input: ["Hello", "World"],
model: "text-embedding-ada-002",
},
},
mockResponse: {
data: [
{ embedding: [0.1, 0.2, 0.3] },
{ embedding: [0.4, 0.5, 0.6] },
],
},
});
});
});
};

View file

@ -44,6 +44,7 @@ describe("LLMLogFormatter", () => {
content: "You are a helpful assistant",
},
],
provider: "watsonx",
});
logger._logItem({
interactionId: "1",
@ -79,6 +80,7 @@ describe("LLMLogFormatter", () => {
promptTokens: 10,
generatedTokens: 20,
thinkingTokens: 0,
usage: undefined,
});
expect(output.getText()).toBe(
@ -113,6 +115,7 @@ describe("LLMLogFormatter", () => {
model: "granite3.2-dense:8b",
},
prompt: "A horse is a horse",
provider: "watsonx",
});
logger._logItem({
interactionId: "1",
@ -149,6 +152,7 @@ describe("LLMLogFormatter", () => {
},
prefix: "A\nB",
suffix: "D\nE",
provider: "watsonx",
});
logger._logItem({
interactionId: "1",
@ -225,6 +229,7 @@ describe("LLMLogFormatter", () => {
promptTokens: 10,
generatedTokens: 20,
thinkingTokens: 0,
usage: undefined,
});
logger._logItem({
interactionId: "3",

View file

@ -1,104 +0,0 @@
import { ChatMessage } from "..";
import { flattenMessages } from "./messages";
describe("flattenMessages", () => {
it("should return an empty array when given an empty array", () => {
expect(flattenMessages([])).toEqual([]);
});
it("should return the same array when there is only one message", () => {
const messages: ChatMessage[] = [{ role: "user", content: "Hello" }];
expect(flattenMessages(messages)).toEqual(messages);
});
it("should return the same array when messages have different roles", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "Hello" },
{ role: "assistant", content: "Hi there!" },
{ role: "user", content: "How are you?" },
];
expect(flattenMessages(messages)).toEqual(messages);
});
it("should combine consecutive messages with the same role", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "Hello" },
{ role: "user", content: "How are you?" },
{ role: "assistant", content: "I am an AI assistant." },
{ role: "assistant", content: "How can I help you?" },
];
const expected: ChatMessage[] = [
{ role: "user", content: "Hello\n\nHow are you?" },
{
role: "assistant",
content: "I am an AI assistant.\n\nHow can I help you?",
},
];
expect(flattenMessages(messages)).toEqual(expected);
});
it("should handle messages with undefined or empty content", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "Hello" },
{ role: "user", content: "" },
{ role: "assistant", content: "" },
{ role: "assistant", content: "Sure, I can help with that." },
];
const expected: ChatMessage[] = [
{ role: "user", content: "Hello\n\n" },
{ role: "assistant", content: "\n\nSure, I can help with that." },
];
expect(flattenMessages(messages)).toEqual(expected);
});
it("should not combine non-consecutive messages with the same role", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "First message" },
{ role: "assistant", content: "Reply to first message" },
{ role: "user", content: "Second message" },
];
expect(flattenMessages(messages)).toEqual(messages);
});
it("should handle a mix of message roles and contents correctly", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "Message one" },
{ role: "user", content: "Message two" },
{ role: "assistant", content: "Reply one" },
{ role: "user", content: "Message three" },
{ role: "user", content: "Message four" },
{ role: "assistant", content: "Reply two" },
];
const expected: ChatMessage[] = [
{ role: "user", content: "Message one\n\nMessage two" },
{ role: "assistant", content: "Reply one" },
{ role: "user", content: "Message three\n\nMessage four" },
{ role: "assistant", content: "Reply two" },
];
expect(flattenMessages(messages)).toEqual(expected);
});
it("should not combine adjacent assistant messages when one of them is a tool call", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "What's the capital of France?" },
{ role: "assistant", content: "Paris" },
{
role: "assistant",
content: " ",
toolCalls: [
{
id: "test",
type: "function",
function: {
name: "getCapital",
arguments: JSON.stringify({
country: "France",
}),
},
},
],
},
];
expect(flattenMessages(messages).length).toBe(3);
});
});

View file

@ -4,27 +4,6 @@ export function messageHasToolCalls(msg: ChatMessage): boolean {
return msg.role === "assistant" && !!msg.toolCalls;
}
export function flattenMessages(msgs: ChatMessage[]): ChatMessage[] {
const flattened: ChatMessage[] = [];
for (let i = 0; i < msgs.length; i++) {
const msg = msgs[i];
if (
flattened.length > 0 &&
flattened[flattened.length - 1].role === msg.role &&
!messageHasToolCalls(msg) &&
!messageHasToolCalls(flattened[flattened.length - 1])
) {
flattened[flattened.length - 1].content += `\n\n${msg.content || ""}`;
} else {
flattened.push(msg);
}
}
return flattened;
}
export function messageIsEmpty(message: ChatMessage): boolean {
if (typeof message.content === "string") {
return message.content.trim() === "";

View file

@ -9,7 +9,7 @@ describe("Rule colocation - glob pattern matching", () => {
generalRule: {
name: "General Rule",
rule: "Follow coding standards",
source: "rules-block",
source: "colocated-markdown",
ruleFile: "src/rules.md",
},
@ -18,7 +18,7 @@ describe("Rule colocation - glob pattern matching", () => {
name: "Redux Rule",
rule: "Use Redux Toolkit",
globs: "src/redux/**/*.{ts,tsx}",
source: "rules-block",
source: "colocated-markdown",
ruleFile: "src/redux/rules.md",
},
@ -27,7 +27,7 @@ describe("Rule colocation - glob pattern matching", () => {
name: "Component Rule",
rule: "Use functional components",
globs: ["src/components/**/*.tsx", "src/components/**/*.jsx"],
source: "rules-block",
source: "colocated-markdown",
ruleFile: "src/components/rules.md",
},
@ -37,7 +37,7 @@ describe("Rule colocation - glob pattern matching", () => {
rule: "Follow these guidelines always",
alwaysApply: true,
globs: "src/specific/**/*.ts", // Should be ignored since alwaysApply is true
source: "rules-block",
source: "colocated-markdown",
ruleFile: ".continue/rules.md",
},
@ -47,7 +47,7 @@ describe("Rule colocation - glob pattern matching", () => {
rule: "This rule should only apply to matching files",
alwaysApply: false,
// No globs, so should never apply
source: "rules-block",
source: "colocated-markdown",
ruleFile: ".continue/rules.md",
},
@ -57,7 +57,7 @@ describe("Rule colocation - glob pattern matching", () => {
rule: "Apply only to matching files",
alwaysApply: false,
globs: "src/utils/**/*.ts",
source: "rules-block",
source: "colocated-markdown",
ruleFile: "src/utils/rules.md",
},
};
@ -127,7 +127,7 @@ describe("Rule colocation - glob pattern matching", () => {
rule: "Follow nested module standards",
// Fix: Specify the exact path prefix to restrict to this directory structure
globs: "src/features/auth/utils/**/*.ts",
source: "rules-block",
source: "colocated-markdown",
ruleFile: "src/features/auth/utils/rules.md",
};
@ -157,7 +157,7 @@ describe("Rule colocation - glob pattern matching", () => {
// Note: Negative globs may not be supported by the current implementation
// Testing with standard pattern instead
globs: "src/**/[!.]*.ts",
source: "rules-block",
source: "colocated-markdown",
ruleFile: "src/rules.md",
};
@ -174,7 +174,7 @@ describe("Rule colocation - glob pattern matching", () => {
// Use a pattern that doesn't match test files
globs: ["src/**/*.ts", "!src/**/*.test.ts", "!src/**/*.spec.ts"],
alwaysApply: false,
source: "rules-block",
source: "colocated-markdown",
ruleFile: "src/rules.md",
};

View file

@ -24,7 +24,12 @@ export async function* llmStreamChat(
void TTS.kill();
}
const { legacySlashCommandData, completionOptions, messages } = msg.data;
const {
legacySlashCommandData,
completionOptions,
messages,
messageOptions,
} = msg.data;
const model = config.selectedModelByRole.chat;
@ -117,6 +122,7 @@ export async function* llmStreamChat(
messages,
abortController.signal,
completionOptions,
messageOptions,
);
let next = await gen.next();
while (!next.done) {

View file

@ -0,0 +1,181 @@
import { Usage } from "../..";
export interface CostBreakdown {
cost: number;
breakdown: string;
}
function calculateAnthropicCost(
model: string,
usage: Usage,
): CostBreakdown | null {
// Normalize model name to handle various formats
const normalizedModel = model.toLowerCase();
// Define pricing per million tokens (MTok)
const pricing: Record<
string,
{ input: number; output: number; cacheWrite: number; cacheRead: number }
> = {
// Claude Opus 4 (most intelligent model)
"claude-3-opus": {
input: 15,
output: 75,
cacheWrite: 18.75,
cacheRead: 1.5,
},
"claude-3-opus-20240229": {
input: 15,
output: 75,
cacheWrite: 18.75,
cacheRead: 1.5,
},
// Claude Sonnet 4 (optimal balance)
"claude-3-5-sonnet": {
input: 3,
output: 15,
cacheWrite: 3.75,
cacheRead: 0.3,
},
"claude-3-5-sonnet-20241022": {
input: 3,
output: 15,
cacheWrite: 3.75,
cacheRead: 0.3,
},
"claude-3-5-sonnet-20240620": {
input: 3,
output: 15,
cacheWrite: 3.75,
cacheRead: 0.3,
},
// Claude Haiku 3.5 (fastest, most cost-effective)
"claude-3-5-haiku": {
input: 0.8,
output: 4,
cacheWrite: 1,
cacheRead: 0.08,
},
"claude-3-5-haiku-20241022": {
input: 0.8,
output: 4,
cacheWrite: 1,
cacheRead: 0.08,
},
// Legacy Claude 3 Haiku
"claude-3-haiku": {
input: 0.25,
output: 1.25,
cacheWrite: 0.3,
cacheRead: 0.03,
},
"claude-3-haiku-20240307": {
input: 0.25,
output: 1.25,
cacheWrite: 0.3,
cacheRead: 0.03,
},
};
// Find matching pricing model
let modelPricing = pricing[normalizedModel];
// If exact match not found, try to find by partial match
if (!modelPricing) {
for (const [key, value] of Object.entries(pricing)) {
if (normalizedModel.includes(key) || key.includes(normalizedModel)) {
modelPricing = value;
break;
}
}
}
// If still no match, try common patterns
if (!modelPricing) {
if (normalizedModel.includes("opus")) {
modelPricing = pricing["claude-3-opus"];
} else if (normalizedModel.includes("sonnet")) {
modelPricing = pricing["claude-3-5-sonnet"];
} else if (normalizedModel.includes("haiku")) {
modelPricing = pricing["claude-3-5-haiku"];
}
}
if (!modelPricing) {
return null; // Unknown model
}
// Calculate costs
const inputCost = (usage.promptTokens / 1_000_000) * modelPricing.input;
const outputCost = (usage.completionTokens / 1_000_000) * modelPricing.output;
// Build breakdown components
const breakdownParts: string[] = [];
// Input tokens breakdown
if (usage.promptTokens > 0) {
breakdownParts.push(
`Input: ${usage.promptTokens.toLocaleString()} tokens × $${modelPricing.input}/MTok = $${inputCost.toFixed(6)}`,
);
}
// Output tokens breakdown
if (usage.completionTokens > 0) {
breakdownParts.push(
`Output: ${usage.completionTokens.toLocaleString()} tokens × $${modelPricing.output}/MTok = $${outputCost.toFixed(6)}`,
);
}
// Handle prompt caching costs if available
let cacheCost = 0;
if (usage.promptTokensDetails) {
const { cachedTokens, cacheWriteTokens } = usage.promptTokensDetails;
if (cacheWriteTokens && cacheWriteTokens > 0) {
const cacheWriteCost =
(cacheWriteTokens / 1_000_000) * modelPricing.cacheWrite;
cacheCost += cacheWriteCost;
breakdownParts.push(
`Cache Write: ${cacheWriteTokens.toLocaleString()} tokens × $${modelPricing.cacheWrite}/MTok = $${cacheWriteCost.toFixed(6)}`,
);
}
if (cachedTokens && cachedTokens > 0) {
const cacheReadCost = (cachedTokens / 1_000_000) * modelPricing.cacheRead;
cacheCost += cacheReadCost;
breakdownParts.push(
`Cache Read: ${cachedTokens.toLocaleString()} tokens × $${modelPricing.cacheRead}/MTok = $${cacheReadCost.toFixed(6)}`,
);
}
}
const totalCost = inputCost + outputCost + cacheCost;
// Build final breakdown string
let breakdown = `Model: ${model}\n`;
breakdown += breakdownParts.join("\n");
if (breakdownParts.length > 1) {
breakdown += `\nTotal: $${totalCost.toFixed(6)}`;
}
return {
cost: totalCost,
breakdown,
};
}
export function calculateRequestCost(
provider: string,
model: string,
usage: Usage,
): CostBreakdown | null {
switch (provider) {
case "anthropic":
return calculateAnthropicCost(model, usage);
default:
return null;
}
}

View file

@ -1,4 +1,4 @@
import { getSecureID } from "../getSecureID";
import { getSecureID } from "./getSecureID";
// Mock the crypto.randomUUID function
const mockRandomUUID = jest.fn();

View file

@ -0,0 +1,481 @@
import { retryAsync, withLLMRetry, withRetry } from "./retry";
// Mock console.warn to avoid noise in tests
const consoleSpy = jest.spyOn(console, "warn").mockImplementation(() => {});
describe("Retry Functionality", () => {
beforeEach(() => {
jest.clearAllMocks();
});
describe("retryAsync", () => {
it("should succeed on first attempt", async () => {
const mockFn = jest.fn().mockResolvedValue("success");
const result = await retryAsync(mockFn);
expect(result).toBe("success");
expect(mockFn).toHaveBeenCalledTimes(1);
});
it("should retry on retryable errors", async () => {
const error = new Error("ECONNRESET");
(error as any).code = "ECONNRESET";
const mockFn = jest
.fn()
.mockRejectedValueOnce(error)
.mockResolvedValue("success");
const result = await retryAsync(mockFn, {
maxAttempts: 2,
baseDelay: 10, // Very short delay for testing
});
expect(result).toBe("success");
expect(mockFn).toHaveBeenCalledTimes(2);
});
it("should not retry on non-retryable errors", async () => {
const error = new Error("Bad Request");
(error as any).status = 400;
const mockFn = jest.fn().mockRejectedValue(error);
await expect(retryAsync(mockFn)).rejects.toThrow("Bad Request");
expect(mockFn).toHaveBeenCalledTimes(1);
});
it("should respect max attempts", async () => {
const error = new Error("ECONNRESET");
(error as any).code = "ECONNRESET";
const mockFn = jest.fn().mockRejectedValue(error);
await expect(
retryAsync(mockFn, {
maxAttempts: 3,
baseDelay: 10,
}),
).rejects.toThrow("ECONNRESET");
expect(mockFn).toHaveBeenCalledTimes(3);
});
it("should throw the last error when all retries are exhausted", async () => {
const firstError = new Error("First error");
(firstError as any).code = "ECONNRESET";
const secondError = new Error("Second error");
(secondError as any).code = "ECONNRESET";
const lastError = new Error("Last error");
(lastError as any).code = "ECONNRESET";
const mockFn = jest
.fn()
.mockRejectedValueOnce(firstError)
.mockRejectedValueOnce(secondError)
.mockRejectedValueOnce(lastError);
await expect(
retryAsync(mockFn, {
maxAttempts: 3,
baseDelay: 10,
}),
).rejects.toThrow("Last error");
expect(mockFn).toHaveBeenCalledTimes(3);
});
it("should handle HTTP 429 errors", async () => {
const error = new Error("Too Many Requests");
(error as any).status = 429;
const mockFn = jest
.fn()
.mockRejectedValueOnce(error)
.mockResolvedValue("success");
const result = await retryAsync(mockFn, {
maxAttempts: 2,
baseDelay: 10,
});
expect(result).toBe("success");
expect(mockFn).toHaveBeenCalledTimes(2);
});
it("should handle HTTP 5xx errors", async () => {
const error = new Error("Internal Server Error");
(error as any).status = 500;
const mockFn = jest
.fn()
.mockRejectedValueOnce(error)
.mockResolvedValue("success");
const result = await retryAsync(mockFn, {
maxAttempts: 2,
baseDelay: 10,
});
expect(result).toBe("success");
expect(mockFn).toHaveBeenCalledTimes(2);
});
it("should handle AWS SDK errors", async () => {
const error = new Error("Throttling");
error.name = "ThrottlingException";
(error as any).$fault = "client";
(error as any).$metadata = {
httpStatusCode: 429,
requestId: "test-request-id",
};
const mockFn = jest
.fn()
.mockRejectedValueOnce(error)
.mockResolvedValue("success");
const result = await retryAsync(mockFn, {
maxAttempts: 2,
baseDelay: 10,
});
expect(result).toBe("success");
expect(mockFn).toHaveBeenCalledTimes(2);
});
it("should not retry AbortError", async () => {
const error = new Error("Aborted");
error.name = "AbortError";
const mockFn = jest.fn().mockRejectedValue(error);
await expect(retryAsync(mockFn)).rejects.toThrow("Aborted");
expect(mockFn).toHaveBeenCalledTimes(1);
});
it("should use custom shouldRetry function", async () => {
const mockFn = jest.fn().mockRejectedValue(new Error("Custom Error"));
const customShouldRetry = jest.fn().mockReturnValue(true);
await expect(
retryAsync(mockFn, {
maxAttempts: 2,
shouldRetry: customShouldRetry,
baseDelay: 10,
}),
).rejects.toThrow("Custom Error");
expect(customShouldRetry).toHaveBeenCalledWith(expect.any(Error), 1);
expect(mockFn).toHaveBeenCalledTimes(2);
});
});
describe("withRetry decorator functional usage", () => {
it("should work when applied manually to methods", async () => {
const testClass = {
attempts: 0,
async testMethod(): Promise<string> {
this.attempts++;
if (this.attempts < 3) {
const error = new Error("ECONNRESET");
(error as any).code = "ECONNRESET";
throw error;
}
return "success";
},
};
// Apply decorator manually
const decorator = withRetry({
maxAttempts: 3,
baseDelay: 10,
});
const descriptor = decorator(testClass, "testMethod", {
value: testClass.testMethod,
writable: true,
enumerable: false,
configurable: true,
});
if (descriptor?.value) {
testClass.testMethod = descriptor.value;
}
const result = await testClass.testMethod();
expect(result).toBe("success");
expect(testClass.attempts).toBe(3);
});
it("should throw the last error when all retries are exhausted", async () => {
const testClass = {
attempts: 0,
async testMethod(): Promise<string> {
this.attempts++;
if (this.attempts === 1) {
const error = new Error("First decorator error");
(error as any).code = "ECONNRESET";
throw error;
} else if (this.attempts === 2) {
const error = new Error("Second decorator error");
(error as any).code = "ECONNRESET";
throw error;
} else {
const error = new Error("Last decorator error");
(error as any).code = "ECONNRESET";
throw error;
}
},
};
// Apply decorator manually
const decorator = withRetry({
maxAttempts: 3,
baseDelay: 10,
});
const descriptor = decorator(testClass, "testMethod", {
value: testClass.testMethod,
writable: true,
enumerable: false,
configurable: true,
});
if (descriptor?.value) {
testClass.testMethod = descriptor.value;
}
await expect(testClass.testMethod()).rejects.toThrow(
"Last decorator error",
);
expect(testClass.attempts).toBe(3);
});
});
describe("withLLMRetry decorator functional usage", () => {
it("should use LLM-specific defaults", async () => {
const testLLM = {
attempts: 0,
async streamChat(): Promise<string> {
this.attempts++;
if (this.attempts < 2) {
const error = new Error("Too Many Requests");
(error as any).status = 429;
throw error;
}
return "success";
},
};
// Apply decorator manually
const decorator = withLLMRetry({ baseDelay: 10 });
const descriptor = decorator(testLLM, "streamChat", {
value: testLLM.streamChat,
writable: true,
enumerable: false,
configurable: true,
});
if (descriptor?.value) {
testLLM.streamChat = descriptor.value;
}
const result = await testLLM.streamChat();
expect(result).toBe("success");
expect(testLLM.attempts).toBe(2);
});
});
describe("exponential backoff with jitter", () => {
it("should increase delay exponentially", async () => {
const delays: number[] = [];
const error = new Error("ECONNRESET");
(error as any).code = "ECONNRESET";
const mockFn = jest.fn().mockRejectedValue(error);
await expect(
retryAsync(mockFn, {
maxAttempts: 3,
baseDelay: 1000,
jitterFactor: 0, // No jitter for predictable testing
onRetry: (error, attempt, delay) => {
delays.push(delay);
},
}),
).rejects.toThrow();
// First retry should be ~1000ms, second should be ~2000ms
expect(delays).toHaveLength(2);
expect(delays[0]).toBe(1000);
expect(delays[1]).toBe(2000);
});
it("should respect maxDelay", async () => {
const delays: number[] = [];
const error = new Error("ECONNRESET");
(error as any).code = "ECONNRESET";
const mockFn = jest.fn().mockRejectedValue(error);
await expect(
retryAsync(mockFn, {
maxAttempts: 4,
baseDelay: 1000,
maxDelay: 2500,
jitterFactor: 0,
onRetry: (error, attempt, delay) => {
delays.push(delay);
},
}),
).rejects.toThrow();
// Delays should be: 1000, 2000, 2500 (capped)
expect(delays).toEqual([1000, 2000, 2500]);
});
});
describe("rate limiting headers", () => {
it("should respect retry-after header in seconds", async () => {
const delays: number[] = [];
const error = new Error("Too Many Requests");
(error as any).status = 429;
(error as any).headers = { "retry-after": "1" }; // 1 second for fast testing
const mockFn = jest
.fn()
.mockRejectedValueOnce(error)
.mockResolvedValue("success");
const result = await retryAsync(mockFn, {
maxAttempts: 2,
baseDelay: 100, // 100ms fallback
onRetry: (error, attempt, delay) => {
delays.push(delay);
},
});
expect(result).toBe("success");
expect(mockFn).toHaveBeenCalledTimes(2);
// Should use header value (1000ms) not exponential backoff (100ms)
expect(delays[0]).toBeGreaterThan(940); // 1000ms with wider tolerance for jitter and system performance
expect(delays[0]).toBeLessThan(1080);
});
it("should respect x-ratelimit-reset header", async () => {
const delays: number[] = [];
const error = new Error("Rate limited");
(error as any).status = 429;
(error as any).headers = { "x-ratelimit-reset": "0.5" }; // 500ms for fast testing
const mockFn = jest
.fn()
.mockRejectedValueOnce(error)
.mockResolvedValue("success");
const result = await retryAsync(mockFn, {
maxAttempts: 2,
baseDelay: 100,
onRetry: (error, attempt, delay) => {
delays.push(delay);
},
});
expect(result).toBe("success");
// Should use header value (500ms) not exponential backoff (100ms)
expect(delays[0]).toBeGreaterThan(470); // 500ms with wider tolerance for jitter and system performance
expect(delays[0]).toBeLessThan(540);
});
it("should handle HTTP date format in retry-after header", async () => {
const delays: number[] = [];
const futureDate = new Date(Date.now() + 2000); // 2 seconds from now to avoid timing issues
const error = new Error("Rate limited");
(error as any).status = 429;
(error as any).headers = { "retry-after": futureDate.toUTCString() };
const mockFn = jest
.fn()
.mockRejectedValueOnce(error)
.mockResolvedValue("success");
const result = await retryAsync(mockFn, {
maxAttempts: 2,
baseDelay: 100,
maxDelay: 300, // Cap at 300ms for fast testing
onRetry: (error, attempt, delay) => {
delays.push(delay);
},
});
expect(result).toBe("success");
// Should be capped at maxDelay (300ms) since original would be ~2000ms
expect(delays[0]).toBeGreaterThan(280);
expect(delays[0]).toBeLessThan(320);
});
it("should fallback to exponential backoff when no headers present", async () => {
const delays: number[] = [];
const error = new Error("Server Error");
(error as any).status = 500;
// No headers property
const mockFn = jest
.fn()
.mockRejectedValueOnce(error)
.mockResolvedValue("success");
const result = await retryAsync(mockFn, {
maxAttempts: 2,
baseDelay: 50, // Fast for testing
jitterFactor: 0,
onRetry: (error, attempt, delay) => {
delays.push(delay);
},
});
expect(result).toBe("success");
// Should use exponential backoff (50ms) since no headers
expect(delays[0]).toBe(50);
});
it("should respect maxDelay even with rate limit headers", async () => {
const delays: number[] = [];
const error = new Error("Rate limited");
(error as any).status = 429;
(error as any).headers = { "retry-after": "10" }; // 10 seconds requested
const mockFn = jest
.fn()
.mockRejectedValueOnce(error)
.mockResolvedValue("success");
const result = await retryAsync(mockFn, {
maxAttempts: 2,
baseDelay: 100,
maxDelay: 200, // Cap at 200ms for fast testing
onRetry: (error, attempt, delay) => {
delays.push(delay);
},
});
expect(result).toBe("success");
// Should be capped at maxDelay (200ms) not header value (10000ms)
expect(delays[0]).toBeGreaterThan(190);
expect(delays[0]).toBeLessThan(210);
});
it("should handle case-insensitive header names", async () => {
const delays: number[] = [];
const error = new Error("Rate limited");
(error as any).status = 429;
(error as any).headers = { "Retry-After": "0.3" }; // 300ms for fast testing
const mockFn = jest
.fn()
.mockRejectedValueOnce(error)
.mockResolvedValue("success");
const result = await retryAsync(mockFn, {
maxAttempts: 2,
baseDelay: 100,
onRetry: (error, attempt, delay) => {
delays.push(delay);
},
});
expect(result).toBe("success");
// Should use header value (300ms)
expect(delays[0]).toBeGreaterThan(284);
expect(delays[0]).toBeLessThan(316);
});
});
});

459
core/llm/utils/retry.ts Normal file
View file

@ -0,0 +1,459 @@
/**
* Configuration options for the retry decorator
*/
export interface RetryOptions {
/** Maximum number of retry attempts (default: 3) */
maxAttempts?: number;
/** Base delay in milliseconds (default: 1000) */
baseDelay?: number;
/** Maximum delay in milliseconds (default: 30000) */
maxDelay?: number;
/** Jitter factor between 0 and 1 (default: 0.3) */
jitterFactor?: number;
/** Custom function to determine if an error should be retried */
shouldRetry?: (error: any, attempt: number) => boolean;
/** Custom function called on each retry attempt */
onRetry?: (error: any, attempt: number, delay: number) => void;
}
/**
* Default configuration for retry behavior
*/
const DEFAULT_RETRY_OPTIONS: Required<RetryOptions> = {
maxAttempts: 3,
baseDelay: 1000,
maxDelay: 30000,
jitterFactor: 0.3,
shouldRetry: defaultShouldRetry,
onRetry: defaultOnRetry,
};
/**
* Default function to determine if an error should be retried
* Retries on:
* - Network errors
* - HTTP 429 (Too Many Requests)
* - HTTP 5xx (Server errors)
* - Specific AWS errors
* - Timeout errors
*/
function defaultShouldRetry(error: any, attempt: number): boolean {
// Note: maxAttempts check is handled by the retry logic itself
// This function only determines if the error type is retryable
// Network/connection errors
if (
error.code === "ENOTFOUND" ||
error.code === "ECONNRESET" ||
error.code === "ECONNREFUSED" ||
error.code === "ETIMEDOUT"
) {
return true;
}
// AWS SDK specific errors (v3 - check for AWS error structure and retryable types)
const isAwsError =
error.$fault || error.$metadata || (error.name && error.__type);
const awsRetryableErrors = [
"ThrottlingException",
"ServiceUnavailableException",
"InternalServerError",
"RequestTimeout",
"ModelNotReadyException",
"ModelTimeoutException",
"ResourceNotFoundException",
];
if (isAwsError && error.name && awsRetryableErrors.includes(error.name)) {
return true;
}
// HTTP status codes
if (error.status || error.statusCode) {
const status = error.status || error.statusCode;
// Rate limiting
if (status === 429) {
return true;
}
// Server errors (5xx)
if (status >= 500 && status < 600) {
return true;
}
// Don't retry client errors (4xx except 429)
if (status >= 400 && status < 500) {
return false;
}
}
// Timeout errors
if (
error.name === "TimeoutError" ||
error.message?.includes("timeout") ||
error.message?.includes("TIMEOUT")
) {
return true;
}
// Abort signal errors should not be retried
if (error.name === "AbortError" || error.code === "ABORT_ERR") {
return false;
}
// Default to not retrying unknown errors
return false;
}
/**
* Default function called on each retry attempt
*/
function defaultOnRetry(error: any, attempt: number, delay: number): void {
console.warn(
`Retry attempt ${attempt} after ${delay}ms delay. Error: ${error.message || error}`,
);
}
/**
* Calculate delay with rate limit header awareness and exponential backoff fallback
*/
function calculateDelay(
attempt: number,
baseDelay: number,
maxDelay: number,
jitterFactor: number,
error?: any,
): number {
// Check for rate limiting headers first (more accurate than exponential backoff)
if (error?.headers) {
const retryAfter =
error.headers["retry-after"] ||
error.headers["x-ratelimit-reset"] ||
error.headers["ratelimit-reset"] ||
error.headers["Retry-After"] ||
error.headers["X-RateLimit-Reset"] ||
error.headers["RateLimit-Reset"];
if (retryAfter) {
let delayMs: number;
// Parse retry-after header (can be seconds or HTTP date)
if (typeof retryAfter === "string" && isNaN(Number(retryAfter))) {
// HTTP date format
const resetTime = new Date(retryAfter).getTime();
const now = Date.now();
delayMs = Math.max(0, resetTime - now);
} else {
// Seconds format
delayMs = Number(retryAfter) * 1000;
}
// Respect maxDelay and add small jitter to spread requests
const cappedDelay = Math.min(delayMs, maxDelay);
const jitterMultiplier = 1 + (Math.random() * 0.1 - 0.05); // Small jitter ±5%
return Math.max(0, Math.floor(cappedDelay * jitterMultiplier));
}
}
// Fallback to exponential backoff if no rate limit headers
const exponentialDelay = baseDelay * Math.pow(2, attempt - 1);
const cappedDelay = Math.min(exponentialDelay, maxDelay);
// Add jitter: random value between (1 - jitterFactor) and (1 + jitterFactor)
const jitterMultiplier = 1 + (Math.random() * 2 - 1) * jitterFactor;
const jitteredDelay = cappedDelay * jitterMultiplier;
return Math.max(0, Math.floor(jitteredDelay));
}
/**
* Sleep for the specified number of milliseconds
*/
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/**
* Retry decorator for async functions with exponential backoff and jitter
*
* @param options Retry configuration options
* @returns Decorator function
*
* @example
* ```typescript
* class MyLLM {
* @withRetry({ maxAttempts: 5, baseDelay: 2000 })
* async streamChat(messages: ChatMessage[]): Promise<AsyncGenerator<ChatMessage>> {
* // Implementation that might fail
* }
* }
* ```
*/
export function withRetry(options: RetryOptions = {}) {
const config = { ...DEFAULT_RETRY_OPTIONS, ...options };
return function (...args: any[]): any {
// Handle different decorator calling patterns
const [target, propertyName, descriptor] = args;
// Get the original method
let originalMethod: Function;
if (descriptor && descriptor.value) {
originalMethod = descriptor.value;
} else {
// Get method from prototype
originalMethod = target[propertyName];
}
if (!originalMethod || typeof originalMethod !== "function") {
throw new Error(`@withRetry can only be applied to methods`);
}
// Check if the original method is an async generator function
const isAsyncGenerator =
originalMethod.constructor.name === "AsyncGeneratorFunction";
const wrappedMethod = isAsyncGenerator
? async function* (this: any, ...methodArgs: any[]) {
let lastError: any;
for (let attempt = 1; attempt <= config.maxAttempts; attempt++) {
try {
const generator = originalMethod.apply(this, methodArgs);
yield* createRetryableAsyncGenerator(
generator,
config,
originalMethod,
this,
methodArgs,
attempt,
);
return; // Successfully completed
} catch (error) {
lastError = error;
// Check if we should retry this error
if (!config.shouldRetry(error, attempt)) {
throw error;
}
// Don't delay on the last attempt
if (attempt === config.maxAttempts) {
break;
}
// Calculate delay and wait
const delay = calculateDelay(
attempt,
config.baseDelay,
config.maxDelay,
config.jitterFactor,
error,
);
config.onRetry(error, attempt, delay);
await sleep(delay);
}
}
// If we get here, all attempts failed
throw lastError;
}
: async function (this: any, ...methodArgs: any[]) {
let lastError: any;
for (let attempt = 1; attempt <= config.maxAttempts; attempt++) {
try {
const result = originalMethod.apply(this, methodArgs);
return await result;
} catch (error) {
lastError = error;
// Check if we should retry this error
if (!config.shouldRetry(error, attempt)) {
throw error;
}
// Don't delay on the last attempt
if (attempt === config.maxAttempts) {
break;
}
// Calculate delay and wait
const delay = calculateDelay(
attempt,
config.baseDelay,
config.maxDelay,
config.jitterFactor,
error,
);
config.onRetry(error, attempt, delay);
await sleep(delay);
}
}
// If we get here, all attempts failed
throw lastError;
};
// Apply the wrapped method based on how the decorator was called
if (descriptor) {
descriptor.value = wrappedMethod;
return descriptor;
} else {
// Handle case where descriptor is not provided
target[propertyName] = wrappedMethod;
return wrappedMethod;
}
};
}
/**
* Creates a retryable async generator that handles errors during iteration
*/
async function* createRetryableAsyncGenerator<T>(
generator: AsyncGenerator<T>,
config: Required<RetryOptions>,
originalMethod: Function,
context: any,
args: any[],
initialAttempt: number,
): AsyncGenerator<T> {
let currentGenerator = generator;
let attempt = initialAttempt;
try {
for await (const value of currentGenerator) {
yield value;
}
} catch (error) {
// If we encounter an error during iteration, we can retry by creating a new generator
let lastError = error;
for (
let retryAttempt = attempt + 1;
retryAttempt <= config.maxAttempts;
retryAttempt++
) {
// Check if we should retry this error
if (!config.shouldRetry(error, retryAttempt)) {
throw error;
}
// Don't delay on the last attempt
if (retryAttempt === config.maxAttempts) {
break;
}
// Calculate delay and wait
const delay = calculateDelay(
retryAttempt,
config.baseDelay,
config.maxDelay,
config.jitterFactor,
error,
);
config.onRetry(error, retryAttempt, delay);
await sleep(delay);
try {
// Create a new generator and continue iteration
const newGenerator = await originalMethod.apply(context, args);
if (
newGenerator &&
typeof newGenerator[Symbol.asyncIterator] === "function"
) {
for await (const value of newGenerator) {
yield value;
}
return; // Successfully completed
} else {
throw new Error("Method did not return an async generator on retry");
}
} catch (retryError) {
lastError = retryError;
error = retryError;
}
}
// If we get here, all retry attempts failed
throw lastError;
}
}
/**
* Functional version of retry for use without decorators
*
* @param fn Function to retry
* @param options Retry configuration options
* @returns Promise that resolves with the function result or rejects with the last error
*
* @example
* ```typescript
* const result = await retryAsync(
* () => someApiCall(),
* { maxAttempts: 3, baseDelay: 1000 }
* );
* ```
*/
export async function retryAsync<T>(
fn: () => Promise<T>,
options: RetryOptions = {},
): Promise<T> {
const config = { ...DEFAULT_RETRY_OPTIONS, ...options };
let lastError: any;
for (let attempt = 1; attempt <= config.maxAttempts; attempt++) {
try {
return await fn();
} catch (error) {
lastError = error;
// Check if we should retry this error
if (!config.shouldRetry(error, attempt)) {
throw error;
}
// Don't delay on the last attempt
if (attempt === config.maxAttempts) {
break;
}
// Calculate delay and wait
const delay = calculateDelay(
attempt,
config.baseDelay,
config.maxDelay,
config.jitterFactor,
error,
);
config.onRetry(error, attempt, delay);
await sleep(delay);
}
}
// If we get here, all attempts failed
throw lastError;
}
/**
* Retry decorator specifically configured for LLM providers
* Uses sensible defaults for LLM API calls, including longer delays
* for capacity provisioning (e.g., AWS Bedrock can require up to 59+ seconds)
*/
export function withLLMRetry(options: Partial<RetryOptions> = {}) {
return withRetry({
maxAttempts: 5, // More attempts for capacity issues
baseDelay: 2000, // Start with 2 seconds
maxDelay: 90000, // Allow up to 90 seconds for capacity provisioning
jitterFactor: 0.4, // Slightly more jitter to spread load
...options,
});
}

View file

@ -158,19 +158,19 @@ export class NextEditProvider {
this.loggingService.cancel();
}
// public accept(completionId: string) {
// const outcome = this.loggingService.accept(completionId);
// if (!outcome) {
// return;
// }
// }
public accept(completionId: string) {
const outcome = this.loggingService.accept(completionId);
if (!outcome) {
return;
}
}
// public reject(completionId: string) {
// const outcome = this.loggingService.reject(completionId);
// if (!outcome) {
// return;
// }
// }
public reject(completionId: string) {
const outcome = this.loggingService.reject(completionId);
if (!outcome) {
return;
}
}
public markDisplayed(completionId: string, outcome: NextEditOutcome) {
this.loggingService.markDisplayed(completionId, outcome);
@ -237,7 +237,6 @@ export class NextEditProvider {
// TODO: Toggle between the default endpoint and the finetuned endpoint.
const prompts: Prompt[] = [];
if (this.endpointType === "default") {
prompts.push(renderDefaultSystemPrompt());
prompts.push(renderDefaultUserPrompt(snippetPayload, helper));
@ -272,17 +271,30 @@ export class NextEditProvider {
cursorPosition: helper.pos,
...helper.options,
};
// When using the JetBrains extension, mark as displayed.
// This helps us not need to make additional network calls just to mark as displayed.
const ideType = (await this.ide.getIdeInfo()).ideType;
if (ideType === "jetbrains") {
this.markDisplayed(input.completionId, outcomeNext);
}
return outcomeNext;
} else {
return undefined;
}
} else {
const msg: ChatMessage = await llm.chat(prompts, token);
if (typeof msg.content === "string") {
// TODO: There are cases where msg.conetnt.split("<|start|>")[1] is undefined
const nextCompletion = replaceEscapedCharacters(
msg.content.split("<|editable_region_start|>\n")[1],
).replace(/\n$/, "");
// NOTE: There are cases where msg.conetnt.split("<|start|>")[1] is undefined
const nextCompletion = msg.content.split(
"<|editable_region_start|>\n",
)[1]
? replaceEscapedCharacters(
msg.content.split("<|editable_region_start|>\n")[1],
).replace(/\n$/, "")
: "";
const currCursorPos = helper.pos;
const editableRegionStartLine = Math.max(
@ -319,6 +331,14 @@ export class NextEditProvider {
cursorPosition: helper.pos,
...helper.options,
};
// When using the JetBrains extension, mark as displayed.
// This helps us not need to make additional network calls just to mark as displayed.
const ideType = (await this.ide.getIdeInfo()).ideType;
if (ideType === "jetbrains") {
this.markDisplayed(input.completionId, outcomeNext);
}
return outcomeNext;
} else {
return undefined;

View file

@ -1,5 +1,5 @@
export const IS_NEXT_EDIT_ACTIVE = false;
export const NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN = 5;
export const NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN = 0;
export const NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN = 5;
export const USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>";
export const EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>";

23
core/package-lock.json generated
View file

@ -51,7 +51,7 @@
"node-html-markdown": "^1.3.0",
"ollama": "^0.4.6",
"onnxruntime-node": "1.14.0",
"openai": "^4.76.0",
"openai": "^4.104.0",
"p-limit": "^6.1.0",
"partial-json": "^0.1.7",
"pg": "^8.11.3",
@ -142,7 +142,7 @@
},
"../packages/config-yaml": {
"name": "@continuedev/config-yaml",
"version": "1.0.95",
"version": "1.0.96",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",
@ -169,16 +169,18 @@
},
"../packages/openai-adapters": {
"name": "@continuedev/openai-adapters",
"version": "1.0.44",
"version": "1.0.45",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.842.0",
"@aws-sdk/credential-providers": "^3.840.0",
"@continuedev/config-types": "^1.0.5",
"@continuedev/config-yaml": "^1.0.51",
"@continuedev/fetch": "^1.0.15",
"dotenv": "^16.5.0",
"json-schema": "^0.4.0",
"node-fetch": "^3.3.2",
"openai": "^4.76.0",
"openai": "^4.104.0",
"uuid": "^11.1.0",
"zod": "^3.24.2"
},
@ -188,7 +190,8 @@
"@types/json-schema": "^7.0.15",
"cross-env": "^7.0.3",
"ts-jest": "^29.2.3",
"ts-node": "^10.9.2"
"ts-node": "^10.9.2",
"vitest": "^1.6.1"
}
},
"node_modules/@75lb/deep-merge": {
@ -14327,9 +14330,9 @@
}
},
"node_modules/openai": {
"version": "4.76.0",
"resolved": "https://registry.npmjs.org/openai/-/openai-4.76.0.tgz",
"integrity": "sha512-QBGIetjX1C9xDp5XGa/3mPnfKI9BgAe2xHQX6PmO98wuW9qQaurBaumcYptQWc9LHZZq7cH/Y1Rjnsr6uUDdVw==",
"version": "4.104.0",
"resolved": "https://registry.npmjs.org/openai/-/openai-4.104.0.tgz",
"integrity": "sha512-p99EFNsA/yX6UhVO93f5kJsDRLAg+CTA2RBqdHK4RtK8u5IJw32Hyb2dTGKbnnFmnuoBv5r7Z2CURI9sGZpSuA==",
"dependencies": {
"@types/node": "^18.11.18",
"@types/node-fetch": "^2.6.4",
@ -14343,9 +14346,13 @@
"openai": "bin/cli"
},
"peerDependencies": {
"ws": "^8.18.0",
"zod": "^3.23.8"
},
"peerDependenciesMeta": {
"ws": {
"optional": true
},
"zod": {
"optional": true
}

View file

@ -78,6 +78,7 @@
"handlebars": "^4.7.8",
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"iconv-lite": "^0.6.3",
"ignore": "^5.3.1",
"is-localhost-ip": "^2.0.0",
"jinja-js": "0.1.8",
@ -91,7 +92,7 @@
"node-html-markdown": "^1.3.0",
"ollama": "^0.4.6",
"onnxruntime-node": "1.14.0",
"openai": "^4.76.0",
"openai": "^4.104.0",
"p-limit": "^6.1.0",
"partial-json": "^0.1.7",
"pg": "^8.11.3",

View file

@ -15,6 +15,7 @@ import { GlobalContextModelSelections } from "../util/GlobalContext";
import {
BrowserSerializedContinueConfig,
ChatMessage,
CompiledMessagesResult,
CompleteOnboardingPayload,
ContextItem,
ContextItemWithId,
@ -25,6 +26,7 @@ import {
FileSymbolMap,
IdeSettings,
LLMFullCompletionOptions,
MessageOption,
ModelDescription,
PromptLog,
RangeInFile,
@ -89,7 +91,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
},
];
"config/deleteModel": [{ title: string }, void];
"config/reload": [undefined, ConfigResult<BrowserSerializedContinueConfig>];
"config/reload": [undefined, void];
"config/refreshProfiles": [
(
| undefined
@ -145,6 +147,9 @@ export type ToCoreFromIdeOrWebviewProtocol = {
"context/indexDocs": [{ reIndex: boolean }, void];
"autocomplete/cancel": [undefined, void];
"autocomplete/accept": [{ completionId: string }, void];
"nextEdit/predict": [AutocompleteInput, string[]];
"nextEdit/reject": [{ completionId: string }, void];
"nextEdit/accept": [{ completionId: string }, void];
"llm/complete": [
{
prompt: string;
@ -159,6 +164,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
messages: ChatMessage[];
completionOptions: LLMFullCompletionOptions;
title: string;
messageOptions?: MessageOption;
legacySlashCommandData?: {
command: SlashCommandDescWithSource;
input: string;
@ -170,12 +176,23 @@ export type ToCoreFromIdeOrWebviewProtocol = {
AsyncGenerator<ChatMessage, PromptLog>,
];
streamDiffLines: [StreamDiffLinesPayload, AsyncGenerator<DiffLine>];
"llm/compileChat": [
{ messages: ChatMessage[]; options: LLMFullCompletionOptions },
CompiledMessagesResult,
];
"chatDescriber/describe": [
{
text: string;
},
string | undefined,
];
"conversation/compact": [
{
index: number;
sessionId: string;
},
string | undefined,
];
"stats/getTokensPerDay": [
undefined,
{ day: string; promptTokens: number; generatedTokens: number }[],

View file

@ -37,12 +37,17 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"autocomplete/complete",
"autocomplete/cancel",
"autocomplete/accept",
"nextEdit/predict",
"nextEdit/reject",
"nextEdit/accept",
"tts/kill",
"llm/complete",
"llm/streamChat",
"llm/listModels",
"llm/compileChat",
"streamDiffLines",
"chatDescriber/describe",
"conversation/compact",
"stats/getTokensPerDay",
"stats/getTokensPerModel",
// Codebase

View file

@ -13,6 +13,7 @@ export const ideSettingsPromise = testIde.getIdeSettings();
export const testControlPlaneClient = new ControlPlaneClient(
Promise.resolve(undefined),
ideSettingsPromise,
testIde.getIdeInfo(),
);
export const testConfigHandler = new ConfigHandler(

View file

@ -16,7 +16,7 @@ export const createRuleBlock: Tool = {
'Creates a "rule" that can be referenced in future conversations. This should be used whenever you want to establish code standards / preferences that should be applied consistently, or when you want to avoid making a mistake again. To modify existing rules, use the edit tool instead.\n\nRule Types:\n- Always: Include only "rule" (always included in model context)\n- Auto Attached: Include "rule", "globs", and/or "regex" (included when files match patterns)\n- Agent Requested: Include "rule" and "description" (AI decides when to apply based on description)\n- Manual: Include only "rule" (only included when explicitly mentioned using @ruleName)',
parameters: {
type: "object",
required: ["name", "rule", "description"],
required: ["name", "rule"],
properties: {
name: {
type: "string",

View file

@ -1,6 +1,7 @@
import { Tool } from "../..";
import { EDIT_CODE_INSTRUCTIONS } from "../../llm/defaultSystemMessages";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
import { NO_PARALLEL_TOOL_CALLING_INSRUCTION } from "./searchAndReplaceInFile";
export interface EditToolArgs {
filepath: string;
@ -18,7 +19,7 @@ export const editFileTool: Tool = {
isInstant: false,
function: {
name: BuiltInToolNames.EditExistingFile,
description: `Use this tool to edit an existing file. If you don't know the contents of the file, read it first.\n${EDIT_CODE_INSTRUCTIONS}`,
description: `Use this tool to edit an existing file. If you don't know the contents of the file, read it first.\n${EDIT_CODE_INSTRUCTIONS}\n${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`,
parameters: {
type: "object",
required: ["filepath", "changes"],

View file

@ -4,7 +4,7 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const lsTool: Tool = {
type: "function",
displayTitle: "LS Tool",
displayTitle: "ls",
wouldLikeTo: "list files and folders in {{{ dirPath }}}",
isCurrently: "listing files and folders in {{{ dirPath }}}",
hasAlready: "listed files and folders in {{{ dirPath }}}",
@ -16,12 +16,11 @@ export const lsTool: Tool = {
description: "List files and folders in a given directory",
parameters: {
type: "object",
required: ["dirPath", "recursive"],
properties: {
dirPath: {
type: "string",
description:
"The directory path relative to the root of the project. Always use forward slash paths like '/'. rather than e.g. '.'",
"The directory path relative to the root of the project. Use forward slash paths like '/'. rather than e.g. '.'",
},
recursive: {
type: "boolean",

View file

@ -3,9 +3,13 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export interface SearchAndReplaceInFileArgs {
filepath: string;
diff: string;
diffs: string[];
}
// Currently unsupported and filtered out in `gui/src/redux/slices/sessionSlice.ts`
export const NO_PARALLEL_TOOL_CALLING_INSRUCTION =
"Note this tool CANNOT be called in parallel.";
/**
* This tool is in an experimental state.
* Our starting point is heavily inspired by Cline's `replace_in_file` tool: https://github.com/cline/cline/blob/2709ccefcddc616e89a70962f017bcbbca1f17bf/src/core/prompts/system.ts#L87-L121
@ -21,20 +25,22 @@ export const searchAndReplaceInFileTool: Tool = {
isInstant: false,
function: {
name: BuiltInToolNames.SearchAndReplaceInFile,
description:
"Request to replace sections of content in an existing file using SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file.",
description: `Request to replace sections of content in an existing file using multiple SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file. ${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`,
parameters: {
type: "object",
required: ["filepath", "diff"],
required: ["filepath", "diffs"],
properties: {
filepath: {
type: "string",
description:
"The path of the file to modify, relative to the root of the workspace.",
},
diff: {
type: "string",
description: `One or more SEARCH/REPLACE blocks following this exact format:
diffs: {
type: "array",
items: {
type: "string",
},
description: `An array of strings, each containing one or more SEARCH/REPLACE blocks following this exact format:
\`\`\`
------- SEARCH
[exact content to find]
@ -51,16 +57,17 @@ Critical rules:
* Including multiple unique SEARCH/REPLACE blocks if you need to make multiple changes.
* Include *just* enough lines in each SEARCH section to uniquely match each set of lines that need to change.
* When using multiple SEARCH/REPLACE blocks, list them in the order they appear in the file.
3. Keep SEARCH/REPLACE blocks concise:
3. **Order matters**: DIFFs in the array should be ordered from top to bottom of the file to ensure correct application.
4. Keep SEARCH/REPLACE blocks concise:
* Break large SEARCH/REPLACE blocks into a series of smaller blocks that each change a small portion of the file.
* Include just the changing lines, and a few surrounding lines if needed for uniqueness.
* Do not include long runs of unchanging lines in SEARCH/REPLACE blocks.
* Each line must be complete. Never truncate lines mid-way through as this can cause matching failures.
4. Splitting up tool calls:
5. Splitting up tool calls:
* When making multiple closely related edits to the same file, you should try to use multiple SEARCH/REPLACE blocks in a single tool call, rather than making multiple separate tool calls
* If you need to make follow up edits or group your work into logical segments, it is okay to perform additional tool calls
* DO NOT make back-to-back tool calls. Instead interleave with brief explanation of what each will do. For example, instead of [explanation, tool call, tool call] you should do [explanation, tool call, explanation, tool call]
5. Special operations:
6. Special operations:
* To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location)
* To delete code: Use empty REPLACE section
@ -78,7 +85,8 @@ Usage:
[new content to replace with]
+++++++ REPLACE
\`\`\`
`,
Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and all will be applied sequentially in the order they appear.`,
},
},
},

View file

@ -1,22 +1,15 @@
import { ToolImpl } from ".";
import { RangeInFile } from "../..";
import { retrieveContextItemsFromEmbeddings } from "../../context/retrieval/retrieval";
import { getStringArg } from "../parseArgs";
export const codebaseToolImpl: ToolImpl = async (args, extras) => {
if (!args.query || args.query.trim() === "") {
return [
{
name: "Error",
description: "Codebase search error",
content: "Query parameter is required and cannot be empty.",
},
];
}
const query = getStringArg(args, "query");
try {
const contextExtras = {
config: extras.config,
fullInput: args.query,
fullInput: query,
embeddingsProvider: extras.config.selectedModelByRole.embed,
reranker: extras.config.selectedModelByRole.rerank,
llm: extras.llm,
@ -39,7 +32,7 @@ export const codebaseToolImpl: ToolImpl = async (args, extras) => {
{
name: "No Results",
description: "Codebase search",
content: `No relevant code found for query: "${args.query}". This could mean:
content: `No relevant code found for query: "${query}". This could mean:
- The codebase hasn't been indexed yet
- No code matches the search criteria
- Embeddings provider is not configured

View file

@ -2,20 +2,24 @@ import { inferResolvedUriFromRelativePath } from "../../util/ideUtils";
import { ToolImpl } from ".";
import { getCleanUriPath, getUriPathBasename } from "../../util/uri";
import { getStringArg } from "../parseArgs";
export const createNewFileImpl: ToolImpl = async (args, extras) => {
const filepath = getStringArg(args, "filepath");
const contents = getStringArg(args, "contents", true);
const resolvedFileUri = await inferResolvedUriFromRelativePath(
args.filepath,
filepath,
extras.ide,
);
if (resolvedFileUri) {
const exists = await extras.ide.fileExists(resolvedFileUri);
if (exists) {
throw new Error(
`File ${args.filepath} already exists. Use the edit tool to edit this file`,
`File ${filepath} already exists. Use the edit tool to edit this file`,
);
}
await extras.ide.writeFile(resolvedFileUri, args.contents);
await extras.ide.writeFile(resolvedFileUri, contents);
await extras.ide.openFile(resolvedFileUri);
await extras.ide.saveFile(resolvedFileUri);
if (extras.codeBaseIndexer) {

View file

@ -2,6 +2,11 @@ import { createRuleMarkdown } from "@continuedev/config-yaml";
import { ToolImpl } from ".";
import { RuleWithSource } from "../..";
import { createRuleFilePath } from "../../config/markdown/utils";
import {
getBooleanArg,
getOptionalStringArg,
getStringArg,
} from "../parseArgs";
export type CreateRuleBlockArgs = Pick<
Required<RuleWithSource>,
@ -9,11 +14,21 @@ export type CreateRuleBlockArgs = Pick<
> &
Pick<RuleWithSource, "globs" | "regex" | "description" | "alwaysApply">;
export const createRuleBlockImpl: ToolImpl = async (
{ name, rule, ...otherArgs }: CreateRuleBlockArgs,
extras,
) => {
const fileContent = createRuleMarkdown(name, rule, otherArgs);
export const createRuleBlockImpl: ToolImpl = async (args, extras) => {
const name = getStringArg(args, "name");
const rule = getStringArg(args, "rule");
const description = getOptionalStringArg(args, "description");
const regex = getOptionalStringArg(args, "regex");
const globs = getOptionalStringArg(args, "globs");
const alwaysApply = getBooleanArg(args, "alwaysApply", false);
const fileContent = createRuleMarkdown(name, rule, {
alwaysApply,
description,
globs,
regex,
});
const [localContinueDir] = await extras.ide.getWorkspaceDirs();
const ruleFilePath = createRuleFilePath(localContinueDir, name);
@ -24,7 +39,7 @@ export const createRuleBlockImpl: ToolImpl = async (
return [
{
name: "New Rule Block",
description: otherArgs.description || "",
description: description || "",
uri: {
type: "file",
value: ruleFilePath,

View file

@ -1,10 +1,13 @@
import { ToolImpl } from ".";
import { getUrlContextItems } from "../../context/providers/URLContextProvider";
import { getStringArg } from "../parseArgs";
const DEFAULT_FETCH_URL_CHAR_LIMIT = 20000;
export const fetchUrlContentImpl: ToolImpl = async (args, extras) => {
const contextItems = await getUrlContextItems(args.url, extras.fetch);
const url = getStringArg(args, "url");
const contextItems = await getUrlContextItems(url, extras.fetch);
// Track truncated content
const truncatedUrls: string[] = [];
@ -12,7 +15,7 @@ export const fetchUrlContentImpl: ToolImpl = async (args, extras) => {
// Check and truncate each context item
const processedItems = contextItems.map((item) => {
if (item.content.length > DEFAULT_FETCH_URL_CHAR_LIMIT) {
truncatedUrls.push(args.url);
truncatedUrls.push(url);
return {
...item,
content: item.content.substring(0, DEFAULT_FETCH_URL_CHAR_LIMIT),

View file

@ -1,10 +1,13 @@
import { ToolImpl } from ".";
import { ContextItem } from "../..";
import { getStringArg } from "../parseArgs";
const MAX_AGENT_GLOB_RESULTS = 100;
export const fileGlobSearchImpl: ToolImpl = async (args, extras) => {
const pattern = getStringArg(args, "pattern");
const results = await extras.ide.getFileResults(
args.pattern,
pattern,
MAX_AGENT_GLOB_RESULTS,
);
const contextItems: ContextItem[] = [

View file

@ -1,6 +1,7 @@
import { ToolImpl } from ".";
import { ContextItem } from "../..";
import { formatGrepSearchResults } from "../../util/grepSearch";
import { getStringArg } from "../parseArgs";
const DEFAULT_GREP_SEARCH_RESULTS_LIMIT = 100;
const DEFAULT_GREP_SEARCH_CHAR_LIMIT = 5000; // ~1000 tokens, will keep truncation simply for now
@ -41,8 +42,10 @@ function splitGrepResultsByFile(content: string): ContextItem[] {
}
export const grepSearchImpl: ToolImpl = async (args, extras) => {
const query = getStringArg(args, "query");
const results = await extras.ide.getSearchResults(
args.query,
query,
DEFAULT_GREP_SEARCH_RESULTS_LIMIT,
);
const { formatted, numResults, truncated } = formatGrepSearchResults(
@ -63,7 +66,7 @@ export const grepSearchImpl: ToolImpl = async (args, extras) => {
let contextItems: ContextItem[] = [];
const splitByFile: boolean = args.splitByFile || false;
const splitByFile: boolean = args?.splitByFile || false;
if (splitByFile) {
contextItems = splitGrepResultsByFile(formatted);
} else {

View file

@ -2,28 +2,28 @@ import { resolveRelativePathInDir } from "../../util/ideUtils";
import { getUriPathBasename } from "../../util/uri";
import { ToolImpl } from ".";
import { getStringArg } from "../parseArgs";
import { throwIfFileExceedsHalfOfContext } from "./readFileLimit";
export const readFileImpl: ToolImpl = async (args, extras) => {
const firstUriMatch = await resolveRelativePathInDir(
args.filepath,
extras.ide,
);
const filepath = getStringArg(args, "filepath");
const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide);
if (!firstUriMatch) {
throw new Error(`Could not find file ${args.filepath}`);
throw new Error(`Could not find file ${filepath}`);
}
const content = await extras.ide.readFile(firstUriMatch);
await throwIfFileExceedsHalfOfContext(
args.filepath,
filepath,
content,
extras.config.selectedModelByRole.chat,
);
return [
{
name: getUriPathBasename(args.filepath),
description: args.filepath,
name: getUriPathBasename(firstUriMatch),
description: filepath,
content,
uri: {
type: "file",

View file

@ -1,13 +1,14 @@
import { ToolImpl } from ".";
import { getStringArg } from "../parseArgs";
export const requestRuleImpl: ToolImpl = async (args, extras) => {
const name = getStringArg(args, "name");
// Find the rule by name in the config
const rule = extras.config.rules.find((r) => r.name === args.name);
const rule = extras.config.rules.find((r) => r.name === name);
if (!rule || !rule.ruleFile) {
throw new Error(
`Rule with name "${args.name}" not found or has no file path`,
);
throw new Error(`Rule with name "${name}" not found or has no file path`);
}
return [

View file

@ -1,5 +1,22 @@
import iconv from "iconv-lite";
import childProcess from "node:child_process";
import util from "node:util";
// Automatically decode the buffer according to the platform to avoid garbled Chinese
function getDecodedOutput(data: Buffer): string {
if (process.platform === "win32") {
try {
let out = iconv.decode(data, "utf-8");
if (/<2F>/.test(out)) {
out = iconv.decode(data, "gbk");
}
return out;
} catch {
return iconv.decode(data, "gbk");
}
} else {
return data.toString();
}
}
import { fileURLToPath } from "node:url";
import { ToolImpl } from ".";
@ -7,6 +24,7 @@ import {
isProcessBackgrounded,
removeBackgroundedProcess,
} from "../../util/processTerminalBackgroundStates";
import { getBooleanArg, getStringArg } from "../parseArgs";
const asyncExec = util.promisify(childProcess.exec);
@ -33,8 +51,11 @@ const ENABLED_FOR_REMOTES = [
];
export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
const command = getStringArg(args, "command");
// Default to waiting for completion if not specified
const waitForCompletion = args.waitForCompletion !== false;
const waitForCompletion =
getBooleanArg(args, "waitForCompletion", false) ?? true;
const ideInfo = await extras.ide.getIdeInfo();
const toolCallId = extras.toolCallId || "";
@ -67,7 +88,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
}
// Use spawn with color environment
const childProc = childProcess.spawn(args.command, {
const childProc = childProcess.spawn(command, {
cwd,
shell: true,
env: getColorEnv(), // Add enhanced environment for colors
@ -77,7 +98,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
// Skip if this process has been backgrounded
if (isProcessBackgrounded(toolCallId)) return;
const newOutput = data.toString();
const newOutput = getDecodedOutput(data);
terminalOutput += newOutput;
// Send partial output to UI
@ -103,7 +124,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
// Skip if this process has been backgrounded
if (isProcessBackgrounded(toolCallId)) return;
const newOutput = data.toString();
const newOutput = getDecodedOutput(data);
terminalOutput += newOutput;
// Send partial output to UI, status is not required
@ -212,7 +233,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
// Standard execution, waiting for completion
try {
// Use color environment for exec as well
const output = await asyncExec(args.command, {
const output = await asyncExec(command, {
cwd,
env: getColorEnv(),
});
@ -241,7 +262,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
// but don't attach any listeners other than error
try {
// Use spawn with color environment
const childProc = childProcess.spawn(args.command, {
const childProc = childProcess.spawn(command, {
cwd,
shell: true,
env: getColorEnv(), // Add color environment
@ -292,7 +313,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
// For remote environments, just run the command
// Note: waitForCompletion is not supported in remote environments yet
await extras.ide.runCommand(args.command);
await extras.ide.runCommand(command);
return [
{
name: "Terminal",

View file

@ -1,10 +1,13 @@
import { ToolImpl } from ".";
import { fetchSearchResults } from "../../context/providers/WebContextProvider";
import { getStringArg } from "../parseArgs";
const DEFAULT_WEB_SEARCH_CHAR_LIMIT = 8000;
export const searchWebImpl: ToolImpl = async (args, extras) => {
const webResults = await fetchSearchResults(args.query, 5, extras.fetch);
const query = getStringArg(args, "query");
const webResults = await fetchSearchResults(query, 5, extras.fetch);
// Track truncated results
const truncatedResults: string[] = [];

View file

@ -2,9 +2,11 @@ import generateRepoMap from "../../util/generateRepoMap";
import { resolveRelativePathInDir } from "../../util/ideUtils";
import { ToolImpl } from ".";
import { getStringArg } from "../parseArgs";
export const viewSubdirectoryImpl: ToolImpl = async (args: any, extras) => {
const { directory_path } = args;
const directory_path = getStringArg(args, "directory_path");
const uri = await resolveRelativePathInDir(directory_path, extras.ide);
if (!uri) {

View file

@ -6,7 +6,7 @@ import { editFileTool } from "./definitions/editFile";
import { fetchUrlContentTool } from "./definitions/fetchUrlContent";
import { globSearchTool } from "./definitions/globSearch";
import { grepSearchTool } from "./definitions/grepSearch";
import { lsTool } from "./definitions/lsTool";
import { lsTool } from "./definitions/ls";
import { readCurrentlyOpenFileTool } from "./definitions/readCurrentlyOpenFile";
import { readFileTool } from "./definitions/readFile";
import { requestRuleTool } from "./definitions/requestRule";

View file

@ -12,3 +12,52 @@ export function safeParseToolCallArgs(
return {};
}
}
export function getStringArg(
args: any,
argName: string,
allowEmpty = false,
): string {
if (!args || !(argName in args) || typeof args[argName] !== "string") {
throw new Error(
`\`${argName}\` argument is required${allowEmpty ? "" : " and must not be empty"}. (type string)`,
);
}
if (!allowEmpty && !args[argName].trim()) {
throw new Error(`Argument ${argName} must not be empty`);
}
return args[argName];
}
export function getOptionalStringArg(
args: any,
argName: string,
allowEmpty = false,
) {
if (typeof args?.[argName] === "undefined") {
return undefined;
}
return getStringArg(args, argName, allowEmpty);
}
export function getBooleanArg(args: any, argName: string, required = false) {
if (!args || !(argName in args)) {
if (required) {
throw new Error(`Argument \`${argName}\` is required (type boolean)`);
} else {
return undefined;
}
}
if (typeof args[argName] === "string") {
if (args[argName].toLowerCase() === "false") {
return false;
}
if (args[argName].toLowerCase() === "true") {
return true;
}
}
if (typeof args[argName] !== "boolean") {
throw new Error(`Argument \`${argName}\` must be a boolean true or false`);
}
return args[argName];
}

View file

@ -0,0 +1,248 @@
import { describe, expect, it } from "vitest";
import { ToolCallDelta } from "..";
import {
getBooleanArg,
getOptionalStringArg,
getStringArg,
safeParseToolCallArgs,
} from "./parseArgs";
describe("safeParseToolCallArgs", () => {
it("should parse valid JSON arguments", () => {
const toolCall: ToolCallDelta = {
id: "1",
function: {
name: "testFunction",
arguments: '{"name": "test", "value": 123}',
},
};
const result = safeParseToolCallArgs(toolCall);
expect(result).toEqual({ name: "test", value: 123 });
});
it("should parse valid JSON arguments with whitespace", () => {
const toolCall: ToolCallDelta = {
id: "1",
function: {
name: "testFunction",
arguments: ' {"name": "test", "value": 123} ',
},
};
const result = safeParseToolCallArgs(toolCall);
expect(result).toEqual({ name: "test", value: 123 });
});
it("should return empty object for invalid JSON", () => {
const toolCall: ToolCallDelta = {
id: "1",
function: {
name: "testFunction",
arguments: '{"name": "test", value: 123', // Invalid JSON
},
};
const result = safeParseToolCallArgs(toolCall);
expect(result).toEqual({});
});
it("should return empty object when arguments is empty", () => {
const toolCall: ToolCallDelta = {
id: "1",
function: {
name: "testFunction",
arguments: "",
},
};
const result = safeParseToolCallArgs(toolCall);
expect(result).toEqual({});
});
it("should return empty object when arguments is null or undefined", () => {
const toolCall1: ToolCallDelta = {
id: "1",
function: {
name: "testFunction",
arguments: null as any,
},
};
const toolCall2: ToolCallDelta = {
id: "1",
function: {
name: "testFunction",
arguments: undefined,
},
};
expect(safeParseToolCallArgs(toolCall1)).toEqual({});
expect(safeParseToolCallArgs(toolCall2)).toEqual({});
});
it("should handle case when function is undefined", () => {
const toolCall: ToolCallDelta = {
id: "1",
function: undefined,
};
const result = safeParseToolCallArgs(toolCall);
expect(result).toEqual({});
});
});
describe("getStringArg", () => {
it("should return string argument when valid", () => {
const args = { name: "test" };
const result = getStringArg(args, "name");
expect(result).toBe("test");
});
it("should throw error when argument is missing", () => {
const args = { otherArg: "test" };
expect(() => getStringArg(args, "name")).toThrowError(
"`name` argument is required and must not be empty. (type string)",
);
});
it("should throw error when argument is not a string", () => {
const args = { name: 123 };
expect(() => getStringArg(args, "name")).toThrowError(
"`name` argument is required and must not be empty. (type string)",
);
});
it("should throw error when argument is empty and empty not allowed", () => {
const args = { name: "" };
expect(() => getStringArg(args, "name")).toThrowError(
"Argument name must not be empty",
);
const argsWithSpace = { name: " " };
expect(() => getStringArg(argsWithSpace, "name")).toThrowError(
"Argument name must not be empty",
);
});
it("should accept empty string when allowEmpty is true", () => {
const args = { name: "" };
const result = getStringArg(args, "name", true);
expect(result).toBe("");
const argsWithSpace = { name: " " };
const resultWithSpace = getStringArg(argsWithSpace, "name", true);
expect(resultWithSpace).toBe(" ");
});
it("should handle null or undefined args", () => {
expect(() => getStringArg(null, "name")).toThrowError(
"`name` argument is required and must not be empty. (type string)",
);
expect(() => getStringArg(undefined, "name")).toThrowError(
"`name` argument is required and must not be empty. (type string)",
);
});
});
describe("getOptionalStringArg", () => {
it("should return undefined when argument is not provided", () => {
const args = { otherArg: "test" };
const result = getOptionalStringArg(args, "name");
expect(result).toBeUndefined();
});
it("should return string argument when valid", () => {
const args = { name: "test" };
const result = getOptionalStringArg(args, "name");
expect(result).toBe("test");
});
it("should throw error when argument is not a string", () => {
const args = { name: 123 };
expect(() => getOptionalStringArg(args, "name")).toThrowError(
"`name` argument is required and must not be empty. (type string)",
);
});
it("should throw error when argument is empty and empty not allowed", () => {
const args = { name: "" };
expect(() => getOptionalStringArg(args, "name")).toThrowError(
"Argument name must not be empty",
);
});
it("should accept empty string when allowEmpty is true", () => {
const args = { name: "" };
const result = getOptionalStringArg(args, "name", true);
expect(result).toBe("");
});
it("should handle null or undefined args", () => {
expect(getOptionalStringArg(null, "name")).toBeUndefined();
expect(getOptionalStringArg(undefined, "name")).toBeUndefined();
});
});
describe("getBooleanArg", () => {
it("should return boolean argument when valid", () => {
const argsTrue = { flag: true };
const argsFalse = { flag: false };
expect(getBooleanArg(argsTrue, "flag")).toBe(true);
expect(getBooleanArg(argsFalse, "flag")).toBe(false);
});
it("should return undefined when argument is not provided and not required", () => {
const args = { otherArg: true };
const result = getBooleanArg(args, "flag");
expect(result).toBeUndefined();
});
it("should throw error when argument is not provided and required", () => {
const args = { otherArg: true };
expect(() => getBooleanArg(args, "flag", true)).toThrowError(
"Argument `flag` is required (type boolean)",
);
});
it('should handle string "true" and "false" values', () => {
const argsStringTrue = { flag: "true" };
const argsStringFalse = { flag: "false" };
const argsStringTrueUppercase = { flag: "TRUE" };
const argsStringFalseUppercase = { flag: "FALSE" };
expect(getBooleanArg(argsStringTrue, "flag")).toBe(true);
expect(getBooleanArg(argsStringFalse, "flag")).toBe(false);
expect(getBooleanArg(argsStringTrueUppercase, "flag")).toBe(true);
expect(getBooleanArg(argsStringFalseUppercase, "flag")).toBe(false);
});
it("should throw error when argument is not a boolean or valid boolean string", () => {
const argsNumber = { flag: 1 };
const argsInvalidString = { flag: "yes" };
const argsObject = { flag: {} };
expect(() => getBooleanArg(argsNumber, "flag")).toThrowError(
"Argument `flag` must be a boolean true or false",
);
expect(() => getBooleanArg(argsInvalidString, "flag")).toThrowError(
"Argument `flag` must be a boolean true or false",
);
expect(() => getBooleanArg(argsObject, "flag")).toThrowError(
"Argument `flag` must be a boolean true or false",
);
});
it("should handle null or undefined args", () => {
expect(getBooleanArg(null, "flag")).toBeUndefined();
expect(getBooleanArg(undefined, "flag")).toBeUndefined();
expect(() => getBooleanArg(null, "flag", true)).toThrowError(
"Argument `flag` is required (type boolean)",
);
expect(() => getBooleanArg(undefined, "flag", true)).toThrowError(
"Argument `flag` is required (type boolean)",
);
});
});

View file

@ -16,6 +16,8 @@
"noEmit": true,
"jsx": "react-jsx",
"noEmitOnError": false,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"types": ["jest", "node"]
},
"include": ["./**/*.ts", "./**/*.js", "./**/*.d.ts"],

View file

@ -1,7 +1,6 @@
// core/util/GlobalContext.test.ts
import { GlobalContext, GlobalContextType } from "./GlobalContext";
import fs from "node:fs";
import path from "path";
import { GlobalContext } from "./GlobalContext";
import { getGlobalContextFilePath } from "./paths";
describe("GlobalContext", () => {
@ -69,13 +68,40 @@ describe("GlobalContext", () => {
const value = globalContext.get("indexingPaused");
expect(value).toBeUndefined();
expect(consoleWarnMock).toHaveBeenCalledWith(
expect.stringContaining("Error parsing global context"),
expect.stringContaining(
"Error parsing global context, deleting corrupted file",
),
);
// Clean up
consoleWarnMock.mockRestore();
});
it("should delete corrupted file on get and allow fresh start", () => {
// Write invalid JSON to the file
fs.writeFileSync(globalContextFilePath, "{ invalid json }");
expect(fs.existsSync(globalContextFilePath)).toBe(true);
const consoleWarnMock = jest
.spyOn(console, "warn")
.mockImplementation(() => {});
// Try to get a value - this should delete the corrupted file
const value = globalContext.get("indexingPaused");
expect(value).toBeUndefined();
// File should be deleted after corruption is detected
expect(fs.existsSync(globalContextFilePath)).toBe(false);
// Now we should be able to update and get values normally
globalContext.update("indexingPaused", true);
const newValue = globalContext.get("indexingPaused");
expect(newValue).toBe(true);
// Clean up
consoleWarnMock.mockRestore();
});
it("should handle JSON parsing errors gracefully on update", () => {
// Write invalid JSON to the file
fs.writeFileSync(globalContextFilePath, "{ invalid json }");
@ -87,15 +113,45 @@ describe("GlobalContext", () => {
// Attempt to update
globalContext.update("indexingPaused", true);
// The update should have been skipped due to JSON parsing error
// So attempting to get the value should return undefined
const value = globalContext.get("indexingPaused");
expect(value).toBeUndefined();
expect(consoleWarnMock).toHaveBeenCalledWith(
expect.stringContaining("Error updating global context"),
expect.stringContaining(
"Error updating global context, deleting corrupted file",
),
);
// The update should have recreated the file with just the new value
const value = globalContext.get("indexingPaused");
expect(value).toBe(true);
// Clean up
consoleWarnMock.mockRestore();
});
it("should delete and recreate corrupted file on update", () => {
// Write invalid JSON to the file
fs.writeFileSync(globalContextFilePath, "{ invalid json }");
expect(fs.existsSync(globalContextFilePath)).toBe(true);
const consoleWarnMock = jest
.spyOn(console, "warn")
.mockImplementation(() => {});
// Try to update - this should delete the corrupted file and recreate it
globalContext.update("indexingPaused", true);
// File should still exist but with valid JSON now
expect(fs.existsSync(globalContextFilePath)).toBe(true);
// Should be able to read the value
const value = globalContext.get("indexingPaused");
expect(value).toBe(true);
// Should be able to add more values
globalContext.update("hasAlreadyCreatedAPromptFile", false);
expect(globalContext.get("hasAlreadyCreatedAPromptFile")).toBe(false);
// Original value should still be there
expect(globalContext.get("indexingPaused")).toBe(true);
// Clean up
consoleWarnMock.mockRestore();
});

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