Merge branch 'main' into nate/onboarding-improvements-p1
This commit is contained in:
commit
18f21e3834
446 changed files with 31164 additions and 6216 deletions
|
|
@ -1,11 +0,0 @@
|
|||
name: Continue Documentation MCP
|
||||
version: 0.0.1
|
||||
schema: v1
|
||||
mcpServers:
|
||||
- name: Continue Docs Search
|
||||
type: stdio
|
||||
command: npx
|
||||
args:
|
||||
- mint-mcp
|
||||
- add
|
||||
- continue-docs
|
||||
6
.continue/rules/typescript-enum-usage.md
Normal file
6
.continue/rules/typescript-enum-usage.md
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
---
|
||||
globs: "**/*.{ts,tsx}"
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
Use enums instead of simple string unions when possible in TypeScript code
|
||||
2
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
2
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
|
|
@ -11,6 +11,8 @@ body:
|
|||
attributes:
|
||||
label: Before submitting your bug report
|
||||
options:
|
||||
- label: I've tried using the "Ask AI" feature on the [Continue docs site](https://docs.continue.dev/) to see if the docs have an answer
|
||||
required: false
|
||||
- label: I believe this is a bug. I'll try to join the [Continue Discord](https://discord.gg/NWtdYexhMs) for questions
|
||||
required: false
|
||||
- label: I'm not able to find an [open issue](https://github.com/continuedev/continue/issues?q=is%3Aopen+is%3Aissue) that reports the same bug
|
||||
|
|
|
|||
4
.github/pull_request_template.md
vendored
4
.github/pull_request_template.md
vendored
|
|
@ -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
|
||||
|
||||
|
|
|
|||
2
.github/workflows/cla.yaml
vendored
2
.github/workflows/cla.yaml
vendored
|
|
@ -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
|
||||
|
|
|
|||
4
.github/workflows/compliance.yaml
vendored
4
.github/workflows/compliance.yaml
vendored
|
|
@ -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:",
|
||||
"```",
|
||||
|
|
|
|||
9
.github/workflows/jetbrains-release.yaml
vendored
9
.github/workflows/jetbrains-release.yaml
vendored
|
|
@ -63,7 +63,6 @@ jobs:
|
|||
|
||||
- name: Bump version in gradle.properties
|
||||
run: |
|
||||
cd extensions/intellij
|
||||
awk '/pluginVersion=/{split($0,a,"="); split(a[2],b,"."); b[3]+=1; printf "%s=%s.%s.%s\n",a[1],b[1],b[2],b[3];next}1' gradle.properties > tmp && mv tmp gradle.properties
|
||||
rm -rf tmp
|
||||
NEW_VERSION=$(grep 'pluginVersion=' gradle.properties | cut -d'=' -f2)
|
||||
|
|
@ -224,10 +223,6 @@ jobs:
|
|||
# apple-product-id: dev.continue.continue-binary
|
||||
# options: --options runtime --entitlements entitlements.xml
|
||||
|
||||
# Build plugin
|
||||
- name: Build plugin
|
||||
run: ./gradlew buildPlugin
|
||||
|
||||
# Publish the plugin to JetBrains Marketplace
|
||||
- name: Publish EAP Plugin
|
||||
if: github.event_name == 'release' || github.event.inputs.publish_build == 'true'
|
||||
|
|
@ -237,7 +232,7 @@ jobs:
|
|||
PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }}
|
||||
PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }}
|
||||
RELEASE_CHANNEL: eap
|
||||
run: ./gradlew publishPlugin
|
||||
run: ./gradlew publishPlugin --info --stacktrace
|
||||
|
||||
- name: Publish Stable Plugin
|
||||
if: github.event_name == 'release' || github.event.inputs.publish_build == 'true'
|
||||
|
|
@ -247,7 +242,7 @@ jobs:
|
|||
PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }}
|
||||
PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }}
|
||||
RELEASE_CHANNEL: default
|
||||
run: ./gradlew publishPlugin
|
||||
run: ./gradlew publishPlugin --info --stacktrace
|
||||
|
||||
# Prepare plugin archive content for creating artifact
|
||||
- name: Prepare Plugin Artifact
|
||||
|
|
|
|||
2
.github/workflows/metrics.yaml
vendored
2
.github/workflows/metrics.yaml
vendored
|
|
@ -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
|
||||
|
|
|
|||
70
.github/workflows/pr_checks.yaml
vendored
70
.github/workflows/pr_checks.yaml
vendored
|
|
@ -50,7 +50,10 @@ jobs:
|
|||
|
||||
install-config-yaml:
|
||||
needs: install-root
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
|
|
@ -77,7 +80,10 @@ jobs:
|
|||
|
||||
install-openai-adapters:
|
||||
needs: install-root
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
|
|
@ -133,7 +139,10 @@ jobs:
|
|||
|
||||
install-core:
|
||||
needs: install-root
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
|
|
@ -381,7 +390,10 @@ jobs:
|
|||
install-vscode:
|
||||
needs:
|
||||
[install-root, install-core, install-config-yaml, install-openai-adapters]
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
|
|
@ -572,6 +584,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,13 +662,19 @@ 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: |
|
||||
echo "Test files: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }}"
|
||||
|
||||
vscode-package-extension:
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest]
|
||||
needs:
|
||||
[
|
||||
install-vscode,
|
||||
|
|
@ -676,7 +731,7 @@ jobs:
|
|||
- name: Upload build artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: vscode-extension-build
|
||||
name: vscode-extension-build-${{ runner.os }}
|
||||
path: extensions/vscode/build
|
||||
|
||||
vscode-download-e2e-dependencies:
|
||||
|
|
@ -772,7 +827,7 @@ jobs:
|
|||
- name: Download build artifact
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: vscode-extension-build
|
||||
name: vscode-extension-build-Linux
|
||||
path: extensions/vscode/build
|
||||
|
||||
- name: Download e2e dependencies
|
||||
|
|
@ -1068,6 +1123,7 @@ jobs:
|
|||
- config-yaml-checks
|
||||
- install-config-yaml
|
||||
- install-openai-adapters
|
||||
- openai-adapters-tests
|
||||
|
||||
steps:
|
||||
- name: Decide whether the needed jobs succeeded or failed
|
||||
|
|
|
|||
16
.github/workflows/release-config-yaml.yml
vendored
16
.github/workflows/release-config-yaml.yml
vendored
|
|
@ -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 }}
|
||||
|
|
|
|||
16
.github/workflows/release-fetch.yml
vendored
16
.github/workflows/release-fetch.yml
vendored
|
|
@ -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 }}
|
||||
|
|
|
|||
8
.github/workflows/release-llm-info.yml
vendored
8
.github/workflows/release-llm-info.yml
vendored
|
|
@ -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 }}
|
||||
16
.github/workflows/release-openai-adapters.yml
vendored
16
.github/workflows/release-openai-adapters.yml
vendored
|
|
@ -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 }}
|
||||
|
|
|
|||
30
.github/workflows/reusable-release.yml
vendored
30
.github/workflows/reusable-release.yml
vendored
|
|
@ -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
|
||||
|
|
|
|||
2
.idea/gradle.xml
generated
2
.idea/gradle.xml
generated
|
|
@ -5,7 +5,7 @@
|
|||
<option name="linkedExternalProjectsSettings">
|
||||
<GradleProjectSettings>
|
||||
<option name="externalProjectPath" value="$PROJECT_DIR$/extensions/intellij" />
|
||||
<option name="gradleJvm" value="homebrew-17" />
|
||||
<option name="gradleJvm" value="#JAVA_HOME" />
|
||||
<option name="modules">
|
||||
<set>
|
||||
<option value="$PROJECT_DIR$/extensions/intellij" />
|
||||
|
|
|
|||
2
.idea/kotlinc.xml
generated
2
.idea/kotlinc.xml
generated
|
|
@ -1,6 +1,6 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="KotlinJpsPluginSettings">
|
||||
<option name="version" value="1.9.0" />
|
||||
<option name="version" value="1.8.0" />
|
||||
</component>
|
||||
</project>
|
||||
48
CLA.md
Normal file
48
CLA.md
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
# Individual Contributor License Agreement (v1.0, Continue)
|
||||
|
||||
_Based on the Apache Software Foundation Individual CLA v 2.2._
|
||||
|
||||
By commenting **“I have read the CLA Document and I hereby sign the CLA”**
|
||||
on a Pull Request, **you (“Contributor”) agree to the following terms** for any
|
||||
past and future “Contributions” submitted to **Continue (the “Project”)**.
|
||||
|
||||
---
|
||||
|
||||
## 1. Definitions
|
||||
|
||||
- **“Contribution”** – any original work of authorship submitted to the Project
|
||||
(code, documentation, designs, etc.).
|
||||
- **“You” / “Your”** – the individual (or legal entity) posting the acceptance
|
||||
comment.
|
||||
|
||||
## 2. Copyright License
|
||||
|
||||
You grant **Continue Dev, Inc.** and all recipients of software distributed by the
|
||||
Project a perpetual, worldwide, non‑exclusive, royalty‑free, irrevocable
|
||||
license to reproduce, prepare derivative works of, publicly display, publicly
|
||||
perform, sublicense, and distribute Your Contributions and derivative works.
|
||||
|
||||
## 3. Patent License
|
||||
|
||||
You grant **Continue Dev, Inc.** and all recipients of the Project a perpetual,
|
||||
worldwide, non‑exclusive, royalty‑free, irrevocable (except as below) patent
|
||||
license to make, have made, use, sell, offer to sell, import, and otherwise
|
||||
transfer Your Contributions alone or in combination with the Project.
|
||||
|
||||
If any entity brings patent litigation alleging that the Project or a
|
||||
Contribution infringes a patent, the patent licenses granted by You to that
|
||||
entity under this CLA terminate.
|
||||
|
||||
## 4. Representations
|
||||
|
||||
1. You are legally entitled to grant the licenses above.
|
||||
2. Each Contribution is either Your original creation or You have authority to
|
||||
submit it under this CLA.
|
||||
3. Your Contributions are provided **“AS IS”** without warranties of any kind.
|
||||
4. You will notify the Project if any statement above becomes inaccurate.
|
||||
|
||||
## 5. Miscellany
|
||||
|
||||
This Agreement is governed by the laws of the **State of California**, USA,
|
||||
excluding its conflict‑of‑laws rules. If any provision is held unenforceable,
|
||||
the remaining provisions remain in force.
|
||||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||

|
||||

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

|
||||

