Merge branch 'main' into pe/required-tool-tests

This commit is contained in:
Nate 2025-07-21 22:04:32 -07:00
commit 7a58fe7116
852 changed files with 38835 additions and 30399 deletions

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

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

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:",
"```",

32
.github/workflows/docs.yml vendored Normal file
View file

@ -0,0 +1,32 @@
name: Docs Check
on:
push:
paths:
- 'docs2/**'
pull_request:
paths:
- 'docs2/**'
jobs:
check-broken-links:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '18'
cache: 'npm'
cache-dependency-path: docs2/package-lock.json
- name: Install dependencies
working-directory: ./docs2
run: npm ci
- name: Check for broken links
working-directory: ./docs2
run: npx mintlify broken-links

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/

View file

@ -17,12 +17,12 @@ past and future “Contributions” submitted to **Continue (the “Project”)*
## 2. Copyright License
You grant **Continue Dev, Inc.** and all recipients of software distributed by the
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
## 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

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>

1
binary/.gitignore vendored
View file

@ -3,3 +3,4 @@ bin
data
out
tmp
tree-sitter

View file

@ -21,6 +21,7 @@ function cleanSlate() {
rimrafSync(out);
rimrafSync(build);
rimrafSync(path.join(__dirname, "tmp"));
rimrafSync(path.join(__dirname, "tree-sitter"));
fs.mkdirSync(bin);
fs.mkdirSync(out);
fs.mkdirSync(build);
@ -142,6 +143,25 @@ async function buildWithEsbuild() {
);
});
// copy tree-sitter colder to binary folder to make it available when running in intellij debug mode
const treeSitterDir = path.join(__dirname, "tree-sitter");
fs.mkdirSync(treeSitterDir);
await new Promise((resolve, reject) => {
ncp(
path.join(__dirname, "..", "extensions", "vscode", "tree-sitter"),
treeSitterDir,
{ dereference: true },
(error) => {
if (error) {
console.warn("[error] Error copying tree-sitter files", error);
reject(error);
} else {
resolve();
}
},
);
});
const filesToCopy = [
"../core/vendor/tree-sitter.wasm",
"../core/llm/llamaTokenizerWorkerPool.mjs",

View file

@ -121,6 +121,8 @@
"@babel/preset-env": "^7.24.7",
"@biomejs/biome": "1.6.4",
"@google/generative-ai": "^0.11.4",
"@shikijs/colorized-brackets": "^3.7.0",
"@shikijs/transformers": "^3.7.0",
"@types/diff": "^7.0.1",
"@types/follow-redirects": "^1.14.4",
"@types/jest": "^29.5.12",

View file

@ -11,6 +11,7 @@
"../../../core/node_modules/sqlite3/**/*",
"../../out/tree-sitter.wasm",
"../../out/tree-sitter-wasms/*",
"../../tree-sitter/**/*",
"../../out/llamaTokenizer.mjs",
"../../out/llamaTokenizerWorkerPool.mjs",
"../../out/tiktokenWorkerPool.mjs",

View file

@ -11,6 +11,7 @@
"../../../core/node_modules/sqlite3/**/*",
"../../out/tree-sitter.wasm",
"../../out/tree-sitter-wasms/*",
"../../tree-sitter/**/*",
"../../out/llamaTokenizer.mjs",
"../../out/llamaTokenizerWorkerPool.mjs",
"../../out/tiktokenWorkerPool.mjs",

View file

@ -11,6 +11,7 @@
"../../../core/node_modules/sqlite3/**/*",
"../../out/tree-sitter.wasm",
"../../out/tree-sitter-wasms/*",
"../../tree-sitter/**/*",
"../../out/llamaTokenizer.mjs",
"../../out/llamaTokenizerWorkerPool.mjs",
"../../out/tiktokenWorkerPool.mjs",

View file

@ -11,6 +11,7 @@
"../../../core/node_modules/sqlite3/**/*",
"../../out/tree-sitter.wasm",
"../../out/tree-sitter-wasms/*",
"../../tree-sitter/**/*",
"../../out/llamaTokenizer.mjs",
"../../out/llamaTokenizerWorkerPool.mjs",
"../../out/tiktokenWorkerPool.mjs",

View file

@ -11,6 +11,7 @@
"../../../core/node_modules/sqlite3/**/*",
"../../out/tree-sitter.wasm",
"../../out/tree-sitter-wasms/*",
"../../tree-sitter/**/*",
"../../node_modules/win-ca/lib/crypt32-ia32.node",
"../../node_modules/win-ca/lib/crypt32-x64.node",
"../../node_modules/win-ca/lib/roots.exe",

View file

@ -11,6 +11,7 @@
"../../../core/node_modules/sqlite3/**/*",
"../../out/tree-sitter.wasm",
"../../out/tree-sitter-wasms/*",
"../../tree-sitter/**/*",
"../../node_modules/win-ca/lib/crypt32-ia32.node",
"../../node_modules/win-ca/lib/crypt32-x64.node",
"../../node_modules/win-ca/lib/roots.exe",

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

@ -10,7 +10,7 @@ import { BracketMatchingService } from "./filtering/BracketMatchingService.js";
import { CompletionStreamer } from "./generation/CompletionStreamer.js";
import { postprocessCompletion } from "./postprocessing/index.js";
import { shouldPrefilter } from "./prefiltering/index.js";
import { getAllSnippets } from "./snippets/index.js";
import { getAllSnippetsWithoutRace } from "./snippets/index.js";
import { renderPrompt } from "./templating/index.js";
import { GetLspDefinitionsFunction } from "./types.js";
import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js";
@ -121,6 +121,12 @@ export class CompletionProvider {
...config?.tabAutocompleteOptions,
...llm.autocompleteOptions,
};
// Enable static contextualization if defined.
if (config?.experimental?.enableStaticContextualization) {
options.experimental_enableStaticContextualization = true;
}
return options;
}
@ -171,7 +177,7 @@ export class CompletionProvider {
}
const [snippetPayload, workspaceDirs] = await Promise.all([
getAllSnippets({
getAllSnippetsWithoutRace({
helper,
ide: this.ide,
getDefinitionsFromLsp: this.getDefinitionsFromLsp,
@ -258,6 +264,10 @@ export class CompletionProvider {
...helper.options,
};
if (options.experimental_enableStaticContextualization) {
outcome.enabledStaticContextualization = true;
}
//////////
// Save to cache

View file

@ -2,16 +2,19 @@ import { IDE } from "../..";
import {
AutocompleteCodeSnippet,
AutocompleteSnippetType,
AutocompleteStaticSnippet,
} from "../snippets/types";
import { HelperVars } from "../util/HelperVars";
import { ImportDefinitionsService } from "./ImportDefinitionsService";
import { getSymbolsForSnippet } from "./ranking";
import { RootPathContextService } from "./root-path-context/RootPathContextService";
import { StaticContextService } from "./static-context/StaticContextService";
export class ContextRetrievalService {
private importDefinitionsService: ImportDefinitionsService;
private rootPathContextService: RootPathContextService;
private staticContextService: StaticContextService;
constructor(private readonly ide: IDE) {
this.importDefinitionsService = new ImportDefinitionsService(this.ide);
@ -19,6 +22,7 @@ export class ContextRetrievalService {
this.importDefinitionsService,
this.ide,
);
this.staticContextService = new StaticContextService(this.ide);
}
public async getSnippetsFromImportDefinitions(
@ -71,6 +75,12 @@ export class ContextRetrievalService {
);
}
public async getStaticContextSnippets(
helper: HelperVars,
): Promise<AutocompleteStaticSnippet[]> {
return this.staticContextService.getContext(helper);
}
/**
* Initialize the import definitions cache for a file.
* This is normally done automatically when the active text editor changes,

View file

@ -0,0 +1,888 @@
import * as fs from "fs/promises";
import path from "path";
import { pathToFileURL } from "url";
import Parser from "web-tree-sitter";
import { IDE, Position } from "../../..";
import { localPathOrUriToPath } from "../../../util/pathToUri";
import { getFullLanguageName, getQueryForFile } from "../../../util/treeSitter";
import {
AutocompleteSnippetType,
AutocompleteStaticSnippet,
} from "../../snippets/types";
import { getAst } from "../../util/ast";
import { HelperVars } from "../../util/HelperVars";
import {
extractFunctionTypeFromDecl,
extractTopLevelDecls,
findEnclosingTypeDeclaration,
unwrapToBaseType,
} from "./tree-sitter-utils";
import {
HoleContext,
RelevantHeaders,
RelevantTypes,
StaticContext,
TypeSpanAndSourceFile,
TypeSpanAndSourceFileAndAst,
} from "./types";
export class StaticContextService {
private readonly ide: IDE;
constructor(ide: IDE) {
this.ide = ide;
}
public logAutocompleteStaticSnippet(
ctx: StaticContext,
label = "Static Snippet",
) {
console.log(`=== ${label} ===`);
console.log("Hole Type:", ctx.holeType);
console.log(`\nRelevant Types (${ctx.relevantTypes.size} files):`);
ctx.relevantTypes.forEach((types, filepath) => {
console.log(` 📁 ${filepath}`);
types.forEach((type) => console.log(` • ${type}`));
});
console.log(`\nRelevant Headers (${ctx.relevantHeaders.size} files):`);
ctx.relevantHeaders.forEach((headers, filepath) => {
console.log(` 📁 ${filepath}`);
headers.forEach((header) => console.log(` • ${header}`));
});
}
public static formatAutocompleteStaticSnippet(ctx: StaticContext): string {
let output = `AutocompleteStaticSnippet:\n`;
output += ` holeType: ${ctx.holeType}\n`;
output += ` relevantTypes:\n`;
if (ctx.relevantTypes.size === 0) {
output += ` (none)\n`;
} else {
ctx.relevantTypes.forEach((types, filepath) => {
output += ` ${filepath}: [${types.join(", ")}]\n`;
});
}
output += ` relevantHeaders:\n`;
if (ctx.relevantHeaders.size === 0) {
output += ` (none)\n`;
} else {
ctx.relevantHeaders.forEach((headers, filepath) => {
output += ` ${filepath}: [${headers.join(", ")}]\n`;
});
}
return output;
}
public async getContext(
helper: HelperVars,
): Promise<AutocompleteStaticSnippet[]> {
const start = Date.now();
const tsFiles = await this.getTypeScriptFilesFromWorkspaces(
helper.workspaceUris,
);
// Get the three contexts holeContext, relevantTypes, relevantHeaders.
const holeContext = await this.getHoleContext(
helper.fileContents,
helper.filepath,
helper.pos,
);
const relevantTypes = await this.extractRelevantTypes(
holeContext.fullHoverResult,
holeContext.functionName,
holeContext.range.start.line,
holeContext.source,
new Map<string, string>(),
);
// if (this.language === "typescript") {
// repo = getAllTSFiles(this.repoPath);
// } else if (this.language === "ocaml") {
// repo = getAllOCamlFiles(this.repoPath);
// }
//
const relevantHeaders = await this.extractRelevantHeaders(
tsFiles,
relevantTypes,
holeContext.functionTypeSpan,
helper.pos,
holeContext.returnTypeIsAny,
);
const relevantTypesToReturn: Map<string, string[]> = new Map<
string,
string[]
>();
relevantTypes.forEach(({ typeSpan: v, sourceFile: src }, _) => {
if (relevantTypesToReturn.has(src)) {
const updated = relevantTypesToReturn.get(src)!;
updated.push(v);
relevantTypesToReturn.set(src, updated);
} else {
relevantTypesToReturn.set(src, [v]);
}
});
const relevantHeadersToReturn: Map<string, string[]> = new Map<
string,
string[]
>();
relevantHeaders.forEach(({ typeSpan: v, sourceFile: src }) => {
if (relevantHeadersToReturn.has(src)) {
const updated = relevantHeadersToReturn.get(src)!;
if (!updated.includes(v)) {
updated.push(v);
}
relevantHeadersToReturn.set(src, updated);
} else {
relevantHeadersToReturn.set(src, [v]);
}
});
const ctx = {
holeType: holeContext.functionTypeSpan,
relevantTypes: relevantTypesToReturn,
relevantHeaders: relevantHeadersToReturn,
};
const end = Date.now();
this.logAutocompleteStaticSnippet(ctx);
// console.log(end - start);
const snippets: AutocompleteStaticSnippet[] = [];
snippets.push({
type: AutocompleteSnippetType.Static,
filepath: pathToFileURL(path.resolve(holeContext.source)).toString(),
content: holeContext.fullHoverResult,
});
for (const [filepath, typs] of ctx.relevantTypes.entries()) {
snippets.push({
type: AutocompleteSnippetType.Static,
filepath: pathToFileURL(path.resolve(filepath)).toString(),
content: typs.join("\n"),
});
}
for (const [filepath, headers] of ctx.relevantHeaders.entries()) {
snippets.push({
type: AutocompleteSnippetType.Static,
filepath: pathToFileURL(path.resolve(filepath)).toString(),
content: headers.join("\n"),
});
}
return snippets;
}
private async getHoleContext(
sketchFileContent: string,
sketchFilePath: string,
cursorPosition: Position,
): Promise<HoleContext> {
// We need to inject the hole @ to trigger a treesitter error node.
sketchFilePath = localPathOrUriToPath(sketchFilePath);
// const sketchFileContent = await fs.readFile(sketchFilePath, "utf8");
const injectedContent = this.insertAtPosition(
sketchFileContent,
cursorPosition,
"@;",
);
// The hole's position is cursorPosition.
// Use treesitter to parse.
const ast = await getAst(sketchFilePath, injectedContent);
if (!ast) {
throw new Error("failed to get ast");
}
const language = getFullLanguageName(sketchFilePath);
const query = await getQueryForFile(
sketchFilePath,
`static-context-queries/hole-queries/${language}.scm`,
);
if (!query) {
throw new Error(
`getHoleContext: failed to get query for file ${sketchFilePath} and language ${language}`,
);
}
const captures = query.captures(ast.rootNode);
const res: HoleContext = {
fullHoverResult: "",
functionName: "",
functionTypeSpan: "",
returnTypeIsAny: false,
range: {
start: { line: 0, character: 0 },
end: { line: 0, character: 0 },
},
source: `file://${sketchFilePath}`,
};
let paramsTypes = "";
for (const c of captures) {
const { name, node } = c;
// console.log(`${name} →`, node.text, node.startPosition, node.endPosition);
switch (name) {
case "function.decl": {
res.fullHoverResult = node.text;
break;
}
case "function.name": {
res.functionName = node.text;
break;
}
case "function.params": {
paramsTypes = node.text;
res.range = {
start: {
line: node.startPosition.row,
character: node.startPosition.column,
},
end: {
line: node.endPosition.row,
character: node.endPosition.column,
},
};
break;
}
case "function.type": {
res.functionTypeSpan = node.text;
res.range = {
start: {
line: node.startPosition.row,
character: node.startPosition.column,
},
end: {
line: node.endPosition.row,
character: node.endPosition.column,
},
};
break;
}
}
}
if (res.functionTypeSpan === "") {
res.functionTypeSpan = `${paramsTypes} => any`;
res.returnTypeIsAny = true;
}
return res;
}
private async extractRelevantTypes(
declText: string,
typeName: string,
startLine: number,
currentFile: string,
foundContents: Map<string, string>, // uri -> contents
): Promise<RelevantTypes> {
const foundSoFar = new Map<string, TypeSpanAndSourceFileAndAst>(); // identifier -> [full hover result, source]
await this.extractRelevantTypesHelper(
declText,
typeName,
startLine,
foundSoFar,
currentFile,
foundContents,
);
return foundSoFar;
}
private async extractRelevantTypesHelper(
declText: string,
typeName: string,
startLine: number,
foundSoFar: Map<string, TypeSpanAndSourceFileAndAst>, // identifier -> [full hover result, source]
currentFile: string,
foundContents: Map<string, string>, // uri -> contents
) {
if (!foundSoFar.has(typeName)) {
const ast = await getAst(currentFile, declText);
if (!ast) {
throw new Error(`failed to get ast for file ${currentFile}`);
}
foundSoFar.set(typeName, {
typeSpan: declText,
sourceFile: currentFile.slice(7),
ast: ast,
});
const language = getFullLanguageName(currentFile);
const query = await getQueryForFile(
currentFile,
`static-context-queries/relevant-types-queries/${language}-extract-identifiers.scm`,
);
if (!query) {
throw new Error(
`failed to get query for file ${currentFile} and language ${language}`,
);
}
const identifiers = query.captures(ast.rootNode);
for (const { name, node } of identifiers) {
if (foundSoFar.has(node.text)) continue;
try {
const typeDefinitionResult = await this.ide.gotoTypeDefinition({
filepath: currentFile,
position: {
character: node.startPosition.column,
line: startLine + node.startPosition.row,
},
});
if (typeDefinitionResult.length > 0) {
const tdLocation = typeDefinitionResult[0];
let content = "";
if (foundContents.has(tdLocation.filepath)) {
content = foundContents.get(tdLocation.filepath)!;
} else {
content = await fs.readFile(
localPathOrUriToPath(tdLocation.filepath),
"utf8",
);
foundContents.set(tdLocation.filepath, content);
}
const ast = await getAst(tdLocation.filepath, content);
if (!ast) {
throw new Error(
`failed to get ast for file ${tdLocation.filepath}`,
);
}
const decl = findEnclosingTypeDeclaration(
content,
tdLocation.range.start.line,
tdLocation.range.start.character,
ast,
);
if (!decl) {
// throw new Error(`failed to get decl for file ${tdLocation.uri}`);
console.error(
`failed to get decl for file ${tdLocation.filepath}`,
);
}
if (decl) {
await this.extractRelevantTypesHelper(
decl.fullText,
node.text,
tdLocation.range.start.line,
foundSoFar,
tdLocation.filepath,
foundContents,
);
} else {
// console.log("decl not found");
}
} else {
// console.log("td not found");
}
} catch (err) {
console.log(err);
}
}
}
}
private async extractRelevantHeaders(
sources: string[],
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
holeType: string,
cursorPosition: Position,
returnTypeIsAny: boolean,
): Promise<RelevantHeaders> {
const relevantContext = new Set<TypeSpanAndSourceFile>();
if (returnTypeIsAny) return relevantContext;
// NOTE: This is necessary because TypeScript sucks.
// There is no way to compare objects by value,
// so sets of objects starts to accumulate tons of duplicates.
const relevantContextMap = new Map<string, TypeSpanAndSourceFile>();
const foundNormalForms = new Map<string, string>();
const targetTypes = await this.generateTargetTypes(relevantTypes, holeType);
for (const source of sources) {
const topLevelDecls = await extractTopLevelDecls(source);
for (const tld of topLevelDecls) {
// pattern 0 is let/const, 1 is var, 2 is fun
// if (!seenDecls.has(JSON.stringify()) {
const originalDeclText =
tld.pattern === 2
? tld.captures.find((d) => d.name === "top.fn.decl")!.node.text
: tld.captures.find((d) => d.name === "top.var.decl")!.node.text;
if (tld.pattern === 2) {
// build a type span
// TODO: this fails sometimes with Cannot read properties of undefined (reading 'text')
// most likely due to my scm query and how I'm not attaching param name along with param type
let funcType = "";
try {
funcType = extractFunctionTypeFromDecl(tld);
} catch (err) {
// Most likely is the case that there is no explicit return type annotation.
const sigHelp = await this.ide.getSignatureHelp({
filepath: source,
position: cursorPosition,
});
if (!sigHelp) continue;
funcType = sigHelp.signatures[0].label;
// TODO: This only works for TypeScript.
function convertToArrowType(signature: string): string {
// Handle various function declaration formats.
const patterns = [
// Standard: functionName(params): returnType.
/^(\w+)\s*\((.*?)\)\s*:\s*(.+)$/,
// With generics: functionName<T>(params): returnType.
/^(\w+)\s*<[^>]*>\s*\((.*?)\)\s*:\s*(.+)$/,
// With modifiers: export function functionName(params): returnType.
/^(?:export\s+)?(?:function\s+)?(\w+)\s*\((.*?)\)\s*:\s*(.+)$/,
];
for (const pattern of patterns) {
const match = signature.match(pattern);
if (match) {
const [, , parameters, returnType] = match;
return `(${parameters}) => ${returnType}`;
}
}
return signature;
}
funcType = convertToArrowType(funcType);
}
const wrapped = `type __TMP = ${funcType};`;
const ast = await getAst("file.ts", wrapped);
if (!ast) {
throw new Error(`failed to generate ast for ${wrapped}`);
}
// console.log(ast.rootNode);
const alias = ast.rootNode.namedChild(0);
// console.log(alias);
if (!alias || alias.type !== "type_alias_declaration") {
throw new Error(
"extractRelevantHeaders: Failed to parse type alias",
);
}
const valueNode = alias.childForFieldName("value");
if (!valueNode) throw new Error("No type value found");
const baseNode = unwrapToBaseType(valueNode);
await this.extractRelevantHeadersHelper(
originalDeclText,
baseNode,
targetTypes,
relevantTypes,
relevantContext,
relevantContextMap,
foundNormalForms,
source,
);
} else {
const varTypNode = tld.captures.find(
(d) => d.name === "top.var.type",
)!.node;
await this.extractRelevantHeadersHelper(
originalDeclText,
varTypNode,
targetTypes,
relevantTypes,
relevantContext,
relevantContextMap,
foundNormalForms,
source,
);
}
}
}
for (const v of relevantContextMap.values()) {
relevantContext.add(v);
}
return relevantContext;
}
private async extractRelevantHeadersHelper(
originalDeclText: string,
node: Parser.SyntaxNode,
targetTypes: Set<Parser.SyntaxNode>,
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
relevantContext: Set<TypeSpanAndSourceFile>,
relevantContextMap: Map<string, TypeSpanAndSourceFile>,
foundNormalForms: Map<string, string>,
source: string,
) {
for (const typ of targetTypes) {
if (
await this.isTypeEquivalent(node, typ, relevantTypes, foundNormalForms)
) {
const ctx = { typeSpan: originalDeclText, sourceFile: source };
relevantContextMap.set(JSON.stringify(ctx), ctx);
}
if (node.type === "function_type") {
const retTypeNode = node.namedChildren.find(
(c) => c && c.type === "return_type",
);
if (retTypeNode) {
await this.extractRelevantHeadersHelper(
originalDeclText,
retTypeNode,
targetTypes,
relevantTypes,
relevantContext,
relevantContextMap,
foundNormalForms,
source,
);
}
} else if (node.type === "tuple_type") {
for (const c of node.namedChildren) {
await this.extractRelevantHeadersHelper(
originalDeclText,
c!,
targetTypes,
relevantTypes,
relevantContext,
relevantContextMap,
foundNormalForms,
source,
);
}
}
}
}
private async generateTargetTypes(
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
holeType: string,
) {
const targetTypes = new Set<Parser.SyntaxNode>();
// const ast = relevantTypes.get(holeIdentifier)!.ast;
const ast = await getAst("file.ts", `type T = ${holeType};`);
if (!ast) {
throw new Error(`failed to generate ast for ${holeType}`);
}
const alias = ast.rootNode.namedChild(0);
if (!alias || alias.type !== "type_alias_declaration") {
throw new Error("generateTargetTypes: Failed to parse type alias");
}
const valueNode = alias.childForFieldName("value");
if (!valueNode) throw new Error("No type value found");
const baseNode = unwrapToBaseType(valueNode);
targetTypes.add(baseNode);
await this.generateTargetTypesHelper(
relevantTypes,
holeType,
targetTypes,
baseNode,
);
return targetTypes;
}
private async generateTargetTypesHelper(
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
currType: string,
targetTypes: Set<Parser.SyntaxNode>,
node: Parser.SyntaxNode | null,
): Promise<void> {
if (!node) return;
if (node.type === "function_type") {
const returnType = node.childForFieldName("return_type");
if (returnType) {
targetTypes.add(returnType);
await this.generateTargetTypesHelper(
relevantTypes,
currType,
targetTypes,
returnType,
);
}
}
if (node.type === "tuple_type") {
for (const child of node.namedChildren) {
if (child) {
targetTypes.add(child);
await this.generateTargetTypesHelper(
relevantTypes,
currType,
targetTypes,
child,
);
}
}
}
if (relevantTypes.has(node.text)) {
// const ast = relevantTypes.get(node.text)!.ast;
const typeSpan = relevantTypes.get(node.text)?.typeSpan;
// const ast = await getAst("file.ts", `type T = ${typeSpan}`);
const ast = await getAst("file.ts", typeSpan!);
if (!ast) {
throw new Error(`failed to generate ast for ${typeSpan}`);
}
const alias = ast.rootNode.namedChild(0);
if (!alias || alias.type !== "type_alias_declaration") {
console.error("generateTargetTypesHelper: Failed to parse type alias");
return;
// throw new Error(
// "generateTargetTypesHelper: Failed to parse type alias",
// );
}
const valueNode = alias.childForFieldName("value");
if (!valueNode) throw new Error("No type value found");
const baseNode = unwrapToBaseType(valueNode);
await this.generateTargetTypesHelper(
relevantTypes,
currType,
targetTypes,
baseNode,
);
}
// if (node.type === "type_identifier" || node.type === "predefined_type") {
// return [node.text];
// }
return;
}
private async isTypeEquivalent(
node: Parser.SyntaxNode,
typ: Parser.SyntaxNode,
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
foundNormalForms: Map<string, string>,
): Promise<boolean> {
if (!node || !typ) {
return false;
}
let normT1 = "";
let normT2 = "";
if (foundNormalForms.has(node.text)) {
// console.log("found t1", true)
normT1 = foundNormalForms.get(node.text)!;
} else {
// console.log("not found t1", false)
normT1 = await this.normalize(node, relevantTypes);
foundNormalForms.set(node.text, normT1);
}
if (foundNormalForms.has(typ.text)) {
// console.log("found t2", true)
normT2 = foundNormalForms.get(typ.text)!;
} else {
// console.log("not found t2", false)
normT2 = await this.normalize(typ, relevantTypes);
foundNormalForms.set(typ.text, normT2);
}
// const normT1 = foundNormalForms.has(t1) ? foundNormalForms.get(t1) : this.normalize2(t1, relevantTypes);
// const normT2 = foundNormalForms.has(t2) ? foundNormalForms.get(t2) : this.normalize2(t2, relevantTypes);
// console.log(`normal forms: ${normT1} {}{} ${normT2}`)
return normT1 === normT2;
}
private async normalize(
node: Parser.SyntaxNode,
relevantTypes: Map<string, TypeSpanAndSourceFileAndAst>,
): Promise<string> {
if (!node) return "";
switch (node.type) {
case "function_type": {
const params = node.child(0); // formal_parameters
const returnType =
node.childForFieldName("type") || node.namedChildren[1]; // function_type → parameters, =>, return
const paramTypes =
params?.namedChildren
.map((param) =>
this.normalize(
param!.childForFieldName("type")! ||
param!.namedChildren.at(-1),
relevantTypes,
),
)
.join(", ") || "";
const ret = this.normalize(returnType!, relevantTypes);
return `(${paramTypes}) => ${ret}`;
}
case "tuple_type": {
const elements = node.namedChildren.map((c) =>
this.normalize(c!, relevantTypes),
);
return `[${elements.join(", ")}]`;
}
case "union_type": {
const parts = node.namedChildren.map((c) =>
this.normalize(c!, relevantTypes),
);
return parts.join(" | ");
}
case "type_identifier": {
const alias = relevantTypes.get(node.text);
if (!alias) return node.text;
// Parse the alias's type span
const wrapped = `type __TMP = ${alias};`;
const tree = await getAst("file.ts", wrapped);
const valueNode = tree!.rootNode
.descendantsOfType("type_alias_declaration")[0]
?.childForFieldName("value");
return this.normalize(valueNode!, relevantTypes);
}
case "predefined_type":
case "number":
case "string":
return node.text;
default:
// Fallback for types like array, etc.
return node.text;
}
}
private insertAtPosition = (
contents: string,
cursorPosition: { line: number; character: number },
insertText: string,
): string => {
const lines = contents.split(/\r?\n/); // Handle both LF and CRLF line endings
const { line, character } = cursorPosition;
if (line < 0 || line >= lines.length) {
throw new Error("Invalid line number");
}
const targetLine = lines[line];
if (character < 0 || character > targetLine.length) {
throw new Error("Invalid character index");
}
// Insert the text
lines[line] =
targetLine.slice(0, character) + insertText + targetLine.slice(character);
return lines.join("\n"); // Reconstruct the file
};
private async getTypeScriptFilesFromWorkspaces(
workspaceUris: string[],
): Promise<string[]> {
const tsExtensions = [".ts"];
const allTsFiles: string[] = [];
for (const workspaceUri of workspaceUris) {
try {
// Convert URI to file path
const folderPath = workspaceUri.startsWith("file://")
? new URL(workspaceUri).pathname
: workspaceUri;
const tsFiles = await this.scanDirectoryForTypeScriptFiles(
folderPath,
tsExtensions,
);
allTsFiles.push(...tsFiles);
} catch (error) {
console.error(`Error scanning workspace ${workspaceUri}:`, error);
}
}
return allTsFiles;
}
private async scanDirectoryForTypeScriptFiles(
dirPath: string,
tsExtensions: string[],
): Promise<string[]> {
const tsFiles: string[] = [];
const shouldSkipDirectory = (dirName: string): boolean => {
const skipDirs = [
"node_modules",
".git",
".vscode",
"dist",
"build",
"out",
".next",
"coverage",
".nyc_output",
"tmp",
"temp",
".cache",
];
return skipDirs.includes(dirName) || dirName.startsWith(".");
};
async function scanRecursively(currentPath: string): Promise<void> {
try {
const entries = await fs.readdir(currentPath, {
withFileTypes: true,
});
for (const entry of entries) {
const fullPath = localPathOrUriToPath(
path.join(currentPath, entry.name),
);
if (entry.isDirectory()) {
// Skip common directories that typically don't contain source files
if (!shouldSkipDirectory(entry.name)) {
await scanRecursively(fullPath);
}
} else if (entry.isFile()) {
const extension = path.extname(entry.name).toLowerCase();
if (tsExtensions.includes(extension)) {
tsFiles.push(fullPath);
}
}
}
} catch (error) {
console.error(`Error reading directory ${currentPath}:`, error);
}
}
await scanRecursively(dirPath);
return tsFiles;
}
}

View file

@ -0,0 +1,222 @@
import * as fs from "fs/promises";
import Parser from "web-tree-sitter";
import { getFullLanguageName, getQueryForFile } from "../../../util/treeSitter";
import { getAst } from "../../util/ast";
export interface TypeDeclarationResult {
name: string;
fullText: string;
startLine: number;
startColumn: number;
endLine: number;
endColumn: number;
kind: string;
}
export function findEnclosingTypeDeclaration(
sourceCode: string,
cursorLine: number,
cursorColumn: number,
ast: Parser.Tree,
): TypeDeclarationResult | null {
const point = { row: cursorLine, column: cursorColumn };
let node = ast.rootNode.descendantForPosition(point);
while (
node &&
![
"type_alias_declaration",
"interface_declaration",
"enum_declaration",
].includes(node.type)
) {
if (!node.parent) return null;
node = node.parent;
}
if (!node) return null;
const nameNode = node.childForFieldName("name");
const name = nameNode?.text ?? "<anonymous>";
const fullText = sourceCode.slice(node.startIndex, node.endIndex);
return {
name,
fullText,
startLine: node.startPosition.row,
startColumn: node.startPosition.column,
endLine: node.endPosition.row,
endColumn: node.endPosition.column,
kind: node.type,
};
}
export async function extractTopLevelDecls(
currentFile: string,
givenParser?: Parser,
) {
const ast = await getAst(currentFile, await fs.readFile(currentFile, "utf8"));
if (!ast) {
throw new Error(`failed to get ast for file ${currentFile}`);
}
let language;
if (givenParser) {
language = givenParser.getLanguage();
} else {
language = getFullLanguageName(currentFile);
}
const query = await getQueryForFile(
currentFile,
`static-context-queries/relevant-headers-queries/${language}-get-toplevel-headers.scm`,
);
if (!query) {
throw new Error(
`failed to get query for file ${currentFile} and language ${language}`,
);
}
return query.matches(ast.rootNode);
}
export async function extractTopLevelDeclsWithFormatting(
currentFile: string,
givenParser?: Parser,
) {
const ast = await getAst(currentFile, await fs.readFile(currentFile, "utf8"));
if (!ast) {
throw new Error(`failed to get ast for file ${currentFile}`);
}
let language;
if (givenParser) {
language = givenParser.getLanguage();
} else {
language = getFullLanguageName(currentFile);
}
const query = await getQueryForFile(
currentFile,
`static-context-queries/relevant-headers-queries/${language}-get-toplevel-headers.scm`,
);
if (!query) {
throw new Error(
`failed to get query for file ${currentFile} and language ${language}`,
);
}
const matches = query.matches(ast.rootNode);
const results = [];
for (const match of matches) {
const item: {
declaration: string;
nodeType: string;
name: string;
declaredType: string;
returnType?: string;
} = {
declaration: "",
nodeType: "",
name: "",
declaredType: "",
};
for (const { name, node } of match.captures) {
if (name === "top.var.decl") {
item.nodeType = "variable";
item.declaration = node.text;
// Attempt to get the declared type (e.g., const x: string = ...)
const typeNode = node.descendantsOfType("type_annotation")[0];
if (typeNode) {
item.declaredType = typeNode.text.replace(/^:\s*/, "");
}
} else if (name === "top.var.name" || name === "top.fn.name") {
item.name = node.text;
} else if (name === "top.fn.decl") {
item.nodeType = "function";
item.declaration = node.text;
// Get the return type (e.g., function foo(): string)
const returnTypeNode = node.childForFieldName("return_type");
if (returnTypeNode) {
item.returnType = returnTypeNode.text.replace(/^:\s*/, "");
}
// Get declaredType if needed (TypeScript style)
const nameNode = node.childForFieldName("name");
if (nameNode && nameNode.nextSibling?.type === "type_annotation") {
item.declaredType = nameNode.nextSibling.text.replace(/^:\s*/, "");
}
}
}
if (item.name && item.declaration) {
results.push(item);
}
}
return results;
}
export function extractFunctionTypeFromDecl(match: Parser.QueryMatch): string {
let paramsNode: Parser.SyntaxNode | undefined = undefined;
let returnNode: Parser.SyntaxNode | undefined = undefined;
for (const capture of match.captures) {
if (capture.name === "top.fn.param.type") {
paramsNode = capture.node;
} else if (capture.name === "top.fn.type") {
returnNode = capture.node;
}
}
if (!paramsNode) {
console.error(
`extractFunctionTypeFromDecl: paramsNode ${paramsNode} not found`,
);
throw new Error(
`extractFunctionTypeFromDecl: paramsNode ${paramsNode} not found`,
);
}
if (!returnNode) {
console.error(
`extractFunctionTypeFromDecl: returnNode ${returnNode} not found`,
);
throw new Error(
`extractFunctionTypeFromDecl: returnNode ${returnNode} not found`,
);
}
return `(${paramsNode!.text}) => ${returnNode!.text}`;
}
export function unwrapToBaseType(node: Parser.SyntaxNode): Parser.SyntaxNode {
if (
[
"function_type",
"tuple_type",
"type_identifier",
"predefined_type",
].includes(node.type)
) {
return node;
}
for (const child of node.namedChildren) {
const unwrapped = unwrapToBaseType(child!);
if (
unwrapped !== child ||
[
"function_type",
"tuple_type",
"type_identifier",
"predefined_type",
].includes(unwrapped.type)
) {
return unwrapped;
}
}
return node;
}

View file

@ -0,0 +1,33 @@
import { Tree } from "web-tree-sitter";
import { Range } from "../../..";
export interface TypeSpanAndSourceFile {
typeSpan: string;
sourceFile: string;
}
export interface TypeSpanAndSourceFileAndAst extends TypeSpanAndSourceFile {
ast: Tree;
}
export interface HoleContext {
fullHoverResult: string;
functionName: string;
functionTypeSpan: string;
returnTypeIsAny: boolean;
range: Range;
source: string;
}
export type RelevantTypes = Map<string, TypeSpanAndSourceFileAndAst>;
export type RelevantHeaders = Set<TypeSpanAndSourceFile>;
export type Filepath = string;
export type RelevantType = string;
export type RelevantHeader = string;
export interface StaticContext {
holeType: string;
relevantTypes: Map<Filepath, RelevantType[]>;
relevantHeaders: Map<Filepath, RelevantHeader[]>;
}

View file

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

@ -11,6 +11,7 @@ import {
AutocompleteCodeSnippet,
AutocompleteDiffSnippet,
AutocompleteSnippetType,
AutocompleteStaticSnippet,
} from "./types";
const IDE_SNIPPETS_ENABLED = false; // ideSnippets is not used, so it's temporarily disabled
@ -24,6 +25,7 @@ export interface SnippetPayload {
diffSnippets: AutocompleteDiffSnippet[];
clipboardSnippets: AutocompleteClipboardSnippet[];
recentlyOpenedFileSnippets: AutocompleteCodeSnippet[];
staticSnippet: AutocompleteStaticSnippet[];
}
function racePromise<T>(promise: Promise<T[]>, timeout = 100): Promise<T[]> {
@ -185,6 +187,7 @@ export const getAllSnippets = async ({
diffSnippets,
clipboardSnippets,
recentlyOpenedFileSnippets,
staticSnippet,
] = await Promise.all([
racePromise(contextRetrievalService.getRootPathSnippets(helper)),
racePromise(
@ -196,6 +199,9 @@ export const getAllSnippets = async ({
[], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882,
racePromise(getClipboardSnippets(ide)),
racePromise(getSnippetsFromRecentlyOpenedFiles(helper, ide)), // giving this one a little more time to complete
helper.options.experimental_enableStaticContextualization
? racePromise(contextRetrievalService.getStaticContextSnippets(helper))
: [],
]);
return {
@ -207,6 +213,7 @@ export const getAllSnippets = async ({
clipboardSnippets,
recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges,
recentlyOpenedFileSnippets,
staticSnippet,
};
};
@ -231,6 +238,7 @@ export const getAllSnippetsWithoutRace = async ({
diffSnippets,
clipboardSnippets,
recentlyOpenedFileSnippets,
staticSnippet,
] = await Promise.all([
contextRetrievalService.getRootPathSnippets(helper),
contextRetrievalService.getSnippetsFromImportDefinitions(helper),
@ -240,6 +248,9 @@ export const getAllSnippetsWithoutRace = async ({
[], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882,
getClipboardSnippets(ide),
getSnippetsFromRecentlyOpenedFiles(helper, ide),
helper.options.experimental_enableStaticContextualization
? contextRetrievalService.getStaticContextSnippets(helper)
: [],
]);
return {
@ -251,5 +262,6 @@ export const getAllSnippetsWithoutRace = async ({
clipboardSnippets,
recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges,
recentlyOpenedFileSnippets,
staticSnippet,
};
};

View file

@ -2,6 +2,7 @@ export enum AutocompleteSnippetType {
Code = "code",
Diff = "diff",
Clipboard = "clipboard",
Static = "static",
}
interface BaseAutocompleteSnippet {
@ -23,7 +24,13 @@ export interface AutocompleteClipboardSnippet extends BaseAutocompleteSnippet {
copiedAt: string;
}
export interface AutocompleteStaticSnippet extends BaseAutocompleteSnippet {
type: AutocompleteSnippetType.Static;
filepath: string;
}
export type AutocompleteSnippet =
| AutocompleteCodeSnippet
| AutocompleteDiffSnippet
| AutocompleteClipboardSnippet;
| AutocompleteClipboardSnippet
| AutocompleteStaticSnippet;

View file

@ -4,6 +4,7 @@ import {
AutocompleteCodeSnippet,
AutocompleteSnippet,
AutocompleteSnippetType,
AutocompleteStaticSnippet,
} from "../snippets/types";
import { HelperVars } from "../util/HelperVars";
import { formatOpenedFilesContext } from "./formatOpenedFilesContext";
@ -32,9 +33,9 @@ const shuffleArray = <T>(array: T[]): T[] => {
};
function filterSnippetsAlreadyInCaretWindow(
snippets: AutocompleteCodeSnippet[],
snippets: (AutocompleteCodeSnippet | AutocompleteStaticSnippet)[],
caretWindow: string,
): AutocompleteCodeSnippet[] {
): (AutocompleteCodeSnippet | AutocompleteStaticSnippet)[] {
return snippets.filter(
(s) => s.content.trim() !== "" && !caretWindow.includes(s.content.trim()),
);
@ -52,7 +53,11 @@ export const getSnippets = (
recentlyOpenedFiles: payload.recentlyOpenedFileSnippets,
base: shuffleArray(
filterSnippetsAlreadyInCaretWindow(
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
[
...payload.rootPathSnippets,
...payload.importDefinitionSnippets,
...payload.staticSnippet,
],
helper.prunedCaretWindow,
),
),
@ -107,7 +112,11 @@ export const getSnippets = (
defaultPriority: 99, // make sure it's the last one to be processed, but still possible to override
snippets: shuffleArray(
filterSnippetsAlreadyInCaretWindow(
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
[
...payload.rootPathSnippets,
...payload.importDefinitionSnippets,
...payload.staticSnippet,
],
helper.prunedCaretWindow,
),
),

View file

@ -5,6 +5,7 @@ import {
AutocompleteDiffSnippet,
AutocompleteSnippet,
AutocompleteSnippetType,
AutocompleteStaticSnippet,
} from "../snippets/types";
import { HelperVars } from "../util/HelperVars";
@ -51,6 +52,12 @@ const formatDiffSnippet = (
return snippet;
};
const formatStaticSnippet = (
snippet: AutocompleteStaticSnippet,
): AutocompleteStaticSnippet => {
return snippet;
};
const commentifySnippet = (
helper: HelperVars,
snippet: AutocompleteSnippet,
@ -81,6 +88,8 @@ export const formatSnippets = (
return formatDiffSnippet(snippet);
case AutocompleteSnippetType.Clipboard:
return formatClipboardSnippet(snippet, workspaceDirs);
case AutocompleteSnippetType.Static:
return formatStaticSnippet(snippet);
}
})
.map((item) => {

View file

@ -105,24 +105,27 @@ export class AutocompleteLoggingService {
});
const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome;
void Telemetry.capture(
"autocomplete",
{
accepted: restOfOutcome.accepted,
cacheHit: restOfOutcome.cacheHit,
completionId: restOfOutcome.completionId,
completionOptions: restOfOutcome.completionOptions,
debounceDelay: restOfOutcome.debounceDelay,
fileExtension: getUriFileExtension(restOfOutcome.filepath),
maxPromptTokens: restOfOutcome.maxPromptTokens,
modelName: restOfOutcome.modelName,
modelProvider: restOfOutcome.modelProvider,
multilineCompletions: restOfOutcome.multilineCompletions,
time: restOfOutcome.time,
useRecentlyEdited: restOfOutcome.useRecentlyEdited,
numLines: restOfOutcome.numLines,
},
true,
);
const toLog = {
accepted: restOfOutcome.accepted,
cacheHit: restOfOutcome.cacheHit,
completionId: restOfOutcome.completionId,
completionOptions: restOfOutcome.completionOptions,
debounceDelay: restOfOutcome.debounceDelay,
fileExtension: getUriFileExtension(restOfOutcome.filepath),
maxPromptTokens: restOfOutcome.maxPromptTokens,
modelName: restOfOutcome.modelName,
modelProvider: restOfOutcome.modelProvider,
multilineCompletions: restOfOutcome.multilineCompletions,
time: restOfOutcome.time,
useRecentlyEdited: restOfOutcome.useRecentlyEdited,
numLines: restOfOutcome.numLines,
};
outcome.enabledStaticContextualization
? void Telemetry.capture("autocomplete", {
...toLog,
enabledStaticContextualization: true,
})
: void Telemetry.capture("autocomplete", toLog);
}
}

View file

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

View file

@ -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,5 +11,6 @@ export function convertCustomCommandToSlashCommand(
description: customCommand.description ?? "",
prompt: customCommand.prompt,
source: "json-custom-command",
promptFile: customCommand.sourceFile, // TODO refactor promptFile to align with sourceFile
};
}

View file

@ -9,5 +9,6 @@ export function convertPromptBlockToSlashCommand(
description: prompt.description ?? "",
prompt: prompt.prompt,
source: "yaml-prompt-block",
promptFile: prompt.sourceFile, // Align with the sourceFile property
};
}

View file

@ -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,
);
@ -467,7 +522,10 @@ export class ConfigHandler {
return config;
}
async openConfigProfile(profileId?: string) {
async openConfigProfile(
profileId?: string,
element?: { sourceFile?: string },
) {
let openProfileId = profileId || this.currentProfile?.profileDescription.id;
if (!openProfileId) {
return;
@ -475,8 +533,10 @@ export class ConfigHandler {
const profile = this.currentOrg.profiles.find(
(p) => p.profileDescription.id === openProfileId,
);
if (profile?.profileDescription.profileType === "local") {
await this.ide.openFile(profile.profileDescription.uri);
const configFile = element?.sourceFile ?? profile.profileDescription.uri;
await this.ide.openFile(configFile);
} else {
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
await this.ide.openUrl(`${env.APP_URL}${openProfileId}`);
@ -487,7 +547,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

@ -652,6 +652,7 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
configurationStatus: llm.getConfigurationStatus(),
apiKeyLocation: llm.apiKeyLocation,
envSecretLocations: llm.envSecretLocations,
sourceFile: llm.sourceFile,
};
}

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,10 +19,10 @@ 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(),
enableStaticContextualization: z.boolean(),
// `ui` in `ContinueConfig`
showSessionTabs: z.boolean(),
@ -181,9 +181,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;
@ -192,6 +189,10 @@ export function modifyAnyConfigWithSharedConfig<
configCopy.experimental.codebaseToolCallingOnly =
sharedConfig.codebaseToolCallingOnly;
}
if (sharedConfig.enableStaticContextualization !== undefined) {
configCopy.experimental.enableStaticContextualization =
sharedConfig.enableStaticContextualization;
}
return configCopy;
}

View file

@ -56,6 +56,7 @@ function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
rule: rule.rule,
globs: rule.globs,
name: rule.name,
ruleFile: rule.sourceFile,
};
}
}
@ -235,6 +236,9 @@ async function configYamlToContinueConfig(options: {
startUrl: doc.startUrl,
rootUrl: doc.rootUrl,
faviconUrl: doc.faviconUrl,
maxDepth: doc.maxDepth,
useLocalCrawling: doc.useLocalCrawling,
sourceFile: doc.sourceFile,
}));
config.mcpServers?.forEach((mcpServer) => {
@ -427,6 +431,7 @@ async function configYamlToContinueConfig(options: {
(config.mcpServers ?? []).map((server) => ({
id: server.name,
name: server.name,
sourceFile: server.sourceFile,
transport: {
type: "stdio",
args: [],

View file

@ -47,7 +47,8 @@ class MCPConnection {
};
constructor(public options: MCPOptions) {
this.transport = this.constructTransport(options);
// Don't construct transport in constructor to avoid blocking
this.transport = {} as Transport; // Will be set in connectClient
this.client = new Client(
{
@ -132,7 +133,8 @@ class MCPConnection {
});
}),
(async () => {
this.transport = this.constructTransport(this.options);
this.transport = await this.constructTransportAsync(this.options);
try {
await this.client.connect(this.transport);
} catch (error) {
@ -295,7 +297,9 @@ class MCPConnection {
};
}
private constructTransport(options: MCPOptions): Transport {
private async constructTransportAsync(
options: MCPOptions,
): Promise<Transport> {
switch (options.transport.type) {
case "stdio":
const env: Record<string, string> = options.transport.env
@ -309,7 +313,7 @@ class MCPConnection {
// For non-Windows platforms, try to get the PATH from user shell
if (process.platform !== "win32") {
try {
const shellEnvPath = getEnvPathFromUserShell();
const shellEnvPath = await getEnvPathFromUserShell();
if (shellEnvPath && shellEnvPath !== process.env.PATH) {
env.PATH = shellEnvPath;
}

View file

@ -3,6 +3,13 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import MCPConnection from "./MCPConnection";
import { StdioOptions } from "../../index.d.js";
// Mock the shell path utility
vi.mock("../../util/shellPath", () => ({
getEnvPathFromUserShell: vi
.fn()
.mockResolvedValue("/usr/local/bin:/usr/bin:/bin"),
}));
describe("MCPConnection", () => {
beforeEach(() => {
vi.restoreAllMocks();
@ -98,7 +105,7 @@ describe("MCPConnection", () => {
expect(conn.status).toBe("not-connected");
});
it("should throw on invalid transport type", () => {
it("should throw on invalid transport type", async () => {
const options = {
name: "test-mcp",
id: "test-id",
@ -107,9 +114,14 @@ describe("MCPConnection", () => {
} as any,
};
expect(() => new MCPConnection(options)).toThrow(
"Unsupported transport type: invalid",
);
const conn = new MCPConnection(options);
const abortController = new AbortController();
// The validation now happens during connectClient, not constructor
await conn.connectClient(false, abortController.signal);
expect(conn.status).toBe("error");
expect(conn.errors[0]).toContain("Unsupported transport type: invalid");
});
});
@ -203,6 +215,15 @@ describe("MCPConnection", () => {
() => new Promise((resolve) => setTimeout(resolve, 1000)),
);
// Mock the required methods for successful connection
const mockGetServerCapabilities = vi
.spyOn(Client.prototype, "getServerCapabilities")
.mockReturnValue({
resources: {},
tools: {},
prompts: {},
});
const abortController = new AbortController();
await conn.connectClient(false, abortController.signal);
@ -211,7 +232,7 @@ describe("MCPConnection", () => {
});
it("should handle connection timeout", async () => {
const conn = new MCPConnection({ ...options, timeout: 1 });
const conn = new MCPConnection({ ...options, timeout: 50 });
const mockConnect = vi
.spyOn(Client.prototype, "connect")
.mockImplementation(
@ -223,7 +244,9 @@ describe("MCPConnection", () => {
expect(conn.status).toBe("error");
expect(conn.errors[0]).toContain("Failed to connect");
expect(mockConnect).toHaveBeenCalled();
// The connection should timeout before connect is called due to transport construction
// Since transport construction happens first, and we're not mocking that,
// the timeout will happen during transport construction or connect attempt
});
it("should handle already connected state", async () => {

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,32 +321,47 @@ 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) => {
await this.configHandler.openConfigProfile(msg.data.profileId);
await this.configHandler.openConfigProfile(
msg.data.profileId,
msg.data?.element,
);
});
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 +380,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 +392,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 +522,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 +553,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 +591,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 +720,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 +745,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 +1023,7 @@ export class Core {
],
}),
);
void this.configHandler.reloadConfig();
void this.configHandler.reloadConfig("Autocomplete model added");
}
private async handleFilesChanged({
@ -964,7 +1053,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 +1063,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 +1162,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: "",

163
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[]>;
@ -230,6 +237,7 @@ export interface SiteIndexingConfig {
maxDepth?: number;
faviconUrl?: string;
useLocalCrawling?: boolean;
sourceFile?: string;
}
export interface DocsIndexingDetails {
@ -362,10 +370,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 +461,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 +491,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 +514,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 +529,7 @@ export interface LLMInteractionStartFim extends LLMInteractionBase {
prefix: string;
suffix: string;
options: CompletionOptions;
provider: string;
}
export interface LLMInteractionChunk extends LLMInteractionBase {
@ -512,6 +546,7 @@ export interface LLMInteractionEnd extends LLMInteractionBase {
promptTokens: number;
generatedTokens: number;
thinkingTokens: number;
usage: Usage | undefined;
}
export interface LLMInteractionSuccess extends LLMInteractionEnd {
@ -626,6 +661,8 @@ export interface LLMOptions {
deploymentId?: string;
env?: Record<string, string | number | boolean>;
sourceFile?: string;
}
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
@ -665,13 +702,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 +741,7 @@ export interface IdeInfo {
version: string;
remoteName: string;
extensionVersion: string;
isPrerelease: boolean;
}
export interface BranchAndDir {
@ -823,6 +874,8 @@ export interface IDE {
// LSP
gotoDefinition(location: Location): Promise<RangeInFile[]>;
gotoTypeDefinition(location: Location): Promise<RangeInFile[]>; // TODO: add to jetbrains
getSignatureHelp(location: Location): Promise<SignatureHelp | null>; // TODO: add to jetbrains
// Callbacks
onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void;
@ -987,6 +1040,7 @@ export interface CustomCommand {
name: string;
prompt: string;
description?: string;
sourceFile?: string;
}
export interface Prediction {
@ -1104,6 +1158,8 @@ export interface ModelDescription {
capabilities?: ModelCapability;
roles?: ModelRole[];
configurationStatus?: LLMConfigurationStatuses;
sourceFile?: string;
}
export interface JSONEmbedOptions {
@ -1161,6 +1217,7 @@ export interface TabAutocompleteOptions {
experimental_includeRecentlyVisitedRanges: boolean | number;
experimental_includeRecentlyEditedRanges: boolean | number;
experimental_includeDiff: boolean | number;
experimental_enableStaticContextualization: boolean;
}
export interface StdioOptions {
@ -1258,6 +1315,7 @@ export interface MCPServerStatus extends MCPOptions {
tools: MCPTool[];
resources: MCPResource[];
resourceTemplates: MCPResourceTemplate[];
sourceFile?: string;
}
export interface ContinueUIConfig {
@ -1268,7 +1326,6 @@ export interface ContinueUIConfig {
codeWrap?: boolean;
showSessionTabs?: boolean;
autoAcceptEditToolDiffs?: boolean;
logEditingData?: boolean;
}
export interface ContextMenuConfig {
@ -1361,6 +1418,68 @@ export interface RangeInFileWithNextEditInfo {
export type SetCodeToEditPayload = RangeInFileWithContents | FileWithContents;
/**
* Signature help represents the signature of something
* callable. There can be multiple signatures but only one
* active and only one active parameter.
*/
export class SignatureHelp {
/**
* One or more signatures.
*/
signatures: SignatureInformation[];
/**
* The active signature.
*/
activeSignature: number;
/**
* The active parameter of the active signature.
*/
activeParameter: number;
}
/**
* Represents the signature of something callable. A signature
* can have a label, like a function-name, a doc-comment, and
* a set of parameters.
*/
export class SignatureInformation {
/**
* The label of this signature. Will be shown in
* the UI.
*/
label: string;
/**
* The parameters of this signature.
*/
parameters: ParameterInformation[];
/**
* The index of the active parameter.
*
* If provided, this is used in place of {@linkcode SignatureHelp.activeParameter}.
*/
activeParameter?: number;
}
/**
* Represents a parameter of a callable-signature. A parameter can
* have a label and a doc-comment.
*/
export class ParameterInformation {
/**
* The label of this signature.
*
* Either a string or inclusive start and exclusive end offsets within its containing
* {@link SignatureInformation.label signature label}. *Note*: A label of type string must be
* a substring of its containing signature information's {@link SignatureInformation.label label}.
*/
label: string | [number, number];
}
/**
* Represents the configuration for a quick action in the Code Lens.
* Quick actions are custom commands that can be added to function and class declarations.
@ -1421,11 +1540,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
*/
@ -1436,6 +1550,12 @@ export interface ExperimentalConfig {
* instead of embeddings, FTS, recently edited files, etc.
*/
codebaseToolCallingOnly?: boolean;
/**
* If enabled, static contextualization will be used to
* gather context for the model where necessary.
*/
enableStaticContextualization?: boolean;
}
export interface AnalyticsConfig {
@ -1649,6 +1769,7 @@ export type RuleSource =
| "model-options-plan"
| "model-options-agent"
| "rules-block"
| "colocated-markdown"
| "json-systemMessage"
| ".continuerules";
@ -1668,3 +1789,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";
@ -185,6 +187,9 @@ export abstract class BaseLLM implements ILLM {
maxEmbeddingChunkSize: number;
maxEmbeddingBatchSize: number;
//URI to local block defining this LLM
sourceFile?: string;
private _llmOptions: LLMOptions;
protected openaiAdapter?: BaseLlmApi;
@ -288,6 +293,7 @@ export abstract class BaseLLM implements ILLM {
this.embeddingId = `${this.constructor.name}::${this.model}::${this.maxEmbeddingChunkSize}`;
this.autocompleteOptions = options.autocompleteOptions;
this.sourceFile = options.sourceFile;
}
getConfigurationStatus() {
@ -326,6 +332,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 +374,7 @@ export abstract class BaseLLM implements ILLM {
promptTokens,
generatedTokens,
thinkingTokens,
usage,
});
return "cancelled";
} else {
@ -378,6 +386,7 @@ export abstract class BaseLLM implements ILLM {
promptTokens,
generatedTokens,
thinkingTokens,
usage,
});
return "error";
}
@ -387,6 +396,7 @@ export abstract class BaseLLM implements ILLM {
promptTokens,
generatedTokens,
thinkingTokens,
usage,
});
return "success";
}
@ -573,6 +583,7 @@ export abstract class BaseLLM implements ILLM {
prefix,
suffix,
options: completionOptions,
provider: this.providerName,
});
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, fimLog);
@ -621,6 +632,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
undefined,
);
} catch (e) {
status = this._logEnd(
@ -629,6 +641,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
undefined,
e,
);
throw e;
@ -640,6 +653,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
undefined,
"cancel",
);
}
@ -680,6 +694,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 +750,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
undefined,
);
} catch (e) {
status = this._logEnd(
@ -743,6 +759,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
undefined,
e,
);
throw e;
@ -754,6 +771,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
undefined,
"cancel",
);
}
@ -795,6 +813,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 +847,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
undefined,
);
} catch (e) {
status = this._logEnd(
@ -836,6 +856,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
undefined,
e,
);
throw e;
@ -847,6 +868,7 @@ export abstract class BaseLLM implements ILLM {
completion,
undefined,
interaction,
undefined,
"cancel",
);
}
@ -867,6 +889,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 +930,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 +941,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 +965,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 +974,7 @@ export abstract class BaseLLM implements ILLM {
let thinking = "";
let completion = "";
let usage: Usage | undefined = undefined;
try {
if (this.templateMessages) {
@ -992,6 +1041,11 @@ export abstract class BaseLLM implements ILLM {
kind: "message",
message: chunk,
});
if (chunk.role === "assistant" && chunk.usage) {
usage = chunk.usage;
}
yield chunk;
}
}
@ -1002,6 +1056,7 @@ export abstract class BaseLLM implements ILLM {
completion,
thinking,
interaction,
usage,
);
} catch (e) {
status = this._logEnd(
@ -1010,6 +1065,7 @@ export abstract class BaseLLM implements ILLM {
completion,
thinking,
interaction,
usage,
e,
);
throw e;
@ -1021,6 +1077,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;

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