|
||||
|
||||
## Autocomplete
|
||||
|
||||
[Autocomplete](https://continue.dev/docs/autocomplete/how-to-use-it) provides inline code suggestions as you type
|
||||
|
||||

|
||||

|
||||
|
||||
## Edit
|
||||
|
||||
[Edit](https://continue.dev/docs/edit/how-to-use-it) is a convenient way to modify code without leaving your current
|
||||
file
|
||||
|
||||

|
||||

|
||||
|
||||
</div>
|
||||
|
||||
|
|
|
|||
|
|
@ -19,5 +19,19 @@
|
|||
"max-depth": ["error", { "max": 6 }],
|
||||
"max-nested-callbacks": ["error", { "max": 4 }],
|
||||
"max-params": ["error", { "max": 8 }]
|
||||
}
|
||||
},
|
||||
"overrides": [
|
||||
{
|
||||
"files": [
|
||||
"**/*.test.ts",
|
||||
"**/*.test.tsx",
|
||||
"**/*.spec.ts",
|
||||
"**/*.spec.tsx",
|
||||
"**/*.vitest.ts"
|
||||
],
|
||||
"rules": {
|
||||
"max-lines-per-function": "off"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
888
core/autocomplete/context/static-context/StaticContextService.ts
Normal file
888
core/autocomplete/context/static-context/StaticContextService.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
222
core/autocomplete/context/static-context/tree-sitter-utils.ts
Normal file
222
core/autocomplete/context/static-context/tree-sitter-utils.ts
Normal 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;
|
||||
}
|
||||
33
core/autocomplete/context/static-context/types.ts
Normal file
33
core/autocomplete/context/static-context/types.ts
Normal 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[]>;
|
||||
}
|
||||
146
core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts
Normal file
146
core/autocomplete/filtering/streamTransforms/filterCodeBlock.ts
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
import { LineStream } from "../../../diff/util";
|
||||
|
||||
import {
|
||||
collectAllLines,
|
||||
MarkdownBlockStateTracker,
|
||||
} from "../../../utils/markdownUtils";
|
||||
|
||||
import {
|
||||
processBlockNesting,
|
||||
shouldStopAtMarkdownBlock,
|
||||
} from "../../../utils/streamMarkdownUtils";
|
||||
|
||||
import { hasNestedMarkdownBlocks, shouldChangeLineAndStop } from "./lineStream";
|
||||
|
||||
/**
|
||||
* Filters and processes lines from a code block, removing unnecessary markers and handling edge cases.
|
||||
* Now includes markdown-aware processing to handle nested markdown blocks properly.
|
||||
*
|
||||
* @param {LineStream} rawLines - The input stream of lines to filter.
|
||||
* @param {string} filepath - Optional filepath to determine if this is a markdown file.
|
||||
* @yields {string} Filtered and processed lines from the code block.
|
||||
*
|
||||
* @description
|
||||
* This generator function performs the following tasks:
|
||||
* 1. Removes initial lines that should be removed before the actual code starts.
|
||||
* 2. For markdown files, applies nested markdown block logic to avoid premature termination.
|
||||
* 3. For mixed content, uses simplified processing to avoid premature termination.
|
||||
* 4. For traditional code blocks, uses original logic.
|
||||
* 5. Yields processed lines that are part of the actual code block content.
|
||||
*/
|
||||
export async function* filterCodeBlockLines(
|
||||
rawLines: LineStream,
|
||||
filepath?: string,
|
||||
): LineStream {
|
||||
// Collect all lines for analysis
|
||||
const allLines = await collectAllLines(rawLines);
|
||||
|
||||
// Check if it has nested markdown blocks (like ```markdown or ```md)
|
||||
const firstLine = allLines[0] || "";
|
||||
const hasNestedMarkdown = hasNestedMarkdownBlocks(firstLine, filepath);
|
||||
|
||||
// TARGETED FIX: Detect if this is mixed content (markdown headers + code blocks)
|
||||
// But exclude cases where we have nested markdown blocks
|
||||
const hasMarkdownHeaders = allLines.some(
|
||||
(line) => line.trim().startsWith("#") && !line.trim().startsWith("```"),
|
||||
);
|
||||
|
||||
const hasCodeBlocks = allLines.some(
|
||||
(line) => line.trim().startsWith("```") && line.trim().length >= 3,
|
||||
);
|
||||
const isMixedContent =
|
||||
hasMarkdownHeaders && hasCodeBlocks && !hasNestedMarkdown;
|
||||
|
||||
// If this is mixed content, use simplified processing
|
||||
if (isMixedContent) {
|
||||
for (let i = 0; i < allLines.length; i++) {
|
||||
const line = allLines[i];
|
||||
|
||||
// Skip initial wrapper lines if they exist
|
||||
if (i === 0 && shouldRemoveLineBeforeStart(line)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
yield line;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Original logic for non-mixed content
|
||||
let seenFirstFence = false;
|
||||
let nestCount = 0;
|
||||
|
||||
// Create optimized state tracker for markdown block analysis if needed
|
||||
let markdownStateTracker: MarkdownBlockStateTracker | undefined;
|
||||
if (hasNestedMarkdown) {
|
||||
markdownStateTracker = new MarkdownBlockStateTracker(allLines);
|
||||
}
|
||||
|
||||
for (let i = 0; i < allLines.length; i++) {
|
||||
const line = allLines[i];
|
||||
|
||||
// Process block nesting logic for the first fence
|
||||
const nesting = processBlockNesting(
|
||||
line,
|
||||
seenFirstFence,
|
||||
shouldRemoveLineBeforeStart,
|
||||
);
|
||||
if (nesting.shouldSkip) {
|
||||
continue; // Filter out starting ``` or START block
|
||||
}
|
||||
if (!seenFirstFence && nesting.newSeenFirstFence) {
|
||||
seenFirstFence = true;
|
||||
nestCount = 1;
|
||||
}
|
||||
|
||||
if (nestCount > 0) {
|
||||
// Inside a block including the outer block
|
||||
const changedEndLine = shouldChangeLineAndStop(line);
|
||||
if (typeof changedEndLine === "string") {
|
||||
// Ending a block with just backticks (```) or STOP
|
||||
|
||||
// For markdown files with nested markdown blocks, apply special logic
|
||||
if (
|
||||
hasNestedMarkdown &&
|
||||
line.trim() === "```" &&
|
||||
markdownStateTracker
|
||||
) {
|
||||
if (shouldStopAtMarkdownBlock(markdownStateTracker, i)) {
|
||||
return; // Stop without yielding the final closing ```
|
||||
} else {
|
||||
// This is an inner block delimiter, yield it as content
|
||||
yield line;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Original logic for non-markdown files or simple cases
|
||||
nestCount--;
|
||||
if (nestCount === 0) {
|
||||
// We've closed the outer wrapper - stop without yielding the closing ```
|
||||
return;
|
||||
} else {
|
||||
// This is a nested block closing, yield it as content
|
||||
yield line;
|
||||
}
|
||||
} else if (line.startsWith("```")) {
|
||||
// Going into a nested codeblock
|
||||
nestCount++;
|
||||
yield line;
|
||||
} else {
|
||||
// Otherwise just yield the line as content
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function shouldRemoveLineBeforeStart(line: string): boolean {
|
||||
return (
|
||||
line.trimStart().startsWith("```") ||
|
||||
line.trim() === "[CODE]" ||
|
||||
line.trim() === "<COMPLETION>" ||
|
||||
line.trim() === "<START EDITING HERE>" ||
|
||||
line.trim() === "{{FILL_HERE}}"
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,452 @@
|
|||
// eslint-disable-next-line max-lines-per-function
|
||||
import { beforeEach, describe, expect, it, Mock, vi } from "vitest";
|
||||
|
||||
import * as lineStream from "./lineStream";
|
||||
|
||||
describe("filterCodeBlock", () => {
|
||||
let mockFullStop: Mock;
|
||||
|
||||
async function getLineGenerator(lines: any) {
|
||||
return (async function* () {
|
||||
for (const line of lines) {
|
||||
yield line;
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
async function getFilteredLines(results: any) {
|
||||
const output = [];
|
||||
|
||||
for await (const line of results) {
|
||||
output.push(line);
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mockFullStop = vi.fn();
|
||||
});
|
||||
|
||||
it("should handle unfenced code", async () => {
|
||||
const linesGenerator = await getLineGenerator(["const x = 5;"]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;"]);
|
||||
});
|
||||
|
||||
it("should handle unfenced code with a code block", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]);
|
||||
});
|
||||
|
||||
it("should handle unfenced code with a complex code block", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"# Manual Testing Sandbox",
|
||||
"",
|
||||
"## Project Structure",
|
||||
"",
|
||||
"```",
|
||||
"manual-testing-sandbox/",
|
||||
"├── readme.md # Project documentation",
|
||||
"├── package.json # Node.js dependencies and scripts",
|
||||
"├── tsconfig.json # TypeScript configuration",
|
||||
"├── jest.config.js # Jest testing configuration",
|
||||
"├── requirements.txt # Python dependencies",
|
||||
"├── Dockerfile # Docker container configuration",
|
||||
"├── data.json # Sample JSON data",
|
||||
"├── example.ipynb # Jupyter notebook example",
|
||||
"│",
|
||||
"├── src/ # Source code directory",
|
||||
"│ ├── example.ts # TypeScript example",
|
||||
"│ ├── JsonToMarkdownConverter.ts # JSON to Markdown converter",
|
||||
"│ ├── JsonToMarkdownConverter.test.ts # Tests for JSON converter",
|
||||
"│ ├── MarkdownProcessor.ts # Markdown processing utility",
|
||||
"│ └── MarkdownProcessor.test.ts # Tests for Markdown processor",
|
||||
"│",
|
||||
"├── react-calculator/ # React calculator application",
|
||||
"├── calculator_test/ # Java calculator implementation",
|
||||
"│ ├── Calculator.java # Calculator class",
|
||||
"│ └── Main.java # Main application entry",
|
||||
"│",
|
||||
"├── nested-folder/ # Nested project example",
|
||||
"│ ├── helloNested.py # Python script",
|
||||
"│ ├── package.json # Nested package configuration",
|
||||
"│ └── rules.md # Documentation",
|
||||
"│",
|
||||
"├── coverage/ # Test coverage reports",
|
||||
"├── logs/ # Application logs",
|
||||
"│",
|
||||
"└── Test Files # Various language examples",
|
||||
" ├── AdvancedPage.tsx # React TypeScript component",
|
||||
" ├── Calculator.java # Java calculator",
|
||||
" ├── program.cs # C# program",
|
||||
" ├── query.sql # SQL query example",
|
||||
" ├── test.css # CSS styles",
|
||||
" ├── test.html # HTML page",
|
||||
" ├── test.js # JavaScript code",
|
||||
" ├── test.kt # Kotlin example",
|
||||
" ├── test.php # PHP script",
|
||||
" ├── test.py # Python script",
|
||||
" ├── test.rb # Ruby script",
|
||||
" ├── test.rs # Rust code",
|
||||
" ├── test.sh # Shell script",
|
||||
" └── test.ts # TypeScript code",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
"# Manual Testing Sandbox",
|
||||
"",
|
||||
"## Project Structure",
|
||||
"",
|
||||
"```",
|
||||
"manual-testing-sandbox/",
|
||||
"├── readme.md # Project documentation",
|
||||
"├── package.json # Node.js dependencies and scripts",
|
||||
"├── tsconfig.json # TypeScript configuration",
|
||||
"├── jest.config.js # Jest testing configuration",
|
||||
"├── requirements.txt # Python dependencies",
|
||||
"├── Dockerfile # Docker container configuration",
|
||||
"├── data.json # Sample JSON data",
|
||||
"├── example.ipynb # Jupyter notebook example",
|
||||
"│",
|
||||
"├── src/ # Source code directory",
|
||||
"│ ├── example.ts # TypeScript example",
|
||||
"│ ├── JsonToMarkdownConverter.ts # JSON to Markdown converter",
|
||||
"│ ├── JsonToMarkdownConverter.test.ts # Tests for JSON converter",
|
||||
"│ ├── MarkdownProcessor.ts # Markdown processing utility",
|
||||
"│ └── MarkdownProcessor.test.ts # Tests for Markdown processor",
|
||||
"│",
|
||||
"├── react-calculator/ # React calculator application",
|
||||
"├── calculator_test/ # Java calculator implementation",
|
||||
"│ ├── Calculator.java # Calculator class",
|
||||
"│ └── Main.java # Main application entry",
|
||||
"│",
|
||||
"├── nested-folder/ # Nested project example",
|
||||
"│ ├── helloNested.py # Python script",
|
||||
"│ ├── package.json # Nested package configuration",
|
||||
"│ └── rules.md # Documentation",
|
||||
"│",
|
||||
"├── coverage/ # Test coverage reports",
|
||||
"├── logs/ # Application logs",
|
||||
"│",
|
||||
"└── Test Files # Various language examples",
|
||||
" ├── AdvancedPage.tsx # React TypeScript component",
|
||||
" ├── Calculator.java # Java calculator",
|
||||
" ├── program.cs # C# program",
|
||||
" ├── query.sql # SQL query example",
|
||||
" ├── test.css # CSS styles",
|
||||
" ├── test.html # HTML page",
|
||||
" ├── test.js # JavaScript code",
|
||||
" ├── test.kt # Kotlin example",
|
||||
" ├── test.php # PHP script",
|
||||
" ├── test.py # Python script",
|
||||
" ├── test.rb # Ruby script",
|
||||
" ├── test.rs # Rust code",
|
||||
" ├── test.sh # Shell script",
|
||||
" └── test.ts # TypeScript code",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle unfenced code with two code blocks", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should remove lines before the first valid line", async () => {
|
||||
const linesGenerator = await getLineGenerator(["```ts", "const x = 5;"]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;"]);
|
||||
});
|
||||
|
||||
it("should remove outer blocks", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```ts",
|
||||
"const x = 5;",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;"]);
|
||||
});
|
||||
|
||||
it("should leave inner blocks intact", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```md",
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]);
|
||||
});
|
||||
|
||||
it("should ignore ticks inside of code blocks such as tests", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```typescript",
|
||||
'it("should handle included inner ticks", async () => {',
|
||||
" const linesGenerator = await getLineGenerator([`",
|
||||
' "```md"',
|
||||
' "const x = 5;"',
|
||||
' "```bash"',
|
||||
' "echo ```test```"',
|
||||
' "```"',
|
||||
' "```"',
|
||||
"]);",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
'it("should handle included inner ticks", async () => {',
|
||||
" const linesGenerator = await getLineGenerator([`",
|
||||
' "```md"',
|
||||
' "const x = 5;"',
|
||||
' "```bash"',
|
||||
' "echo ```test```"',
|
||||
' "```"',
|
||||
' "```"',
|
||||
"]);",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle included inner ticks", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```md",
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"echo ```test```",
|
||||
"```",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"echo ```test```",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should leave single inner blocks intact but not return trailing text", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```md",
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"```",
|
||||
"trailing text",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]);
|
||||
});
|
||||
|
||||
it("should leave double inner blocks intact but not return trailing text", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```md",
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"const y = 10;",
|
||||
"```sh",
|
||||
"echo `hello world`",
|
||||
"```",
|
||||
"```",
|
||||
"trailing text",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"const y = 10;",
|
||||
"```sh",
|
||||
"echo `hello world`",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should leave inner blocks intact but not return trailing or leading text", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"[CODE]",
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"[/CODE]",
|
||||
"trailing text",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;", "```bash", "ls -al", "```"]);
|
||||
});
|
||||
|
||||
// Markdown-aware tests
|
||||
it("should handle markdown files with nested code blocks and a filename is included", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```markdown README.md",
|
||||
"# Project Structure",
|
||||
"",
|
||||
"```",
|
||||
"debug-test-folder/",
|
||||
"├── AdvancedPage.tsx",
|
||||
"├── Calculator.java",
|
||||
"└── test.ts",
|
||||
"```",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator, "README.md");
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
// Should include all content up to the final closing ```
|
||||
expect(filteredLines).toEqual([
|
||||
"# Project Structure",
|
||||
"",
|
||||
"```",
|
||||
"debug-test-folder/",
|
||||
"├── AdvancedPage.tsx",
|
||||
"├── Calculator.java",
|
||||
"└── test.ts",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
// Markdown-aware tests
|
||||
it("should handle markdown files with nested code blocks and a filename is excluded", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```markdown README.md",
|
||||
"# Project Structure",
|
||||
"",
|
||||
"```",
|
||||
"debug-test-folder/",
|
||||
"├── AdvancedPage.tsx",
|
||||
"├── Calculator.java",
|
||||
"└── test.ts",
|
||||
"```",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
// Should include all content up to the final closing ```
|
||||
expect(filteredLines).toEqual([
|
||||
"# Project Structure",
|
||||
"",
|
||||
"```",
|
||||
"debug-test-folder/",
|
||||
"├── AdvancedPage.tsx",
|
||||
"├── Calculator.java",
|
||||
"└── test.ts",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle non-markdown files normally with filepath parameter", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```",
|
||||
"function test() {",
|
||||
" return 'hello';",
|
||||
"}",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator, "test.js");
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
"function test() {",
|
||||
" return 'hello';",
|
||||
"}",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle simple markdown code blocks", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```",
|
||||
"Here's some code:",
|
||||
"```",
|
||||
"function example() {",
|
||||
" console.log('test');",
|
||||
"}",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator, "README.md");
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
// Should remove the outer markdown wrapper, and return just the inner content.
|
||||
// The lack of an end tag should cause it to return all remaining lines.
|
||||
expect(filteredLines).toEqual([
|
||||
"Here's some code:",
|
||||
"```",
|
||||
"function example() {",
|
||||
" console.log('test');",
|
||||
"}",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
|
@ -3,6 +3,11 @@ import { distance } from "fastest-levenshtein";
|
|||
import { DiffLine } from "../../..";
|
||||
import { LineStream } from "../../../diff/util";
|
||||
|
||||
import { headerIsMarkdown, isMarkdownFile } from "../../../utils/markdownUtils";
|
||||
import { processBlockNesting as processBlockNestingUtil } from "../../../utils/streamMarkdownUtils";
|
||||
|
||||
export { filterCodeBlockLines } from "./filterCodeBlock";
|
||||
|
||||
export type LineFilter = (args: {
|
||||
lines: LineStream;
|
||||
fullStop: () => void;
|
||||
|
|
@ -50,13 +55,72 @@ function shouldRemoveLineBeforeStart(line: string): boolean {
|
|||
);
|
||||
}
|
||||
|
||||
function shouldChangeLineAndStop(line: string): string | undefined {
|
||||
/**
|
||||
* Shared utility for validating patterns in lines to avoid code duplication.
|
||||
* Checks if a pattern appears in a valid context (not inside quotes or identifiers).
|
||||
*/
|
||||
export function validatePatternInLine(
|
||||
line: string,
|
||||
pattern: string,
|
||||
): {
|
||||
isValid: boolean;
|
||||
patternIndex: number;
|
||||
beforePattern: string;
|
||||
} {
|
||||
const patternIndex = line.indexOf(pattern);
|
||||
|
||||
if (patternIndex === -1) {
|
||||
return { isValid: false, patternIndex: -1, beforePattern: "" };
|
||||
}
|
||||
|
||||
// Check if pattern is preceded by a non-whitespace character
|
||||
// If so, it might be part of an identifier, so don't handle it
|
||||
if (patternIndex > 0) {
|
||||
const charBefore = line[patternIndex - 1];
|
||||
if (charBefore && !charBefore.match(/\s/)) {
|
||||
return { isValid: false, patternIndex, beforePattern: "" };
|
||||
}
|
||||
}
|
||||
|
||||
// Check if pattern appears to be inside quotes
|
||||
// Simple heuristic: count unmatched quotes before the pattern
|
||||
const beforePattern = line.substring(0, patternIndex);
|
||||
const singleQuotes = (beforePattern.match(/'/g) || []).length;
|
||||
const doubleQuotes = (beforePattern.match(/"/g) || []).length;
|
||||
|
||||
// If there's an odd number of quotes before pattern, we're likely inside quotes
|
||||
if (singleQuotes % 2 !== 0 || doubleQuotes % 2 !== 0) {
|
||||
return { isValid: false, patternIndex, beforePattern };
|
||||
}
|
||||
|
||||
return { isValid: true, patternIndex, beforePattern };
|
||||
}
|
||||
|
||||
export function shouldChangeLineAndStop(line: string): string | undefined {
|
||||
if (line.trimStart() === "```") {
|
||||
return line;
|
||||
}
|
||||
|
||||
// Check if [/CODE] appears in the line
|
||||
if (line.includes(CODE_STOP_BLOCK)) {
|
||||
return line.split(CODE_STOP_BLOCK)[0].trimEnd();
|
||||
const validation = validatePatternInLine(line, CODE_STOP_BLOCK);
|
||||
|
||||
if (!validation.isValid) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Get the trimmed line to check if [/CODE] is at logical start
|
||||
const trimmedLine = line.trimStart();
|
||||
|
||||
if (trimmedLine.startsWith(CODE_STOP_BLOCK)) {
|
||||
// [/CODE] is at the logical start (after whitespace only)
|
||||
if (trimmedLine === CODE_STOP_BLOCK) {
|
||||
return line; // Return the whole line including leading whitespace
|
||||
}
|
||||
}
|
||||
|
||||
// [/CODE] appears after some content (separated by whitespace) - return part before
|
||||
return validation.beforePattern.trimEnd();
|
||||
}
|
||||
|
||||
return undefined;
|
||||
|
|
@ -71,6 +135,32 @@ function isUselessLine(line: string): boolean {
|
|||
return hasUselessLine || trimmed.startsWith("// end");
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if the code block has nested markdown blocks.
|
||||
*/
|
||||
export function hasNestedMarkdownBlocks(
|
||||
firstLine: string,
|
||||
filepath?: string,
|
||||
): boolean {
|
||||
return (
|
||||
(firstLine.startsWith("```") &&
|
||||
headerIsMarkdown(firstLine.replace(/`/g, ""))) ||
|
||||
Boolean(filepath && isMarkdownFile(filepath))
|
||||
);
|
||||
}
|
||||
|
||||
// Wrapper for processBlockNesting with local shouldRemoveLineBeforeStart function
|
||||
export function processBlockNesting(
|
||||
line: string,
|
||||
seenFirstFence: boolean,
|
||||
): { newSeenFirstFence: boolean; shouldSkip: boolean } {
|
||||
return processBlockNestingUtil(
|
||||
line,
|
||||
seenFirstFence,
|
||||
shouldRemoveLineBeforeStart,
|
||||
);
|
||||
}
|
||||
|
||||
export const USELESS_LINES = [""];
|
||||
export const CODE_KEYWORDS_ENDING_IN_SEMICOLON = ["def"];
|
||||
export const CODE_STOP_BLOCK = "[/CODE]";
|
||||
|
|
@ -138,7 +228,7 @@ export async function* avoidPathLine(
|
|||
// Sometimes the model with copy this pattern, which is unwanted
|
||||
for await (const line of stream) {
|
||||
if (line.startsWith(`${comment} Path: `)) {
|
||||
continue;
|
||||
continue; // continue in the Continue codebase! How meta!
|
||||
}
|
||||
yield line;
|
||||
}
|
||||
|
|
@ -261,7 +351,40 @@ export async function* stopAtLines(
|
|||
linesToStopAt: string[] = LINES_TO_STOP_AT,
|
||||
): LineStream {
|
||||
for await (const line of stream) {
|
||||
if (linesToStopAt.some((stopAt) => line.trim().includes(stopAt))) {
|
||||
let shouldStop = false;
|
||||
|
||||
// Check each stop phrase
|
||||
for (const stopAt of linesToStopAt) {
|
||||
if (line.includes(stopAt)) {
|
||||
const validation = validatePatternInLine(line, stopAt);
|
||||
|
||||
if (!validation.isValid) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Get the trimmed line to check if stop phrase is at logical start
|
||||
const trimmedLine = line.trimStart();
|
||||
|
||||
if (trimmedLine.startsWith(stopAt)) {
|
||||
// Stop phrase is at the logical start (after whitespace only) - should stop
|
||||
shouldStop = true;
|
||||
break;
|
||||
} else {
|
||||
// Stop phrase appears after some content - check if it's separated by whitespace
|
||||
const contentBeforeStopPhrase = validation.beforePattern.trimEnd();
|
||||
if (
|
||||
contentBeforeStopPhrase.length < validation.beforePattern.length
|
||||
) {
|
||||
// There's whitespace before the stop phrase, so it's properly separated
|
||||
shouldStop = true;
|
||||
break;
|
||||
}
|
||||
// If no whitespace separation, it's part of larger text, so continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (shouldStop) {
|
||||
fullStop();
|
||||
break;
|
||||
}
|
||||
|
|
@ -329,64 +452,6 @@ export async function* removeTrailingWhitespace(
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters and processes lines from a code block, removing unnecessary markers and handling edge cases.
|
||||
*
|
||||
* @param {LineStream} rawLines - The input stream of lines to filter.
|
||||
* @yields {string} Filtered and processed lines from the code block.
|
||||
*
|
||||
* @description
|
||||
* This generator function performs the following tasks:
|
||||
* 1. Removes initial lines that should be removed before the actual code starts.
|
||||
* 2. Filters out ending code block markers (```) unless they are the last line.
|
||||
* 3. Handles special cases where lines should be changed and the stream should stop.
|
||||
* 4. Yields processed lines that are part of the actual code block content.
|
||||
*/
|
||||
export async function* filterCodeBlockLines(rawLines: LineStream): LineStream {
|
||||
let seenFirstFence = false;
|
||||
// nestCount is set to 1 when the entire code block is wrapped with ``` or START blocks. It's then incremented
|
||||
// when an inner code block is discovered to avoid exiting the function prematurly. The function will exit early
|
||||
// when all blocks are matched. When no outer fence is discovered the function will always continue to the end.
|
||||
let nestCount = 0;
|
||||
|
||||
for await (const line of rawLines) {
|
||||
if (!seenFirstFence) {
|
||||
if (shouldRemoveLineBeforeStart(line)) {
|
||||
// Filter out starting ``` or START block
|
||||
continue;
|
||||
}
|
||||
// Regardless of a fence or START block start tracking the nesting level
|
||||
seenFirstFence = true;
|
||||
nestCount = 1;
|
||||
}
|
||||
|
||||
if (nestCount > 0) {
|
||||
// Inside a block including the outer block
|
||||
const changedEndLine = shouldChangeLineAndStop(line);
|
||||
if (typeof changedEndLine === "string") {
|
||||
// Ending a block with just backticks (```) or STOP
|
||||
nestCount--;
|
||||
if (nestCount === 0) {
|
||||
// if we are closing the outer block then exit early
|
||||
// only exit early if the outer block was started with a block
|
||||
// it it was text, we will never exit early
|
||||
return;
|
||||
} else {
|
||||
// otherwise just yield the line
|
||||
yield line;
|
||||
}
|
||||
} else if (line.startsWith("```")) {
|
||||
// Going into a nested codeblock
|
||||
nestCount++;
|
||||
yield line;
|
||||
} else {
|
||||
// otherwise just yield the line
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters out English explanations at the start of a code block.
|
||||
*
|
||||
|
|
|
|||
|
|
@ -1,5 +1,10 @@
|
|||
import { beforeEach, describe, expect, it, Mock, vi } from "vitest";
|
||||
|
||||
import {
|
||||
collectAllLines,
|
||||
MarkdownBlockStateTracker,
|
||||
} from "../../../utils/markdownUtils";
|
||||
import { shouldStopAtMarkdownBlock } from "../../../utils/streamMarkdownUtils";
|
||||
import * as lineStream from "./lineStream";
|
||||
|
||||
// eslint-disable-next-line max-lines-per-function
|
||||
|
|
@ -174,6 +179,93 @@ describe("lineStream", () => {
|
|||
expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
|
||||
expect(mockFullStop).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("should stop at lines with leading whitespace", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"const x = 5;",
|
||||
"let y = 10;",
|
||||
` ${lineStream.LINES_TO_STOP_AT[0]}`,
|
||||
"const z = 15;",
|
||||
]);
|
||||
|
||||
const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
|
||||
expect(mockFullStop).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("should NOT stop when stop phrase is inside quotes", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"const x = 5;",
|
||||
'console.log("# End of file. not really");',
|
||||
"let y = 10;",
|
||||
"const z = 15;",
|
||||
]);
|
||||
|
||||
const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
// Should not stop, should yield all lines
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
'console.log("# End of file. not really");',
|
||||
"let y = 10;",
|
||||
"const z = 15;",
|
||||
]);
|
||||
expect(mockFullStop).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
|
||||
it("should NOT stop when stop phrase is inside single quotes", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"const x = 5;",
|
||||
"const message = '# End of file. not really';",
|
||||
"let y = 10;",
|
||||
]);
|
||||
|
||||
const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
"const message = '# End of file. not really';",
|
||||
"let y = 10;",
|
||||
]);
|
||||
expect(mockFullStop).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
|
||||
it("should NOT stop when stop phrase is part of larger text", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"const x = 5;",
|
||||
"// This function stops<STOP EDITING HERE>after processing",
|
||||
"let y = 10;",
|
||||
]);
|
||||
|
||||
const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
"// This function stops<STOP EDITING HERE>after processing",
|
||||
"let y = 10;",
|
||||
]);
|
||||
expect(mockFullStop).toHaveBeenCalledTimes(0);
|
||||
});
|
||||
|
||||
it("should stop when stop phrase appears properly at start of content", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"const x = 5;",
|
||||
"let y = 10;",
|
||||
"# End of file. Done here",
|
||||
"const z = 15;",
|
||||
]);
|
||||
|
||||
const result = lineStream.stopAtLines(linesGenerator, mockFullStop);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]);
|
||||
expect(mockFullStop).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("skipPrefixes", () => {
|
||||
|
|
@ -301,6 +393,37 @@ describe("lineStream", () => {
|
|||
]);
|
||||
});
|
||||
|
||||
it("should ignore ticks inside of code blocks such as tests", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```typescript",
|
||||
'it("should handle included inner ticks", async () => {',
|
||||
" const linesGenerator = await getLineGenerator([`",
|
||||
' "```md"',
|
||||
' "const x = 5;"',
|
||||
' "```bash"',
|
||||
' "echo ```test```"',
|
||||
' "```"',
|
||||
' "```"',
|
||||
"]);",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
'it("should handle included inner ticks", async () => {',
|
||||
" const linesGenerator = await getLineGenerator([`",
|
||||
' "```md"',
|
||||
' "const x = 5;"',
|
||||
' "```bash"',
|
||||
' "echo ```test```"',
|
||||
' "```"',
|
||||
' "```"',
|
||||
"]);",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle included inner ticks", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```md",
|
||||
|
|
@ -395,6 +518,119 @@ describe("lineStream", () => {
|
|||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
// Markdown-aware tests
|
||||
it("should handle markdown files with nested code blocks and a filename is included", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```markdown README.md",
|
||||
"# Project Structure",
|
||||
"",
|
||||
"```",
|
||||
"debug-test-folder/",
|
||||
"├── AdvancedPage.tsx",
|
||||
"├── Calculator.java",
|
||||
"└── test.ts",
|
||||
"```",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(
|
||||
linesGenerator,
|
||||
"README.md",
|
||||
);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
// Should include all content up to the final closing ```
|
||||
expect(filteredLines).toEqual([
|
||||
"# Project Structure",
|
||||
"",
|
||||
"```",
|
||||
"debug-test-folder/",
|
||||
"├── AdvancedPage.tsx",
|
||||
"├── Calculator.java",
|
||||
"└── test.ts",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
// Markdown-aware tests
|
||||
it("should handle markdown files with nested code blocks and a filename is excluded", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```markdown README.md",
|
||||
"# Project Structure",
|
||||
"",
|
||||
"```",
|
||||
"debug-test-folder/",
|
||||
"├── AdvancedPage.tsx",
|
||||
"├── Calculator.java",
|
||||
"└── test.ts",
|
||||
"```",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
// Should include all content up to the final closing ```
|
||||
expect(filteredLines).toEqual([
|
||||
"# Project Structure",
|
||||
"",
|
||||
"```",
|
||||
"debug-test-folder/",
|
||||
"├── AdvancedPage.tsx",
|
||||
"├── Calculator.java",
|
||||
"└── test.ts",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle non-markdown files normally with filepath parameter", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```",
|
||||
"function test() {",
|
||||
" return 'hello';",
|
||||
"}",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator, "test.js");
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
"function test() {",
|
||||
" return 'hello';",
|
||||
"}",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle simple markdown code blocks", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```",
|
||||
"Here's some code:",
|
||||
"```",
|
||||
"function example() {",
|
||||
" console.log('test');",
|
||||
"}",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(
|
||||
linesGenerator,
|
||||
"README.md",
|
||||
);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
// Should remove the outer markdown wrapper, and return just the inner content.
|
||||
// The lack of an end tag should cause it to return all remaining lines.
|
||||
expect(filteredLines).toEqual([
|
||||
"Here's some code:",
|
||||
"```",
|
||||
"function example() {",
|
||||
" console.log('test');",
|
||||
"}",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("filterEnglishLinesAtStart", () => {
|
||||
|
|
@ -613,4 +849,453 @@ describe("lineStream", () => {
|
|||
expect(mockFullStop).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
// Tests for new helper functions
|
||||
|
||||
describe("hasNestedMarkdownBlocks", () => {
|
||||
it("should detect nested markdown blocks from first line", () => {
|
||||
expect(lineStream.hasNestedMarkdownBlocks("```markdown", undefined)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(lineStream.hasNestedMarkdownBlocks("```md", undefined)).toBe(true);
|
||||
expect(lineStream.hasNestedMarkdownBlocks("```gfm", undefined)).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("should detect nested markdown blocks from filepath", () => {
|
||||
expect(
|
||||
lineStream.hasNestedMarkdownBlocks("```typescript", "README.md"),
|
||||
).toBe(true);
|
||||
expect(
|
||||
lineStream.hasNestedMarkdownBlocks("```javascript", "docs.markdown"),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false for non-markdown scenarios", () => {
|
||||
expect(
|
||||
lineStream.hasNestedMarkdownBlocks("```typescript", "script.js"),
|
||||
).toBe(false);
|
||||
expect(lineStream.hasNestedMarkdownBlocks("```python", undefined)).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
lineStream.hasNestedMarkdownBlocks("const x = 5;", undefined),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should handle complex first line scenarios", () => {
|
||||
expect(
|
||||
lineStream.hasNestedMarkdownBlocks("```markdown README.md", undefined),
|
||||
).toBe(true);
|
||||
expect(
|
||||
lineStream.hasNestedMarkdownBlocks("```md with extra text", undefined),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("collectAllLines", () => {
|
||||
it("should collect all lines from a stream", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"line1",
|
||||
"line2",
|
||||
"line3",
|
||||
]);
|
||||
|
||||
const result = await collectAllLines(linesGenerator);
|
||||
|
||||
expect(result).toEqual(["line1", "line2", "line3"]);
|
||||
});
|
||||
|
||||
it("should handle empty stream", async () => {
|
||||
const linesGenerator = await getLineGenerator([]);
|
||||
|
||||
const result = await collectAllLines(linesGenerator);
|
||||
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("should handle stream with empty lines", async () => {
|
||||
const linesGenerator = await getLineGenerator(["", "line2", "", "line4"]);
|
||||
|
||||
const result = await collectAllLines(linesGenerator);
|
||||
|
||||
expect(result).toEqual(["", "line2", "", "line4"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("shouldStopAtMarkdownBlock", () => {
|
||||
it("should return false when current line is not closing backticks", () => {
|
||||
const allLines = ["```markdown", "content", "more content"];
|
||||
const state = new MarkdownBlockStateTracker(allLines);
|
||||
expect(shouldStopAtMarkdownBlock(state, 2)).toBe(false);
|
||||
});
|
||||
|
||||
it("should handle simple nested markdown case", () => {
|
||||
const allLines = ["```markdown", "# Title", "```"];
|
||||
const state = new MarkdownBlockStateTracker(allLines);
|
||||
expect(shouldStopAtMarkdownBlock(state, 2)).toBe(true);
|
||||
});
|
||||
|
||||
it("should handle complex nested markdown with inner code blocks", () => {
|
||||
const allLines = [
|
||||
"```markdown",
|
||||
"# Title",
|
||||
"```javascript",
|
||||
"console.log('hello');",
|
||||
"```",
|
||||
"```",
|
||||
];
|
||||
const state = new MarkdownBlockStateTracker(allLines);
|
||||
// At index 4 (first inner closing), should not stop
|
||||
expect(shouldStopAtMarkdownBlock(state, 4)).toBe(false);
|
||||
// At index 5 (outer closing), should stop
|
||||
expect(shouldStopAtMarkdownBlock(state, 5)).toBe(true);
|
||||
});
|
||||
|
||||
it("should handle multiple bare backticks scenario", () => {
|
||||
const allLines = [
|
||||
"```markdown",
|
||||
"Content with ```inline code```",
|
||||
"```",
|
||||
"More content",
|
||||
"```",
|
||||
];
|
||||
const state = new MarkdownBlockStateTracker(allLines);
|
||||
// At index 2, should not stop (not the last bare backticks)
|
||||
expect(shouldStopAtMarkdownBlock(state, 2)).toBe(false);
|
||||
// At index 4, should stop (last bare backticks)
|
||||
expect(shouldStopAtMarkdownBlock(state, 4)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("shouldChangeLineAndStop", () => {
|
||||
it("should handle [/CODE] at start of line", () => {
|
||||
const result = lineStream.shouldChangeLineAndStop("[/CODE]");
|
||||
expect(result).toBe("[/CODE]");
|
||||
});
|
||||
|
||||
it("should handle [/CODE] with leading whitespace", () => {
|
||||
const result = lineStream.shouldChangeLineAndStop(" [/CODE]");
|
||||
expect(result).toBe(" [/CODE]");
|
||||
});
|
||||
|
||||
it("should return partial line before [/CODE] when at start/after whitespace", () => {
|
||||
const result = lineStream.shouldChangeLineAndStop(
|
||||
"some code [/CODE] more text",
|
||||
);
|
||||
expect(result).toBe("some code");
|
||||
});
|
||||
|
||||
it("should NOT trigger on [/CODE] within quotes or non-whitespace preceded", () => {
|
||||
// This test demonstrates the current bug - it WILL fail initially
|
||||
const result = lineStream.shouldChangeLineAndStop(
|
||||
'console.log("test [/CODE] end");',
|
||||
);
|
||||
expect(result).toBeUndefined(); // Should not trigger stopping
|
||||
});
|
||||
|
||||
it("should NOT trigger on [/CODE] in middle of identifier", () => {
|
||||
// Another case that shows the bug
|
||||
const result = lineStream.shouldChangeLineAndStop(
|
||||
'const var[/CODE]Name = "test";',
|
||||
);
|
||||
expect(result).toBeUndefined(); // Should not trigger stopping
|
||||
});
|
||||
|
||||
it("should handle ``` with trimStart correctly", () => {
|
||||
const result = lineStream.shouldChangeLineAndStop(" ```");
|
||||
expect(result).toBe(" ```");
|
||||
});
|
||||
|
||||
it("should NOT handle ``` in middle of line", () => {
|
||||
const result = lineStream.shouldChangeLineAndStop(
|
||||
'console.log("test ``` end");',
|
||||
);
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("MarkdownBlockState", () => {
|
||||
it("should initialize with correct state", () => {
|
||||
const allLines = ["```markdown", "content", "```", "more content", "```"];
|
||||
const state = new MarkdownBlockStateTracker(allLines);
|
||||
|
||||
// Test basic initialization - we can't directly test private properties,
|
||||
// but we can test the behavior through shouldStopAtPosition
|
||||
expect(state).toBeDefined();
|
||||
});
|
||||
|
||||
it("should correctly identify bare backticks positions", () => {
|
||||
const allLines = ["```markdown", "```", "content", "```"];
|
||||
const state = new MarkdownBlockStateTracker(allLines);
|
||||
|
||||
// At position 1 (first bare backticks), should not stop
|
||||
expect(state.shouldStopAtPosition(1)).toBe(false);
|
||||
// At position 3 (last bare backticks), should stop
|
||||
expect(state.shouldStopAtPosition(3)).toBe(true);
|
||||
});
|
||||
|
||||
it("should maintain state across multiple calls", () => {
|
||||
const allLines = [
|
||||
"```markdown",
|
||||
"# Title",
|
||||
"```javascript",
|
||||
"console.log('test');",
|
||||
"```",
|
||||
"More content",
|
||||
"```",
|
||||
];
|
||||
const state = new MarkdownBlockStateTracker(allLines);
|
||||
|
||||
// Process positions incrementally
|
||||
expect(state.shouldStopAtPosition(2)).toBe(false); // Start of inner block
|
||||
expect(state.shouldStopAtPosition(4)).toBe(false); // End of inner block
|
||||
expect(state.shouldStopAtPosition(6)).toBe(true); // End of outer block
|
||||
});
|
||||
|
||||
it("should handle complex nesting scenarios efficiently", () => {
|
||||
const allLines = [
|
||||
"```markdown",
|
||||
"# Documentation",
|
||||
"```typescript",
|
||||
"interface Config {",
|
||||
" name: string;",
|
||||
"}",
|
||||
"```",
|
||||
"",
|
||||
"```bash",
|
||||
"npm install",
|
||||
"```",
|
||||
"",
|
||||
"Final notes",
|
||||
"```",
|
||||
];
|
||||
const state = new MarkdownBlockStateTracker(allLines);
|
||||
|
||||
// Test multiple positions in sequence
|
||||
expect(state.shouldStopAtPosition(6)).toBe(false); // End of first inner block
|
||||
expect(state.shouldStopAtPosition(10)).toBe(false); // End of second inner block
|
||||
expect(state.shouldStopAtPosition(13)).toBe(true); // End of outer markdown block
|
||||
});
|
||||
|
||||
it("should handle non-backtick lines correctly", () => {
|
||||
const allLines = ["```markdown", "regular content", "```"];
|
||||
const state = new MarkdownBlockStateTracker(allLines);
|
||||
|
||||
// Position 1 is not backticks, should return false
|
||||
expect(state.shouldStopAtPosition(1)).toBe(false);
|
||||
});
|
||||
|
||||
it("should handle empty lines and edge cases", () => {
|
||||
const allLines = ["```markdown", "", "```"];
|
||||
const state = new MarkdownBlockStateTracker(allLines);
|
||||
|
||||
expect(state.shouldStopAtPosition(1)).toBe(false); // Empty line
|
||||
expect(state.shouldStopAtPosition(2)).toBe(true); // Closing backticks
|
||||
});
|
||||
|
||||
it("should reset nest count when reaching final bare backticks", () => {
|
||||
const allLines = ["```markdown", "content", "```"];
|
||||
const state = new MarkdownBlockStateTracker(allLines);
|
||||
|
||||
// First call should stop and reset count
|
||||
expect(state.shouldStopAtPosition(2)).toBe(true);
|
||||
|
||||
// If we had more content, it should start fresh
|
||||
// (This tests the internal state management)
|
||||
});
|
||||
});
|
||||
|
||||
describe("shouldStopAtMarkdownBlock optimization", () => {
|
||||
it("should maintain performance benefits with state reuse", () => {
|
||||
const allLines = Array.from({ length: 100 }, (_, i) => {
|
||||
if (i === 0) return "```markdown";
|
||||
if (i === 99) return "```";
|
||||
if (i % 10 === 0) return "```javascript";
|
||||
if (i % 10 === 5) return "```";
|
||||
return `line ${i}`;
|
||||
});
|
||||
|
||||
const state = new MarkdownBlockStateTracker(allLines);
|
||||
|
||||
// Test that we can call multiple times without recomputing everything
|
||||
const start = performance.now();
|
||||
|
||||
// Test several positions in sequence
|
||||
for (let i = 10; i < 90; i += 10) {
|
||||
if (allLines[i].trim() === "```") {
|
||||
shouldStopAtMarkdownBlock(state, i);
|
||||
}
|
||||
}
|
||||
|
||||
const duration = performance.now() - start;
|
||||
expect(duration).toBeLessThan(10); // Should be very fast due to state caching
|
||||
});
|
||||
});
|
||||
|
||||
describe("filterCodeBlockLines with optimized MarkdownBlockState", () => {
|
||||
it("should use optimized state tracker for markdown files", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```markdown",
|
||||
"# Documentation",
|
||||
"```typescript",
|
||||
"const config = { name: 'test' };",
|
||||
"```",
|
||||
"Final notes",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(
|
||||
linesGenerator,
|
||||
"README.md",
|
||||
);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
"# Documentation",
|
||||
"```typescript",
|
||||
"const config = { name: 'test' };",
|
||||
"```",
|
||||
"Final notes",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should fall back to legacy behavior when no markdown nesting detected", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```typescript",
|
||||
"const x = 5;",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(
|
||||
linesGenerator,
|
||||
"script.ts",
|
||||
);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;"]);
|
||||
});
|
||||
|
||||
it("should handle mixed markdown and code scenarios with optimization", async () => {
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```md",
|
||||
"## API Reference",
|
||||
"",
|
||||
"```javascript",
|
||||
"async function fetchData() {",
|
||||
" return await fetch('/api/data');",
|
||||
"}",
|
||||
"```",
|
||||
"",
|
||||
"Usage notes and more documentation.",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual([
|
||||
"## API Reference",
|
||||
"",
|
||||
"```javascript",
|
||||
"async function fetchData() {",
|
||||
" return await fetch('/api/data');",
|
||||
"}",
|
||||
"```",
|
||||
"",
|
||||
"Usage notes and more documentation.",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("validatePatternInLine", () => {
|
||||
it("should return false when pattern is not found", () => {
|
||||
const result = lineStream.validatePatternInLine(
|
||||
"const x = 5;",
|
||||
"[/CODE]",
|
||||
);
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.patternIndex).toBe(-1);
|
||||
expect(result.beforePattern).toBe("");
|
||||
});
|
||||
|
||||
it("should return false when pattern is preceded by non-whitespace", () => {
|
||||
const result = lineStream.validatePatternInLine(
|
||||
'const var[/CODE]Name = "test";',
|
||||
"[/CODE]",
|
||||
);
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.patternIndex).toBe(9);
|
||||
});
|
||||
|
||||
it("should return false when pattern is inside double quotes", () => {
|
||||
const result = lineStream.validatePatternInLine(
|
||||
'console.log("test [/CODE] end");',
|
||||
"[/CODE]",
|
||||
);
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.patternIndex).toBe(18);
|
||||
});
|
||||
|
||||
it("should return false when pattern is inside single quotes", () => {
|
||||
const result = lineStream.validatePatternInLine(
|
||||
"const message = 'test [/CODE] end';",
|
||||
"[/CODE]",
|
||||
);
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.patternIndex).toBe(22);
|
||||
});
|
||||
|
||||
it("should return true when pattern is properly separated by whitespace", () => {
|
||||
const result = lineStream.validatePatternInLine(
|
||||
"some code [/CODE] more text",
|
||||
"[/CODE]",
|
||||
);
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.patternIndex).toBe(10);
|
||||
expect(result.beforePattern).toBe("some code ");
|
||||
});
|
||||
|
||||
it("should return true when pattern is at start of line", () => {
|
||||
const result = lineStream.validatePatternInLine("[/CODE]", "[/CODE]");
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.patternIndex).toBe(0);
|
||||
expect(result.beforePattern).toBe("");
|
||||
});
|
||||
|
||||
it("should return true when pattern has only whitespace before it", () => {
|
||||
const result = lineStream.validatePatternInLine(" [/CODE]", "[/CODE]");
|
||||
expect(result.isValid).toBe(true);
|
||||
expect(result.patternIndex).toBe(4);
|
||||
expect(result.beforePattern).toBe(" ");
|
||||
});
|
||||
|
||||
it("should handle complex quote scenarios correctly", () => {
|
||||
// Unmatched quote should make it invalid
|
||||
const result1 = lineStream.validatePatternInLine(
|
||||
'const x = "unclosed quote [/CODE]',
|
||||
"[/CODE]",
|
||||
);
|
||||
expect(result1.isValid).toBe(false);
|
||||
|
||||
// Matched quotes should make it valid
|
||||
const result2 = lineStream.validatePatternInLine(
|
||||
'const x = "closed"; [/CODE]',
|
||||
"[/CODE]",
|
||||
);
|
||||
expect(result2.isValid).toBe(true);
|
||||
});
|
||||
|
||||
it("should work with different patterns", () => {
|
||||
const result1 = lineStream.validatePatternInLine(
|
||||
"# End of file. Done",
|
||||
"# End of file.",
|
||||
);
|
||||
expect(result1.isValid).toBe(true);
|
||||
|
||||
const result2 = lineStream.validatePatternInLine(" ```", "```");
|
||||
expect(result2.isValid).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
};
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
),
|
||||
),
|
||||
|
|
|
|||
|
|
@ -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) => {
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -42,4 +42,5 @@ export interface AutocompleteOutcome extends TabAutocompleteOptions {
|
|||
completionId: string;
|
||||
uniqueId: string;
|
||||
timestamp: string;
|
||||
enabledStaticContextualization?: boolean;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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")}`;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,18 +424,21 @@ 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,
|
||||
errors: [],
|
||||
errors: [{ message: "Current profile not found", fatal: true }],
|
||||
configLoadInterrupted: true,
|
||||
};
|
||||
}
|
||||
|
|
@ -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 };
|
||||
}
|
||||
|
||||
|
|
@ -440,7 +494,7 @@ export class ConfigHandler {
|
|||
if (!this.currentProfile) {
|
||||
return {
|
||||
config: undefined,
|
||||
errors: [],
|
||||
errors: [{ message: "Current profile not found", fatal: true }],
|
||||
configLoadInterrupted: true,
|
||||
};
|
||||
}
|
||||
|
|
@ -453,10 +507,11 @@ export class ConfigHandler {
|
|||
if (!this.currentProfile) {
|
||||
return {
|
||||
config: undefined,
|
||||
errors: [],
|
||||
errors: [{ message: "Current profile not found", fatal: true }],
|
||||
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".
|
||||
|
|
|
|||
|
|
@ -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
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -652,6 +652,7 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
|
|||
configurationStatus: llm.getConfigurationStatus(),
|
||||
apiKeyLocation: llm.apiKeyLocation,
|
||||
envSecretLocations: llm.envSecretLocations,
|
||||
sourceFile: llm.sourceFile,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1057,6 +1057,7 @@ declare global {
|
|||
numDiffs?: number;
|
||||
filepath?: string;
|
||||
fileContent?: string;
|
||||
originalFileContent?: string;
|
||||
}
|
||||
|
||||
export interface RangeInFileWithContents {
|
||||
|
|
|
|||
|
|
@ -56,6 +56,8 @@ function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
|
|||
rule: rule.rule,
|
||||
globs: rule.globs,
|
||||
name: rule.name,
|
||||
ruleFile: rule.sourceFile,
|
||||
alwaysApply: rule.alwaysApply,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -235,6 +237,8 @@ async function configYamlToContinueConfig(options: {
|
|||
startUrl: doc.startUrl,
|
||||
rootUrl: doc.rootUrl,
|
||||
faviconUrl: doc.faviconUrl,
|
||||
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: [],
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
);
|
||||
|
|
|
|||
|
|
@ -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),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
163
core/core.ts
163
core/core.ts
|
|
@ -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,13 +392,18 @@ 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;
|
||||
});
|
||||
|
||||
on("controlPlane/openUrl", async (msg) => {
|
||||
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
|
||||
let url = `${env.APP_URL}${msg.data.path}`;
|
||||
const urlPath = msg.data.path.startsWith("/")
|
||||
? msg.data.path.slice(1)
|
||||
: msg.data.path;
|
||||
let url = `${env.APP_URL}${urlPath}`;
|
||||
if (msg.data.orgSlug) {
|
||||
url += `?org=${msg.data.orgSlug}`;
|
||||
}
|
||||
|
|
@ -487,6 +525,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 +556,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 +594,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 +723,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 +748,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 +1026,7 @@ export class Core {
|
|||
],
|
||||
}),
|
||||
);
|
||||
void this.configHandler.reloadConfig();
|
||||
void this.configHandler.reloadConfig("Autocomplete model added");
|
||||
}
|
||||
|
||||
private async handleFilesChanged({
|
||||
|
|
@ -964,7 +1056,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 +1066,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 +1165,7 @@ export class Core {
|
|||
|
||||
editConfigFile((c) => c, editConfigYamlCallback);
|
||||
|
||||
void this.configHandler.reloadConfig();
|
||||
void this.configHandler.reloadConfig("Onboarding completed");
|
||||
}
|
||||
|
||||
private getContextItems = async (
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
||||
|
|
|
|||
|
|
@ -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: "",
|
||||
|
|
|
|||
|
|
@ -1,8 +1,5 @@
|
|||
import { ILLM } from "../..";
|
||||
import {
|
||||
filterLeadingNewline,
|
||||
stopAtLines,
|
||||
} from "../../autocomplete/filtering/streamTransforms/lineStream";
|
||||
import { filterLeadingNewline } from "../../autocomplete/filtering/streamTransforms/lineStream";
|
||||
import { streamLines } from "../../diff/util";
|
||||
import { dedent } from "../../util";
|
||||
|
||||
|
|
@ -90,11 +87,18 @@ export async function* getReplacementWithLlm(
|
|||
{ role: "assistant", content: assistantPrompt },
|
||||
],
|
||||
abortController.signal,
|
||||
{
|
||||
raw: true,
|
||||
prediction: undefined,
|
||||
reasoning: false,
|
||||
},
|
||||
);
|
||||
|
||||
let lines = streamLines(completion);
|
||||
lines = filterLeadingNewline(lines);
|
||||
lines = stopAtLines(lines, () => {}, ["```"]);
|
||||
// We want to retrive everything from the llm
|
||||
// then let the filterCodeBlocks function clean up for any trailing text.
|
||||
// if we stop here early, we run the risk of loosing inner markdown content.
|
||||
|
||||
for await (const line of lines) {
|
||||
yield line;
|
||||
|
|
|
|||
459
core/edit/lazy/streamLazyApply.test.ts
Normal file
459
core/edit/lazy/streamLazyApply.test.ts
Normal file
|
|
@ -0,0 +1,459 @@
|
|||
import { streamLazyApply } from "./streamLazyApply";
|
||||
|
||||
// Mock LLM for testing
|
||||
class MockLLM {
|
||||
model = "claude-3-5-sonnet-20241022";
|
||||
providerName = "anthropic";
|
||||
|
||||
async *streamChat(messages: any[], signal?: AbortSignal) {
|
||||
// Simulate LLM response for markdown file with nested blocks
|
||||
const lines = [
|
||||
"# Project Structure",
|
||||
"",
|
||||
"```markdown README.md",
|
||||
"# Project Structure",
|
||||
"",
|
||||
"```",
|
||||
".",
|
||||
"├── src/",
|
||||
"│ └── main.js",
|
||||
"└── package.json",
|
||||
"```",
|
||||
"```",
|
||||
];
|
||||
|
||||
// Yield each line separately (more realistic streaming)
|
||||
for (const line of lines) {
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class MockJavaScriptLLM {
|
||||
model = "claude-3-5-sonnet-20241022";
|
||||
providerName = "anthropic";
|
||||
|
||||
async *streamChat(messages: any[], signal?: AbortSignal) {
|
||||
// Simulate LLM response for JavaScript file
|
||||
const lines = [
|
||||
"function calculateSum(a, b) {",
|
||||
" return a + b;",
|
||||
"}",
|
||||
"",
|
||||
"function calculateProduct(a, b) {",
|
||||
" return a * b;",
|
||||
"}",
|
||||
];
|
||||
|
||||
for (const line of lines) {
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class MockPythonLLM {
|
||||
model = "claude-3-5-sonnet-20241022";
|
||||
providerName = "anthropic";
|
||||
|
||||
async *streamChat(messages: any[], signal?: AbortSignal) {
|
||||
// Simulate LLM response for Python file
|
||||
const lines = [
|
||||
"def calculate_sum(a, b):",
|
||||
" return a + b",
|
||||
"",
|
||||
"def calculate_product(a, b):",
|
||||
" return a * b",
|
||||
];
|
||||
|
||||
for (const line of lines) {
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class MockWithUnchangedCodeLLM {
|
||||
model = "claude-3-5-sonnet-20241022";
|
||||
providerName = "anthropic";
|
||||
|
||||
async *streamChat(messages: any[], signal?: AbortSignal) {
|
||||
// Simulate LLM response with UNCHANGED_CODE markers
|
||||
const lines = [
|
||||
"function newFunction() {",
|
||||
" return 'new';",
|
||||
"}",
|
||||
"",
|
||||
"// ... unchanged code ...",
|
||||
"",
|
||||
"function anotherFunction() {",
|
||||
" return 'updated';",
|
||||
"}",
|
||||
];
|
||||
|
||||
for (const line of lines) {
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class MockTypeScriptLLM {
|
||||
model = "claude-3-5-sonnet-20241022";
|
||||
providerName = "anthropic";
|
||||
|
||||
async *streamChat(messages: any[], signal?: AbortSignal) {
|
||||
const lines = [
|
||||
"interface User {",
|
||||
" id: number;",
|
||||
" name: string;",
|
||||
"}",
|
||||
"",
|
||||
"function getUser(id: number): User {",
|
||||
" return { id, name: 'Test User' };",
|
||||
"}",
|
||||
];
|
||||
|
||||
for (const line of lines) {
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class MockEmptyLLM {
|
||||
model = "claude-3-5-sonnet-20241022";
|
||||
providerName = "anthropic";
|
||||
|
||||
async *streamChat(messages: any[], signal?: AbortSignal) {
|
||||
// Empty response
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
class MockSimpleLLM {
|
||||
model = "claude-3-5-sonnet-20241022";
|
||||
providerName = "anthropic";
|
||||
|
||||
async *streamChat(messages: any[], signal?: AbortSignal) {
|
||||
const lines = ["function test() {", " return true;", "}"];
|
||||
for (const line of lines) {
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class MockRegularMarkdownLLM {
|
||||
model = "claude-3-5-sonnet-20241022";
|
||||
providerName = "anthropic";
|
||||
|
||||
async *streamChat(messages: any[], signal?: AbortSignal) {
|
||||
// Simulate regular markdown with simple code block
|
||||
const lines = [
|
||||
"# Debug Test Folder",
|
||||
"The sole purpose of this folder is to open it when debugging.",
|
||||
"",
|
||||
"## File Structure",
|
||||
"```",
|
||||
"debug-test-folder/",
|
||||
"├── AdvancedPage.tsx",
|
||||
"├── Calculator.java",
|
||||
"├── Dockerfile",
|
||||
"└── test.ts",
|
||||
"```",
|
||||
];
|
||||
|
||||
for (const line of lines) {
|
||||
yield line;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe("streamLazyApply", () => {
|
||||
test("should handle markdown files with nested blocks without stopping early", async () => {
|
||||
const oldCode = "# Project\n\nBasic readme content.";
|
||||
const newCode = `# Project Structure
|
||||
|
||||
\`\`\`markdown README.md
|
||||
# Project Structure
|
||||
|
||||
\`\`\`
|
||||
.
|
||||
├── src/
|
||||
│ └── main.js
|
||||
└── package.json
|
||||
\`\`\`
|
||||
\`\`\``;
|
||||
const filename = "README.md";
|
||||
const llm = new MockLLM() as any;
|
||||
const abortController = new AbortController();
|
||||
|
||||
const diffLines = [];
|
||||
for await (const diffLine of streamLazyApply(
|
||||
oldCode,
|
||||
filename,
|
||||
newCode,
|
||||
llm,
|
||||
abortController,
|
||||
)) {
|
||||
diffLines.push(diffLine);
|
||||
}
|
||||
|
||||
// Should have received diff lines (not empty)
|
||||
expect(diffLines.length).toBeGreaterThan(0);
|
||||
|
||||
// Should contain the nested markdown content
|
||||
const allContent = diffLines.map((d) => d.line).join("\n");
|
||||
expect(allContent).toContain("```markdown README.md");
|
||||
expect(allContent).toContain("└── package.json");
|
||||
|
||||
// Should not have been truncated at the first ```
|
||||
expect(allContent).toContain("src/");
|
||||
});
|
||||
|
||||
test("should handle JavaScript files correctly", async () => {
|
||||
const oldCode = "function calculateSum(a, b) {\n return a + b;\n}";
|
||||
const newCode = `function calculateSum(a, b) {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
function calculateProduct(a, b) {
|
||||
return a * b;
|
||||
}`;
|
||||
const filename = "calculator.js";
|
||||
const llm = new MockJavaScriptLLM() as any;
|
||||
const abortController = new AbortController();
|
||||
|
||||
const diffLines = [];
|
||||
for await (const diffLine of streamLazyApply(
|
||||
oldCode,
|
||||
filename,
|
||||
newCode,
|
||||
llm,
|
||||
abortController,
|
||||
)) {
|
||||
diffLines.push(diffLine);
|
||||
}
|
||||
|
||||
// Should have received diff lines
|
||||
expect(diffLines.length).toBeGreaterThan(0);
|
||||
|
||||
// Should contain the JavaScript functions
|
||||
const allContent = diffLines.map((d) => d.line).join("\n");
|
||||
expect(allContent).toContain("calculateSum");
|
||||
expect(allContent).toContain("calculateProduct");
|
||||
});
|
||||
|
||||
test("should handle Python files correctly", async () => {
|
||||
const oldCode = "def calculate_sum(a, b):\n return a + b";
|
||||
const newCode = `def calculate_sum(a, b):
|
||||
return a + b
|
||||
|
||||
def calculate_product(a, b):
|
||||
return a * b`;
|
||||
const filename = "calculator.py";
|
||||
const llm = new MockPythonLLM() as any;
|
||||
const abortController = new AbortController();
|
||||
|
||||
const diffLines = [];
|
||||
for await (const diffLine of streamLazyApply(
|
||||
oldCode,
|
||||
filename,
|
||||
newCode,
|
||||
llm,
|
||||
abortController,
|
||||
)) {
|
||||
diffLines.push(diffLine);
|
||||
}
|
||||
|
||||
// Should have received diff lines
|
||||
expect(diffLines.length).toBeGreaterThan(0);
|
||||
|
||||
// Should contain the Python functions
|
||||
const allContent = diffLines.map((d) => d.line).join("\n");
|
||||
expect(allContent).toContain("calculate_sum");
|
||||
expect(allContent).toContain("calculate_product");
|
||||
});
|
||||
|
||||
test("should handle UNCHANGED_CODE markers in responses", async () => {
|
||||
const oldCode = `function oldFunction() {
|
||||
return 'old';
|
||||
}
|
||||
|
||||
function existingFunction() {
|
||||
return 'existing';
|
||||
}`;
|
||||
const newCode = `function newFunction() {
|
||||
return 'new';
|
||||
}
|
||||
|
||||
function existingFunction() {
|
||||
return 'existing';
|
||||
}
|
||||
|
||||
function anotherFunction() {
|
||||
return 'updated';
|
||||
}`;
|
||||
const filename = "example.js";
|
||||
const llm = new MockWithUnchangedCodeLLM() as any;
|
||||
const abortController = new AbortController();
|
||||
|
||||
const diffLines = [];
|
||||
for await (const diffLine of streamLazyApply(
|
||||
oldCode,
|
||||
filename,
|
||||
newCode,
|
||||
llm,
|
||||
abortController,
|
||||
)) {
|
||||
diffLines.push(diffLine);
|
||||
}
|
||||
|
||||
// Should have received diff lines
|
||||
expect(diffLines.length).toBeGreaterThan(0);
|
||||
|
||||
// Should contain new and updated functions
|
||||
const allContent = diffLines.map((d) => d.line).join("\n");
|
||||
expect(allContent).toContain("newFunction");
|
||||
expect(allContent).toContain("anotherFunction");
|
||||
});
|
||||
|
||||
test("should handle TypeScript files correctly", async () => {
|
||||
const oldCode = "interface User {\n id: number;\n}";
|
||||
const newCode = `interface User {
|
||||
id: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
function getUser(id: number): User {
|
||||
return { id, name: 'Test User' };
|
||||
}`;
|
||||
const filename = "user.ts";
|
||||
const llm = new MockTypeScriptLLM() as any;
|
||||
const abortController = new AbortController();
|
||||
|
||||
const diffLines = [];
|
||||
for await (const diffLine of streamLazyApply(
|
||||
oldCode,
|
||||
filename,
|
||||
newCode,
|
||||
llm,
|
||||
abortController,
|
||||
)) {
|
||||
diffLines.push(diffLine);
|
||||
}
|
||||
|
||||
// Should have received diff lines
|
||||
expect(diffLines.length).toBeGreaterThan(0);
|
||||
|
||||
// Should contain TypeScript interface and function
|
||||
const allContent = diffLines.map((d) => d.line).join("\n");
|
||||
expect(allContent).toContain("interface User");
|
||||
expect(allContent).toContain("getUser");
|
||||
expect(allContent).toContain("name: string");
|
||||
});
|
||||
|
||||
test("should work with empty LLM responses", async () => {
|
||||
const oldCode = "function test() { return 1; }";
|
||||
const newCode = "function test() { return 2; }";
|
||||
const filename = "test.js";
|
||||
const llm = new MockEmptyLLM() as any;
|
||||
const abortController = new AbortController();
|
||||
|
||||
const diffLines = [];
|
||||
for await (const diffLine of streamLazyApply(
|
||||
oldCode,
|
||||
filename,
|
||||
newCode,
|
||||
llm,
|
||||
abortController,
|
||||
)) {
|
||||
diffLines.push(diffLine);
|
||||
}
|
||||
|
||||
// Should handle empty response gracefully
|
||||
expect(diffLines).toBeDefined();
|
||||
});
|
||||
|
||||
test("should correctly identify markdown vs non-markdown files", async () => {
|
||||
// Test that our isMarkdownFile logic works
|
||||
const markdownFiles = ["README.md", "docs.markdown", "example.gfm"];
|
||||
const nonMarkdownFiles = [
|
||||
"script.js",
|
||||
"code.py",
|
||||
"style.css",
|
||||
"component.tsx",
|
||||
];
|
||||
|
||||
// This is more of a unit test, but verifies our file detection logic
|
||||
// We can test this indirectly by checking that different file types
|
||||
// are processed through different code paths
|
||||
|
||||
const oldCode = "function test() { return false; }";
|
||||
const newCode = "function test() { return true; }";
|
||||
const llm = new MockSimpleLLM() as any;
|
||||
|
||||
// Test each file type
|
||||
for (const filename of [...markdownFiles, ...nonMarkdownFiles]) {
|
||||
const abortController = new AbortController();
|
||||
const diffLines = [];
|
||||
|
||||
for await (const diffLine of streamLazyApply(
|
||||
oldCode,
|
||||
filename,
|
||||
newCode,
|
||||
llm,
|
||||
abortController,
|
||||
)) {
|
||||
diffLines.push(diffLine);
|
||||
}
|
||||
|
||||
// Should work for all file types
|
||||
expect(diffLines.length).toBeGreaterThan(0);
|
||||
|
||||
const allContent = diffLines.map((d) => d.line).join("\n");
|
||||
expect(allContent).toContain("test");
|
||||
}
|
||||
});
|
||||
|
||||
test("should handle regular markdown files with simple code blocks", async () => {
|
||||
const oldCode = "# Old Content";
|
||||
const newCode = `# Debug Test Folder
|
||||
The sole purpose of this folder is to open it when debugging.
|
||||
|
||||
## File Structure
|
||||
\`\`\`
|
||||
debug-test-folder/
|
||||
├── AdvancedPage.tsx
|
||||
├── Calculator.java
|
||||
├── Dockerfile
|
||||
└── test.ts
|
||||
\`\`\``;
|
||||
|
||||
const filename = "README.md";
|
||||
const llm = new MockRegularMarkdownLLM() as any;
|
||||
const abortController = new AbortController();
|
||||
|
||||
const diffLines = [];
|
||||
for await (const diffLine of streamLazyApply(
|
||||
oldCode,
|
||||
filename,
|
||||
newCode,
|
||||
llm,
|
||||
abortController,
|
||||
)) {
|
||||
diffLines.push(diffLine);
|
||||
}
|
||||
|
||||
// Should have received diff lines (not empty)
|
||||
expect(diffLines.length).toBeGreaterThan(0);
|
||||
|
||||
// Should contain the full file structure
|
||||
const allContent = diffLines.map((d) => d.line).join("\n");
|
||||
expect(allContent).toContain("Debug Test Folder");
|
||||
expect(allContent).toContain("File Structure");
|
||||
expect(allContent).toContain("debug-test-folder/");
|
||||
expect(allContent).toContain("├── AdvancedPage.tsx");
|
||||
expect(allContent).toContain("└── test.ts");
|
||||
|
||||
// Should not have been truncated at the opening ```
|
||||
expect(allContent).toContain("Calculator.java");
|
||||
expect(allContent).toContain("Dockerfile");
|
||||
});
|
||||
});
|
||||
|
|
@ -2,11 +2,11 @@ import {
|
|||
filterLeadingAndTrailingNewLineInsertion,
|
||||
filterLeadingNewline,
|
||||
removeTrailingWhitespace,
|
||||
stopAtLines,
|
||||
} from "../../autocomplete/filtering/streamTransforms/lineStream.js";
|
||||
import { streamDiff } from "../../diff/streamDiff.js";
|
||||
import { LineStream, streamLines } from "../../diff/util.js";
|
||||
import { DiffLine, ILLM } from "../../index.js";
|
||||
import { stopAtLinesWithMarkdownSupport } from "../../utils/streamMarkdownUtils.js";
|
||||
|
||||
import { lazyApplyPromptForModel, UNCHANGED_CODE } from "./prompts.js";
|
||||
import { BUFFER_LINES_BELOW, getReplacementWithLlm } from "./replace.js";
|
||||
|
|
@ -44,9 +44,12 @@ export async function* streamLazyApply(
|
|||
}
|
||||
|
||||
let lazyCompletionLines = streamLines(lazyCompletion, true);
|
||||
// Process line output
|
||||
// lazyCompletionLines = filterEnglishLinesAtStart(lazyCompletionLines);
|
||||
lazyCompletionLines = stopAtLines(lazyCompletionLines, () => {}, ["```"]);
|
||||
|
||||
lazyCompletionLines = stopAtLinesWithMarkdownSupport(
|
||||
lazyCompletionLines,
|
||||
filename,
|
||||
);
|
||||
|
||||
lazyCompletionLines = filterLeadingNewline(lazyCompletionLines);
|
||||
lazyCompletionLines = removeTrailingWhitespace(lazyCompletionLines);
|
||||
|
||||
|
|
@ -92,7 +95,6 @@ async function* streamFillUnchangedCode(
|
|||
newLines.push(replacementLine);
|
||||
replacement += replacementLine + "\n";
|
||||
}
|
||||
|
||||
// Yield the buffered lines
|
||||
for (const bufferedLine of buffer) {
|
||||
yield bufferedLine;
|
||||
|
|
|
|||
|
|
@ -63,7 +63,8 @@ export async function* recursiveStream(
|
|||
}
|
||||
} else {
|
||||
const generator = llm.streamChat(prompt, abortController.signal, {
|
||||
prediction,
|
||||
raw: true,
|
||||
prediction: undefined,
|
||||
reasoning: false,
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -55,11 +55,7 @@ export async function* addIndentation(
|
|||
}
|
||||
|
||||
function modelIsInept(model: string): boolean {
|
||||
return !(
|
||||
model.includes("gpt") ||
|
||||
model.includes("claude") ||
|
||||
model.includes("nova")
|
||||
);
|
||||
return !(model.includes("gpt") || model.includes("claude"));
|
||||
}
|
||||
|
||||
export async function* streamDiffLines({
|
||||
|
|
|
|||
164
core/index.d.ts
vendored
164
core/index.d.ts
vendored
|
|
@ -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 {
|
||||
|
|
@ -1303,6 +1360,7 @@ export interface ApplyState {
|
|||
numDiffs?: number;
|
||||
filepath?: string;
|
||||
fileContent?: string;
|
||||
originalFileContent?: string;
|
||||
toolCallId?: string;
|
||||
}
|
||||
|
||||
|
|
@ -1361,6 +1419,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 +1541,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 +1551,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 +1770,7 @@ export type RuleSource =
|
|||
| "model-options-plan"
|
||||
| "model-options-agent"
|
||||
| "rules-block"
|
||||
| "colocated-markdown"
|
||||
| "json-systemMessage"
|
||||
| ".continuerules";
|
||||
|
||||
|
|
@ -1668,3 +1790,13 @@ export interface CompleteOnboardingPayload {
|
|||
provider?: string;
|
||||
apiKey?: string;
|
||||
}
|
||||
|
||||
export interface CompiledMessagesResult {
|
||||
compiledChatMessages: ChatMessage[];
|
||||
didPrune: boolean;
|
||||
contextPercentage: number;
|
||||
}
|
||||
|
||||
export interface MessageOption {
|
||||
precompiled: boolean;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
]);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
import path from "path";
|
||||
|
||||
import { shouldChunk } from "./chunk";
|
||||
import { Chunk, ChunkWithoutID } from "../../index.js";
|
||||
import { cleanupAsyncEncoders } from "../../llm/countTokens.js";
|
||||
import { chunkDocument, chunkDocumentWithoutId, shouldChunk } from "./chunk";
|
||||
|
||||
describe("shouldChunk", () => {
|
||||
test("should chunk a typescript file", () => {
|
||||
|
|
@ -28,6 +30,126 @@ describe("shouldChunk", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe("chunkDocument", () => {
|
||||
afterAll(async () => {
|
||||
// Clean up the global async encoders to prevent Jest from hanging
|
||||
await cleanupAsyncEncoders();
|
||||
});
|
||||
|
||||
test("should return multiple chunks for large content with small maxChunkSize", async () => {
|
||||
const filepath = "/test/file.txt";
|
||||
const maxChunkSize = 10; // small limit
|
||||
const digest = "test-digest";
|
||||
|
||||
// Create content with multiple short lines - each line should fit within maxChunkSize
|
||||
const lines = ["short line", "another line", "third line"];
|
||||
const contents = lines.join("\n");
|
||||
|
||||
const chunks: Chunk[] = [];
|
||||
for await (const chunk of chunkDocument({
|
||||
filepath,
|
||||
contents,
|
||||
maxChunkSize,
|
||||
digest,
|
||||
})) {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
|
||||
// Verify chunks have valid content
|
||||
chunks.forEach((chunk) => {
|
||||
expect(chunk.content.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
test("should filter out chunks that exceed maxChunkSize in tokens", async () => {
|
||||
const filepath = "/test/large.txt";
|
||||
const maxChunkSize = 10; // small limit
|
||||
const digest = "test-digest-2";
|
||||
|
||||
const contents =
|
||||
"This is a much longer line with many words that will likely exceed the maxChunkSize token limit and should be filtered out by the chunkDocument function. This is a much longer line with many words that will likely exceed the maxChunkSize token limit and should be filtered out by the chunkDocument function.";
|
||||
|
||||
const chunks: Chunk[] = [];
|
||||
for await (const chunk of chunkDocument({
|
||||
filepath,
|
||||
contents,
|
||||
maxChunkSize,
|
||||
digest,
|
||||
})) {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
|
||||
// Verify that no chunks were created since the content exceeds maxChunkSize
|
||||
chunks.forEach((chunk) => {
|
||||
expect(chunk.content.length).toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("chunkDocumentWithoutId", () => {
|
||||
afterAll(async () => {
|
||||
await cleanupAsyncEncoders();
|
||||
});
|
||||
|
||||
test("should return no chunks for empty content", async () => {
|
||||
const contents = "";
|
||||
const chunks: ChunkWithoutID[] = [];
|
||||
for await (const chunk of chunkDocumentWithoutId(
|
||||
"file.txt",
|
||||
contents,
|
||||
100,
|
||||
)) {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
expect(chunks).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("should chunk text files", async () => {
|
||||
const contents = "Line 1\nLine 2\nLine 3";
|
||||
const chunks: ChunkWithoutID[] = [];
|
||||
for await (const chunk of chunkDocumentWithoutId(
|
||||
"file.txt",
|
||||
contents,
|
||||
100,
|
||||
)) {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
expect(chunks.length).toBeGreaterThan(0);
|
||||
expect(chunks[0].content).toContain("Line 1");
|
||||
});
|
||||
|
||||
test("should chunk for code files", async () => {
|
||||
const contents = "function test() {\n return 42;\n}";
|
||||
const chunks: ChunkWithoutID[] = [];
|
||||
for await (const chunk of chunkDocumentWithoutId(
|
||||
"file.js",
|
||||
contents,
|
||||
100,
|
||||
)) {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
expect(chunks.length).toBeGreaterThan(0);
|
||||
expect(chunks[0].content).toContain("function test");
|
||||
});
|
||||
|
||||
test("should chunk large content", async () => {
|
||||
const contents = Array(100).fill("short line").join("\n"); // Large content with many lines
|
||||
const maxChunkSize = 50;
|
||||
const chunks: ChunkWithoutID[] = [];
|
||||
for await (const chunk of chunkDocumentWithoutId(
|
||||
"file.txt",
|
||||
contents,
|
||||
maxChunkSize,
|
||||
)) {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
expect(chunks.length).toBeGreaterThan(1); // Should create multiple chunks
|
||||
chunks.forEach((chunk) => {
|
||||
expect(chunk.content.length).toBeGreaterThan(0); // Each chunk should have content
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function generateString(length: number) {
|
||||
return "a".repeat(length);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ export type ChunkDocumentParam = {
|
|||
digest: string;
|
||||
};
|
||||
|
||||
async function* chunkDocumentWithoutId(
|
||||
export async function* chunkDocumentWithoutId(
|
||||
fileUri: string,
|
||||
contents: string,
|
||||
maxChunkSize: number,
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -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";
|
||||
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
const DEFAULT_MAX_TOKENS = 4096;
|
||||
const DEFAULT_CONTEXT_LENGTH = 32_768;
|
||||
const DEFAULT_TEMPERATURE = 0.5;
|
||||
const DEFAULT_PRUNING_LENGTH = 128000;
|
||||
|
||||
const DEFAULT_ARGS = {
|
||||
maxTokens: DEFAULT_MAX_TOKENS,
|
||||
|
|
@ -24,5 +25,6 @@ export {
|
|||
DEFAULT_MAX_BATCH_SIZE,
|
||||
DEFAULT_MAX_CHUNK_SIZE,
|
||||
DEFAULT_MAX_TOKENS,
|
||||
DEFAULT_PRUNING_LENGTH,
|
||||
PROXY_URL,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,10 +1,12 @@
|
|||
// @ts-nocheck
|
||||
// Generated by continue
|
||||
import { ChatMessage, MessagePart } from "../index.js";
|
||||
import { ChatMessage, MessagePart, ToolCall } from "../index.js";
|
||||
import {
|
||||
cleanupAsyncEncoders,
|
||||
compileChatMessages,
|
||||
countTokens,
|
||||
countTokensAsync,
|
||||
extractToolSequence,
|
||||
pruneLinesFromBottom,
|
||||
pruneLinesFromTop,
|
||||
pruneRawPromptFromTop,
|
||||
|
|
@ -26,7 +28,12 @@ describe.skip("countTokens", () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe.skip("countTokensAsync", () => {
|
||||
describe("countTokensAsync", () => {
|
||||
afterAll(async () => {
|
||||
// Clean up the global async encoders to prevent Jest from hanging
|
||||
await cleanupAsyncEncoders();
|
||||
});
|
||||
|
||||
it("should count tokens asynchronously for a simple string", async () => {
|
||||
const content = "Hello world!";
|
||||
const tokenCount = await countTokensAsync(content, "gpt-4");
|
||||
|
|
@ -174,3 +181,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
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,22 +1,24 @@
|
|||
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 { DEFAULT_PRUNING_LENGTH } from "./constants.js";
|
||||
import llamaTokenizer from "./llamaTokenizer.js";
|
||||
interface Encoding {
|
||||
encode: Tiktoken["encode"];
|
||||
decode: Tiktoken["decode"];
|
||||
|
|
@ -47,7 +49,6 @@ class NonWorkerAsyncEncoder implements AsyncEncoder {
|
|||
}
|
||||
|
||||
let gptEncoding: Encoding | null = null;
|
||||
const gptAsyncEncoder = new GPTAsyncEncoder();
|
||||
const llamaEncoding = new LlamaEncoding();
|
||||
const llamaAsyncEncoder = new LlamaAsyncEncoder();
|
||||
|
||||
|
|
@ -213,6 +214,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 +363,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,28 +377,53 @@ 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,
|
||||
contextLength,
|
||||
knownContextLength,
|
||||
maxTokens,
|
||||
supportsImages,
|
||||
tools,
|
||||
}: {
|
||||
modelName: string;
|
||||
msgs: ChatMessage[];
|
||||
contextLength: number;
|
||||
knownContextLength: number | undefined;
|
||||
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 +445,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
|
||||
|
|
@ -408,8 +466,9 @@ function compileChatMessages({
|
|||
toolTokens = countToolsTokens(tools, modelName);
|
||||
}
|
||||
|
||||
const contextLength = knownContextLength ?? DEFAULT_PRUNING_LENGTH;
|
||||
const countingSafetyBuffer = getTokenCountingBufferSafety(contextLength);
|
||||
const minOutputTokens = getMinResponseTokens(maxTokens);
|
||||
const minOutputTokens = Math.min(MIN_RESPONSE_TOKENS, maxTokens);
|
||||
|
||||
let inputTokensAvailable = contextLength;
|
||||
|
||||
|
|
@ -423,17 +482,16 @@ function compileChatMessages({
|
|||
inputTokensAvailable -= lastMessagesTokens;
|
||||
|
||||
// Make sure there's enough context for the non-excludable items
|
||||
if (inputTokensAvailable < 0) {
|
||||
if (knownContextLength !== undefined && inputTokensAvailable < 0) {
|
||||
throw new Error(
|
||||
`Not enough context available to include the system message, last user message, and tools.
|
||||
There must be at least ${minOutputTokens} tokens remaining for output.
|
||||
Request had the following token counts:
|
||||
- contextLength: ${contextLength}
|
||||
- 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: ${knownContextLength}
|
||||
- counting safety buffer: ${countingSafetyBuffer}
|
||||
- tools: ~${toolTokens}
|
||||
- system message: ~${systemMsgTokens}
|
||||
- max output tokens: ${maxTokens}`,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -451,6 +509,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 +524,32 @@ 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,
|
||||
};
|
||||
}
|
||||
|
||||
async function cleanupAsyncEncoders(): Promise<void> {
|
||||
try {
|
||||
await llamaAsyncEncoder.close();
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
export {
|
||||
cleanupAsyncEncoders,
|
||||
compileChatMessages,
|
||||
countTokens,
|
||||
countTokensAsync,
|
||||
extractToolSequence,
|
||||
pruneLinesFromBottom,
|
||||
pruneLinesFromTop,
|
||||
pruneRawPromptFromTop,
|
||||
|
|
|
|||
|
|
@ -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";
|
||||
|
|
@ -143,7 +145,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
baseChatSystemMessage?: string;
|
||||
basePlanSystemMessage?: string;
|
||||
baseAgentSystemMessage?: string;
|
||||
contextLength: number;
|
||||
_contextLength: number | undefined;
|
||||
maxStopWords?: number | undefined;
|
||||
completionOptions: CompletionOptions;
|
||||
requestOptions?: RequestOptions;
|
||||
|
|
@ -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;
|
||||
|
|
@ -215,8 +220,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
this.baseAgentSystemMessage = options.baseAgentSystemMessage;
|
||||
this.basePlanSystemMessage = options.basePlanSystemMessage;
|
||||
this.baseChatSystemMessage = options.baseChatSystemMessage;
|
||||
this.contextLength =
|
||||
options.contextLength ?? llmInfo?.contextLength ?? DEFAULT_CONTEXT_LENGTH;
|
||||
this._contextLength = options.contextLength ?? llmInfo?.contextLength;
|
||||
this.maxStopWords = options.maxStopWords ?? this.maxStopWords;
|
||||
this.completionOptions = {
|
||||
...options.completionOptions,
|
||||
|
|
@ -288,6 +292,11 @@ export abstract class BaseLLM implements ILLM {
|
|||
this.embeddingId = `${this.constructor.name}::${this.model}::${this.maxEmbeddingChunkSize}`;
|
||||
|
||||
this.autocompleteOptions = options.autocompleteOptions;
|
||||
this.sourceFile = options.sourceFile;
|
||||
}
|
||||
|
||||
get contextLength() {
|
||||
return this._contextLength ?? DEFAULT_CONTEXT_LENGTH;
|
||||
}
|
||||
|
||||
getConfigurationStatus() {
|
||||
|
|
@ -326,6 +335,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 +377,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
promptTokens,
|
||||
generatedTokens,
|
||||
thinkingTokens,
|
||||
usage,
|
||||
});
|
||||
return "cancelled";
|
||||
} else {
|
||||
|
|
@ -378,6 +389,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
promptTokens,
|
||||
generatedTokens,
|
||||
thinkingTokens,
|
||||
usage,
|
||||
});
|
||||
return "error";
|
||||
}
|
||||
|
|
@ -387,6 +399,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
promptTokens,
|
||||
generatedTokens,
|
||||
thinkingTokens,
|
||||
usage,
|
||||
});
|
||||
return "success";
|
||||
}
|
||||
|
|
@ -573,6 +586,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
prefix,
|
||||
suffix,
|
||||
options: completionOptions,
|
||||
provider: this.providerName,
|
||||
});
|
||||
if (this.llmRequestHook) {
|
||||
this.llmRequestHook(completionOptions.model, fimLog);
|
||||
|
|
@ -621,6 +635,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
);
|
||||
} catch (e) {
|
||||
status = this._logEnd(
|
||||
|
|
@ -629,6 +644,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
e,
|
||||
);
|
||||
throw e;
|
||||
|
|
@ -640,6 +656,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
"cancel",
|
||||
);
|
||||
}
|
||||
|
|
@ -680,6 +697,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 +753,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
);
|
||||
} catch (e) {
|
||||
status = this._logEnd(
|
||||
|
|
@ -743,6 +762,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
e,
|
||||
);
|
||||
throw e;
|
||||
|
|
@ -754,6 +774,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
"cancel",
|
||||
);
|
||||
}
|
||||
|
|
@ -795,6 +816,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 +850,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
);
|
||||
} catch (e) {
|
||||
status = this._logEnd(
|
||||
|
|
@ -836,6 +859,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
e,
|
||||
);
|
||||
throw e;
|
||||
|
|
@ -847,6 +871,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
undefined,
|
||||
"cancel",
|
||||
);
|
||||
}
|
||||
|
|
@ -867,6 +892,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,
|
||||
knownContextLength: this._contextLength,
|
||||
maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS,
|
||||
supportsImages: this.supportsImages(),
|
||||
tools: options.tools,
|
||||
});
|
||||
}
|
||||
|
||||
protected modifyChatBody(
|
||||
body: ChatCompletionCreateParams,
|
||||
): ChatCompletionCreateParams {
|
||||
|
|
@ -891,6 +933,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 +944,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,
|
||||
knownContextLength: 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 +968,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 +977,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
|
||||
let thinking = "";
|
||||
let completion = "";
|
||||
let usage: Usage | undefined = undefined;
|
||||
|
||||
try {
|
||||
if (this.templateMessages) {
|
||||
|
|
@ -992,6 +1044,11 @@ export abstract class BaseLLM implements ILLM {
|
|||
kind: "message",
|
||||
message: chunk,
|
||||
});
|
||||
|
||||
if (chunk.role === "assistant" && chunk.usage) {
|
||||
usage = chunk.usage;
|
||||
}
|
||||
|
||||
yield chunk;
|
||||
}
|
||||
}
|
||||
|
|
@ -1002,6 +1059,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
thinking,
|
||||
interaction,
|
||||
usage,
|
||||
);
|
||||
} catch (e) {
|
||||
status = this._logEnd(
|
||||
|
|
@ -1010,6 +1068,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
thinking,
|
||||
interaction,
|
||||
usage,
|
||||
e,
|
||||
);
|
||||
throw e;
|
||||
|
|
@ -1021,6 +1080,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
completion,
|
||||
undefined,
|
||||
interaction,
|
||||
usage,
|
||||
"cancel",
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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";
|
||||
|
|
@ -167,52 +172,10 @@ class Anthropic extends BaseLLM {
|
|||
}
|
||||
}
|
||||
|
||||
protected async *_streamChat(
|
||||
messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
async *handleResponse(
|
||||
response: any,
|
||||
stream: boolean | undefined,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
if (!this.apiKey || this.apiKey === "") {
|
||||
throw new Error(
|
||||
"Request not sent. You have an Anthropic model configured in your config.json, but the API key is not set.",
|
||||
);
|
||||
}
|
||||
|
||||
const systemMessage = stripImages(
|
||||
messages.filter((m) => m.role === "system")[0]?.content ?? "",
|
||||
);
|
||||
const shouldCacheSystemMessage = !!(
|
||||
this.cacheBehavior?.cacheSystemMessage && systemMessage
|
||||
);
|
||||
|
||||
const msgs = this.convertMessages(messages);
|
||||
const response = await this.fetch(new URL("messages", this.apiBase), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"anthropic-version": "2023-06-01",
|
||||
"x-api-key": this.apiKey as string,
|
||||
...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation
|
||||
? { "anthropic-beta": "prompt-caching-2024-07-31" }
|
||||
: {}),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
...this.convertArgs(options),
|
||||
messages: msgs,
|
||||
system: shouldCacheSystemMessage
|
||||
? [
|
||||
{
|
||||
type: "text",
|
||||
text: systemMessage,
|
||||
cache_control: { type: "ephemeral" },
|
||||
},
|
||||
]
|
||||
: systemMessage,
|
||||
}),
|
||||
signal,
|
||||
});
|
||||
|
||||
if (response.status === 499) {
|
||||
return; // Aborted by user
|
||||
}
|
||||
|
|
@ -232,17 +195,51 @@ class Anthropic extends BaseLLM {
|
|||
);
|
||||
}
|
||||
|
||||
if (options.stream === false) {
|
||||
if (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 +247,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 +299,61 @@ class Anthropic extends BaseLLM {
|
|||
break;
|
||||
}
|
||||
}
|
||||
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
usage,
|
||||
};
|
||||
}
|
||||
|
||||
protected async *_streamChat(
|
||||
messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
if (!this.apiKey || this.apiKey === "") {
|
||||
throw new Error(
|
||||
"Request not sent. You have an Anthropic model configured in your config.json, but the API key is not set.",
|
||||
);
|
||||
}
|
||||
|
||||
const systemMessage = stripImages(
|
||||
messages.filter((m) => m.role === "system")[0]?.content ?? "",
|
||||
);
|
||||
const shouldCacheSystemMessage = !!(
|
||||
this.cacheBehavior?.cacheSystemMessage && systemMessage
|
||||
);
|
||||
|
||||
const msgs = this.convertMessages(messages);
|
||||
const response = await this.fetch(new URL("messages", this.apiBase), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
"anthropic-version": "2023-06-01",
|
||||
"x-api-key": this.apiKey as string,
|
||||
...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation
|
||||
? { "anthropic-beta": "prompt-caching-2024-07-31" }
|
||||
: {}),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
...this.convertArgs(options),
|
||||
messages: msgs,
|
||||
system: shouldCacheSystemMessage
|
||||
? [
|
||||
{
|
||||
type: "text",
|
||||
text: systemMessage,
|
||||
cache_control: { type: "ephemeral" },
|
||||
},
|
||||
]
|
||||
: systemMessage,
|
||||
}),
|
||||
signal,
|
||||
});
|
||||
|
||||
yield* this.handleResponse(response, options.stream);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
495
core/llm/llms/Anthropic.vitest.ts
Normal file
495
core/llm/llms/Anthropic.vitest.ts
Normal 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.",
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -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 } = {
|
||||
|
|
|
|||
12
core/llm/llms/Fireworks.vitest.ts
Normal file
12
core/llm/llms/Fireworks.vitest.ts
Normal 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",
|
||||
});
|
||||
|
|
@ -200,6 +200,7 @@ class Gemini extends BaseLLM {
|
|||
messages: ChatMessage[],
|
||||
options: CompletionOptions,
|
||||
isV1API: boolean,
|
||||
includeToolIds: boolean,
|
||||
): GeminiChatRequestBody {
|
||||
const toolCallIdToNameMap = new Map<string, string>();
|
||||
messages.forEach((msg) => {
|
||||
|
|
@ -231,7 +232,7 @@ class Gemini extends BaseLLM {
|
|||
parts: [
|
||||
{
|
||||
functionResponse: {
|
||||
id: msg.toolCallId,
|
||||
id: includeToolIds ? msg.toolCallId : undefined,
|
||||
name: functionName || "unknown",
|
||||
response: {
|
||||
output: msg.content, // "output" key is opinionated - not all functions will output objects
|
||||
|
|
@ -406,7 +407,7 @@ class Gemini extends BaseLLM {
|
|||
const isV1API = !!this.apiBase?.includes("/v1/");
|
||||
|
||||
// Convert chat messages to contents
|
||||
const body = this.prepareBody(messages, options, isV1API);
|
||||
const body = this.prepareBody(messages, options, isV1API, true);
|
||||
|
||||
const response = await this.fetch(apiURL, {
|
||||
method: "POST",
|
||||
|
|
|
|||
12
core/llm/llms/Groq.vitest.ts
Normal file
12
core/llm/llms/Groq.vitest.ts
Normal 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",
|
||||
},
|
||||
});
|
||||
|
|
@ -25,7 +25,7 @@ class HuggingFaceTGI extends BaseLLM {
|
|||
}
|
||||
const json = await response.json();
|
||||
this.model = json.model_id;
|
||||
this.contextLength = Number.parseInt(json.max_input_length);
|
||||
this._contextLength = Number.parseInt(json.max_input_length);
|
||||
})
|
||||
.catch((e) => {
|
||||
console.log(`Failed to list models for HuggingFace TGI: ${e.message}`);
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -67,7 +67,7 @@ class Mistral extends OpenAI {
|
|||
return Mistral.modelConversion[model] ?? model;
|
||||
}
|
||||
|
||||
protected _convertArgs(options: any, messages: ChatMessage[]) {
|
||||
_convertArgs(options: any, messages: ChatMessage[]) {
|
||||
const finalOptions = super._convertArgs(options, messages);
|
||||
|
||||
const lastMessage = finalOptions.messages[finalOptions.messages.length - 1];
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -184,7 +184,7 @@ class Ollama extends BaseLLM implements ModelInstaller {
|
|||
let value = parts[2];
|
||||
switch (key) {
|
||||
case "num_ctx":
|
||||
this.contextLength =
|
||||
this._contextLength =
|
||||
options.contextLength ?? Number.parseInt(value);
|
||||
break;
|
||||
case "stop":
|
||||
|
|
|
|||
294
core/llm/llms/OpenAI-compatible-core.vitest.ts
Normal file
294
core/llm/llms/OpenAI-compatible-core.vitest.ts
Normal 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",
|
||||
},
|
||||
});
|
||||
453
core/llm/llms/OpenAI-compatible.vitest.ts
Normal file
453
core/llm/llms/OpenAI-compatible.vitest.ts
Normal 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/",
|
||||
});
|
||||
427
core/llm/llms/OpenAI.vitest.ts
Normal file
427
core/llm/llms/OpenAI.vitest.ts
Normal 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] }],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -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(
|
||||
|
|
|
|||
|
|
@ -254,24 +254,7 @@ class VertexAI extends BaseLLM {
|
|||
signal,
|
||||
});
|
||||
|
||||
if (response.status === 499) {
|
||||
return; // Aborted by user
|
||||
}
|
||||
|
||||
if (options.stream === false) {
|
||||
const data = await response.json();
|
||||
yield { role: "assistant", content: data.content[0].text };
|
||||
return;
|
||||
}
|
||||
|
||||
for await (const value of streamSse(response)) {
|
||||
if (value.type === "message_start") {
|
||||
console.log(value);
|
||||
}
|
||||
if (value.delta?.text) {
|
||||
yield { role: "assistant", content: value.delta.text };
|
||||
}
|
||||
}
|
||||
yield* this.anthropicInstance.handleResponse(response, options.stream);
|
||||
}
|
||||
|
||||
// Gemini
|
||||
|
|
@ -285,17 +268,19 @@ class VertexAI extends BaseLLM {
|
|||
this.apiBase,
|
||||
);
|
||||
|
||||
const body = this.geminiInstance.prepareBody(messages, options, false);
|
||||
// For some reason gemini through vertex does not support ids in functionResponses yet
|
||||
const body = this.geminiInstance.prepareBody(
|
||||
messages,
|
||||
options,
|
||||
false,
|
||||
false,
|
||||
);
|
||||
const response = await this.fetch(apiURL, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
signal,
|
||||
});
|
||||
for await (const message of this.geminiInstance.processGeminiResponse(
|
||||
streamResponse(response),
|
||||
)) {
|
||||
yield message;
|
||||
}
|
||||
yield* this.geminiInstance.processGeminiResponse(streamResponse(response));
|
||||
}
|
||||
|
||||
private async *streamChatBison(
|
||||
|
|
|
|||
|
|
@ -72,7 +72,7 @@ class Vllm extends OpenAI {
|
|||
const json = await response.json();
|
||||
const data = json.data[0];
|
||||
this.model = data.id;
|
||||
this.contextLength = Number.parseInt(data.max_model_len);
|
||||
this._contextLength = Number.parseInt(data.max_model_len);
|
||||
})
|
||||
.catch((e) => {
|
||||
console.log(`Failed to list models for vLLM: ${e.message}`);
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
93
core/llm/llms/llmTestHarness.ts
Normal file
93
core/llm/llms/llmTestHarness.ts
Normal 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);
|
||||
}
|
||||
}
|
||||
|
|
@ -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
|
||||
|
|
|
|||
758
core/llm/llms/stubs/ContinueProxy.vitest.ts
Normal file
758
core/llm/llms/stubs/ContinueProxy.vitest.ts
Normal 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] }],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
375
core/llm/llms/test-utils/openai-test-utils.ts
Normal file
375
core/llm/llms/test-utils/openai-test-utils.ts
Normal 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] },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue