merge: main
This commit is contained in:
commit
ff335487aa
468 changed files with 81510 additions and 8883 deletions
|
|
@ -35,7 +35,6 @@ IMPORTANT: Do NOT mock the fixtures above other than using `jest.spyOn`. DO mock
|
|||
Instead, generate actual mock files and data for operations
|
||||
Pure mocks should only be used to emulate specific network responses/error or hard-to-duplicate errors, or to prevent long-duration tests
|
||||
|
||||
Additional types can be imported from @core/index.d.ts
|
||||
If any needed types, functions, constants, or classes are still not found, warn the user and do not generate tests.
|
||||
Additional types can be imported from @core/index.d.ts. If any needed types, functions, constants, or classes are still not found, warn the user and do not generate tests.
|
||||
|
||||
Write the comment "// Generated by continue" at the top of the generated code/file (not the filepath)
|
||||
Write the comment "// Generated by continue" at the top of the generated code/file (not the filepath)
|
||||
|
|
|
|||
11
.continue/prompts/sub-agent-background.md
Normal file
11
.continue/prompts/sub-agent-background.md
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
---
|
||||
name: Sub Agent Background Prompt
|
||||
description: Start a subagent using the continue cli in the background
|
||||
invokable: true
|
||||
---
|
||||
|
||||
# Continue Sub Agent Background Prompt
|
||||
|
||||
Take the prompt provided by the user and using the terminal tool run the following command in the background:
|
||||
|
||||
cn -p "{{prompt}}"
|
||||
11
.continue/prompts/sub-agent-foreground.md
Normal file
11
.continue/prompts/sub-agent-foreground.md
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
---
|
||||
name: Sub Agent Foreground Prompt
|
||||
description: Start a subagent using the continue cli in the foreground
|
||||
invokable: true
|
||||
---
|
||||
|
||||
# Continue Sub Agent Foreground Prompt
|
||||
|
||||
Take the prompt provided by the user and using the terminal tool run the following command in the foreground:
|
||||
|
||||
cn -p "{{prompt}}"
|
||||
2
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
2
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
|
|
@ -13,7 +13,7 @@ body:
|
|||
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
|
||||
- label: I'm not able to find a related conversation on [GitHub discussions](https://github.com/continuedev/continue/discussions) that reports the same bug
|
||||
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
|
||||
required: false
|
||||
|
|
|
|||
8
.github/actions/setup-component/action.yml
vendored
8
.github/actions/setup-component/action.yml
vendored
|
|
@ -31,12 +31,18 @@ runs:
|
|||
packages/*/node_modules
|
||||
key: ${{ runner.os }}-packages-node-modules-${{ hashFiles('packages/*/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
- uses: actions/cache@v4
|
||||
if: inputs.include-root == 'true'
|
||||
id: root-cache
|
||||
with:
|
||||
path: node_modules
|
||||
key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }}
|
||||
|
||||
- name: Install root dependencies
|
||||
if: inputs.include-root == 'true' && steps.root-cache.outputs.cache-hit != 'true'
|
||||
shell: bash
|
||||
run: npm ci
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: component-cache
|
||||
with:
|
||||
|
|
|
|||
2
.github/workflows/auto-fix-failed-tests.yml
vendored
2
.github/workflows/auto-fix-failed-tests.yml
vendored
|
|
@ -89,7 +89,7 @@ jobs:
|
|||
|
||||
- name: Checkout repository
|
||||
if: steps.workflow-details.outputs.has_failed_tests == 'true'
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
fetch-depth: 0
|
||||
|
|
|
|||
4
.github/workflows/auto-release.yml
vendored
4
.github/workflows/auto-release.yml
vendored
|
|
@ -16,7 +16,7 @@ jobs:
|
|||
contents: write # Needed for creating releases
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Get version from package.json
|
||||
id: get_version
|
||||
|
|
@ -45,7 +45,7 @@ jobs:
|
|||
contents: write # Needed for creating releases
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
|
|
|
|||
4
.github/workflows/beta-release.yml
vendored
4
.github/workflows/beta-release.yml
vendored
|
|
@ -16,9 +16,11 @@ jobs:
|
|||
beta-release:
|
||||
name: Beta Release
|
||||
runs-on: ubuntu-latest
|
||||
# Only run this workflow on the main repository (continuedev/continue)
|
||||
if: github.repository == 'continuedev/continue'
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
|
||||
|
|
|
|||
2
.github/workflows/cla.yaml
vendored
2
.github/workflows/cla.yaml
vendored
|
|
@ -27,5 +27,5 @@ jobs:
|
|||
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,agent@continue.dev,action@github.com
|
||||
allowlist: dependabot[bot],fbricon,panyamkeerthana,Jazzcort,owtaylor,halfline,agent@continue.dev,action@github.com,snyk-bot,noreply@continue.dev
|
||||
signed-commit-message: "CLA signed in $pullRequestNo"
|
||||
|
|
|
|||
6
.github/workflows/cli-pr-checks.yml
vendored
6
.github/workflows/cli-pr-checks.yml
vendored
|
|
@ -14,7 +14,7 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
if: github.run_attempt > 1
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v6
|
||||
- name: Track workflow rerun
|
||||
uses: ./.github/actions/track-rerun
|
||||
|
||||
|
|
@ -22,7 +22,7 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
|
|
@ -64,7 +64,7 @@ jobs:
|
|||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v6
|
||||
|
|
|
|||
4
.github/workflows/compliance.yaml
vendored
4
.github/workflows/compliance.yaml
vendored
|
|
@ -101,7 +101,7 @@ jobs:
|
|||
contents: read
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
|
|
@ -134,7 +134,7 @@ jobs:
|
|||
if: ${{ !github.event.pull_request.draft }}
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Check required files
|
||||
run: |
|
||||
|
|
|
|||
24
.github/workflows/delete-stale-branches.yaml
vendored
Normal file
24
.github/workflows/delete-stale-branches.yaml
vendored
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
name: Delete Stale Branches
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 6 * * 1-5"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
stale_branches:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Stale Branches
|
||||
uses: crs-k/stale-branches@v8.2.2
|
||||
with:
|
||||
repo-token: "${{ secrets.GITHUB_TOKEN }}"
|
||||
days-before-stale: 59
|
||||
days-before-delete: 60
|
||||
pr-check: true
|
||||
ignore-issue-interaction: true
|
||||
branches-filter-regex: "^(?!cla-signatures$).*"
|
||||
42
.github/workflows/jetbrains-release.yaml
vendored
42
.github/workflows/jetbrains-release.yaml
vendored
|
|
@ -56,7 +56,7 @@ jobs:
|
|||
# steps:
|
||||
# # 0. Setup git
|
||||
# - name: Checkout
|
||||
# uses: actions/checkout@v5
|
||||
# uses: actions/checkout@v6
|
||||
|
||||
# - name: Set up Git
|
||||
# run: |
|
||||
|
|
@ -95,14 +95,14 @@ jobs:
|
|||
needs: check_release_name
|
||||
if: needs.check_release_name.outputs.should_run == 'true' || github.event_name == 'workflow_dispatch'
|
||||
name: Build Plugin
|
||||
runs-on: macos-13
|
||||
runs-on: macos-latest
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
# Check out current repository
|
||||
- name: Fetch Sources
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.event.release.tag_name }}
|
||||
|
||||
|
|
@ -294,44 +294,44 @@ jobs:
|
|||
|
||||
# Store already-built plugin as an artifact for downloading
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: ${{ steps.artifact.outputs.filename }}
|
||||
path: ./extensions/intellij/build/distributions/content/*/*
|
||||
|
||||
# Upload binaries as artifacts
|
||||
- name: Upload artifact (darwin-arm64)
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: continue-binary-darwin-arm64
|
||||
path: ./binary/bin/darwin-arm64/
|
||||
|
||||
- name: Upload artifact (darwin-x64)
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: continue-binary-darwin-x64
|
||||
path: ./binary/bin/darwin-x64/
|
||||
|
||||
- name: Upload artifact (win32-x64)
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: continue-binary-win32-x64
|
||||
path: ./binary/bin/win32-x64/
|
||||
|
||||
- name: Upload artifact (win32-arm64)
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: continue-binary-win32-arm64
|
||||
path: ./binary/bin/win32-arm64/
|
||||
|
||||
- name: Upload artifact (linux-arm64)
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: continue-binary-linux-arm64
|
||||
path: ./binary/bin/linux-arm64/
|
||||
|
||||
- name: Upload artifact (linux-x64)
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: continue-binary-linux-x64
|
||||
path: ./binary/bin/linux-x64/
|
||||
|
|
@ -358,7 +358,7 @@ jobs:
|
|||
platform: darwin
|
||||
arch: x64
|
||||
npm_config_arch: x64
|
||||
- os: macos-13
|
||||
- os: macos-latest
|
||||
platform: darwin
|
||||
arch: arm64
|
||||
npm_config_arch: arm64
|
||||
|
|
@ -366,7 +366,7 @@ jobs:
|
|||
steps:
|
||||
# 1. Check-out repository
|
||||
- name: Check-out repository
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v6
|
||||
|
||||
# 2. Install npm dependencies
|
||||
- name: Use Node.js from .nvmrc
|
||||
|
|
@ -398,7 +398,7 @@ jobs:
|
|||
|
||||
# Download the binary artifact
|
||||
- name: Download binary artifact
|
||||
uses: actions/download-artifact@v5
|
||||
uses: actions/download-artifact@v6
|
||||
with:
|
||||
name: continue-binary-${{ matrix.platform }}-${{ matrix.arch }}
|
||||
path: ./binary/bin/${{ matrix.platform }}-${{ matrix.arch }}/
|
||||
|
|
@ -420,7 +420,7 @@ jobs:
|
|||
|
||||
- name: Upload logs
|
||||
if: ${{ always() }}
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: core-logs-${{ matrix.platform }}-${{ matrix.arch }}
|
||||
path: ~/.continue/logs/core.log
|
||||
|
|
@ -433,7 +433,7 @@ jobs:
|
|||
steps:
|
||||
# Check out current repository
|
||||
- name: Fetch Sources
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v6
|
||||
|
||||
# Set up Java environment for the next steps
|
||||
- name: Setup Java
|
||||
|
|
@ -455,7 +455,7 @@ jobs:
|
|||
# Collect Tests Result of failed tests
|
||||
- name: Collect Tests Result
|
||||
if: ${{ failure() }}
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: tests-result
|
||||
path: ${{ github.workspace }}/extensions/intellij/build/reports/tests
|
||||
|
|
@ -480,7 +480,7 @@ jobs:
|
|||
|
||||
# Check out current repository
|
||||
- name: Fetch Sources
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v6
|
||||
|
||||
# Set up Java environment for the next steps
|
||||
- name: Setup Java
|
||||
|
|
@ -491,7 +491,7 @@ jobs:
|
|||
|
||||
# Run Qodana inspections
|
||||
- name: Qodana - Code Inspection
|
||||
uses: JetBrains/qodana-action@v2025.2.1
|
||||
uses: JetBrains/qodana-action@v2025.2.2
|
||||
with:
|
||||
cache-default-branch-only: true
|
||||
|
||||
|
|
@ -511,7 +511,7 @@ jobs:
|
|||
|
||||
# Check out current repository
|
||||
- name: Fetch Sources
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v6
|
||||
|
||||
# Set up Java environment for the next steps
|
||||
- name: Setup Java
|
||||
|
|
@ -540,7 +540,7 @@ jobs:
|
|||
# Collect Plugin Verifier Result
|
||||
- name: Collect Plugin Verifier Result
|
||||
if: ${{ always() }}
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: pluginVerifier-result
|
||||
path: ${{ github.workspace }}/build/reports/pluginVerifier
|
||||
|
|
@ -563,7 +563,7 @@ jobs:
|
|||
# ./gradlew patchChangelog --release-note="$CHANGELOG"
|
||||
|
||||
- name: Download the plugin
|
||||
uses: actions/download-artifact@v5
|
||||
uses: actions/download-artifact@v6
|
||||
with:
|
||||
name: ${{ steps.artifact.outputs.filename }}
|
||||
path: ./build/distributions/
|
||||
|
|
|
|||
2
.github/workflows/label-merged-prs.yml
vendored
2
.github/workflows/label-merged-prs.yml
vendored
|
|
@ -13,7 +13,7 @@ jobs:
|
|||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Check if author is in tier list
|
||||
id: check-author
|
||||
|
|
|
|||
4
.github/workflows/main-build.yaml
vendored
4
.github/workflows/main-build.yaml
vendored
|
|
@ -18,7 +18,7 @@ jobs:
|
|||
matrix:
|
||||
platform: [Linux, macOS]
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 2 # Get the last 2 commits to find the merge commit
|
||||
|
||||
|
|
@ -101,7 +101,7 @@ jobs:
|
|||
echo "✅ Successfully downloaded artifact"
|
||||
|
||||
- name: Republish as main branch artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: vscode-extension-build-${{ matrix.platform }}
|
||||
path: ./temp-download/*
|
||||
|
|
|
|||
18
.github/workflows/main.yaml
vendored
18
.github/workflows/main.yaml
vendored
|
|
@ -30,7 +30,7 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0 # This ensures all tags are fetched
|
||||
|
||||
|
|
@ -73,16 +73,16 @@ jobs:
|
|||
platform: alpine
|
||||
arch: x64
|
||||
npm_config_arch: x64
|
||||
- os: macos-13
|
||||
- os: macos-latest
|
||||
platform: darwin
|
||||
arch: x64
|
||||
npm_config_arch: x64
|
||||
- os: macos-13
|
||||
- os: macos-latest
|
||||
platform: darwin
|
||||
arch: arm64
|
||||
npm_config_arch: arm64
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
|
|
@ -99,7 +99,7 @@ jobs:
|
|||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Upload .vsix artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: ${{ matrix.platform }}-${{ matrix.arch }}-vsix
|
||||
path: "extensions/vscode/*.vsix"
|
||||
|
|
@ -112,7 +112,7 @@ jobs:
|
|||
- build
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up Git
|
||||
run: |
|
||||
|
|
@ -120,7 +120,7 @@ jobs:
|
|||
git config --local user.name "GitHub Action"
|
||||
|
||||
# Download the .vsix artifacts
|
||||
- uses: actions/download-artifact@v5
|
||||
- uses: actions/download-artifact@v6
|
||||
with:
|
||||
pattern: "*-vsix"
|
||||
path: vsix-artifacts
|
||||
|
|
@ -145,7 +145,7 @@ jobs:
|
|||
steps:
|
||||
# 0. Setup git
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up Git
|
||||
run: |
|
||||
|
|
@ -156,7 +156,7 @@ jobs:
|
|||
run: git fetch origin ${{ github.ref }} && git checkout ${{ github.ref }}
|
||||
|
||||
# 1. Download the artifacts
|
||||
- uses: actions/download-artifact@v5
|
||||
- uses: actions/download-artifact@v6
|
||||
with:
|
||||
pattern: "*-vsix"
|
||||
path: vsix-artifacts
|
||||
|
|
|
|||
4
.github/workflows/metrics.yaml
vendored
4
.github/workflows/metrics.yaml
vendored
|
|
@ -16,6 +16,8 @@ jobs:
|
|||
build:
|
||||
name: issue metrics
|
||||
runs-on: ubuntu-latest
|
||||
# Only run this workflow on the main repository (continuedev/continue)
|
||||
if: github.repository == 'continuedev/continue'
|
||||
permissions:
|
||||
issues: write
|
||||
pull-requests: read
|
||||
|
|
@ -69,7 +71,7 @@ jobs:
|
|||
${{ steps.read-metrics.outputs.metrics_content }}
|
||||
|
||||
- name: Upload metrics report as artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: issue-metrics-report
|
||||
path: ./issue_metrics.md
|
||||
|
|
|
|||
6
.github/workflows/pr-build-upload-vsix.yaml
vendored
6
.github/workflows/pr-build-upload-vsix.yaml
vendored
|
|
@ -24,7 +24,7 @@ jobs:
|
|||
runner: macos-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
|
|
@ -39,13 +39,13 @@ jobs:
|
|||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Upload build artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: vscode-extension-build-${{ matrix.platform }}-${{ matrix.arch }}
|
||||
path: extensions/vscode/build
|
||||
|
||||
- name: Upload .vsix artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: ${{ matrix.platform }}-${{ matrix.arch }}-vsix
|
||||
path: "extensions/vscode/*.vsix"
|
||||
|
|
|
|||
37
.github/workflows/pr-checks.yaml
vendored
37
.github/workflows/pr-checks.yaml
vendored
|
|
@ -15,14 +15,14 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
if: github.run_attempt > 1
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v6
|
||||
- name: Track workflow rerun
|
||||
uses: ./.github/actions/track-rerun
|
||||
|
||||
prettier-check:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
|
@ -43,7 +43,7 @@ jobs:
|
|||
core-checks:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0 # Needed for git diff to work
|
||||
- name: Setup packages
|
||||
|
|
@ -91,7 +91,7 @@ jobs:
|
|||
gui-checks:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v6
|
||||
- name: Setup packages
|
||||
uses: ./.github/actions/setup-packages
|
||||
- name: Setup core component
|
||||
|
|
@ -121,7 +121,7 @@ jobs:
|
|||
binary-checks:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v6
|
||||
- name: Setup packages
|
||||
uses: ./.github/actions/setup-packages
|
||||
- name: Setup core component
|
||||
|
|
@ -143,7 +143,7 @@ jobs:
|
|||
vscode-checks:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v6
|
||||
- name: Setup packages
|
||||
uses: ./.github/actions/setup-packages
|
||||
- name: Setup core component
|
||||
|
|
@ -176,7 +176,7 @@ jobs:
|
|||
outputs:
|
||||
packages: ${{ steps.get-packages.outputs.packages }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v6
|
||||
- name: Get package list
|
||||
id: get-packages
|
||||
run: |
|
||||
|
|
@ -191,7 +191,7 @@ jobs:
|
|||
matrix:
|
||||
package: ${{ fromJson(needs.get-packages-matrix.outputs.packages) }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0 # Needed for git diff to work
|
||||
- name: Setup packages
|
||||
|
|
@ -228,7 +228,7 @@ jobs:
|
|||
outputs:
|
||||
test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
|
@ -288,7 +288,7 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
|
|
@ -303,7 +303,7 @@ jobs:
|
|||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Upload build artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: vscode-extension-build-Linux
|
||||
path: extensions/vscode/build
|
||||
|
|
@ -320,7 +320,7 @@ jobs:
|
|||
test_file: ${{ fromJson(needs.vscode-get-test-file-matrix.outputs.test_file_matrix) }}
|
||||
command: ["e2e:ci:run", "e2e:ci:run-yaml"]
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v6
|
||||
- name: Run VS Code E2E test
|
||||
uses: ./.github/actions/run-vscode-e2e-test
|
||||
with:
|
||||
|
|
@ -334,7 +334,18 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- name: Free disk space
|
||||
uses: jlumbroso/free-disk-space@main
|
||||
with:
|
||||
tool-cache: false
|
||||
android: true
|
||||
dotnet: true
|
||||
haskell: true
|
||||
large-packages: false
|
||||
docker-images: true
|
||||
swap-storage: true
|
||||
|
||||
- uses: actions/checkout@v6
|
||||
- name: Run JetBrains tests
|
||||
uses: ./.github/actions/run-jetbrains-tests
|
||||
with:
|
||||
|
|
|
|||
16
.github/workflows/preview.yaml
vendored
16
.github/workflows/preview.yaml
vendored
|
|
@ -57,16 +57,16 @@ jobs:
|
|||
platform: alpine
|
||||
arch: x64
|
||||
npm_config_arch: x64
|
||||
- os: macos-13
|
||||
- os: macos-latest
|
||||
platform: darwin
|
||||
arch: x64
|
||||
npm_config_arch: x64
|
||||
- os: macos-13
|
||||
- os: macos-latest
|
||||
platform: darwin
|
||||
arch: arm64
|
||||
npm_config_arch: arm64
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
|
|
@ -83,7 +83,7 @@ jobs:
|
|||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Upload .vsix artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: ${{ matrix.platform }}-${{ matrix.arch }}-vsix
|
||||
path: "extensions/vscode/*.vsix"
|
||||
|
|
@ -96,7 +96,7 @@ jobs:
|
|||
- build
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up Git
|
||||
run: |
|
||||
|
|
@ -104,7 +104,7 @@ jobs:
|
|||
git config --local user.name "GitHub Action"
|
||||
|
||||
# Download the .vsix artifacts
|
||||
- uses: actions/download-artifact@v5
|
||||
- uses: actions/download-artifact@v6
|
||||
with:
|
||||
pattern: "*-vsix"
|
||||
path: vsix-artifacts
|
||||
|
|
@ -131,7 +131,7 @@ jobs:
|
|||
steps:
|
||||
# 0. Setup git
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Set up Git
|
||||
run: |
|
||||
|
|
@ -142,7 +142,7 @@ jobs:
|
|||
run: git fetch origin ${{ github.ref }} && git checkout ${{ github.ref }}
|
||||
|
||||
# 1. Download the artifacts
|
||||
- uses: actions/download-artifact@v5
|
||||
- uses: actions/download-artifact@v6
|
||||
with:
|
||||
pattern: "*-vsix"
|
||||
path: vsix-artifacts
|
||||
|
|
|
|||
2
.github/workflows/release-config-yaml.yml
vendored
2
.github/workflows/release-config-yaml.yml
vendored
|
|
@ -16,6 +16,8 @@ permissions:
|
|||
|
||||
jobs:
|
||||
release:
|
||||
# Only run this workflow on the main repository (continuedev/continue)
|
||||
if: github.repository == 'continuedev/continue'
|
||||
uses: ./.github/workflows/reusable-release.yml
|
||||
with:
|
||||
package-name: "config-yaml"
|
||||
|
|
|
|||
2
.github/workflows/release-fetch.yml
vendored
2
.github/workflows/release-fetch.yml
vendored
|
|
@ -16,6 +16,8 @@ permissions:
|
|||
|
||||
jobs:
|
||||
release:
|
||||
# Only run this workflow on the main repository (continuedev/continue)
|
||||
if: github.repository == 'continuedev/continue'
|
||||
uses: ./.github/workflows/reusable-release.yml
|
||||
with:
|
||||
package-name: "fetch"
|
||||
|
|
|
|||
2
.github/workflows/release-llm-info.yml
vendored
2
.github/workflows/release-llm-info.yml
vendored
|
|
@ -15,6 +15,8 @@ permissions:
|
|||
|
||||
jobs:
|
||||
release:
|
||||
# Only run this workflow on the main repository (continuedev/continue)
|
||||
if: github.repository == 'continuedev/continue'
|
||||
uses: ./.github/workflows/reusable-release.yml
|
||||
with:
|
||||
package-name: "llm-info"
|
||||
|
|
|
|||
|
|
@ -16,6 +16,8 @@ permissions:
|
|||
|
||||
jobs:
|
||||
release:
|
||||
# Only run this workflow on the main repository (continuedev/continue)
|
||||
if: github.repository == 'continuedev/continue'
|
||||
uses: ./.github/workflows/reusable-release.yml
|
||||
with:
|
||||
package-name: "openai-adapters"
|
||||
|
|
|
|||
2
.github/workflows/reusable-release.yml
vendored
2
.github/workflows/reusable-release.yml
vendored
|
|
@ -51,7 +51,7 @@ jobs:
|
|||
working-directory: ${{ inputs.package-path }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
|
|
|
|||
15
.github/workflows/run-continue-agent.yml
vendored
15
.github/workflows/run-continue-agent.yml
vendored
|
|
@ -4,14 +4,15 @@ on:
|
|||
workflow_call:
|
||||
inputs:
|
||||
prompt:
|
||||
description: "The prompt to send to the Continue agent"
|
||||
required: true
|
||||
type: string
|
||||
config:
|
||||
description: "The config to use (e.g., continuedev/default-background-agent)"
|
||||
description: "Additional prompting to send to the Continue agent"
|
||||
required: false
|
||||
type: string
|
||||
default: "continuedev/default-background-agent"
|
||||
default: ""
|
||||
agent:
|
||||
description: "The agent to use (e.g., continuedev/github-pr-agent)"
|
||||
required: true
|
||||
type: string
|
||||
default: "continuedev/github-pr-agent"
|
||||
branch_name:
|
||||
description: "The base branch name to work from"
|
||||
required: false
|
||||
|
|
@ -33,7 +34,7 @@ jobs:
|
|||
-H "Authorization: Bearer ${{ secrets.CONTINUE_API_KEY }}" \
|
||||
-d '{
|
||||
"prompt": "${{ inputs.prompt }}",
|
||||
"config": "${{ inputs.config }}",
|
||||
"agent": "${{ inputs.agent }}",
|
||||
"branchName": "${{ inputs.branch_name }}",
|
||||
"repoUrl": "https://github.com/${{ github.repository }}"
|
||||
}')
|
||||
|
|
|
|||
|
|
@ -3,8 +3,6 @@
|
|||
"system_setup_commands": [
|
||||
"npm i -g @continuedev/cli@latest",
|
||||
"sudo apt update",
|
||||
"sudo apt install -y ripgrep",
|
||||
"sudo apt install asciinema",
|
||||
"sudo apt install expect"
|
||||
"sudo apt install -y ripgrep"
|
||||
]
|
||||
}
|
||||
|
|
|
|||
2
.github/workflows/similar-issues.yml
vendored
2
.github/workflows/similar-issues.yml
vendored
|
|
@ -16,7 +16,7 @@ jobs:
|
|||
|
||||
steps:
|
||||
- name: Checkout deja-view
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
repository: "bdougie/deja-view"
|
||||
# Option 1: Pin to specific commit (most secure)
|
||||
|
|
|
|||
4
.github/workflows/snyk-agent.yaml
vendored
4
.github/workflows/snyk-agent.yaml
vendored
|
|
@ -9,9 +9,11 @@ on:
|
|||
jobs:
|
||||
run-cn-task:
|
||||
runs-on: ubuntu-latest
|
||||
# Only run this workflow on the main repository (continuedev/continue)
|
||||
if: github.repository == 'continuedev/continue'
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
fetch-depth: 0
|
||||
|
|
|
|||
4
.github/workflows/stable-release.yml
vendored
4
.github/workflows/stable-release.yml
vendored
|
|
@ -32,9 +32,11 @@ jobs:
|
|||
stable-release:
|
||||
name: Stable Release
|
||||
runs-on: ubuntu-latest
|
||||
# Only run this workflow on the main repository (continuedev/continue)
|
||||
if: github.repository == 'continuedev/continue'
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
token: ${{ secrets.SEMANTIC_RELEASE_TOKEN }}
|
||||
|
|
|
|||
|
|
@ -10,9 +10,11 @@ permissions:
|
|||
jobs:
|
||||
dependency-submission:
|
||||
runs-on: ubuntu-latest
|
||||
# Only run this workflow on the main repository (continuedev/continue)
|
||||
if: github.repository == 'continuedev/continue'
|
||||
steps:
|
||||
- name: Checkout sources
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v6
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
|
|
|
|||
3
.github/workflows/tidy-up-codebase.yml
vendored
3
.github/workflows/tidy-up-codebase.yml
vendored
|
|
@ -10,8 +10,7 @@ jobs:
|
|||
run-cn-task:
|
||||
uses: ./.github/workflows/run-continue-agent.yml
|
||||
with:
|
||||
prompt: "Review every Markdown documentation file and verify that descriptions, examples, or behavior outlines accurately reflect the current code. Only update documentation; do not modify code. Check the corresponding code to confirm behavior before making changes. Correct any inaccuracies or outdated information in descriptions, examples, or behavior outlines. Preserve existing Markdown formatting, style, and structure. Do not add new sections, speculative explanations, or details not present in the code. Only update statements that are clearly incorrect or misleading; do not rewrite text for style or preference. Keep edits minimal and focused, ensuring that the Markdown matches what the code actually does. If verification against the code is ambiguous, leave the documentation unchanged. Use branch name bot/cleanup-<YYMMDD>-<HHMM>"
|
||||
config: continuedev/default-background-agent
|
||||
agent: continuedev/tidy-up-markdown-agent
|
||||
branch_name: main
|
||||
secrets:
|
||||
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
|
||||
|
|
|
|||
2
.github/workflows/vscode-prerelease.yml
vendored
2
.github/workflows/vscode-prerelease.yml
vendored
|
|
@ -22,7 +22,7 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ inputs.main_commit_sha || 'main' }}
|
||||
fetch-depth: 0
|
||||
|
|
|
|||
2
.github/workflows/vscode-version-bump.yml
vendored
2
.github/workflows/vscode-version-bump.yml
vendored
|
|
@ -12,7 +12,7 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v5
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0 # Fetch all history and tags
|
||||
|
||||
|
|
|
|||
28
README.md
28
README.md
|
|
@ -27,35 +27,29 @@
|
|||
|
||||
**Ship faster with Continuous AI**
|
||||
|
||||
**Build and run custom agents across your IDE, terminal, and CI**
|
||||
**The future of coding isn't writing more code. It's delegating the boring parts, so you can build the interesting stuff**
|
||||
|
||||
</div>
|
||||
|
||||
Get started in [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue), [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension), or [CLI](https://docs.continue.dev/guides/cli)
|
||||
Get started in [Mission Control](https://hub.continue.dev/agents), [CLI (Headless Mode)](https://docs.continue.dev/cli/quick-start#headless-mode), or [CLI (TUI mode)](https://docs.continue.dev/cli/quick-start#tui-mode)
|
||||
|
||||
## Agent
|
||||
## Cloud Agents
|
||||
|
||||
[Agent](https://docs.continue.dev/ide-extensions/agent/quick-start) to work on development tasks together with AI
|
||||
Set workflows to run automatically on [PR opens](https://docs.continue.dev/guides/continuous-ai#pattern-2-the-pr-review-agent), [schedules](https://docs.continue.dev/guides/continuous-ai#pattern-1-the-async-triage-bot), or [any event trigger](https://docs.continue.dev/cli/quick-start#headless-mode)
|
||||
|
||||

|
||||

|
||||
|
||||
## Chat
|
||||
## CLI Agents
|
||||
|
||||
[Chat](https://docs.continue.dev/ide-extensions/chat/quick-start) to ask general questions and clarify code sections
|
||||
Watch workflows execute in real-time and approve decisions step-by-step from your [terminal](https://docs.continue.dev/cli/quick-start#tui-mode)
|
||||
|
||||

|
||||

|
||||
|
||||
## Edit
|
||||
## IDE Agents
|
||||
|
||||
[Edit](https://docs.continue.dev/ide-extensions/edit/quick-start) to modify a code section without leaving your current file
|
||||
Trigger workflows from [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) or [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension)—let agents handle the refactoring while you keep coding
|
||||
|
||||

|
||||
|
||||
## Autocomplete
|
||||
|
||||
[Autocomplete](https://docs.continue.dev/ide-extensions/autocomplete/quick-start) to receive inline code suggestions as you type
|
||||
|
||||

|
||||

|
||||
|
||||
</div>
|
||||
|
||||
|
|
|
|||
|
|
@ -115,6 +115,45 @@ runs:
|
|||
shell: bash
|
||||
run: npm install -g @continuedev/cli@latest
|
||||
|
||||
- name: Setup Action Scripts
|
||||
if: env.SHOULD_RUN == 'true'
|
||||
shell: bash
|
||||
run: |
|
||||
# Create directory for scripts
|
||||
mkdir -p .continue-action-scripts
|
||||
|
||||
# Check if we're running in the Continue repo itself (scripts exist locally)
|
||||
if [ -f "actions/general-review/scripts/buildPrompt.js" ] && [ -f "actions/general-review/scripts/writeMarkdown.js" ]; then
|
||||
echo "Running in Continue repo - using local scripts from current checkout"
|
||||
cp actions/general-review/scripts/buildPrompt.js .continue-action-scripts/buildPrompt.js
|
||||
cp actions/general-review/scripts/writeMarkdown.js .continue-action-scripts/writeMarkdown.js
|
||||
else
|
||||
echo "Running in external repo - downloading scripts from Continue repo"
|
||||
|
||||
# Download scripts from Continue repo
|
||||
echo "Downloading buildPrompt.js..."
|
||||
curl -sSL https://raw.githubusercontent.com/continuedev/continue/main/actions/general-review/scripts/buildPrompt.js \
|
||||
-o .continue-action-scripts/buildPrompt.js
|
||||
|
||||
echo "Downloading writeMarkdown.js..."
|
||||
curl -sSL https://raw.githubusercontent.com/continuedev/continue/main/actions/general-review/scripts/writeMarkdown.js \
|
||||
-o .continue-action-scripts/writeMarkdown.js
|
||||
fi
|
||||
|
||||
# Verify scripts exist
|
||||
if [ ! -f .continue-action-scripts/buildPrompt.js ]; then
|
||||
echo "Error: buildPrompt.js not found"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ ! -f .continue-action-scripts/writeMarkdown.js ]; then
|
||||
echo "Error: writeMarkdown.js not found"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Scripts ready:"
|
||||
ls -lh .continue-action-scripts/
|
||||
|
||||
- name: Post Initial Comment
|
||||
if: env.SHOULD_RUN == 'true'
|
||||
id: initial-comment
|
||||
|
|
@ -218,7 +257,7 @@ runs:
|
|||
# Gather PR context and build prompt without heredocs
|
||||
gh pr diff "$PR_NUMBER" > pr_diff.txt
|
||||
gh pr view "$PR_NUMBER" --json title,author,body,files > pr_data.json
|
||||
node actions/general-review/scripts/buildPrompt.js "$PR_NUMBER"
|
||||
node .continue-action-scripts/buildPrompt.js "$PR_NUMBER"
|
||||
rm -f pr_data.json
|
||||
|
||||
- name: Run Continue CLI Review
|
||||
|
|
@ -241,7 +280,7 @@ runs:
|
|||
if [ -z "$CONTINUE_API_KEY" ]; then
|
||||
echo "Warning: CONTINUE_API_KEY environment variable is not set"
|
||||
# Create fallback review and continue
|
||||
node actions/general-review/scripts/writeMarkdown.js code_review.md missing_api_key
|
||||
node .continue-action-scripts/writeMarkdown.js code_review.md missing_api_key
|
||||
echo "SKIP_CLI=true" >> $GITHUB_ENV
|
||||
else
|
||||
echo "SKIP_CLI=false" >> $GITHUB_ENV
|
||||
|
|
@ -263,7 +302,7 @@ runs:
|
|||
echo "Testing Continue CLI..."
|
||||
if ! which cn > /dev/null 2>&1; then
|
||||
echo "Warning: Continue CLI not found or not working"
|
||||
node actions/general-review/scripts/writeMarkdown.js code_review.md cli_install_failed
|
||||
node .continue-action-scripts/writeMarkdown.js code_review.md cli_install_failed
|
||||
echo "SKIP_CLI=true" >> $GITHUB_ENV
|
||||
else
|
||||
echo "Continue CLI found at: $(which cn)"
|
||||
|
|
@ -299,7 +338,7 @@ runs:
|
|||
# Check if output is empty
|
||||
if [ ! -s code_review.md ]; then
|
||||
echo "Warning: Continue CLI returned empty output"
|
||||
node actions/general-review/scripts/writeMarkdown.js code_review.md empty_output
|
||||
node .continue-action-scripts/writeMarkdown.js code_review.md empty_output
|
||||
fi
|
||||
else
|
||||
echo "Error: Continue CLI command failed with exit code $?"
|
||||
|
|
@ -308,13 +347,13 @@ runs:
|
|||
|
||||
# Check for specific error patterns
|
||||
if grep -q "not found\|ENOENT" cli_error.log 2>/dev/null; then
|
||||
node actions/general-review/scripts/writeMarkdown.js code_review.md cli_not_found
|
||||
node .continue-action-scripts/writeMarkdown.js code_review.md cli_not_found
|
||||
elif grep -q "config\|assistant" cli_error.log 2>/dev/null; then
|
||||
node actions/general-review/scripts/writeMarkdown.js code_review.md config_error
|
||||
node .continue-action-scripts/writeMarkdown.js code_review.md config_error
|
||||
elif grep -q "api\|auth" cli_error.log 2>/dev/null; then
|
||||
node actions/general-review/scripts/writeMarkdown.js code_review.md auth_error
|
||||
node .continue-action-scripts/writeMarkdown.js code_review.md auth_error
|
||||
else
|
||||
node actions/general-review/scripts/writeMarkdown.js code_review.md generic_failure
|
||||
node .continue-action-scripts/writeMarkdown.js code_review.md generic_failure
|
||||
fi
|
||||
fi
|
||||
|
||||
|
|
|
|||
59082
binary/package-lock.json
generated
59082
binary/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -42,7 +42,7 @@
|
|||
"typescript": "^5.6.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"@octokit/rest": "^20.0.2",
|
||||
"@octokit/rest": "^20.1.2",
|
||||
"adm-zip": "^0.5.16",
|
||||
"commander": "^12.0.0",
|
||||
"core": "file:../core",
|
||||
|
|
@ -52,8 +52,8 @@
|
|||
"node-fetch": "^3.3.2",
|
||||
"posthog-node": "^3.6.3",
|
||||
"system-ca": "^1.0.2",
|
||||
"tar": "^7.4.3",
|
||||
"undici": "^7.10.0",
|
||||
"tar": "^7.5.1",
|
||||
"undici": "^7.16.0",
|
||||
"uuid": "^9.0.1",
|
||||
"vectordb": "^0.4.20",
|
||||
"win-ca": "^3.5.1"
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ import AutocompleteLruCache from "./util/AutocompleteLruCache.js";
|
|||
import { HelperVars } from "./util/HelperVars.js";
|
||||
import { AutocompleteInput, AutocompleteOutcome } from "./util/types.js";
|
||||
|
||||
const autocompleteCache = AutocompleteLruCache.get();
|
||||
const autocompleteCachePromise = AutocompleteLruCache.get();
|
||||
|
||||
// Errors that can be expected on occasion even during normal functioning should not be shown.
|
||||
// Not worth disrupting the user to tell them that a single autocomplete request didn't go through
|
||||
|
|
@ -31,7 +31,7 @@ const ERRORS_TO_IGNORE = [
|
|||
];
|
||||
|
||||
export class CompletionProvider {
|
||||
private autocompleteCache = AutocompleteLruCache.get();
|
||||
private autocompleteCache?: AutocompleteLruCache;
|
||||
public errorsShown: Set<string> = new Set();
|
||||
private bracketMatchingService = new BracketMatchingService();
|
||||
private debouncer = new AutocompleteDebouncer();
|
||||
|
|
@ -48,6 +48,22 @@ export class CompletionProvider {
|
|||
) {
|
||||
this.completionStreamer = new CompletionStreamer(this.onError.bind(this));
|
||||
this.contextRetrievalService = new ContextRetrievalService(this.ide);
|
||||
void this.initCache();
|
||||
}
|
||||
|
||||
private async initCache() {
|
||||
try {
|
||||
this.autocompleteCache = await autocompleteCachePromise;
|
||||
} catch (e) {
|
||||
console.error("Failed to initialize autocomplete cache:", e);
|
||||
}
|
||||
}
|
||||
|
||||
private async getCache(): Promise<AutocompleteLruCache> {
|
||||
if (!this.autocompleteCache) {
|
||||
this.autocompleteCache = await autocompleteCachePromise;
|
||||
}
|
||||
return this.autocompleteCache;
|
||||
}
|
||||
|
||||
private async _prepareLlm(): Promise<ILLM | undefined> {
|
||||
|
|
@ -201,14 +217,12 @@ export class CompletionProvider {
|
|||
|
||||
// Completion
|
||||
let completion: string | undefined = "";
|
||||
|
||||
const cache = await autocompleteCache;
|
||||
const cache = await this.getCache();
|
||||
const cachedCompletion = helper.options.useCache
|
||||
? await cache.get(helper.prunedPrefix)
|
||||
: undefined;
|
||||
let cacheHit = false;
|
||||
if (cachedCompletion) {
|
||||
// Cache
|
||||
cacheHit = true;
|
||||
completion = cachedCompletion;
|
||||
} else {
|
||||
|
|
@ -277,16 +291,12 @@ export class CompletionProvider {
|
|||
outcome.enabledStaticContextualization = true;
|
||||
}
|
||||
|
||||
//////////
|
||||
|
||||
// Save to cache
|
||||
if (!outcome.cacheHit && helper.options.useCache) {
|
||||
(await this.autocompleteCache)
|
||||
void cache
|
||||
.put(outcome.prefix, outcome.completion)
|
||||
.catch((e) => console.warn(`Failed to save to cache: ${e.message}`));
|
||||
}
|
||||
|
||||
// When using the JetBrains extension, Mark as displayed
|
||||
const ideType = (await this.ide.getIdeInfo()).ideType;
|
||||
if (ideType === "jetbrains") {
|
||||
this.markDisplayed(input.completionId, outcome);
|
||||
|
|
@ -299,4 +309,10 @@ export class CompletionProvider {
|
|||
this.loggingService.deleteAbortController(input.completionId);
|
||||
}
|
||||
}
|
||||
|
||||
public async dispose() {
|
||||
if (this.autocompleteCache) {
|
||||
await this.autocompleteCache.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,7 @@
|
|||
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 { FileType, IDE, Position } from "../../../";
|
||||
import { localPathOrUriToPath } from "../../../util/pathToUri";
|
||||
import { getFullLanguageName, getQueryForFile } from "../../../util/treeSitter";
|
||||
import {
|
||||
|
|
@ -353,10 +352,7 @@ export class StaticContextService {
|
|||
if (foundContents.has(tdLocation.filepath)) {
|
||||
content = foundContents.get(tdLocation.filepath)!;
|
||||
} else {
|
||||
content = await fs.readFile(
|
||||
localPathOrUriToPath(tdLocation.filepath),
|
||||
"utf8",
|
||||
);
|
||||
content = await this.ide.readFile(tdLocation.filepath);
|
||||
foundContents.set(tdLocation.filepath, content);
|
||||
}
|
||||
|
||||
|
|
@ -854,24 +850,19 @@ export class StaticContextService {
|
|||
return skipDirs.includes(dirName) || dirName.startsWith(".");
|
||||
};
|
||||
|
||||
async function scanRecursively(currentPath: string): Promise<void> {
|
||||
const scanRecursively = async (currentPath: string): Promise<void> => {
|
||||
try {
|
||||
const entries = await fs.readdir(currentPath, {
|
||||
withFileTypes: true,
|
||||
});
|
||||
const currentUri = pathToFileURL(currentPath).toString();
|
||||
const entries = await this.ide.listDir(currentUri);
|
||||
for (const [name, fileType] of entries) {
|
||||
const fullPath = localPathOrUriToPath(path.join(currentPath, name));
|
||||
|
||||
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)) {
|
||||
if (fileType === (2 as FileType.Directory)) {
|
||||
if (!shouldSkipDirectory(name)) {
|
||||
await scanRecursively(fullPath);
|
||||
}
|
||||
} else if (entry.isFile()) {
|
||||
const extension = path.extname(entry.name).toLowerCase();
|
||||
} else if (fileType === (1 as FileType.File)) {
|
||||
const extension = path.extname(name).toLowerCase();
|
||||
if (tsExtensions.includes(extension)) {
|
||||
tsFiles.push(fullPath);
|
||||
}
|
||||
|
|
@ -880,7 +871,7 @@ export class StaticContextService {
|
|||
} catch (error) {
|
||||
console.error(`Error reading directory ${currentPath}:`, error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
await scanRecursively(dirPath);
|
||||
return tsFiles;
|
||||
|
|
|
|||
|
|
@ -71,6 +71,21 @@ const qwenCoderFimTemplate: AutocompleteTemplate = {
|
|||
},
|
||||
};
|
||||
|
||||
// https://www.ibm.com/granite/docs/models/granite#fim
|
||||
const granite4FimTemplate: AutocompleteTemplate = {
|
||||
template:
|
||||
"<|fim_prefix|>{{{prefix}}}<|fim_suffix|>{{{suffix}}}<|fim_middle|>",
|
||||
completionOptions: {
|
||||
stop: [
|
||||
"<|end_of_text|>",
|
||||
"<|fim_prefix|>",
|
||||
"<|fim_middle|>",
|
||||
"<|fim_suffix|>",
|
||||
"<|fim_pad|>",
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const seedCoderFimTemplate: AutocompleteTemplate = {
|
||||
template:
|
||||
"<[fim-prefix]>{{{prefix}}}<[fim-suffix]>{{{suffix}}}<[fim-middle]>",
|
||||
|
|
@ -177,7 +192,7 @@ const mercuryMultifileFimTemplate: AutocompleteTemplate = {
|
|||
suffix,
|
||||
];
|
||||
}
|
||||
return [`<|fim_prefix|>${prefix}`, suffix];
|
||||
return [`${prefix}`, suffix];
|
||||
}
|
||||
|
||||
const relativePaths = getShortestUniqueRelativeUriPaths(
|
||||
|
|
@ -442,6 +457,10 @@ export function getTemplateForModel(model: string): AutocompleteTemplate {
|
|||
return qwenCoderFimTemplate;
|
||||
}
|
||||
|
||||
if (lowerCaseModel.includes("granite") && lowerCaseModel.includes("4")) {
|
||||
return granite4FimTemplate;
|
||||
}
|
||||
|
||||
if (lowerCaseModel.includes("seed") && lowerCaseModel.includes("coder")) {
|
||||
return seedCoderFimTemplate;
|
||||
}
|
||||
|
|
|
|||
650
core/autocomplete/util/AutocompleteLruCache.test.ts
Normal file
650
core/autocomplete/util/AutocompleteLruCache.test.ts
Normal file
|
|
@ -0,0 +1,650 @@
|
|||
import AutocompleteLruCache from "./AutocompleteLruCache";
|
||||
|
||||
jest.mock("async-mutex", () => {
|
||||
const acquire = jest.fn().mockResolvedValue(jest.fn());
|
||||
return {
|
||||
Mutex: jest.fn().mockImplementation(() => ({ acquire })),
|
||||
};
|
||||
});
|
||||
jest.mock("sqlite");
|
||||
jest.mock("sqlite3");
|
||||
|
||||
jest.useFakeTimers();
|
||||
|
||||
describe("AutocompleteLruCache", () => {
|
||||
let mockDb: any;
|
||||
let cache: AutocompleteLruCache;
|
||||
let currentTime: number;
|
||||
|
||||
const createMockDb = () => ({
|
||||
run: jest.fn().mockResolvedValue(undefined),
|
||||
all: jest.fn().mockResolvedValue([]),
|
||||
exec: jest.fn().mockResolvedValue(undefined),
|
||||
close: jest.fn().mockResolvedValue(undefined),
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllTimers();
|
||||
jest.clearAllMocks();
|
||||
currentTime = 1000000;
|
||||
jest.spyOn(Date, "now").mockImplementation(() => currentTime);
|
||||
|
||||
mockDb = createMockDb();
|
||||
cache = new (AutocompleteLruCache as any)(mockDb);
|
||||
|
||||
// Reset static properties
|
||||
(AutocompleteLruCache as any).capacity = 1000;
|
||||
(AutocompleteLruCache as any).flushInterval = 30000;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
// Clean up any running timers
|
||||
if ((cache as any).flushTimer) {
|
||||
clearInterval((cache as any).flushTimer);
|
||||
}
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// BASIC CACHE OPERATIONS
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
describe("Basic Cache Operations", () => {
|
||||
describe("put() method", () => {
|
||||
it("should store a new entry in the cache", async () => {
|
||||
await cache.put("hello", "world");
|
||||
|
||||
const internalCache = (cache as any).cache;
|
||||
expect(internalCache.has("hello")).toBe(true);
|
||||
expect(internalCache.get("hello")).toEqual({
|
||||
value: "world",
|
||||
timestamp: currentTime,
|
||||
});
|
||||
});
|
||||
|
||||
it("should mark entry as dirty after put", async () => {
|
||||
await cache.put("key", "value");
|
||||
|
||||
const dirtySet = (cache as any).dirty;
|
||||
expect(dirtySet.has("key")).toBe(true);
|
||||
});
|
||||
|
||||
it("should update existing entry with new value and timestamp", async () => {
|
||||
await cache.put("key", "old");
|
||||
currentTime += 5000;
|
||||
await cache.put("key", "new");
|
||||
|
||||
const entry = (cache as any).cache.get("key");
|
||||
expect(entry.value).toBe("new");
|
||||
expect(entry.timestamp).toBe(currentTime);
|
||||
});
|
||||
|
||||
it("should handle prefix storage correctly", async () => {
|
||||
await cache.put("original_prefix", "completion");
|
||||
const internalCache = (cache as any).cache;
|
||||
expect(internalCache.size).toBe(1);
|
||||
});
|
||||
|
||||
it("should acquire mutex lock during put operation", async () => {
|
||||
const releaseSpy = jest.fn();
|
||||
const mutex = (cache as any).mutex;
|
||||
const acquireSpy = jest
|
||||
.spyOn(mutex, "acquire")
|
||||
.mockResolvedValue(releaseSpy);
|
||||
|
||||
await cache.put("test", "value");
|
||||
|
||||
expect(acquireSpy).toHaveBeenCalled();
|
||||
expect(releaseSpy).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("get() method", () => {
|
||||
it("should retrieve exact match from cache", async () => {
|
||||
await cache.put("prefix", "completion");
|
||||
|
||||
const result = await cache.get("prefix");
|
||||
expect(result).toBe("completion");
|
||||
});
|
||||
|
||||
it("should return undefined when no match exists", async () => {
|
||||
const result = await cache.get("nonexistent");
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should update timestamp when entry is accessed", async () => {
|
||||
await cache.put("key", "value");
|
||||
const originalTimestamp = (cache as any).cache.get("key").timestamp;
|
||||
|
||||
currentTime += 10000;
|
||||
await cache.get("key");
|
||||
|
||||
const updatedTimestamp = (cache as any).cache.get("key").timestamp;
|
||||
expect(updatedTimestamp).toBe(currentTime);
|
||||
expect(updatedTimestamp).toBeGreaterThan(originalTimestamp);
|
||||
});
|
||||
|
||||
it("should mark entry as dirty after updating timestamp", async () => {
|
||||
await cache.put("key", "value");
|
||||
(cache as any).dirty.clear();
|
||||
|
||||
await cache.get("key");
|
||||
|
||||
expect((cache as any).dirty.has("key")).toBe(true);
|
||||
});
|
||||
|
||||
it("should find longest matching prefix", async () => {
|
||||
await cache.put("hel", "lo_world");
|
||||
await cache.put("hello", "_user_suffix");
|
||||
const result = await cache.get("hello_user");
|
||||
expect(result).toBe("_suffix");
|
||||
});
|
||||
|
||||
it("should return completion with correct prefix stripped", async () => {
|
||||
await cache.put("pre", "fix_completion");
|
||||
|
||||
const result = await cache.get("prefix");
|
||||
expect(result).toBe("_completion");
|
||||
});
|
||||
|
||||
it("should validate that completion starts with remaining prefix", async () => {
|
||||
await cache.put("abc", "xyz");
|
||||
|
||||
// "abcdef" starts with "abc", remaining is "def"
|
||||
// But cached value "xyz" doesn't start with "def"
|
||||
const result = await cache.get("abcdef");
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should handle prefix matching logic", async () => {
|
||||
await cache.put("pre", "fix_completion");
|
||||
|
||||
const result = await cache.get("prefix");
|
||||
// Result depends on truncateSqliteLikePattern behavior
|
||||
expect(
|
||||
result === "fix_completion" ||
|
||||
result === "_completion" ||
|
||||
result === undefined,
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// LRU EVICTION MECHANISM
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
describe("LRU Eviction", () => {
|
||||
beforeEach(() => {
|
||||
(AutocompleteLruCache as any).capacity = 3;
|
||||
});
|
||||
|
||||
it("should respect capacity limit", async () => {
|
||||
await cache.put("a", "1");
|
||||
await cache.put("b", "2");
|
||||
await cache.put("c", "3");
|
||||
|
||||
expect((cache as any).cache.size).toBe(3);
|
||||
|
||||
await cache.put("d", "4");
|
||||
|
||||
expect((cache as any).cache.size).toBe(3);
|
||||
});
|
||||
|
||||
it("should evict oldest entry when capacity exceeded", async () => {
|
||||
await cache.put("a", "1");
|
||||
currentTime += 1000;
|
||||
await cache.put("b", "2");
|
||||
currentTime += 1000;
|
||||
await cache.put("c", "3");
|
||||
currentTime += 1000;
|
||||
await cache.put("d", "4"); // Should evict "a"
|
||||
|
||||
expect(await cache.get("a")).toBeUndefined();
|
||||
expect(await cache.get("b")).toBe("2");
|
||||
expect(await cache.get("c")).toBe("3");
|
||||
expect(await cache.get("d")).toBe("4");
|
||||
});
|
||||
|
||||
it("should keep recently accessed entries during eviction", async () => {
|
||||
await cache.put("a", "1");
|
||||
currentTime += 1000;
|
||||
await cache.put("b", "2");
|
||||
currentTime += 1000;
|
||||
await cache.put("c", "3");
|
||||
currentTime += 1000;
|
||||
|
||||
// Access "a" to make it recent
|
||||
await cache.get("a");
|
||||
currentTime += 1000;
|
||||
|
||||
await cache.put("d", "4"); // Should evict "b" (oldest)
|
||||
|
||||
expect(await cache.get("a")).toBe("1");
|
||||
expect(await cache.get("b")).toBeUndefined();
|
||||
expect(await cache.get("c")).toBe("3");
|
||||
expect(await cache.get("d")).toBe("4");
|
||||
});
|
||||
|
||||
it("should mark evicted entry as dirty for database deletion", async () => {
|
||||
await cache.put("a", "1");
|
||||
await cache.put("b", "2");
|
||||
await cache.put("c", "3");
|
||||
|
||||
(cache as any).dirty.clear();
|
||||
|
||||
await cache.put("d", "4");
|
||||
|
||||
const dirtySet = (cache as any).dirty;
|
||||
expect(dirtySet.size).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("should handle capacity of 1", async () => {
|
||||
(AutocompleteLruCache as any).capacity = 1;
|
||||
|
||||
await cache.put("a", "1");
|
||||
await cache.put("b", "2");
|
||||
|
||||
expect((cache as any).cache.size).toBe(1);
|
||||
expect(await cache.get("a")).toBeUndefined();
|
||||
expect(await cache.get("b")).toBe("2");
|
||||
});
|
||||
|
||||
it("should find oldest entry among multiple old entries", async () => {
|
||||
await cache.put("a", "1");
|
||||
currentTime += 100;
|
||||
await cache.put("b", "2");
|
||||
currentTime += 100;
|
||||
await cache.put("c", "3");
|
||||
|
||||
// Make "b" oldest by accessing "a" and "c"
|
||||
currentTime += 100;
|
||||
await cache.get("c");
|
||||
currentTime += 100;
|
||||
await cache.get("a");
|
||||
currentTime += 100;
|
||||
|
||||
await cache.put("d", "4"); // Should evict "b"
|
||||
|
||||
expect(await cache.get("b")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// DATABASE PERSISTENCE & FLUSH
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
describe("Database Persistence", () => {
|
||||
describe("flush() method", () => {
|
||||
it("should do nothing when dirty set is empty", async () => {
|
||||
await cache.flush();
|
||||
|
||||
expect(mockDb.run).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should wrap operations in transaction", async () => {
|
||||
await cache.put("key", "value");
|
||||
await cache.flush();
|
||||
|
||||
const calls = mockDb.run.mock.calls;
|
||||
expect(calls[0][0]).toBe("BEGIN TRANSACTION");
|
||||
expect(calls[calls.length - 1][0]).toBe("COMMIT");
|
||||
});
|
||||
|
||||
it("should perform upsert for existing cache entries", async () => {
|
||||
await cache.put("foo", "bar");
|
||||
await cache.flush();
|
||||
|
||||
expect(mockDb.run).toHaveBeenCalledWith(
|
||||
expect.stringContaining("INSERT INTO cache"),
|
||||
"foo",
|
||||
"bar",
|
||||
currentTime,
|
||||
"bar",
|
||||
currentTime,
|
||||
);
|
||||
});
|
||||
|
||||
it("should delete entries removed from cache", async () => {
|
||||
await cache.put("temp", "value");
|
||||
(cache as any).cache.delete("temp");
|
||||
(cache as any).dirty.add("temp");
|
||||
|
||||
await cache.flush();
|
||||
|
||||
expect(mockDb.run).toHaveBeenCalledWith(
|
||||
"DELETE FROM cache WHERE key = ?",
|
||||
"temp",
|
||||
);
|
||||
});
|
||||
|
||||
it("should clear dirty set after successful flush", async () => {
|
||||
await cache.put("key1", "val1");
|
||||
await cache.put("key2", "val2");
|
||||
|
||||
expect((cache as any).dirty.size).toBe(2);
|
||||
|
||||
await cache.flush();
|
||||
|
||||
expect((cache as any).dirty.size).toBe(0);
|
||||
});
|
||||
|
||||
it("should rollback transaction on error", async () => {
|
||||
await cache.put("key", "value");
|
||||
mockDb.run.mockImplementation((sql: string) => {
|
||||
if (sql.includes("INSERT")) {
|
||||
return Promise.reject(new Error("DB Error"));
|
||||
}
|
||||
return Promise.resolve();
|
||||
});
|
||||
|
||||
await cache.flush();
|
||||
|
||||
expect(mockDb.run).toHaveBeenCalledWith("ROLLBACK");
|
||||
});
|
||||
|
||||
it("should log error when flush fails", async () => {
|
||||
const consoleError = jest.spyOn(console, "error").mockImplementation();
|
||||
await cache.put("key", "value");
|
||||
const dbError = new Error("Database failure");
|
||||
mockDb.run.mockRejectedValueOnce(dbError);
|
||||
|
||||
await cache.flush();
|
||||
|
||||
expect(consoleError).toHaveBeenCalledWith(
|
||||
"Error flushing cache:",
|
||||
dbError,
|
||||
);
|
||||
|
||||
consoleError.mockRestore();
|
||||
});
|
||||
|
||||
it("should acquire mutex during flush", async () => {
|
||||
const releaseSpy = jest.fn();
|
||||
const mutex = (cache as any).mutex;
|
||||
const acquireSpy = jest
|
||||
.spyOn(mutex, "acquire")
|
||||
.mockResolvedValue(releaseSpy);
|
||||
|
||||
await cache.put("key", "value");
|
||||
await cache.flush();
|
||||
|
||||
expect(acquireSpy).toHaveBeenCalled();
|
||||
expect(releaseSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should release mutex even if error occurs", async () => {
|
||||
const consoleError = jest.spyOn(console, "error").mockImplementation();
|
||||
const releaseSpy = jest.fn();
|
||||
jest
|
||||
.spyOn((cache as any).mutex, "acquire")
|
||||
.mockResolvedValue(releaseSpy);
|
||||
|
||||
await cache.put("key", "value");
|
||||
|
||||
const originalRun = mockDb.run;
|
||||
mockDb.run = jest.fn().mockImplementation((sql: string) => {
|
||||
if (sql === "BEGIN TRANSACTION" || sql === "ROLLBACK") {
|
||||
return Promise.resolve();
|
||||
}
|
||||
return Promise.reject(new Error("DB Error"));
|
||||
});
|
||||
|
||||
await cache.flush();
|
||||
|
||||
expect(releaseSpy).toHaveBeenCalled();
|
||||
expect(mockDb.run).toHaveBeenCalledWith("ROLLBACK");
|
||||
|
||||
// Restore
|
||||
mockDb.run = originalRun;
|
||||
consoleError.mockRestore();
|
||||
});
|
||||
|
||||
it("should handle multiple dirty entries in one flush", async () => {
|
||||
await cache.put("key1", "val1");
|
||||
await cache.put("key2", "val2");
|
||||
await cache.put("key3", "val3");
|
||||
|
||||
await cache.flush();
|
||||
|
||||
const insertCalls = mockDb.run.mock.calls.filter((call: any) =>
|
||||
call[0].includes("INSERT INTO cache"),
|
||||
);
|
||||
expect(insertCalls.length).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("loadFromDb() method", () => {
|
||||
it("should load all entries from database", async () => {
|
||||
mockDb.all.mockResolvedValue([
|
||||
{ key: "a", value: "alpha", timestamp: 1000 },
|
||||
{ key: "b", value: "beta", timestamp: 2000 },
|
||||
]);
|
||||
|
||||
await (cache as any).loadFromDb();
|
||||
|
||||
const internalCache = (cache as any).cache;
|
||||
expect(internalCache.size).toBe(2);
|
||||
expect(internalCache.get("a")).toEqual({
|
||||
value: "alpha",
|
||||
timestamp: 1000,
|
||||
});
|
||||
expect(internalCache.get("b")).toEqual({
|
||||
value: "beta",
|
||||
timestamp: 2000,
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle empty database", async () => {
|
||||
mockDb.all.mockResolvedValue([]);
|
||||
|
||||
await (cache as any).loadFromDb();
|
||||
|
||||
expect((cache as any).cache.size).toBe(0);
|
||||
});
|
||||
|
||||
it("should query with correct SQL", async () => {
|
||||
await (cache as any).loadFromDb();
|
||||
|
||||
expect(mockDb.all).toHaveBeenCalledWith(
|
||||
"SELECT key, value, timestamp FROM cache",
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// AUTOMATIC FLUSH TIMER
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
describe("Automatic Flush Timer", () => {
|
||||
it("should start timer on startFlushTimer()", () => {
|
||||
(cache as any).startFlushTimer();
|
||||
|
||||
expect((cache as any).flushTimer).toBeDefined();
|
||||
});
|
||||
|
||||
it("should call flush at configured intervals", async () => {
|
||||
(AutocompleteLruCache as any).flushInterval = 1000;
|
||||
const flushSpy = jest.spyOn(cache, "flush").mockResolvedValue();
|
||||
|
||||
(cache as any).startFlushTimer();
|
||||
|
||||
jest.advanceTimersByTime(1000);
|
||||
expect(flushSpy).toHaveBeenCalledTimes(1);
|
||||
|
||||
jest.advanceTimersByTime(1000);
|
||||
expect(flushSpy).toHaveBeenCalledTimes(2);
|
||||
|
||||
jest.advanceTimersByTime(1000);
|
||||
expect(flushSpy).toHaveBeenCalledTimes(3);
|
||||
|
||||
flushSpy.mockRestore();
|
||||
});
|
||||
|
||||
it("should handle flush errors gracefully", async () => {
|
||||
const consoleError = jest.spyOn(console, "error").mockImplementation();
|
||||
const flushError = new Error("Flush failed");
|
||||
jest.spyOn(cache, "flush").mockRejectedValue(flushError);
|
||||
|
||||
(AutocompleteLruCache as any).flushInterval = 1000;
|
||||
(cache as any).startFlushTimer();
|
||||
|
||||
jest.advanceTimersByTime(1000);
|
||||
await Promise.resolve(); // Let error handler run
|
||||
|
||||
expect(consoleError).toHaveBeenCalledWith(
|
||||
"Error flushing cache:",
|
||||
flushError,
|
||||
);
|
||||
|
||||
consoleError.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// RESOURCE CLEANUP
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
describe("Resource Cleanup", () => {
|
||||
it("should clear timer on close()", async () => {
|
||||
(cache as any).startFlushTimer();
|
||||
const timerId = (cache as any).flushTimer;
|
||||
const clearSpy = jest.spyOn(global, "clearInterval");
|
||||
|
||||
await cache.close();
|
||||
|
||||
expect(clearSpy).toHaveBeenCalledWith(timerId);
|
||||
});
|
||||
|
||||
it("should flush pending changes on close()", async () => {
|
||||
await cache.put("key", "value");
|
||||
|
||||
await cache.close();
|
||||
|
||||
expect(mockDb.run).toHaveBeenCalledWith(
|
||||
expect.stringContaining("INSERT INTO cache"),
|
||||
"key",
|
||||
"value",
|
||||
currentTime,
|
||||
"value",
|
||||
currentTime,
|
||||
);
|
||||
});
|
||||
|
||||
it("should close database connection", async () => {
|
||||
await cache.close();
|
||||
|
||||
expect(mockDb.close).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should execute cleanup in correct order", async () => {
|
||||
(cache as any).startFlushTimer();
|
||||
await cache.put("key", "value");
|
||||
|
||||
const operations: string[] = [];
|
||||
|
||||
const originalClearInterval = clearInterval;
|
||||
const clearIntervalSpy = jest
|
||||
.spyOn(global, "clearInterval")
|
||||
.mockImplementation((id) => {
|
||||
operations.push("clearTimer");
|
||||
return originalClearInterval(id);
|
||||
});
|
||||
|
||||
const flushSpy = jest
|
||||
.spyOn(cache, "flush")
|
||||
.mockImplementation(async () => {
|
||||
operations.push("flush");
|
||||
});
|
||||
|
||||
const closeDbSpy = mockDb.close.mockImplementation(() => {
|
||||
operations.push("dbClose");
|
||||
return Promise.resolve();
|
||||
});
|
||||
|
||||
await cache.close();
|
||||
|
||||
expect(operations).toEqual(["clearTimer", "flush", "dbClose"]);
|
||||
|
||||
clearIntervalSpy.mockRestore();
|
||||
flushSpy.mockRestore();
|
||||
});
|
||||
|
||||
it("should handle close() when timer not started", async () => {
|
||||
// Don't start timer
|
||||
await expect(cache.close()).resolves.not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// EDGE CASES & SPECIAL SCENARIOS
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
describe("Edge Cases", () => {
|
||||
it("should handle empty string as prefix", async () => {
|
||||
await cache.put("", "empty");
|
||||
const result = await cache.get("");
|
||||
|
||||
expect(result).toBe("empty");
|
||||
});
|
||||
|
||||
it("should handle very long prefixes", async () => {
|
||||
const longPrefix = "a".repeat(1000);
|
||||
await cache.put(longPrefix, "completion");
|
||||
|
||||
const result = await cache.get(longPrefix);
|
||||
expect(result).toBe("completion");
|
||||
});
|
||||
|
||||
it("should handle special characters in prefix", async () => {
|
||||
const specialPrefix = "test%_\\[";
|
||||
await cache.put(specialPrefix, "special");
|
||||
|
||||
const result = await cache.get(specialPrefix);
|
||||
expect(result).toBe("special");
|
||||
});
|
||||
|
||||
it("should handle Unicode characters", async () => {
|
||||
await cache.put("🚀", "rocket");
|
||||
const result = await cache.get("🚀");
|
||||
|
||||
expect(result).toBe("rocket");
|
||||
});
|
||||
|
||||
it("should handle multiple puts of same key", async () => {
|
||||
await cache.put("key", "first");
|
||||
await cache.put("key", "second");
|
||||
await cache.put("key", "third");
|
||||
|
||||
expect(await cache.get("key")).toBe("third");
|
||||
expect((cache as any).cache.size).toBe(1);
|
||||
});
|
||||
|
||||
it("should handle concurrent get operations", async () => {
|
||||
await cache.put("shared", "value");
|
||||
|
||||
const results = await Promise.all([
|
||||
cache.get("shared"),
|
||||
cache.get("shared"),
|
||||
cache.get("shared"),
|
||||
]);
|
||||
|
||||
expect(results).toEqual(["value", "value", "value"]);
|
||||
});
|
||||
});
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// SINGLETON PATTERN (Static get() method)
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
describe("Singleton Pattern", () => {
|
||||
beforeEach(() => {
|
||||
// Reset singleton
|
||||
(AutocompleteLruCache as any).instancePromise = undefined;
|
||||
});
|
||||
|
||||
it("should return same instance on multiple calls", async () => {
|
||||
const mockOpen = jest.fn().mockResolvedValue(mockDb);
|
||||
jest.doMock("sqlite", () => ({ open: mockOpen }));
|
||||
|
||||
const instance1 = await AutocompleteLruCache.get();
|
||||
const instance2 = await AutocompleteLruCache.get();
|
||||
|
||||
expect(instance1).toBe(instance2);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,121 +1,227 @@
|
|||
import { Mutex } from "async-mutex";
|
||||
import { open } from "sqlite";
|
||||
import sqlite3 from "sqlite3";
|
||||
|
||||
import {
|
||||
DatabaseConnection,
|
||||
truncateSqliteLikePattern,
|
||||
} from "../../indexing/refreshIndex.js";
|
||||
import { getTabAutocompleteCacheSqlitePath } from "../../util/paths.js";
|
||||
|
||||
interface CacheEntry {
|
||||
value: string;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* LRU cache for autocomplete results with SQLite persistence.
|
||||
*
|
||||
* Implements a least-recently-used cache that:
|
||||
* - Stores prefix-to-completion mappings in memory
|
||||
* - Periodically flushes changes to SQLite for persistence
|
||||
* - Evicts oldest entries when capacity is exceeded
|
||||
* - Supports prefix matching for flexible autocomplete retrieval
|
||||
*/
|
||||
export class AutocompleteLruCache {
|
||||
private static capacity = 1000;
|
||||
private static flushInterval = 30000;
|
||||
private static instancePromise?: Promise<AutocompleteLruCache>;
|
||||
private mutex = new Mutex();
|
||||
private cache: Map<string, CacheEntry> = new Map();
|
||||
private dirty: Set<string> = new Set();
|
||||
private flushTimer?: NodeJS.Timeout;
|
||||
|
||||
constructor(private db: DatabaseConnection) {}
|
||||
|
||||
/**
|
||||
* Singleton accessor that initializes the cache with SQLite persistence.
|
||||
* Creates the database table if it doesn't exist and loads existing entries.
|
||||
*/
|
||||
static async get(): Promise<AutocompleteLruCache> {
|
||||
const db = await open({
|
||||
filename: getTabAutocompleteCacheSqlitePath(),
|
||||
driver: sqlite3.Database,
|
||||
});
|
||||
if (!AutocompleteLruCache.instancePromise) {
|
||||
AutocompleteLruCache.instancePromise = (async () => {
|
||||
const db = await open({
|
||||
filename: getTabAutocompleteCacheSqlitePath(),
|
||||
driver: sqlite3.Database,
|
||||
});
|
||||
await db.exec("PRAGMA busy_timeout = 3000;");
|
||||
await db.run(`
|
||||
CREATE TABLE IF NOT EXISTS cache (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL,
|
||||
timestamp INTEGER NOT NULL
|
||||
)
|
||||
`);
|
||||
|
||||
await db.exec("PRAGMA busy_timeout = 3000;");
|
||||
|
||||
await db.run(`
|
||||
CREATE TABLE IF NOT EXISTS cache (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL,
|
||||
timestamp INTEGER NOT NULL
|
||||
)
|
||||
`);
|
||||
|
||||
return new AutocompleteLruCache(db);
|
||||
const instance = new AutocompleteLruCache(db);
|
||||
await instance.loadFromDb();
|
||||
instance.startFlushTimer();
|
||||
return instance;
|
||||
})();
|
||||
}
|
||||
return AutocompleteLruCache.instancePromise;
|
||||
}
|
||||
|
||||
async get(prefix: string): Promise<string | undefined> {
|
||||
// NOTE: Right now prompts with different suffixes will be considered the same
|
||||
/** Loads all cached entries from SQLite into memory on initialization. */
|
||||
private async loadFromDb() {
|
||||
const rows = await this.db.all("SELECT key, value, timestamp FROM cache");
|
||||
for (const row of rows) {
|
||||
this.cache.set(row.key, {
|
||||
value: row.value,
|
||||
timestamp: row.timestamp,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// If the query is "co" and we have "c" -> "ontinue" in the cache,
|
||||
// we should return "ntinue" as the completion.
|
||||
// Have to make sure we take the key with shortest length
|
||||
/** Starts periodic flush timer to persist dirty entries to database. */
|
||||
private startFlushTimer() {
|
||||
this.flushTimer = setInterval(() => {
|
||||
this.flush().catch((e) => console.error("Error flushing cache:", e));
|
||||
}, AutocompleteLruCache.flushInterval);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves cached completion for a prefix using longest-match strategy.
|
||||
*
|
||||
* Algorithm:
|
||||
* 1. Finds the longest cached prefix that the query starts with
|
||||
* 2. Validates that cached completion starts with the remaining query text
|
||||
* 3. Returns the completion with the matched portion stripped
|
||||
* 4. Updates the entry's timestamp (LRU tracking)
|
||||
*
|
||||
* @param prefix - The prefix to search for
|
||||
* @returns The completion string with prefix removed, or undefined if no match
|
||||
*/
|
||||
async get(prefix: string): Promise<string | undefined> {
|
||||
const truncatedPrefix = truncateSqliteLikePattern(prefix);
|
||||
try {
|
||||
const result = await this.db.get(
|
||||
"SELECT key, value FROM cache WHERE ? LIKE key || '%' ORDER BY LENGTH(key) DESC LIMIT 1",
|
||||
truncatedPrefix,
|
||||
);
|
||||
// Validate that the cached completion is a valid completion for the prefix
|
||||
if (
|
||||
result &&
|
||||
result.value.startsWith(truncatedPrefix.slice(result.key.length))
|
||||
) {
|
||||
await this.db.run(
|
||||
"UPDATE cache SET timestamp = ? WHERE key = ?",
|
||||
Date.now(),
|
||||
truncatedPrefix,
|
||||
);
|
||||
// And then truncate so we aren't writing something that's already there
|
||||
return result.value.slice(truncatedPrefix.length - result.key.length);
|
||||
let bestMatch: { key: string; entry: CacheEntry } | null = null;
|
||||
|
||||
for (const [key, entry] of this.cache.entries()) {
|
||||
if (truncatedPrefix.startsWith(key)) {
|
||||
if (!bestMatch || key.length > bestMatch.key.length) {
|
||||
bestMatch = { key, entry };
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// catches e.g. old SQLITE LIKE OR GLOB PATTERN TOO COMPLEX
|
||||
console.error(e);
|
||||
}
|
||||
|
||||
if (
|
||||
bestMatch &&
|
||||
bestMatch.entry.value.startsWith(
|
||||
truncatedPrefix.slice(bestMatch.key.length),
|
||||
)
|
||||
) {
|
||||
bestMatch.entry.timestamp = Date.now();
|
||||
this.dirty.add(bestMatch.key);
|
||||
|
||||
return bestMatch.entry.value.slice(
|
||||
truncatedPrefix.length - bestMatch.key.length,
|
||||
);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores a prefix-to-completion mapping in the cache.
|
||||
*
|
||||
* Thread-safe operation that:
|
||||
* - Truncates the prefix for SQLite pattern safety
|
||||
* - Updates or inserts the entry with current timestamp
|
||||
* - Evicts oldest entry if capacity exceeded
|
||||
* - Marks entry as dirty for next flush
|
||||
*
|
||||
* @param prefix - The prefix key
|
||||
* @param completion - The completion value to cache
|
||||
*/
|
||||
async put(prefix: string, completion: string) {
|
||||
const release = await this.mutex.acquire();
|
||||
|
||||
const truncatedPrefix = truncateSqliteLikePattern(prefix);
|
||||
|
||||
try {
|
||||
await this.db.run("BEGIN TRANSACTION");
|
||||
const now = Date.now();
|
||||
|
||||
try {
|
||||
const result = await this.db.get(
|
||||
"SELECT key FROM cache WHERE key = ?",
|
||||
truncatedPrefix,
|
||||
);
|
||||
this.cache.set(truncatedPrefix, {
|
||||
value: completion,
|
||||
timestamp: now,
|
||||
});
|
||||
this.dirty.add(truncatedPrefix);
|
||||
|
||||
if (result) {
|
||||
await this.db.run(
|
||||
"UPDATE cache SET value = ?, timestamp = ? WHERE key = ?",
|
||||
completion,
|
||||
Date.now(),
|
||||
truncatedPrefix,
|
||||
);
|
||||
} else {
|
||||
const count = await this.db.get(
|
||||
"SELECT COUNT(*) as count FROM cache",
|
||||
);
|
||||
if (this.cache.size > AutocompleteLruCache.capacity) {
|
||||
let oldestKey: string | null = null;
|
||||
let oldestTime = Infinity;
|
||||
|
||||
if (count.count >= AutocompleteLruCache.capacity) {
|
||||
await this.db.run(
|
||||
"DELETE FROM cache WHERE key = (SELECT key FROM cache ORDER BY timestamp ASC LIMIT 1)",
|
||||
);
|
||||
for (const [key, entry] of this.cache.entries()) {
|
||||
if (entry.timestamp < oldestTime) {
|
||||
oldestTime = entry.timestamp;
|
||||
oldestKey = key;
|
||||
}
|
||||
|
||||
await this.db.run(
|
||||
"INSERT INTO cache (key, value, timestamp) VALUES (?, ?, ?)",
|
||||
truncatedPrefix,
|
||||
completion,
|
||||
Date.now(),
|
||||
);
|
||||
}
|
||||
|
||||
await this.db.run("COMMIT");
|
||||
} catch (error) {
|
||||
await this.db.run("ROLLBACK");
|
||||
throw error;
|
||||
if (oldestKey) {
|
||||
this.cache.delete(oldestKey);
|
||||
this.dirty.add(oldestKey);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Error creating transaction: ", e);
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Persists all dirty entries to SQLite in a single transaction.
|
||||
*
|
||||
* Performs upserts for existing cache entries and deletes for evicted entries.
|
||||
* Skips if no changes pending. Rolls back transaction on error.
|
||||
*/
|
||||
async flush() {
|
||||
if (this.dirty.size === 0) return;
|
||||
|
||||
const release = await this.mutex.acquire();
|
||||
const dirtyKeys = Array.from(this.dirty);
|
||||
this.dirty.clear();
|
||||
|
||||
try {
|
||||
await this.db.run("BEGIN TRANSACTION");
|
||||
|
||||
for (const key of dirtyKeys) {
|
||||
const entry = this.cache.get(key);
|
||||
|
||||
if (entry) {
|
||||
// Upsert
|
||||
await this.db.run(
|
||||
`INSERT INTO cache (key, value, timestamp) VALUES (?, ?, ?)
|
||||
ON CONFLICT(key) DO UPDATE SET value = ?, timestamp = ?`,
|
||||
key,
|
||||
entry.value,
|
||||
entry.timestamp,
|
||||
entry.value,
|
||||
entry.timestamp,
|
||||
);
|
||||
} else {
|
||||
// Delete
|
||||
await this.db.run("DELETE FROM cache WHERE key = ?", key);
|
||||
}
|
||||
}
|
||||
|
||||
await this.db.run("COMMIT");
|
||||
} catch (error) {
|
||||
await this.db.run("ROLLBACK");
|
||||
console.error("Error flushing cache:", error);
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gracefully shuts down the cache.
|
||||
* Stops the flush timer, persists pending changes, and closes database connection.
|
||||
*/
|
||||
async close() {
|
||||
if (this.flushTimer) {
|
||||
clearInterval(this.flushTimer);
|
||||
}
|
||||
await this.flush();
|
||||
await this.db.close();
|
||||
AutocompleteLruCache.instancePromise = undefined;
|
||||
}
|
||||
}
|
||||
export default AutocompleteLruCache;
|
||||
|
|
|
|||
|
|
@ -502,11 +502,13 @@ export class ConfigHandler {
|
|||
this.totalConfigReloads += 1;
|
||||
// console.log(`Reloading config (#${this.totalConfigLoads}): ${reason}`); // Uncomment to see config loading logs
|
||||
if (!this.currentProfile) {
|
||||
return {
|
||||
const out = {
|
||||
config: undefined,
|
||||
errors: injectErrors,
|
||||
configLoadInterrupted: true,
|
||||
};
|
||||
this.notifyConfigListeners(out);
|
||||
return out;
|
||||
}
|
||||
|
||||
for (const org of this.organizations) {
|
||||
|
|
|
|||
|
|
@ -79,7 +79,13 @@ export async function loadMarkdownRules(ide: IDE): Promise<{
|
|||
uriType: "file",
|
||||
fileUri: file.path,
|
||||
});
|
||||
rules.push({ ...rule, source: "rules-block", sourceFile: file.path });
|
||||
if (!rule.invokable) {
|
||||
rules.push({
|
||||
...rule,
|
||||
source: "rules-block",
|
||||
sourceFile: file.path,
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
errors.push({
|
||||
fatal: false,
|
||||
|
|
|
|||
|
|
@ -173,13 +173,6 @@ export function migrateJsonSharedConfig(filepath: string, ide: IDE): void {
|
|||
effected = true;
|
||||
}
|
||||
|
||||
const { autoAcceptEditToolDiffs, ...withoutAutoApply } = migratedUI;
|
||||
if (autoAcceptEditToolDiffs !== undefined) {
|
||||
shareConfigUpdates.autoAcceptEditToolDiffs = autoAcceptEditToolDiffs;
|
||||
migratedUI = withoutAutoApply;
|
||||
effected = true;
|
||||
}
|
||||
|
||||
const { showChatScrollbar, ...withoutShowChatScrollbar } = migratedUI;
|
||||
if (showChatScrollbar !== undefined) {
|
||||
shareConfigUpdates.showChatScrollbar = showChatScrollbar;
|
||||
|
|
|
|||
|
|
@ -348,7 +348,12 @@ export default async function doLoadConfig(options: {
|
|||
}
|
||||
});
|
||||
|
||||
if (newConfig.allowAnonymousTelemetry !== false) {
|
||||
// VS Code has an IDE telemetry setting
|
||||
// Since it's a security concern we use OR behavior on false
|
||||
if (
|
||||
newConfig.allowAnonymousTelemetry !== false &&
|
||||
ideInfo.ideType === "vscode"
|
||||
) {
|
||||
if ((await ide.isTelemetryEnabled()) === false) {
|
||||
newConfig.allowAnonymousTelemetry = false;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,7 +31,6 @@ export const sharedConfigSchema = z
|
|||
codeWrap: z.boolean(),
|
||||
displayRawMarkdown: z.boolean(),
|
||||
showChatScrollbar: z.boolean(),
|
||||
autoAcceptEditToolDiffs: z.boolean(),
|
||||
continueAfterToolRejection: z.boolean(),
|
||||
|
||||
// `tabAutocompleteOptions` in `ContinueConfig`
|
||||
|
|
@ -140,10 +139,6 @@ export function modifyAnyConfigWithSharedConfig<
|
|||
if (sharedConfig.showChatScrollbar !== undefined) {
|
||||
configCopy.ui.showChatScrollbar = sharedConfig.showChatScrollbar;
|
||||
}
|
||||
if (sharedConfig.autoAcceptEditToolDiffs !== undefined) {
|
||||
configCopy.ui.autoAcceptEditToolDiffs =
|
||||
sharedConfig.autoAcceptEditToolDiffs;
|
||||
}
|
||||
|
||||
if (sharedConfig.allowAnonymousTelemetry !== undefined) {
|
||||
configCopy.allowAnonymousTelemetry = sharedConfig.allowAnonymousTelemetry;
|
||||
|
|
|
|||
|
|
@ -3,10 +3,12 @@ import {
|
|||
ConfigYaml,
|
||||
createPromptMarkdown,
|
||||
createRuleMarkdown,
|
||||
sanitizeRuleName,
|
||||
} from "@continuedev/config-yaml";
|
||||
import * as YAML from "yaml";
|
||||
import { IDE } from "../..";
|
||||
import { getContinueGlobalPath } from "../../util/paths";
|
||||
import { localPathToUri } from "../../util/pathToUri";
|
||||
import { joinPathsToUri } from "../../util/uri";
|
||||
|
||||
const BLOCK_TYPE_CONFIG: Record<
|
||||
|
|
@ -115,13 +117,28 @@ export async function findAvailableFilename(
|
|||
fileExists: (uri: string) => Promise<boolean>,
|
||||
extension?: string,
|
||||
isGlobal?: boolean,
|
||||
baseFilenameOverride?: string,
|
||||
): Promise<string> {
|
||||
// Differentiate filename based on whether its a global rule or a workspace rule
|
||||
const baseFilename =
|
||||
blockType === "rules" && isGlobal
|
||||
? "global-rule"
|
||||
: `new-${BLOCK_TYPE_CONFIG[blockType]?.filename}`;
|
||||
const fileExtension = extension ?? getFileExtension(blockType);
|
||||
let baseFilename = "";
|
||||
|
||||
const trimmedOverride = baseFilenameOverride?.trim();
|
||||
if (trimmedOverride) {
|
||||
if (blockType === "rules") {
|
||||
const withoutExtension = trimmedOverride.replace(/\.[^./\\]+$/, "");
|
||||
const sanitized = sanitizeRuleName(withoutExtension);
|
||||
baseFilename = sanitized;
|
||||
} else {
|
||||
baseFilename = trimmedOverride;
|
||||
}
|
||||
}
|
||||
if (!baseFilename) {
|
||||
baseFilename =
|
||||
blockType === "rules" && isGlobal
|
||||
? "global-rule"
|
||||
: `new-${BLOCK_TYPE_CONFIG[blockType]?.filename}`;
|
||||
}
|
||||
|
||||
let counter = 0;
|
||||
let fileUri: string;
|
||||
|
||||
|
|
@ -140,6 +157,7 @@ export async function findAvailableFilename(
|
|||
export async function createNewWorkspaceBlockFile(
|
||||
ide: IDE,
|
||||
blockType: BlockType,
|
||||
baseFilename?: string,
|
||||
): Promise<void> {
|
||||
const workspaceDirs = await ide.getWorkspaceDirs();
|
||||
if (workspaceDirs.length === 0) {
|
||||
|
|
@ -154,6 +172,9 @@ export async function createNewWorkspaceBlockFile(
|
|||
baseDirUri,
|
||||
blockType,
|
||||
ide.fileExists.bind(ide),
|
||||
undefined,
|
||||
false,
|
||||
baseFilename,
|
||||
);
|
||||
|
||||
const fileContent = getFileContent(blockType);
|
||||
|
|
@ -162,9 +183,12 @@ export async function createNewWorkspaceBlockFile(
|
|||
await ide.openFile(fileUri);
|
||||
}
|
||||
|
||||
export async function createNewGlobalRuleFile(ide: IDE): Promise<void> {
|
||||
export async function createNewGlobalRuleFile(
|
||||
ide: IDE,
|
||||
baseFilename?: string,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const globalDir = getContinueGlobalPath();
|
||||
const globalDir = localPathToUri(getContinueGlobalPath());
|
||||
|
||||
// Create the rules subdirectory within the global directory
|
||||
const rulesDir = joinPathsToUri(globalDir, "rules");
|
||||
|
|
@ -175,6 +199,7 @@ export async function createNewGlobalRuleFile(ide: IDE): Promise<void> {
|
|||
ide.fileExists.bind(ide),
|
||||
undefined,
|
||||
true, // isGlobal = true for global rules
|
||||
baseFilename,
|
||||
);
|
||||
|
||||
const fileContent = getFileContent("rules");
|
||||
|
|
|
|||
|
|
@ -97,7 +97,12 @@ export class LocalPlatformClient implements PlatformClient {
|
|||
return [];
|
||||
}
|
||||
|
||||
const results = await this.client.resolveFQSNs(fqsns, this.orgScopeId);
|
||||
let results: (SecretResult | undefined)[] = [];
|
||||
try {
|
||||
results = await this.client.resolveFQSNs(fqsns, this.orgScopeId);
|
||||
} catch (e) {
|
||||
console.error("Error getting secrets from control plane", e);
|
||||
}
|
||||
|
||||
// For any secret that isn't found, look in .env files, then process.env
|
||||
for (let i = 0; i < results.length; i++) {
|
||||
|
|
|
|||
|
|
@ -9,7 +9,6 @@ import {
|
|||
ModelRole,
|
||||
PackageIdentifier,
|
||||
RegistryClient,
|
||||
TEMPLATE_VAR_REGEX,
|
||||
unrollAssistant,
|
||||
validateConfigYaml,
|
||||
} from "@continuedev/config-yaml";
|
||||
|
|
@ -237,22 +236,6 @@ export async function configYamlToContinueConfig(options: {
|
|||
sourceFile: doc.sourceFile,
|
||||
}));
|
||||
|
||||
config.mcpServers?.forEach((mcpServer) => {
|
||||
if ("args" in mcpServer) {
|
||||
const mcpArgVariables =
|
||||
mcpServer.args?.filter((arg) => TEMPLATE_VAR_REGEX.test(arg)) ?? [];
|
||||
|
||||
if (mcpArgVariables.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
localErrors.push({
|
||||
fatal: false,
|
||||
message: `MCP server "${mcpServer.name}" has unsubstituted variables in args: ${mcpArgVariables.join(", ")}. Please refer to https://docs.continue.dev/hub/secrets/secret-types for managing hub secrets.`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Prompt files -
|
||||
try {
|
||||
const promptFiles = await getAllPromptFiles(ide, undefined, true);
|
||||
|
|
|
|||
|
|
@ -52,7 +52,7 @@ describe("llmsFromModelConfig requestOptions merging", () => {
|
|||
requestOptions: {
|
||||
timeout: 30000,
|
||||
headers: {
|
||||
"User-Agent": "Continue/1.0.0",
|
||||
"user-agent": "Continue/1.0.0",
|
||||
},
|
||||
proxy: "global-proxy",
|
||||
},
|
||||
|
|
@ -112,7 +112,7 @@ describe("llmsFromModelConfig requestOptions merging", () => {
|
|||
expect(llm.requestOptions).toEqual({
|
||||
timeout: 60000, // model-specific takes precedence
|
||||
headers: {
|
||||
"User-Agent": "Continue/1.0.0", // from global request options
|
||||
"user-agent": "Continue/1.0.0", // from global request options
|
||||
Authorization: "Bearer token123", // from model
|
||||
},
|
||||
proxy: "model-proxy", // model-specific takes precedence
|
||||
|
|
@ -236,7 +236,7 @@ describe("llmsFromModelConfig requestOptions merging", () => {
|
|||
expect(llm.requestOptions).toEqual({
|
||||
timeout: 120000, // model-specific takes precedence
|
||||
headers: {
|
||||
"User-Agent": "Continue/1.0.0", // from global request options
|
||||
"user-agent": "Continue/1.0.0", // from global request options
|
||||
"X-Custom": "autodetect", // from model
|
||||
},
|
||||
proxy: "global-proxy", // from global request options
|
||||
|
|
@ -302,7 +302,7 @@ describe("llmsFromModelConfig requestOptions merging", () => {
|
|||
expect(llm.requestOptions).toEqual({
|
||||
timeout: 90000,
|
||||
headers: {
|
||||
"User-Agent": "Continue/1.0.0",
|
||||
"user-agent": "Continue/1.0.0",
|
||||
},
|
||||
proxy: "global-proxy",
|
||||
});
|
||||
|
|
@ -345,7 +345,7 @@ describe("llmsFromModelConfig requestOptions merging", () => {
|
|||
const llm = result[0];
|
||||
|
||||
expect(llm.requestOptions?.headers).toEqual({
|
||||
"User-Agent": "Continue/1.0.0", // from global request options
|
||||
"user-agent": "Continue/1.0.0", // from global request options
|
||||
"Cache-Control": "no-cache", // from global request options
|
||||
Authorization: "Bearer model-token", // from model
|
||||
Accept: "application/json", // from model (overrides config)
|
||||
|
|
|
|||
|
|
@ -2,6 +2,10 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|||
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
import {
|
||||
decodeSecretLocation,
|
||||
getTemplateVariables,
|
||||
} from "@continuedev/config-yaml";
|
||||
import {
|
||||
SSEClientTransport,
|
||||
SseError,
|
||||
|
|
@ -163,6 +167,24 @@ class MCPConnection {
|
|||
}
|
||||
}
|
||||
|
||||
const vars = getTemplateVariables(JSON.stringify(this.options));
|
||||
const unrendered = vars.map((v) => {
|
||||
const stripped = v.replace("secrets.", "");
|
||||
try {
|
||||
return decodeSecretLocation(stripped).secretName;
|
||||
} catch {
|
||||
return stripped;
|
||||
}
|
||||
});
|
||||
|
||||
if (unrendered.length > 0) {
|
||||
this.errors.push(
|
||||
`${this.options.name} MCP Server has unresolved secrets: ${unrendered.join(", ")}.
|
||||
For personal use you can set the secret in the hub at https://hub.continue.dev/settings/secrets.
|
||||
Org-level secrets can only be used for MCP by Background Agents (https://docs.continue.dev/hub/agents/overview) when \"Include in Env\" is enabled.`,
|
||||
);
|
||||
}
|
||||
|
||||
this.connectionPromise = Promise.race([
|
||||
// If aborted by a refresh or other, cancel and don't do anything
|
||||
new Promise((resolve) => {
|
||||
|
|
|
|||
|
|
@ -33,39 +33,40 @@ export async function getUrlContextItems(
|
|||
query: string,
|
||||
fetchFn: FetchFunction,
|
||||
): Promise<ContextItem[]> {
|
||||
try {
|
||||
const url = new URL(query);
|
||||
const icon = await fetchFavicon(url);
|
||||
const resp = await fetchFn(url);
|
||||
const html = await resp.text();
|
||||
const url = new URL(query);
|
||||
const icon = await fetchFavicon(url);
|
||||
const resp = await fetchFn(url);
|
||||
|
||||
const dom = new JSDOM(html);
|
||||
let reader = new Readability(dom.window.document);
|
||||
let article = reader.parse();
|
||||
const content = article?.content || "";
|
||||
const markdown = NodeHtmlMarkdown.translate(
|
||||
content,
|
||||
{},
|
||||
undefined,
|
||||
undefined,
|
||||
);
|
||||
|
||||
const title = article?.title || url.pathname;
|
||||
|
||||
return [
|
||||
{
|
||||
icon,
|
||||
description: url.toString(),
|
||||
content: markdown,
|
||||
name: title,
|
||||
uri: {
|
||||
type: "url",
|
||||
value: url.toString(),
|
||||
},
|
||||
},
|
||||
];
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
return [];
|
||||
// Check if the response is not OK
|
||||
if (!resp.ok) {
|
||||
throw new Error(`HTTP ${resp.status} ${resp.statusText}`);
|
||||
}
|
||||
|
||||
const html = await resp.text();
|
||||
|
||||
const dom = new JSDOM(html);
|
||||
let reader = new Readability(dom.window.document);
|
||||
let article = reader.parse();
|
||||
const content = article?.content || "";
|
||||
const markdown = NodeHtmlMarkdown.translate(
|
||||
content,
|
||||
{},
|
||||
undefined,
|
||||
undefined,
|
||||
);
|
||||
|
||||
const title = article?.title || url.pathname;
|
||||
|
||||
return [
|
||||
{
|
||||
icon,
|
||||
description: url.toString(),
|
||||
content: markdown,
|
||||
name: title,
|
||||
uri: {
|
||||
type: "url",
|
||||
value: url.toString(),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
|
|
|||
|
|
@ -54,6 +54,39 @@ export interface RemoteSessionMetadata extends BaseSessionMetadata {
|
|||
remoteId: string;
|
||||
}
|
||||
|
||||
export interface AgentSessionMetadata {
|
||||
createdBy: string;
|
||||
github_repo: string;
|
||||
organizationId?: string;
|
||||
idempotencyKey?: string;
|
||||
source?: string;
|
||||
continueApiKeyId?: string;
|
||||
s3Url?: string;
|
||||
prompt?: string | null;
|
||||
createdBySlug?: string;
|
||||
}
|
||||
|
||||
export interface AgentSessionView {
|
||||
id: string;
|
||||
devboxId: string | null;
|
||||
name: string | null;
|
||||
icon: string | null;
|
||||
status: string;
|
||||
agentStatus: string | null;
|
||||
unread: boolean;
|
||||
state: string;
|
||||
metadata: AgentSessionMetadata;
|
||||
repoUrl: string;
|
||||
branch: string | null;
|
||||
pullRequestUrl: string | null;
|
||||
pullRequestStatus: string | null;
|
||||
tunnelUrl: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
create_time_ms: string;
|
||||
end_time_ms: string;
|
||||
}
|
||||
|
||||
export class ControlPlaneClient {
|
||||
constructor(
|
||||
readonly sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
|
||||
|
|
@ -319,7 +352,6 @@ export class ControlPlaneClient {
|
|||
|
||||
/**
|
||||
* Check if remote sessions should be enabled based on feature flags
|
||||
* Requires: PostHog feature flag AND @continue.dev email
|
||||
*/
|
||||
public async shouldEnableRemoteSessions(): Promise<boolean> {
|
||||
// Check if user is signed in
|
||||
|
|
@ -327,17 +359,13 @@ export class ControlPlaneClient {
|
|||
return false;
|
||||
}
|
||||
|
||||
// Check if user has @continue.dev email
|
||||
try {
|
||||
const sessionInfo = await this.sessionInfoPromise;
|
||||
if (isOnPremSession(sessionInfo) || !sessionInfo) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const hubSession = sessionInfo as HubSessionInfo;
|
||||
const email = hubSession.account?.id;
|
||||
|
||||
return email ? email.includes("@continue.dev") : false;
|
||||
return true;
|
||||
} catch (e) {
|
||||
Logger.error(e, {
|
||||
context: "control_plane_check_remote_sessions_enabled",
|
||||
|
|
@ -355,7 +383,6 @@ export class ControlPlaneClient {
|
|||
|
||||
/**
|
||||
* Fetch remote agents/sessions from the control plane
|
||||
* Currently restricted to @continue.dev emails for internal use
|
||||
*/
|
||||
public async listRemoteSessions(): Promise<RemoteSessionMetadata[]> {
|
||||
if (!(await this.isSignedIn())) {
|
||||
|
|
@ -363,8 +390,6 @@ export class ControlPlaneClient {
|
|||
}
|
||||
|
||||
try {
|
||||
// Note: This endpoint is currently restricted to internal @continue.dev users
|
||||
// In the future, this may be expanded to support broader remote session access
|
||||
const resp = await this.requestAndHandleError("agents/devboxes", {
|
||||
method: "GET",
|
||||
});
|
||||
|
|
@ -545,23 +570,19 @@ export class ControlPlaneClient {
|
|||
});
|
||||
|
||||
const result = (await resp.json()) as {
|
||||
agents: any[];
|
||||
agents: AgentSessionView[];
|
||||
totalCount: number;
|
||||
};
|
||||
|
||||
return {
|
||||
agents: result.agents.map((agent: any) => ({
|
||||
agents: result.agents.map((agent) => ({
|
||||
id: agent.id,
|
||||
name: agent.name || agent.metadata?.name || null,
|
||||
name: agent.name,
|
||||
status: agent.status,
|
||||
repoUrl: agent.metadata?.repo_url || agent.repo_url || "",
|
||||
createdAt:
|
||||
agent.created_at || agent.create_time_ms
|
||||
? new Date(agent.created_at || agent.create_time_ms).toISOString()
|
||||
: new Date().toISOString(),
|
||||
repoUrl: agent.repoUrl,
|
||||
createdAt: agent.createdAt,
|
||||
metadata: {
|
||||
github_repo:
|
||||
agent.metadata?.github_repo || agent.metadata?.repo_url,
|
||||
github_repo: agent.metadata.github_repo,
|
||||
},
|
||||
})),
|
||||
totalCount: result.totalCount,
|
||||
|
|
@ -573,4 +594,73 @@ export class ControlPlaneClient {
|
|||
return { agents: [], totalCount: 0 };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the full agent session information
|
||||
* @param agentSessionId - The ID of the agent session
|
||||
* @returns The agent session view including metadata and status
|
||||
*/
|
||||
public async getAgentSession(
|
||||
agentSessionId: string,
|
||||
): Promise<AgentSessionView | null> {
|
||||
if (!(await this.isSignedIn())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const resp = await this.requestAndHandleError(
|
||||
`agents/${agentSessionId}`,
|
||||
{
|
||||
method: "GET",
|
||||
},
|
||||
);
|
||||
|
||||
return (await resp.json()) as AgentSessionView;
|
||||
} catch (e) {
|
||||
Logger.error(e, {
|
||||
context: "control_plane_get_agent_session",
|
||||
agentSessionId,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the state of a specific background agent
|
||||
* @param agentSessionId - The ID of the agent session
|
||||
* @returns The agent's session state including history, workspace, and branch
|
||||
*/
|
||||
public async getAgentState(agentSessionId: string): Promise<{
|
||||
session: Session;
|
||||
isProcessing: boolean;
|
||||
messageQueueLength: number;
|
||||
pendingPermission: any;
|
||||
} | null> {
|
||||
if (!(await this.isSignedIn())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const resp = await this.requestAndHandleError(
|
||||
`agents/${agentSessionId}/state`,
|
||||
{
|
||||
method: "GET",
|
||||
},
|
||||
);
|
||||
|
||||
const result = (await resp.json()) as {
|
||||
session: Session;
|
||||
isProcessing: boolean;
|
||||
messageQueueLength: number;
|
||||
pendingPermission: any;
|
||||
};
|
||||
return result;
|
||||
} catch (e) {
|
||||
Logger.error(e, {
|
||||
context: "control_plane_get_agent_state",
|
||||
agentSessionId,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
25
core/core.ts
25
core/core.ts
|
|
@ -70,6 +70,7 @@ import {
|
|||
import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton";
|
||||
import { performAuth, removeMCPAuth } from "./context/mcp/MCPOauth";
|
||||
import { setMdmLicenseKey } from "./control-plane/mdm/mdm";
|
||||
import { myersDiff } from "./diff/myers";
|
||||
import { ApplyAbortManager } from "./edit/applyAbortManager";
|
||||
import { streamDiffLines } from "./edit/streamDiffLines";
|
||||
import { shouldIgnore } from "./indexing/shouldIgnore";
|
||||
|
|
@ -408,7 +409,11 @@ export class Core {
|
|||
});
|
||||
|
||||
on("config/addLocalWorkspaceBlock", async (msg) => {
|
||||
await createNewWorkspaceBlockFile(this.ide, msg.data.blockType);
|
||||
await createNewWorkspaceBlockFile(
|
||||
this.ide,
|
||||
msg.data.blockType,
|
||||
msg.data.baseFilename,
|
||||
);
|
||||
await this.configHandler.reloadConfig(
|
||||
"Local block created (config/addLocalWorkspaceBlock message)",
|
||||
);
|
||||
|
|
@ -416,7 +421,7 @@ export class Core {
|
|||
|
||||
on("config/addGlobalRule", async (msg) => {
|
||||
try {
|
||||
await createNewGlobalRuleFile(this.ide);
|
||||
await createNewGlobalRuleFile(this.ide, msg.data?.baseFilename);
|
||||
await this.configHandler.reloadConfig(
|
||||
"Global rule created (config/addGlobalRule message)",
|
||||
);
|
||||
|
|
@ -796,6 +801,10 @@ export class Core {
|
|||
);
|
||||
});
|
||||
|
||||
on("getDiffLines", (msg) => {
|
||||
return myersDiff(msg.data.oldContent, msg.data.newContent);
|
||||
});
|
||||
|
||||
on("cancelApply", async (msg) => {
|
||||
const abortManager = ApplyAbortManager.getInstance();
|
||||
abortManager.clear(); // for now abort all streams
|
||||
|
|
@ -1093,7 +1102,7 @@ export class Core {
|
|||
|
||||
on(
|
||||
"tools/evaluatePolicy",
|
||||
async ({ data: { toolName, basePolicy, args } }) => {
|
||||
async ({ data: { toolName, basePolicy, parsedArgs, processedArgs } }) => {
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
if (!config) {
|
||||
throw new Error("Config not loaded");
|
||||
|
|
@ -1106,12 +1115,16 @@ export class Core {
|
|||
|
||||
// Extract display value for specific tools
|
||||
let displayValue: string | undefined;
|
||||
if (toolName === "runTerminalCommand" && args.command) {
|
||||
displayValue = args.command as string;
|
||||
if (toolName === "runTerminalCommand" && parsedArgs.command) {
|
||||
displayValue = parsedArgs.command as string;
|
||||
}
|
||||
|
||||
if (tool.evaluateToolCallPolicy) {
|
||||
const evaluatedPolicy = tool.evaluateToolCallPolicy(basePolicy, args);
|
||||
const evaluatedPolicy = tool.evaluateToolCallPolicy(
|
||||
basePolicy,
|
||||
parsedArgs,
|
||||
processedArgs,
|
||||
);
|
||||
return { policy: evaluatedPolicy, displayValue };
|
||||
}
|
||||
return { policy: basePolicy, displayValue };
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ const RULES = [
|
|||
`Whenever any part of the code is the same as before, you may simply indicate this with a comment that says "${UNCHANGED_CODE}" instead of rewriting.`,
|
||||
"You must keep at least one line above and below from the original code, so that we can identify what the previous code was.",
|
||||
`Do not place miscellaneous "${UNCHANGED_CODE}" comments at the top or bottom of the file when there is nothing to replace them.`,
|
||||
"Leave existing comments in place unless changes require modifying them.",
|
||||
// `You should write "${UNCHANGED_CODE}" at least for each function that is unchanged, rather than grouping them into a single comment.`,
|
||||
// `You should lean toward using a smaller number of these comments rather than rewriting it for every function if all of them are unchanged.`,
|
||||
// `You may do this for imports as well if needed.`,
|
||||
|
|
@ -21,7 +22,7 @@ const RULES = [
|
|||
"The code should always be syntactically valid, even with the comments.",
|
||||
];
|
||||
|
||||
function claude35SonnetLazyApplyPrompt(
|
||||
function claudeSonnetLazyApplyPrompt(
|
||||
...args: Parameters<LazyApplyPrompt>
|
||||
): ReturnType<LazyApplyPrompt> {
|
||||
const userContent = dedent`
|
||||
|
|
@ -55,7 +56,7 @@ export function lazyApplyPromptForModel(
|
|||
provider: string,
|
||||
): LazyApplyPrompt | undefined {
|
||||
if (model.includes("sonnet")) {
|
||||
return claude35SonnetLazyApplyPrompt;
|
||||
return claudeSonnetLazyApplyPrompt;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
|
|
|
|||
31
core/index.d.ts
vendored
31
core/index.d.ts
vendored
|
|
@ -272,6 +272,10 @@ export interface Session {
|
|||
title: string;
|
||||
workspaceDirectory: string;
|
||||
history: ChatHistoryItem[];
|
||||
/** Optional: per-session UI mode (chat/agent/plan/background) */
|
||||
mode?: MessageModes;
|
||||
/** Optional: title of the selected chat model for this session */
|
||||
chatModelTitle?: string | null;
|
||||
}
|
||||
|
||||
export interface BaseSessionMetadata {
|
||||
|
|
@ -359,11 +363,15 @@ export interface ToolResultChatMessage {
|
|||
role: "tool";
|
||||
content: string;
|
||||
toolCallId: string;
|
||||
/** Arbitrary per-message metadata (IDs, provider-specific info, etc.) */
|
||||
metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface UserChatMessage {
|
||||
role: "user";
|
||||
content: MessageContent;
|
||||
/** Arbitrary per-message metadata (IDs, provider-specific info, etc.) */
|
||||
metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface ThinkingChatMessage {
|
||||
|
|
@ -372,6 +380,12 @@ export interface ThinkingChatMessage {
|
|||
signature?: string;
|
||||
redactedThinking?: string;
|
||||
toolCalls?: ToolCallDelta[];
|
||||
reasoning_details?: {
|
||||
signature?: string;
|
||||
[key: string]: any;
|
||||
}[];
|
||||
/** Arbitrary per-message metadata (IDs, provider-specific info, etc.) */
|
||||
metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -400,11 +414,15 @@ export interface AssistantChatMessage {
|
|||
content: MessageContent;
|
||||
toolCalls?: ToolCallDelta[];
|
||||
usage?: Usage;
|
||||
/** Arbitrary per-message metadata (IDs, provider-specific info, etc.) */
|
||||
metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface SystemChatMessage {
|
||||
role: "system";
|
||||
content: string;
|
||||
/** Arbitrary per-message metadata (IDs, provider-specific info, etc.) */
|
||||
metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export type ChatMessage =
|
||||
|
|
@ -499,7 +517,7 @@ export interface ChatHistoryItem {
|
|||
toolCallStates?: ToolCallState[];
|
||||
isGatheringContext?: boolean;
|
||||
reasoning?: Reasoning;
|
||||
appliedRules?: RuleWithSource[];
|
||||
appliedRules?: RuleMetadata[];
|
||||
conversationSummary?: string;
|
||||
}
|
||||
|
||||
|
|
@ -1110,6 +1128,7 @@ export interface Tool {
|
|||
evaluateToolCallPolicy?: (
|
||||
basePolicy: ToolPolicy,
|
||||
parsedArgs: Record<string, unknown>,
|
||||
processedArgs?: Record<string, unknown>,
|
||||
) => ToolPolicy;
|
||||
}
|
||||
|
||||
|
|
@ -1389,7 +1408,6 @@ export interface ContinueUIConfig {
|
|||
showChatScrollbar?: boolean;
|
||||
codeWrap?: boolean;
|
||||
showSessionTabs?: boolean;
|
||||
autoAcceptEditToolDiffs?: boolean;
|
||||
continueAfterToolRejection?: boolean;
|
||||
}
|
||||
|
||||
|
|
@ -1789,7 +1807,7 @@ export interface BrowserSerializedContinueConfig {
|
|||
experimental?: ExperimentalConfig;
|
||||
analytics?: AnalyticsConfig;
|
||||
docs?: SiteIndexingConfig[];
|
||||
tools: Omit<Tool, "preprocessArgs", "evaluatePolicy">[];
|
||||
tools: Omit<Tool, "preprocessArgs", "evaluateToolCallPolicy">[];
|
||||
mcpServerStatuses: MCPServerStatus[];
|
||||
rules: RuleWithSource[];
|
||||
usePlatform: boolean;
|
||||
|
|
@ -1854,18 +1872,21 @@ export type RuleSource =
|
|||
| ".continuerules"
|
||||
| "agentFile";
|
||||
|
||||
export interface RuleWithSource {
|
||||
export interface RuleMetadata {
|
||||
name?: string;
|
||||
slug?: string;
|
||||
source: RuleSource;
|
||||
globs?: string | string[];
|
||||
regex?: string | string[];
|
||||
rule: string;
|
||||
description?: string;
|
||||
sourceFile?: string;
|
||||
alwaysApply?: boolean;
|
||||
invokable?: boolean;
|
||||
}
|
||||
export interface RuleWithSource extends RuleMetadata {
|
||||
rule: string;
|
||||
}
|
||||
|
||||
export interface CompleteOnboardingPayload {
|
||||
mode: OnboardingModes;
|
||||
provider?: string;
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ const TIMEOUT_MS = 1_000_000_000;
|
|||
// so that we don't delete the Chromium install between tests
|
||||
ChromiumInstaller.PCR_CONFIG = { downloadPath: os.tmpdir() };
|
||||
|
||||
describe("DocsCrawler", () => {
|
||||
describe.skip("DocsCrawler", () => {
|
||||
let config: ContinueConfig;
|
||||
let mockIde: FileSystemIde;
|
||||
let chromiumInstaller: ChromiumInstaller;
|
||||
|
|
|
|||
|
|
@ -63,6 +63,47 @@ const PROVIDER_HANDLES_TEMPLATING: string[] = [
|
|||
"watsonx",
|
||||
"nebius",
|
||||
"relace",
|
||||
"openrouter",
|
||||
"deepseek",
|
||||
"xAI",
|
||||
"groq",
|
||||
"gemini",
|
||||
"docker",
|
||||
// TODO add these, change to inverted logic so only the ones that need templating are hardcoded
|
||||
// Asksage.ts
|
||||
// Azure.ts
|
||||
// BedrockImport.ts
|
||||
// Cerebras.ts
|
||||
// Cloudflare.ts
|
||||
// CometAPI.ts
|
||||
// CustomLLM.ts
|
||||
// DeepInfra.ts
|
||||
// Fireworks.ts
|
||||
// Flowise.ts
|
||||
// FunctionNetwork.ts
|
||||
// HuggingFaceInferenceAPI.ts
|
||||
// HuggingFaceTEI.ts
|
||||
// HuggingFaceTGI.ts
|
||||
// Inception.ts
|
||||
// Kindo.ts
|
||||
// LlamaCpp.ts
|
||||
// LlamaStack.ts
|
||||
// Llamafile.ts
|
||||
// Mock.ts
|
||||
// Moonshot.ts
|
||||
// NCompass.ts
|
||||
// OVHcloud.ts
|
||||
// Replicate.ts
|
||||
// Scaleway.ts
|
||||
// SiliconFlow.ts
|
||||
// TARS.ts
|
||||
// Test.ts
|
||||
// TextGenWebUI.ts
|
||||
// TransformersJsEmbeddingsProvider.ts
|
||||
// Venice.ts
|
||||
// Vllm.ts
|
||||
// Voyage.ts
|
||||
// etc
|
||||
];
|
||||
|
||||
const PROVIDER_SUPPORTS_IMAGES: string[] = [
|
||||
|
|
@ -105,6 +146,8 @@ const MODEL_SUPPORTS_IMAGES: RegExp[] = [
|
|||
/\bgemma-?3(?!n)/, // gemma3 supports vision, but gemma3n doesn't!
|
||||
/\b(pali|med)gemma/,
|
||||
/qwen(.*)vl/,
|
||||
/mistral-small/,
|
||||
/mistral-medium/,
|
||||
];
|
||||
|
||||
function modelSupportsImages(
|
||||
|
|
@ -142,16 +185,29 @@ function modelSupportsReasoning(
|
|||
if (!model) {
|
||||
return false;
|
||||
}
|
||||
if ("anthropic" === model.underlyingProviderName) {
|
||||
if (model.completionOptions?.reasoning !== undefined) {
|
||||
// Reasoning support is forced at the config level. Model might not necessarily support it though!
|
||||
return model.completionOptions.reasoning;
|
||||
}
|
||||
// Seems our current way of disabling reasoning is not working for grok code so results in useless lightbulb
|
||||
// if (model.model.includes("grok-code")) {
|
||||
// return true;
|
||||
// }
|
||||
// do not turn reasoning on by default for claude 3 models
|
||||
if (
|
||||
model.model.includes("claude") &&
|
||||
!model.model.includes("-3-") &&
|
||||
!model.model.includes("-3.5-")
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
if (model.model.includes("command-a-reasoning")) {
|
||||
return true;
|
||||
}
|
||||
if (model.model.includes("deepseek-r")) {
|
||||
return true;
|
||||
}
|
||||
if (model.completionOptions?.reasoning) {
|
||||
// Reasoning support is forced at the config level. Model might not necessarily support it though!
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -63,7 +63,7 @@ export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\
|
|||
<important_rules>
|
||||
You are in agent mode.
|
||||
|
||||
If you need to use multiple tools, you can call multiple read only tools simultaneously.
|
||||
If you need to use multiple tools, you can call multiple read-only tools simultaneously.
|
||||
|
||||
${CODEBLOCK_FORMATTING_INSTRUCTIONS}
|
||||
|
||||
|
|
|
|||
|
|
@ -87,6 +87,9 @@ type InteractionStatus = "in_progress" | "success" | "error" | "cancelled";
|
|||
export abstract class BaseLLM implements ILLM {
|
||||
static providerName: string;
|
||||
static defaultOptions: Partial<LLMOptions> | undefined = undefined;
|
||||
// Provider capabilities (overridable by subclasses)
|
||||
protected supportsReasoningField: boolean = false;
|
||||
protected supportsReasoningDetailsField: boolean = false;
|
||||
|
||||
get providerName(): string {
|
||||
return (this.constructor as typeof BaseLLM).providerName;
|
||||
|
|
@ -993,6 +996,114 @@ export abstract class BaseLLM implements ILLM {
|
|||
return completionOptions;
|
||||
}
|
||||
|
||||
// Update the processChatChunk method:
|
||||
private processChatChunk(
|
||||
chunk: ChatMessage,
|
||||
interaction: ILLMInteractionLog | undefined,
|
||||
): {
|
||||
completion: string[];
|
||||
thinking: string[];
|
||||
usage: Usage | null;
|
||||
chunk: ChatMessage;
|
||||
} {
|
||||
const completion: string[] = [];
|
||||
const thinking: string[] = [];
|
||||
let usage: Usage | null = null;
|
||||
|
||||
if (chunk.role === "assistant") {
|
||||
completion.push(this._formatChatMessage(chunk));
|
||||
} else if (chunk.role === "thinking" && typeof chunk.content === "string") {
|
||||
thinking.push(chunk.content);
|
||||
}
|
||||
|
||||
interaction?.logItem({
|
||||
kind: "message",
|
||||
message: chunk,
|
||||
});
|
||||
|
||||
if (chunk.role === "assistant" && chunk.usage) {
|
||||
usage = chunk.usage;
|
||||
}
|
||||
|
||||
return {
|
||||
completion,
|
||||
thinking,
|
||||
usage,
|
||||
chunk,
|
||||
};
|
||||
}
|
||||
|
||||
private canUseOpenAIResponses(options: CompletionOptions): boolean {
|
||||
return (
|
||||
this.providerName === "openai" &&
|
||||
typeof (this as any)._streamResponses === "function" &&
|
||||
(this as any).isOSeriesOrGpt5Model(options.model)
|
||||
);
|
||||
}
|
||||
|
||||
private async *openAIAdapterStream(
|
||||
body: ChatCompletionCreateParams,
|
||||
signal: AbortSignal,
|
||||
onCitations: (c: string[]) => void,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
const stream = this.openaiAdapter!.chatCompletionStream(
|
||||
{ ...body, stream: true },
|
||||
signal,
|
||||
);
|
||||
for await (const chunk of stream) {
|
||||
if (!this.lastRequestId && typeof (chunk as any).id === "string") {
|
||||
this.lastRequestId = (chunk as any).id;
|
||||
}
|
||||
const chatChunk = fromChatCompletionChunk(chunk as any);
|
||||
if (chatChunk) {
|
||||
yield chatChunk;
|
||||
}
|
||||
if ((chunk as any).citations && Array.isArray((chunk as any).citations)) {
|
||||
onCitations((chunk as any).citations);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async *openAIAdapterNonStream(
|
||||
body: ChatCompletionCreateParams,
|
||||
signal: AbortSignal,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
const response = await this.openaiAdapter!.chatCompletionNonStream(
|
||||
{ ...body, stream: false },
|
||||
signal,
|
||||
);
|
||||
this.lastRequestId = response.id ?? this.lastRequestId;
|
||||
const messages = fromChatResponse(response as any);
|
||||
for (const msg of messages) {
|
||||
yield msg;
|
||||
}
|
||||
}
|
||||
|
||||
private async *responsesStream(
|
||||
messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
const g = (this as any)._streamResponses(
|
||||
messages,
|
||||
signal,
|
||||
options,
|
||||
) as AsyncGenerator<ChatMessage>;
|
||||
for await (const m of g) {
|
||||
yield m;
|
||||
}
|
||||
}
|
||||
|
||||
private async *responsesNonStream(
|
||||
messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
const msg = await (this as any)._responses(messages, signal, options);
|
||||
yield msg as ChatMessage;
|
||||
}
|
||||
|
||||
// Update the streamChat method:
|
||||
async *streamChat(
|
||||
_messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
|
|
@ -1025,9 +1136,12 @@ export abstract class BaseLLM implements ILLM {
|
|||
messages = compiledChatMessages;
|
||||
}
|
||||
|
||||
const messagesCopy = [...messages]; // templateMessages may modify messages.
|
||||
|
||||
const prompt = this.templateMessages
|
||||
? this.templateMessages(messages)
|
||||
: this._formatChatMessages(messages);
|
||||
? this.templateMessages(messagesCopy)
|
||||
: this._formatChatMessages(messagesCopy);
|
||||
|
||||
if (logEnabled) {
|
||||
interaction?.logItem({
|
||||
kind: "startChat",
|
||||
|
|
@ -1040,9 +1154,14 @@ export abstract class BaseLLM implements ILLM {
|
|||
}
|
||||
}
|
||||
|
||||
let thinking = "";
|
||||
let completion = "";
|
||||
// Performance optimization: Use arrays instead of string concatenation.
|
||||
// String concatenation in loops creates new string objects for each operation,
|
||||
// which is O(n²) for n chunks. Arrays with push() are O(1) per operation,
|
||||
// making the total O(n). We join() only once at the end.
|
||||
const thinking: string[] = [];
|
||||
const completion: string[] = [];
|
||||
let usage: Usage | undefined = undefined;
|
||||
let citations: null | string[] = null;
|
||||
|
||||
try {
|
||||
if (this.templateMessages) {
|
||||
|
|
@ -1051,7 +1170,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
signal,
|
||||
completionOptions,
|
||||
)) {
|
||||
completion += chunk;
|
||||
completion.push(chunk);
|
||||
interaction?.logItem({
|
||||
kind: "chunk",
|
||||
chunk: chunk,
|
||||
|
|
@ -1060,80 +1179,99 @@ export abstract class BaseLLM implements ILLM {
|
|||
}
|
||||
} else {
|
||||
if (this.shouldUseOpenAIAdapter("streamChat") && this.openaiAdapter) {
|
||||
let body = toChatBody(messages, completionOptions);
|
||||
let body = toChatBody(messages, completionOptions, {
|
||||
includeReasoningField: this.supportsReasoningField,
|
||||
includeReasoningDetailsField: this.supportsReasoningDetailsField,
|
||||
});
|
||||
body = this.modifyChatBody(body);
|
||||
|
||||
if (completionOptions.stream === false) {
|
||||
// Stream false
|
||||
const response = await this.openaiAdapter.chatCompletionNonStream(
|
||||
{ ...body, stream: false },
|
||||
signal,
|
||||
);
|
||||
this.lastRequestId = response.id ?? this.lastRequestId;
|
||||
const msg = fromChatResponse(response);
|
||||
yield msg;
|
||||
completion = this._formatChatMessage(msg);
|
||||
if (logEnabled) {
|
||||
interaction?.logItem({
|
||||
kind: "message",
|
||||
message: msg,
|
||||
kind: "startChat",
|
||||
messages,
|
||||
options: {
|
||||
...completionOptions,
|
||||
requestBody: body,
|
||||
} as CompletionOptions,
|
||||
provider: this.providerName,
|
||||
});
|
||||
} else {
|
||||
// Stream true
|
||||
const stream = this.openaiAdapter.chatCompletionStream(
|
||||
{
|
||||
...body,
|
||||
stream: true,
|
||||
},
|
||||
signal,
|
||||
);
|
||||
for await (const chunk of stream) {
|
||||
if (
|
||||
!this.lastRequestId &&
|
||||
typeof (chunk as any).id === "string"
|
||||
) {
|
||||
this.lastRequestId = (chunk as any).id;
|
||||
}
|
||||
const result = fromChatCompletionChunk(chunk);
|
||||
if (result) {
|
||||
completion += this._formatChatMessage(result);
|
||||
interaction?.logItem({
|
||||
kind: "message",
|
||||
message: result,
|
||||
});
|
||||
yield result;
|
||||
}
|
||||
if (this.llmRequestHook) {
|
||||
this.llmRequestHook(completionOptions.model, prompt);
|
||||
}
|
||||
}
|
||||
|
||||
const canUseResponses = this.canUseOpenAIResponses(completionOptions);
|
||||
const useStream = completionOptions.stream !== false;
|
||||
|
||||
let iterable: AsyncIterable<ChatMessage>;
|
||||
if (canUseResponses) {
|
||||
iterable = useStream
|
||||
? this.responsesStream(messages, signal, completionOptions)
|
||||
: this.responsesNonStream(messages, signal, completionOptions);
|
||||
} else {
|
||||
iterable = useStream
|
||||
? this.openAIAdapterStream(body, signal, (c) => {
|
||||
if (!citations) {
|
||||
citations = c;
|
||||
}
|
||||
})
|
||||
: this.openAIAdapterNonStream(body, signal);
|
||||
}
|
||||
|
||||
for await (const chunk of iterable) {
|
||||
const result = this.processChatChunk(chunk, interaction);
|
||||
completion.push(...result.completion);
|
||||
thinking.push(...result.thinking);
|
||||
if (result.usage !== null) {
|
||||
usage = result.usage;
|
||||
}
|
||||
yield result.chunk;
|
||||
}
|
||||
} else {
|
||||
if (logEnabled) {
|
||||
interaction?.logItem({
|
||||
kind: "startChat",
|
||||
messages,
|
||||
options: completionOptions,
|
||||
provider: this.providerName,
|
||||
});
|
||||
if (this.llmRequestHook) {
|
||||
this.llmRequestHook(completionOptions.model, prompt);
|
||||
}
|
||||
}
|
||||
|
||||
for await (const chunk of this._streamChat(
|
||||
messages,
|
||||
signal,
|
||||
completionOptions,
|
||||
)) {
|
||||
if (chunk.role === "assistant") {
|
||||
completion += this._formatChatMessage(chunk);
|
||||
} else if (chunk.role === "thinking") {
|
||||
thinking += chunk.content;
|
||||
const result = this.processChatChunk(chunk, interaction);
|
||||
completion.push(...result.completion);
|
||||
thinking.push(...result.thinking);
|
||||
if (result.usage !== null) {
|
||||
usage = result.usage;
|
||||
}
|
||||
|
||||
interaction?.logItem({
|
||||
kind: "message",
|
||||
message: chunk,
|
||||
});
|
||||
|
||||
if (chunk.role === "assistant" && chunk.usage) {
|
||||
usage = chunk.usage;
|
||||
}
|
||||
|
||||
yield chunk;
|
||||
yield result.chunk;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (citations) {
|
||||
const cits = citations as string[];
|
||||
interaction?.logItem({
|
||||
kind: "message",
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: `\n\nCitations:\n${cits.map((c: string, i: number) => `${i + 1}: ${c}`).join("\n")}\n\n`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
status = this._logEnd(
|
||||
completionOptions.model,
|
||||
prompt,
|
||||
completion,
|
||||
thinking,
|
||||
completion.join(""),
|
||||
thinking.join(""),
|
||||
interaction,
|
||||
usage,
|
||||
);
|
||||
|
|
@ -1151,8 +1289,8 @@ export abstract class BaseLLM implements ILLM {
|
|||
status = this._logEnd(
|
||||
completionOptions.model,
|
||||
prompt,
|
||||
completion,
|
||||
thinking,
|
||||
completion.join(""),
|
||||
thinking.join(""),
|
||||
interaction,
|
||||
usage,
|
||||
e,
|
||||
|
|
@ -1163,7 +1301,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
this._logEnd(
|
||||
completionOptions.model,
|
||||
prompt,
|
||||
completion,
|
||||
completion.join(""),
|
||||
undefined,
|
||||
interaction,
|
||||
usage,
|
||||
|
|
@ -1172,20 +1310,20 @@ export abstract class BaseLLM implements ILLM {
|
|||
}
|
||||
}
|
||||
/*
|
||||
TODO: According to: https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking
|
||||
During tool use, you must pass thinking and redacted_thinking blocks back to the API,
|
||||
and you must include the complete unmodified block back to the API. This is critical
|
||||
for maintaining the model's reasoning flow and conversation integrity.
|
||||
TODO: According to: https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking
|
||||
During tool use, you must pass thinking and redacted_thinking blocks back to the API,
|
||||
and you must include the complete unmodified block back to the API. This is critical
|
||||
for maintaining the model's reasoning flow and conversation integrity.
|
||||
|
||||
On the other hand, adding thinking and redacted_thinking blocks are ignored on subsequent
|
||||
requests when not using tools, so it's the simplest option to always add to history.
|
||||
*/
|
||||
On the other hand, adding thinking and redacted_thinking blocks are ignored on subsequent
|
||||
requests when not using tools, so it's the simplest option to always add to history.
|
||||
*/
|
||||
|
||||
return {
|
||||
modelTitle: this.title ?? completionOptions.model,
|
||||
modelProvider: this.underlyingProviderName,
|
||||
prompt,
|
||||
completion,
|
||||
completion: completion.join(""),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ import {
|
|||
} from "../../index.js";
|
||||
import { safeParseToolCallArgs } from "../../tools/parseArgs.js";
|
||||
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
|
||||
import { extractBase64FromDataUrl } from "../../util/url.js";
|
||||
import { DEFAULT_REASONING_TOKENS } from "../constants.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
|
||||
|
|
@ -87,30 +88,44 @@ class Anthropic extends BaseLLM {
|
|||
private convertMessageContentToBlocks(
|
||||
content: MessageContent,
|
||||
): ContentBlockParam[] {
|
||||
const parts: ContentBlockParam[] = [];
|
||||
if (typeof content === "string") {
|
||||
return [
|
||||
{
|
||||
if (content) {
|
||||
parts.push({
|
||||
type: "text",
|
||||
text: content,
|
||||
},
|
||||
];
|
||||
}
|
||||
return content.map((part) => {
|
||||
if (part.type === "text") {
|
||||
return {
|
||||
type: "text",
|
||||
text: part.text,
|
||||
};
|
||||
});
|
||||
}
|
||||
return {
|
||||
type: "image",
|
||||
source: {
|
||||
type: "base64",
|
||||
media_type: getAnthropicMediaTypeFromDataUrl(part.imageUrl.url),
|
||||
data: part.imageUrl.url.split(",")[1],
|
||||
},
|
||||
};
|
||||
});
|
||||
} else {
|
||||
for (const part of content) {
|
||||
if (part.type === "text") {
|
||||
if (part.text) {
|
||||
parts.push({
|
||||
type: "text",
|
||||
text: part.text,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
const base64Data = extractBase64FromDataUrl(part.imageUrl.url);
|
||||
if (base64Data) {
|
||||
parts.push({
|
||||
type: "image",
|
||||
source: {
|
||||
type: "base64",
|
||||
media_type: getAnthropicMediaTypeFromDataUrl(part.imageUrl.url),
|
||||
data: base64Data,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
console.warn(
|
||||
"Anthropic: skipping image with invalid data URL format",
|
||||
part.imageUrl.url,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
private convertToolCallsToBlocks(
|
||||
|
|
@ -152,20 +167,30 @@ class Anthropic extends BaseLLM {
|
|||
},
|
||||
];
|
||||
}
|
||||
// Strip thinking that has no signature
|
||||
const signature = message.signature;
|
||||
if (!signature) {
|
||||
return [];
|
||||
}
|
||||
if (typeof message.content === "string") {
|
||||
if (!message.content) {
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
{
|
||||
type: "thinking",
|
||||
thinking: message.content,
|
||||
signature: message.signature ?? "", // TODO - unsafe signature
|
||||
signature,
|
||||
},
|
||||
];
|
||||
}
|
||||
const textParts = message.content.filter((p) => p.type === "text");
|
||||
const textParts = message.content
|
||||
.filter((p) => p.type === "text")
|
||||
.filter((p) => !!p.text);
|
||||
return textParts.map((part) => ({
|
||||
type: "thinking",
|
||||
thinking: part.text,
|
||||
signature: message.signature ?? "", // TODO - unsafe signature
|
||||
signature,
|
||||
}));
|
||||
case "assistant":
|
||||
const blocks: ContentBlockParam[] = this.convertMessageContentToBlocks(
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ 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 { parseDataUrl } from "../../util/url.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { PROVIDER_TOOL_SUPPORT } from "../toolSupport.js";
|
||||
import { getSecureID } from "../utils/getSecureID.js";
|
||||
|
|
@ -545,8 +546,9 @@ class Bedrock extends BaseLLM {
|
|||
if (part.type === "text") {
|
||||
blocks.push({ text: part.text });
|
||||
} else if (part.type === "imageUrl" && part.imageUrl) {
|
||||
try {
|
||||
const [mimeType, base64Data] = part.imageUrl.url.split(",");
|
||||
const parsed = parseDataUrl(part.imageUrl.url);
|
||||
if (parsed) {
|
||||
const { mimeType, base64Data } = parsed;
|
||||
const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg";
|
||||
if (
|
||||
format === ImageFormat.JPEG ||
|
||||
|
|
@ -568,8 +570,8 @@ class Bedrock extends BaseLLM {
|
|||
part,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("Bedrock: failed to process image part", error, part);
|
||||
} else {
|
||||
console.warn("Bedrock: failed to process image part", part);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,10 +4,10 @@ import {
|
|||
Chunk,
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
MessageContent,
|
||||
} from "../../index.js";
|
||||
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import { DEFAULT_REASONING_TOKENS } from "../constants.js";
|
||||
|
||||
class Cohere extends BaseLLM {
|
||||
static providerName = "cohere";
|
||||
|
|
@ -19,7 +19,6 @@ class Cohere extends BaseLLM {
|
|||
|
||||
private _convertMessages(msgs: ChatMessage[]): any[] {
|
||||
const messages = [];
|
||||
let lastToolPlan: MessageContent | undefined;
|
||||
for (const m of msgs) {
|
||||
if (!m.content) {
|
||||
continue;
|
||||
|
|
@ -48,36 +47,48 @@ class Cohere extends BaseLLM {
|
|||
});
|
||||
break;
|
||||
case "thinking":
|
||||
lastToolPlan = m.content;
|
||||
messages.push({
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
type: "thinking",
|
||||
thinking: m.content,
|
||||
},
|
||||
],
|
||||
});
|
||||
break;
|
||||
case "assistant":
|
||||
if (m.toolCalls) {
|
||||
if (!lastToolPlan) {
|
||||
throw new Error("No tool plan found");
|
||||
}
|
||||
messages.push({
|
||||
let msg: any;
|
||||
if (messages.at(-1)?.content[0]?.thinking) {
|
||||
msg = messages.pop();
|
||||
} else {
|
||||
msg = {
|
||||
role: m.role,
|
||||
tool_calls: m.toolCalls.map((toolCall) => ({
|
||||
id: toolCall.id,
|
||||
type: "function",
|
||||
function: {
|
||||
name: toolCall.function?.name,
|
||||
arguments: toolCall.function?.arguments,
|
||||
},
|
||||
})),
|
||||
// Ideally the tool plan would be in this message, but it is
|
||||
// split in another, usually the previous, this one's content is
|
||||
// a space.
|
||||
// tool_plan: m.content,
|
||||
tool_plan: lastToolPlan,
|
||||
});
|
||||
lastToolPlan = undefined;
|
||||
break;
|
||||
content: [],
|
||||
};
|
||||
}
|
||||
messages.push({
|
||||
role: m.role,
|
||||
content: m.content,
|
||||
});
|
||||
|
||||
if (m.toolCalls) {
|
||||
msg.tool_calls = m.toolCalls.map((toolCall) => ({
|
||||
id: toolCall.id,
|
||||
type: "function",
|
||||
function: {
|
||||
name: toolCall.function?.name,
|
||||
arguments: toolCall.function?.arguments,
|
||||
},
|
||||
}));
|
||||
} else {
|
||||
if (typeof m.content === "string") {
|
||||
msg.content.push({
|
||||
type: "text",
|
||||
text: m.content,
|
||||
});
|
||||
} else {
|
||||
msg.content.push(...m.content);
|
||||
}
|
||||
}
|
||||
|
||||
messages.push(msg);
|
||||
break;
|
||||
case "system":
|
||||
messages.push({
|
||||
|
|
@ -110,6 +121,15 @@ class Cohere extends BaseLLM {
|
|||
stop_sequences: options.stop?.slice(0, Cohere.maxStopSequences),
|
||||
frequency_penalty: options.frequencyPenalty,
|
||||
presence_penalty: options.presencePenalty,
|
||||
thinking: options.reasoning
|
||||
? {
|
||||
type: "enabled" as const,
|
||||
token_budget:
|
||||
options.reasoningBudgetTokens ?? DEFAULT_REASONING_TOKENS,
|
||||
}
|
||||
: // Reasoning is enabled by default for models that support it.
|
||||
// https://docs.cohere.com/reference/chat-stream#request.body.thinking
|
||||
{ type: "disabled" as const },
|
||||
tools: options.tools?.map((tool) => ({
|
||||
type: "function",
|
||||
function: {
|
||||
|
|
@ -159,14 +179,17 @@ class Cohere extends BaseLLM {
|
|||
|
||||
if (options.stream === false) {
|
||||
const data = await resp.json();
|
||||
for (const content of data.message.content) {
|
||||
if (content.thinking) {
|
||||
yield { role: "thinking", content: content.thinking };
|
||||
continue;
|
||||
}
|
||||
yield { role: "assistant", content: content.text };
|
||||
}
|
||||
if (data.message.tool_calls) {
|
||||
yield {
|
||||
// Use the "thinking" role for `tool_plan`, since there is no such
|
||||
// role in the Cohere API at the moment and it is a "a
|
||||
// chain-of-thought style reflection".
|
||||
role: "thinking",
|
||||
content: data.message.tool_plan,
|
||||
};
|
||||
if (data.message.tool_plan) {
|
||||
yield { role: "thinking", content: data.message.tool_plan };
|
||||
}
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
|
|
@ -181,7 +204,6 @@ class Cohere extends BaseLLM {
|
|||
};
|
||||
return;
|
||||
}
|
||||
yield { role: "assistant", content: data.message.content[0].text };
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -192,6 +214,13 @@ class Cohere extends BaseLLM {
|
|||
switch (value.type) {
|
||||
// https://docs.cohere.com/v2/docs/streaming#content-delta
|
||||
case "content-delta":
|
||||
if (value.delta.message.content.thinking) {
|
||||
yield {
|
||||
role: "thinking",
|
||||
content: value.delta.message.content.thinking,
|
||||
};
|
||||
break;
|
||||
}
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: value.delta.message.content.text,
|
||||
|
|
@ -199,9 +228,6 @@ class Cohere extends BaseLLM {
|
|||
break;
|
||||
// https://docs.cohere.com/reference/chat-stream#request.body.messages.assistant.tool_plan
|
||||
case "tool-plan-delta":
|
||||
// Use the "thinking" role for `tool_plan`, since there is no such
|
||||
// role in the Cohere API at the moment and it is a "a
|
||||
// chain-of-thought style reflection".
|
||||
yield {
|
||||
role: "thinking",
|
||||
content: value.delta.message.tool_plan,
|
||||
|
|
|
|||
845
core/llm/llms/Cohere.vitest.ts
Normal file
845
core/llm/llms/Cohere.vitest.ts
Normal file
|
|
@ -0,0 +1,845 @@
|
|||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { ILLM } from "../../index.js";
|
||||
import Cohere from "./Cohere.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("Cohere", () => {
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
test("streamChat should send a valid request", async () => {
|
||||
const cohere = new Cohere({
|
||||
apiKey: "test-api-key",
|
||||
model: "command-a-03-2025",
|
||||
apiBase: "https://api.cohere.com/v2/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: cohere,
|
||||
methodToTest: "streamChat",
|
||||
params: [
|
||||
[{ role: "user", content: "hello" }],
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.cohere.com/v2/chat",
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: "Bearer test-api-key",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: {
|
||||
model: "command-a-03-2025",
|
||||
max_tokens: 8192,
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
stream: true,
|
||||
thinking: { type: "disabled" },
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"id":"94e3907b-d214-475e-a53f-ae81c76b6e43","type":"message-start","delta":{"message":{"role":"assistant","content":[],"tool_plan":"","tool_calls":[],"citations":[]}}}',
|
||||
'{"type":"content-start","index":0,"delta":{"message":{"content":{"type":"text","text":""}}}}',
|
||||
'{"type":"content-delta","index":0,"delta":{"message":{"content":{"text":"Hello!"}}}}',
|
||||
'{"type":"content-delta","index":0,"delta":{"message":{"content":{"text":" How can I help you today?"}}}}',
|
||||
'{"type":"content-end","index":0}',
|
||||
'{"type":"message-end","delta":{"finish_reason":"COMPLETE","usage":{"billed_units":{"input_tokens":1,"output_tokens":9},"tokens":{"input_tokens":496,"output_tokens":11},"cached_tokens":448}}}',
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("streamChat should send a valid request with tool calls messages", async () => {
|
||||
const cohere = new Cohere({
|
||||
apiKey: "test-api-key",
|
||||
model: "command-a-03-2025",
|
||||
apiBase: "https://api.cohere.com/v2/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: cohere,
|
||||
methodToTest: "streamChat",
|
||||
params: [
|
||||
[
|
||||
{ role: "user", content: "What's the weather in New York?" },
|
||||
{
|
||||
role: "thinking",
|
||||
content: "I will look up the weather in New York",
|
||||
},
|
||||
{
|
||||
role: "assistant",
|
||||
content: " ",
|
||||
toolCalls: [
|
||||
{
|
||||
id: "get_weather_qm3vz6v54dmw",
|
||||
function: {
|
||||
name: "get_weather",
|
||||
arguments: '{"location": "New York"}',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: "tool",
|
||||
content: "Sunny",
|
||||
toolCallId: "get_weather_qm3vz6v54dmw",
|
||||
},
|
||||
],
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.cohere.com/v2/chat",
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: "Bearer test-api-key",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: {
|
||||
model: "command-a-03-2025",
|
||||
max_tokens: 8192,
|
||||
messages: [
|
||||
{ role: "user", content: "What's the weather in New York?" },
|
||||
{
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
type: "thinking",
|
||||
thinking: "I will look up the weather in New York",
|
||||
},
|
||||
],
|
||||
tool_calls: [
|
||||
{
|
||||
id: "get_weather_qm3vz6v54dmw",
|
||||
type: "function",
|
||||
function: {
|
||||
name: "get_weather",
|
||||
arguments: '{"location": "New York"}',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: "tool",
|
||||
content: "Sunny",
|
||||
tool_call_id: "get_weather_qm3vz6v54dmw",
|
||||
},
|
||||
],
|
||||
stream: true,
|
||||
thinking: { type: "disabled" },
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"id":"94e3907b-d214-475e-a53f-ae81c76b6e43","type":"message-start","delta":{"message":{"role":"assistant","content":[],"tool_plan":"","tool_calls":[],"citations":[]}}}',
|
||||
'{"type":"content-start","index":0,"delta":{"message":{"content":{"type":"text","text":""}}}}',
|
||||
'{"type":"content-delta","index":0,"delta":{"message":{"content":{"text":"It\'s sunny"}}}}',
|
||||
'{"type":"content-delta","index":0,"delta":{"message":{"content":{"text":" in New York."}}}}',
|
||||
'{"type":"content-end","index":1}',
|
||||
'{"type":"message-end","delta":{"finish_reason":"COMPLETE","usage":{"billed_units":{"input_tokens":11,"output_tokens":7},"tokens":{"input_tokens":600,"output_tokens":9},"cached_tokens":448}}}',
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("streamChat should send a valid request with images", async () => {
|
||||
const cohere = new Cohere({
|
||||
apiKey: "test-api-key",
|
||||
model: "command-a-vision-07-2025",
|
||||
apiBase: "https://api.cohere.com/v2/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: cohere,
|
||||
methodToTest: "streamChat",
|
||||
params: [
|
||||
[
|
||||
{
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "hello",
|
||||
},
|
||||
{
|
||||
type: "imageUrl",
|
||||
imageUrl: {
|
||||
url: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mMsKL5ZDwAFVAI9A6eNqwAAAABJRU5ErkJggg==",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.cohere.com/v2/chat",
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: "Bearer test-api-key",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: {
|
||||
model: "command-a-vision-07-2025",
|
||||
max_tokens: 8192,
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: "hello",
|
||||
},
|
||||
{
|
||||
type: "image_url",
|
||||
image_url: {
|
||||
url: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mMsKL5ZDwAFVAI9A6eNqwAAAABJRU5ErkJggg==",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
stream: true,
|
||||
thinking: { type: "disabled" },
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"id":"94e3907b-d214-475e-a53f-ae81c76b6e43","type":"message-start","delta":{"message":{"role":"assistant","content":[],"tool_plan":"","tool_calls":[],"citations":[]}}}',
|
||||
'{"type":"content-start","index":0,"delta":{"message":{"content":{"type":"text","text":""}}}}',
|
||||
'{"type":"content-delta","index":0,"delta":{"message":{"content":{"text":"Hello!"}}}}',
|
||||
'{"type":"content-delta","index":0,"delta":{"message":{"content":{"text":" How can I assist you today?"}}}}',
|
||||
'{"type":"content-end","index":0}',
|
||||
'{"type":"message-end","delta":{"finish_reason":"COMPLETE","usage":{"billed_units":{"input_tokens":260,"output_tokens":10},"tokens":{"input_tokens":497,"output_tokens":10,"image_tokens":259},"cached_tokens":480}}}',
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("streamChat should send a valid request with thinking messages", async () => {
|
||||
const cohere = new Cohere({
|
||||
apiKey: "test-api-key",
|
||||
model: "command-a-reasoning-08-2025",
|
||||
apiBase: "https://api.cohere.com/v2/",
|
||||
completionOptions: {
|
||||
model: "command-a-reasoning-08-2025",
|
||||
reasoning: true,
|
||||
},
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: cohere,
|
||||
methodToTest: "streamChat",
|
||||
params: [
|
||||
[
|
||||
{ role: "user", content: "hello" },
|
||||
{
|
||||
role: "thinking",
|
||||
content:
|
||||
'Okay, the user just said "hello". Let me figure out how to respond. Since they\'re greeting me, I should greet them back.',
|
||||
},
|
||||
{ role: "assistant", content: "Hello! How can I assist you today?" },
|
||||
{ role: "user", content: "hello again" },
|
||||
],
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.cohere.com/v2/chat",
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: "Bearer test-api-key",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: {
|
||||
model: "command-a-reasoning-08-2025",
|
||||
max_tokens: 32768,
|
||||
messages: [
|
||||
{ role: "user", content: "hello" },
|
||||
{
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
type: "thinking",
|
||||
thinking:
|
||||
'Okay, the user just said "hello". Let me figure out how to respond. Since they\'re greeting me, I should greet them back.',
|
||||
},
|
||||
{ type: "text", text: "Hello! How can I assist you today?" },
|
||||
],
|
||||
},
|
||||
{ role: "user", content: "hello again" },
|
||||
],
|
||||
stream: true,
|
||||
thinking: { type: "enabled", token_budget: 2048 },
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"id":"94e3907b-d214-475e-a53f-ae81c76b6e43","type":"message-start","delta":{"message":{"role":"assistant","content":[],"tool_plan":"","tool_calls":[],"citations":[]}}}',
|
||||
'{"type":"content-start","index":0,"delta":{"message":{"content":{"type":"thinking","thinking":""}}}}',
|
||||
'{"type":"content-delta","index":0,"delta":{"message":{"content":{"thinking":"Alright, the user said \"hello again\". Let me check the chat history."}}}}',
|
||||
'{"type":"content-delta","index":0,"delta":{"message":{"content":{"thinking":" The user first said \"hello\", and I\'ll keep it friendly and open-ended."}}}}',
|
||||
'{"type":"content-end","index":0}',
|
||||
'{"type":"content-start","index":1,"delta":{"message":{"content":{"type":"text","text":""}}}}',
|
||||
'{"type":"content-delta","index":1,"delta":{"message":{"content":{"text":"Hello again!"}}}}',
|
||||
'{"type":"content-delta","index":1,"delta":{"message":{"content":{"text":" It\'s nice to see you back. Is there something specific you need help with, or would you just like to chat?"}}}}',
|
||||
'{"type":"content-end","index":1}',
|
||||
'{"type":"message-end","delta":{"finish_reason":"COMPLETE","usage":{"billed_units":{"input_tokens":12,"output_tokens":138},"tokens":{"input_tokens":1437,"output_tokens":142},"cached_tokens":1344}}}',
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("chat should send a valid request", async () => {
|
||||
const cohere = new Cohere({
|
||||
apiKey: "test-api-key",
|
||||
model: "command-a-03-2025",
|
||||
apiBase: "https://api.cohere.com/v2/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: cohere,
|
||||
methodToTest: "chat",
|
||||
params: [
|
||||
[{ role: "user", content: "hello" }],
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.cohere.com/v2/chat",
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: "Bearer test-api-key",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: {
|
||||
model: "command-a-03-2025",
|
||||
max_tokens: 8192,
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
stream: true,
|
||||
thinking: { type: "disabled" },
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"id":"94e3907b-d214-475e-a53f-ae81c76b6e43","type":"message-start","delta":{"message":{"role":"assistant","content":[],"tool_plan":"","tool_calls":[],"citations":[]}}}',
|
||||
'{"type":"content-start","index":0,"delta":{"message":{"content":{"type":"text","text":""}}}}',
|
||||
'{"type":"content-delta","index":0,"delta":{"message":{"content":{"text":"Hello!"}}}}',
|
||||
'{"type":"content-delta","index":0,"delta":{"message":{"content":{"text":" How can I help you today?"}}}}',
|
||||
'{"type":"content-end","index":0}',
|
||||
'{"type":"message-end","delta":{"finish_reason":"COMPLETE","usage":{"billed_units":{"input_tokens":1,"output_tokens":9},"tokens":{"input_tokens":496,"output_tokens":11},"cached_tokens":448}}}',
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("streamComplete should send a valid request", async () => {
|
||||
const cohere = new Cohere({
|
||||
apiKey: "test-api-key",
|
||||
model: "command-a-03-2025",
|
||||
apiBase: "https://api.cohere.com/v2/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: cohere,
|
||||
methodToTest: "streamComplete",
|
||||
params: ["Complete this: Hello", new AbortController().signal],
|
||||
expectedRequest: {
|
||||
url: "https://api.cohere.com/v2/chat",
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: "Bearer test-api-key",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: {
|
||||
model: "command-a-03-2025",
|
||||
max_tokens: 8192,
|
||||
messages: [{ role: "user", content: "Complete this: Hello" }],
|
||||
stream: true,
|
||||
thinking: { type: "disabled" },
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"id":"94e3907b-d214-475e-a53f-ae81c76b6e43","type":"message-start","delta":{"message":{"role":"assistant","content":[],"tool_plan":"","tool_calls":[],"citations":[]}}}',
|
||||
'{"type":"content-start","index":0,"delta":{"message":{"content":{"type":"text","text":""}}}}',
|
||||
'{"type":"content-delta","index":0,"delta":{"message":{"content":{"text":" world!"}}}}',
|
||||
'{"type":"content-end","index":0}',
|
||||
'{"type":"message-end","delta":{"finish_reason":"COMPLETE","usage":{"billed_units":{"input_tokens":4,"output_tokens":3},"tokens":{"input_tokens":499,"output_tokens":5},"cached_tokens":448}}}',
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("complete should send a valid request", async () => {
|
||||
const cohere = new Cohere({
|
||||
apiKey: "test-api-key",
|
||||
model: "command-a-03-2025",
|
||||
apiBase: "https://api.cohere.com/v2/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: cohere,
|
||||
methodToTest: "complete",
|
||||
params: ["Complete this: Hello", new AbortController().signal],
|
||||
expectedRequest: {
|
||||
url: "https://api.cohere.com/v2/chat",
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: "Bearer test-api-key",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: {
|
||||
model: "command-a-03-2025",
|
||||
max_tokens: 8192,
|
||||
messages: [{ role: "user", content: "Complete this: Hello" }],
|
||||
stream: true,
|
||||
thinking: { type: "disabled" },
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"id":"94e3907b-d214-475e-a53f-ae81c76b6e43","type":"message-start","delta":{"message":{"role":"assistant","content":[],"tool_plan":"","tool_calls":[],"citations":[]}}}',
|
||||
'{"type":"content-start","index":0,"delta":{"message":{"content":{"type":"text","text":""}}}}',
|
||||
'{"type":"content-delta","index":0,"delta":{"message":{"content":{"text":" world!"}}}}',
|
||||
'{"type":"content-end","index":0}',
|
||||
'{"type":"message-end","delta":{"finish_reason":"COMPLETE","usage":{"billed_units":{"input_tokens":4,"output_tokens":3},"tokens":{"input_tokens":499,"output_tokens":5},"cached_tokens":448}}}',
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
describe("Different configurations", () => {
|
||||
test("should handle system message", async () => {
|
||||
const cohere = new Cohere({
|
||||
apiKey: "test-api-key",
|
||||
model: "command-a-03-2025",
|
||||
apiBase: "https://api.cohere.com/v2/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: cohere,
|
||||
methodToTest: "streamChat",
|
||||
params: [
|
||||
[
|
||||
{ role: "system", content: "You are a helpful assistant." },
|
||||
{ role: "user", content: "Hello!" },
|
||||
],
|
||||
new AbortController().signal,
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.cohere.com/v2/chat",
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: "Bearer test-api-key",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: {
|
||||
model: "command-a-03-2025",
|
||||
max_tokens: 8192,
|
||||
messages: [
|
||||
{ role: "system", content: "You are a helpful assistant." },
|
||||
{ role: "user", content: "Hello!" },
|
||||
],
|
||||
stream: true,
|
||||
thinking: { type: "disabled" },
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"id":"94e3907b-d214-475e-a53f-ae81c76b6e43","type":"message-start","delta":{"message":{"role":"assistant","content":[],"tool_plan":"","tool_calls":[],"citations":[]}}}',
|
||||
'{"type":"content-start","index":0,"delta":{"message":{"content":{"type":"text","text":""}}}}',
|
||||
'{"type":"content-delta","index":0,"delta":{"message":{"content":{"text":"Hello!"}}}}',
|
||||
'{"type":"content-delta","index":0,"delta":{"message":{"content":{"text":" How can I assist you today?"}}}}',
|
||||
'{"type":"content-end","index":0}',
|
||||
'{"type":"message-end","delta":{"finish_reason":"COMPLETE","usage":{"billed_units":{"input_tokens":10,"output_tokens":9},"tokens":{"input_tokens":539,"output_tokens":11},"cached_tokens":496}}}',
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle tool calls with tool plan (legacy)", async () => {
|
||||
const cohere = new Cohere({
|
||||
apiKey: "test-api-key",
|
||||
model: "command-a-03-2025",
|
||||
apiBase: "https://api.cohere.com/v2/",
|
||||
});
|
||||
|
||||
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: cohere,
|
||||
methodToTest: "streamChat",
|
||||
params: [
|
||||
[{ role: "user", content: "What's the weather in New York?" }],
|
||||
new AbortController().signal,
|
||||
{ tools },
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.cohere.com/v2/chat",
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: "Bearer test-api-key",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: {
|
||||
model: "command-a-03-2025",
|
||||
max_tokens: 8192,
|
||||
messages: [
|
||||
{ role: "user", content: "What's the weather in New York?" },
|
||||
],
|
||||
stream: true,
|
||||
thinking: { type: "disabled" },
|
||||
tools: [
|
||||
{
|
||||
type: "function",
|
||||
function: {
|
||||
name: "get_weather",
|
||||
description: "Get the current weather",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
location: { type: "string" },
|
||||
},
|
||||
required: ["location"],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"id":"94e3907b-d214-475e-a53f-ae81c76b6e43","type":"message-start","delta":{"message":{"role":"assistant","content":[],"tool_plan":"","tool_calls":[],"citations":[]}}}',
|
||||
'{"type":"tool-plan-delta","delta":{"message":{"tool_plan":"I will look up the weather"}}}',
|
||||
'{"type":"tool-plan-delta","delta":{"message":{"tool_plan":" in New York"}}}',
|
||||
'{"type":"tool-call-start","index":0,"delta":{"message":{"tool_calls":{"id":"get_weather_qm3vz6v54dmw","type":"function","function":{"name":"get_weather","arguments":""}}}}}',
|
||||
'{"type":"tool-call-delta","index":0,"delta":{"message":{"tool_calls":{"function":{"arguments":"{\\"location\\": \\""}}}}',
|
||||
'{"type":"tool-call-delta","index":0,"delta":{"message":{"tool_calls":{"function":{"arguments":"\\"New York\\"}"}}}}',
|
||||
'{"type":"tool-call-end","index":0}',
|
||||
'{"type":"message-end","delta":{"finish_reason":"TOOL_CALL","usage":{"billed_units":{"input_tokens":17,"output_tokens":19},"tokens":{"input_tokens":1434,"output_tokens":48},"cached_tokens":992}}}',
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle tool calls with thinking disabled", async () => {
|
||||
const cohere = new Cohere({
|
||||
apiKey: "test-api-key",
|
||||
model: "command-a-reasoning-08-2025",
|
||||
apiBase: "https://api.cohere.com/v2/",
|
||||
});
|
||||
|
||||
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: cohere,
|
||||
methodToTest: "streamChat",
|
||||
params: [
|
||||
[{ role: "user", content: "What's the weather in New York?" }],
|
||||
new AbortController().signal,
|
||||
{ tools },
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.cohere.com/v2/chat",
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: "Bearer test-api-key",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: {
|
||||
model: "command-a-reasoning-08-2025",
|
||||
max_tokens: 32768,
|
||||
messages: [
|
||||
{ role: "user", content: "What's the weather in New York?" },
|
||||
],
|
||||
stream: true,
|
||||
thinking: { type: "disabled" },
|
||||
tools: [
|
||||
{
|
||||
type: "function",
|
||||
function: {
|
||||
name: "get_weather",
|
||||
description: "Get the current weather",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
location: { type: "string" },
|
||||
},
|
||||
required: ["location"],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"id":"94e3907b-d214-475e-a53f-ae81c76b6e43","type":"message-start","delta":{"message":{"role":"assistant","content":[],"tool_plan":"","tool_calls":[],"citations":[]}}}',
|
||||
'{"type":"tool-call-start","index":0,"delta":{"message":{"tool_calls":{"id":"get_weather_qm3vz6v54dmw","type":"function","function":{"name":"get_weather","arguments":""}}}}}',
|
||||
'{"type":"tool-call-delta","index":0,"delta":{"message":{"tool_calls":{"function":{"arguments":"{\\"location\\": \\""}}}}',
|
||||
'{"type":"tool-call-delta","index":0,"delta":{"message":{"tool_calls":{"function":{"arguments":"\\"New York\\"}"}}}}',
|
||||
'{"type":"tool-call-end","index":0}',
|
||||
'{"type":"message-end","delta":{"finish_reason":"TOOL_CALL","usage":{"billed_units":{"input_tokens":17,"output_tokens":9},"tokens":{"input_tokens":1174,"output_tokens":36},"cached_tokens":0}}}',
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle tool calls with thinking enabled", async () => {
|
||||
const cohere = new Cohere({
|
||||
apiKey: "test-api-key",
|
||||
model: "command-a-reasoning-08-2025",
|
||||
apiBase: "https://api.cohere.com/v2/",
|
||||
completionOptions: {
|
||||
model: "command-a-reasoning-08-2025",
|
||||
reasoning: true,
|
||||
},
|
||||
});
|
||||
|
||||
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: cohere,
|
||||
methodToTest: "streamChat",
|
||||
params: [
|
||||
[{ role: "user", content: "What's the weather in New York?" }],
|
||||
new AbortController().signal,
|
||||
{ tools },
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.cohere.com/v2/chat",
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: "Bearer test-api-key",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: {
|
||||
model: "command-a-reasoning-08-2025",
|
||||
max_tokens: 32768,
|
||||
messages: [
|
||||
{ role: "user", content: "What's the weather in New York?" },
|
||||
],
|
||||
stream: true,
|
||||
thinking: { type: "enabled", token_budget: 2048 },
|
||||
tools: [
|
||||
{
|
||||
type: "function",
|
||||
function: {
|
||||
name: "get_weather",
|
||||
description: "Get the current weather",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
location: { type: "string" },
|
||||
},
|
||||
required: ["location"],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"id":"94e3907b-d214-475e-a53f-ae81c76b6e43","type":"message-start","delta":{"message":{"role":"assistant","content":[],"tool_plan":"","tool_calls":[],"citations":[]}}}',
|
||||
'{"type":"content-start","index":0,"delta":{"message":{"content":{"type":"thinking","thinking":""}}}}',
|
||||
'{"type":"content-delta","index":0,"delta":{"message":{"content":{"thinking":"Okay, the user is asking for the weather in New York. Let me check the available tools. There\'s a tool called get_weather that requires a location parameter. Since the user mentioned New York, I can use that as the location."}}}}',
|
||||
'{"type":"content-delta","index":0,"delta":{"message":{"content":{"thinking":" I need to call the get_weather tool with location set to \"New York\" to retrieve the current weather data. No other tools are available, so this should be the only step needed. Once I get the weather data, I can present it to the user."}}}}',
|
||||
'{"type":"content-end","index":0}',
|
||||
'{"type":"tool-call-start","index":0,"delta":{"message":{"tool_calls":{"id":"get_weather_qm3vz6v54dmw","type":"function","function":{"name":"get_weather","arguments":""}}}}}',
|
||||
'{"type":"tool-call-delta","index":0,"delta":{"message":{"tool_calls":{"function":{"arguments":"{\\"location\\": \\""}}}}',
|
||||
'{"type":"tool-call-delta","index":0,"delta":{"message":{"tool_calls":{"function":{"arguments":"\\"New York\\"}"}}}}',
|
||||
'{"type":"tool-call-end","index":0}',
|
||||
'{"type":"message-end","delta":{"finish_reason":"TOOL_CALL","usage":{"billed_units":{"input_tokens":17,"output_tokens":9},"tokens":{"input_tokens":1174,"output_tokens":36},"cached_tokens":0}}}',
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("should handle custom max tokens", async () => {
|
||||
const cohere = new Cohere({
|
||||
apiKey: "test-api-key",
|
||||
model: "command-a-03-2025",
|
||||
apiBase: "https://api.cohere.com/v2/",
|
||||
});
|
||||
|
||||
await runLlmTest({
|
||||
llm: cohere,
|
||||
methodToTest: "streamChat",
|
||||
params: [
|
||||
[{ role: "user", content: "hello" }],
|
||||
new AbortController().signal,
|
||||
{ maxTokens: 1000 },
|
||||
],
|
||||
expectedRequest: {
|
||||
url: "https://api.cohere.com/v2/chat",
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: "Bearer test-api-key",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: {
|
||||
model: "command-a-03-2025",
|
||||
max_tokens: 1000,
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
stream: true,
|
||||
thinking: { type: "disabled" },
|
||||
},
|
||||
},
|
||||
mockStream: [
|
||||
'{"id":"94e3907b-d214-475e-a53f-ae81c76b6e43","type":"message-start","delta":{"message":{"role":"assistant","content":[],"tool_plan":"","tool_calls":[],"citations":[]}}}',
|
||||
'{"type":"content-start","index":0,"delta":{"message":{"content":{"type":"text","text":""}}}}',
|
||||
'{"type":"content-delta","index":0,"delta":{"message":{"content":{"text":"Hello! "}}}}',
|
||||
'{"type":"content-delta","index":0,"delta":{"message":{"content":{"text":"How can I help you today?"}}}}',
|
||||
'{"type":"content-end","index":0}',
|
||||
'{"type":"message-end","delta":{"finish_reason":"COMPLETE","usage":{"billed_units":{"input_tokens":1,"output_tokens":9},"tokens":{"input_tokens":496,"output_tokens":11},"cached_tokens":448}}}',
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import { LLMOptions } from "../../index.js";
|
||||
import { allModelProviders } from "@continuedev/llm-info";
|
||||
import { LLMOptions } from "../../index.js";
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
/**
|
||||
|
|
@ -183,6 +183,7 @@ class CometAPI extends OpenAI {
|
|||
*/
|
||||
private static RECOMMENDED_MODELS = [
|
||||
// GPT series
|
||||
"gpt-5.1",
|
||||
"gpt-5-chat-latest",
|
||||
"chatgpt-4o-latest",
|
||||
"gpt-5-mini",
|
||||
|
|
|
|||
|
|
@ -6,6 +6,8 @@ import OpenAI from "./OpenAI.js";
|
|||
|
||||
class Deepseek extends OpenAI {
|
||||
static providerName = "deepseek";
|
||||
protected supportsReasoningField = true;
|
||||
protected supportsReasoningDetailsField = false;
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.deepseek.com/",
|
||||
model: "deepseek-coder",
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import {
|
|||
} from "../../index.js";
|
||||
import { safeParseToolCallArgs } from "../../tools/parseArgs.js";
|
||||
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
|
||||
import { extractBase64FromDataUrl } from "../../util/url.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
import {
|
||||
GeminiChatContent,
|
||||
|
|
@ -22,6 +23,14 @@ import {
|
|||
convertContinueToolToGeminiFunction,
|
||||
} from "./gemini-types";
|
||||
|
||||
interface GeminiToolCallDelta extends ToolCallDelta {
|
||||
extra_content?: {
|
||||
google?: {
|
||||
thought_signature?: string;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
class Gemini extends BaseLLM {
|
||||
static providerName = "gemini";
|
||||
|
||||
|
|
@ -184,16 +193,31 @@ class Gemini extends BaseLLM {
|
|||
}
|
||||
|
||||
continuePartToGeminiPart(part: MessagePart): GeminiChatContentPart {
|
||||
return part.type === "text"
|
||||
? {
|
||||
text: part.text,
|
||||
}
|
||||
: {
|
||||
inlineData: {
|
||||
mimeType: "image/jpeg",
|
||||
data: part.imageUrl?.url.split(",")[1],
|
||||
},
|
||||
};
|
||||
if (part.type === "text") {
|
||||
return {
|
||||
text: part.text,
|
||||
};
|
||||
}
|
||||
|
||||
let data = "";
|
||||
if (part.imageUrl?.url) {
|
||||
const extracted = extractBase64FromDataUrl(part.imageUrl.url);
|
||||
if (extracted) {
|
||||
data = extracted;
|
||||
} else {
|
||||
console.warn(
|
||||
"Gemini: skipping image with invalid data URL format",
|
||||
part.imageUrl.url,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
inlineData: {
|
||||
mimeType: "image/jpeg",
|
||||
data,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
public prepareBody(
|
||||
|
|
@ -250,18 +274,37 @@ class Gemini extends BaseLLM {
|
|||
? [{ text: msg.content }]
|
||||
: msg.content.map(this.continuePartToGeminiPart),
|
||||
};
|
||||
if (msg.toolCalls) {
|
||||
msg.toolCalls.forEach((toolCall) => {
|
||||
if (toolCall.function?.name) {
|
||||
assistantMsg.parts.push({
|
||||
functionCall: {
|
||||
name: toolCall.function.name,
|
||||
args: safeParseToolCallArgs(toolCall),
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
if (msg.toolCalls && msg.toolCalls.length) {
|
||||
(msg.toolCalls as GeminiToolCallDelta[]).forEach(
|
||||
(toolCall, index) => {
|
||||
if (toolCall.function?.name) {
|
||||
const signatureForCall =
|
||||
toolCall?.extra_content?.google?.thought_signature;
|
||||
|
||||
let thoughtSignature: string | undefined;
|
||||
if (index === 0) {
|
||||
if (typeof signatureForCall === "string") {
|
||||
thoughtSignature = signatureForCall;
|
||||
} else {
|
||||
// Fallback per https://ai.google.dev/gemini-api/docs/thought-signatures
|
||||
// for histories that were not generated by Gemini or are missing signatures.
|
||||
thoughtSignature = "skip_thought_signature_validator";
|
||||
}
|
||||
}
|
||||
|
||||
assistantMsg.parts.push({
|
||||
functionCall: {
|
||||
name: toolCall.function.name,
|
||||
args: safeParseToolCallArgs(toolCall),
|
||||
},
|
||||
...(thoughtSignature && { thoughtSignature }),
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return assistantMsg;
|
||||
}
|
||||
return {
|
||||
|
|
@ -354,6 +397,7 @@ class Gemini extends BaseLLM {
|
|||
if ("text" in part) {
|
||||
textParts.push({ type: "text", text: part.text });
|
||||
} else if ("functionCall" in part) {
|
||||
const thoughtSignature = part.thoughtSignature;
|
||||
toolCalls.push({
|
||||
type: "function",
|
||||
id: part.functionCall.id ?? uuidv4(),
|
||||
|
|
@ -364,6 +408,13 @@ class Gemini extends BaseLLM {
|
|||
? part.functionCall.args
|
||||
: JSON.stringify(part.functionCall.args),
|
||||
},
|
||||
...(thoughtSignature && {
|
||||
extra_content: {
|
||||
google: {
|
||||
thought_signature: thoughtSignature,
|
||||
},
|
||||
},
|
||||
}),
|
||||
});
|
||||
} else {
|
||||
// Note: function responses shouldn't be streamed, images not supported
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ import {
|
|||
} from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { getRemoteModelInfo } from "../../util/ollamaHelper.js";
|
||||
import { extractBase64FromDataUrl } from "../../util/url.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
|
||||
type OllamaChatMessage = {
|
||||
|
|
@ -114,6 +115,18 @@ type OllamaErrorResponse = {
|
|||
error: string;
|
||||
};
|
||||
|
||||
type N8nChatReponse = {
|
||||
type: string;
|
||||
content?: string;
|
||||
metadata: {
|
||||
nodeId: string;
|
||||
nodeName: string;
|
||||
itemIndex: number;
|
||||
runIndex: number;
|
||||
timestamps: number;
|
||||
};
|
||||
};
|
||||
|
||||
type OllamaRawResponse =
|
||||
| OllamaErrorResponse
|
||||
| (OllamaBaseResponse & {
|
||||
|
|
@ -124,7 +137,8 @@ type OllamaChatResponse =
|
|||
| OllamaErrorResponse
|
||||
| (OllamaBaseResponse & {
|
||||
message: OllamaChatMessage;
|
||||
});
|
||||
})
|
||||
| N8nChatReponse;
|
||||
|
||||
interface OllamaTool {
|
||||
type: "function";
|
||||
|
|
@ -303,9 +317,16 @@ class Ollama extends BaseLLM implements ModelInstaller {
|
|||
const images: string[] = [];
|
||||
message.content.forEach((part) => {
|
||||
if (part.type === "imageUrl" && part.imageUrl) {
|
||||
const image = part.imageUrl?.url.split(",").at(-1);
|
||||
const image = part.imageUrl?.url
|
||||
? extractBase64FromDataUrl(part.imageUrl.url)
|
||||
: undefined;
|
||||
if (image) {
|
||||
images.push(image);
|
||||
} else if (part.imageUrl?.url) {
|
||||
console.warn(
|
||||
"Ollama: skipping image with invalid data URL format",
|
||||
part.imageUrl.url,
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
|
@ -427,12 +448,47 @@ class Ollama extends BaseLLM implements ModelInstaller {
|
|||
body: JSON.stringify(chatOptions),
|
||||
signal,
|
||||
});
|
||||
let isThinking: boolean = false;
|
||||
|
||||
function convertChatMessage(res: OllamaChatResponse): ChatMessage[] {
|
||||
if ("error" in res) {
|
||||
throw new Error(res.error);
|
||||
}
|
||||
|
||||
if ("type" in res) {
|
||||
const { content } = res;
|
||||
|
||||
if (content === "<think>") {
|
||||
isThinking = true;
|
||||
}
|
||||
|
||||
if (isThinking && content) {
|
||||
// TODO better support for streaming thinking chunks, or remove this and depend on redux <think/> parsing logic
|
||||
const thinkingMessage: ThinkingChatMessage = {
|
||||
role: "thinking",
|
||||
content: content,
|
||||
};
|
||||
|
||||
if (thinkingMessage) {
|
||||
// could cause issues with termination if chunk doesn't match this exactly
|
||||
if (content === "</think>") {
|
||||
isThinking = false;
|
||||
}
|
||||
// When Streaming you can't have both thinking and content
|
||||
return [thinkingMessage];
|
||||
}
|
||||
}
|
||||
|
||||
if (content) {
|
||||
const chatMessage: ChatMessage = {
|
||||
role: "assistant",
|
||||
content: content,
|
||||
};
|
||||
return [chatMessage];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
const { role, content, thinking, tool_calls: toolCalls } = res.message;
|
||||
|
||||
if (role === "tool") {
|
||||
|
|
|
|||
|
|
@ -14,9 +14,18 @@ import { renderChatMessage } from "../../util/messageContent.js";
|
|||
import { BaseLLM } from "../index.js";
|
||||
import {
|
||||
fromChatCompletionChunk,
|
||||
fromResponsesChunk,
|
||||
LlmApiRequestType,
|
||||
toChatBody,
|
||||
toResponsesInput,
|
||||
} from "../openaiTypeConverters.js";
|
||||
import {
|
||||
ResponseInput,
|
||||
ResponseInputItem,
|
||||
ResponseInputMessageContentList,
|
||||
ResponseCreateParamsBase,
|
||||
Tool as ResponsesTool,
|
||||
} from "openai/resources/responses/responses.mjs";
|
||||
|
||||
const NON_CHAT_MODELS = [
|
||||
"text-davinci-002",
|
||||
|
|
@ -49,6 +58,139 @@ const formatMessageForO1OrGpt5 = (messages: ChatCompletionMessageParam[]) => {
|
|||
});
|
||||
};
|
||||
|
||||
const formatMessageForO1OrGpt5ForResponses = (
|
||||
messages: ChatCompletionMessageParam[],
|
||||
): ResponseInputItem[] => {
|
||||
const input: ResponseInputItem[] = [];
|
||||
|
||||
const pushMessage = (
|
||||
role: "user" | "assistant" | "system" | "developer",
|
||||
content: string | ResponseInputMessageContentList,
|
||||
) => {
|
||||
// o-series / gpt-5 use `developer` instead of `system`
|
||||
const normalizedRole: "user" | "assistant" | "system" | "developer" =
|
||||
role === "system" ? "developer" : role;
|
||||
|
||||
input.push({ role: normalizedRole, content });
|
||||
};
|
||||
|
||||
for (const message of messages) {
|
||||
switch (message.role) {
|
||||
case "system":
|
||||
case "developer": {
|
||||
const content = message.content;
|
||||
if (typeof content === "string") {
|
||||
pushMessage("developer", content);
|
||||
} else if (Array.isArray(content)) {
|
||||
const parts: ResponseInputMessageContentList = content
|
||||
.filter(
|
||||
(p): p is { type: "text"; text: string } => p.type === "text",
|
||||
)
|
||||
.map((p) => ({ type: "input_text" as const, text: p.text }));
|
||||
pushMessage("developer", parts.length ? parts : "");
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case "user": {
|
||||
const content = message.content;
|
||||
if (typeof content === "string") {
|
||||
pushMessage("user", content);
|
||||
} else if (Array.isArray(content)) {
|
||||
const parts: ResponseInputMessageContentList = [];
|
||||
for (const part of content) {
|
||||
if (part.type === "text") {
|
||||
parts.push({ type: "input_text", text: part.text });
|
||||
} else if (part.type === "image_url") {
|
||||
parts.push({
|
||||
type: "input_image",
|
||||
image_url: part.image_url.url,
|
||||
detail: part.image_url.detail ?? "auto",
|
||||
});
|
||||
} else if (part.type === "file") {
|
||||
parts.push({
|
||||
type: "input_file",
|
||||
file_data: part.file.file_data,
|
||||
file_id: part.file.file_id ?? undefined,
|
||||
filename: part.file.filename,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (parts.length) {
|
||||
pushMessage("user", parts);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case "assistant": {
|
||||
const content = message.content;
|
||||
if (typeof content === "string") {
|
||||
if (content.length) pushMessage("assistant", content);
|
||||
} else if (Array.isArray(content)) {
|
||||
const text = content
|
||||
.filter(
|
||||
(p): p is { type: "text"; text: string } => p.type === "text",
|
||||
)
|
||||
.map((p) => p.text)
|
||||
.join("");
|
||||
if (text.length) pushMessage("assistant", text);
|
||||
}
|
||||
|
||||
if (Array.isArray(message.tool_calls)) {
|
||||
for (const tc of message.tool_calls) {
|
||||
if (tc.type === "function") {
|
||||
input.push({
|
||||
type: "function_call",
|
||||
name: tc.function.name,
|
||||
arguments: tc.function.arguments,
|
||||
call_id: tc.id,
|
||||
});
|
||||
} else if (tc.type === "custom") {
|
||||
input.push({
|
||||
type: "custom_tool_call",
|
||||
name: tc.custom.name,
|
||||
input: tc.custom.input,
|
||||
call_id: tc.id,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case "tool": {
|
||||
const content = message.content;
|
||||
const output =
|
||||
typeof content === "string"
|
||||
? content
|
||||
: content
|
||||
.filter(
|
||||
(p): p is { type: "text"; text: string } => p.type === "text",
|
||||
)
|
||||
.map((p) => p.text)
|
||||
.join("");
|
||||
input.push({
|
||||
type: "function_call_output",
|
||||
call_id: message.tool_call_id,
|
||||
output,
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case "function": {
|
||||
// Deprecated in Chat Completions; no safe mapping into Responses input
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return input;
|
||||
};
|
||||
|
||||
class OpenAI extends BaseLLM {
|
||||
public useLegacyCompletionsEndpoint: boolean | undefined = undefined;
|
||||
|
||||
|
|
@ -134,7 +276,10 @@ class OpenAI extends BaseLLM {
|
|||
options: CompletionOptions,
|
||||
messages: ChatMessage[],
|
||||
): ChatCompletionCreateParams {
|
||||
const finalOptions = toChatBody(messages, options);
|
||||
const finalOptions = toChatBody(messages, options, {
|
||||
includeReasoningField: this.supportsReasoningField,
|
||||
includeReasoningDetailsField: this.supportsReasoningDetailsField,
|
||||
});
|
||||
|
||||
finalOptions.stop = options.stop?.slice(0, this.getMaxStopWords());
|
||||
|
||||
|
|
@ -171,6 +316,60 @@ class OpenAI extends BaseLLM {
|
|||
return finalOptions;
|
||||
}
|
||||
|
||||
protected _convertArgsResponses(
|
||||
options: CompletionOptions,
|
||||
messages: ChatMessage[],
|
||||
): ResponseCreateParamsBase {
|
||||
// Specialized conversion for Responses API (strongly typed body)
|
||||
const model = options.model;
|
||||
|
||||
const input = toResponsesInput(messages);
|
||||
|
||||
const body: ResponseCreateParamsBase = {
|
||||
model,
|
||||
input,
|
||||
temperature: options.temperature ?? null,
|
||||
top_p: options.topP ?? null,
|
||||
reasoning: {
|
||||
effort: "medium",
|
||||
summary: "auto",
|
||||
},
|
||||
include: ["reasoning.encrypted_content"],
|
||||
};
|
||||
|
||||
// Tools support for Responses API (schema differs from Chat Completions)
|
||||
if (options.tools?.length) {
|
||||
body.tools = options.tools
|
||||
.filter((t) => !t.type || t.type === "function")
|
||||
.map(
|
||||
(t) =>
|
||||
({
|
||||
type: "function",
|
||||
name: t.function.name,
|
||||
description: t.function.description ?? undefined,
|
||||
parameters: t.function.parameters ?? undefined,
|
||||
strict: t.function.strict ?? undefined,
|
||||
}) as ResponsesTool,
|
||||
);
|
||||
}
|
||||
if (options.toolChoice) {
|
||||
body.tool_choice = {
|
||||
type: "function",
|
||||
name: options.toolChoice.function.name,
|
||||
} as ResponseCreateParamsBase["tool_choice"];
|
||||
}
|
||||
|
||||
if (typeof options.maxTokens === "number") {
|
||||
body.max_output_tokens = options.maxTokens;
|
||||
}
|
||||
|
||||
if (model === "o1") {
|
||||
body.stream = false;
|
||||
}
|
||||
|
||||
return body;
|
||||
}
|
||||
|
||||
protected _getHeaders() {
|
||||
return {
|
||||
"Content-Type": "application/json",
|
||||
|
|
@ -197,7 +396,7 @@ class OpenAI extends BaseLLM {
|
|||
}
|
||||
|
||||
protected _getEndpoint(
|
||||
endpoint: "chat/completions" | "completions" | "models",
|
||||
endpoint: "chat/completions" | "completions" | "models" | "responses",
|
||||
) {
|
||||
if (!this.apiBase) {
|
||||
throw new Error(
|
||||
|
|
@ -368,6 +567,91 @@ class OpenAI extends BaseLLM {
|
|||
}
|
||||
}
|
||||
|
||||
// Minimal draft: Responses API support for select models
|
||||
protected async *_streamResponses(
|
||||
messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
if (!this.isOSeriesOrGpt5Model(options.model)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const body: any = this._convertArgsResponses(options, messages);
|
||||
|
||||
// o1 does not support streaming
|
||||
if (body.model === "o1") {
|
||||
const res = await this._responses(messages, signal, options);
|
||||
if (Array.isArray(res)) {
|
||||
for (const m of res) {
|
||||
if (m) yield m;
|
||||
}
|
||||
} else if (res) {
|
||||
yield res;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const response = await this.fetch(this._getEndpoint("responses"), {
|
||||
method: "POST",
|
||||
headers: this._getHeaders(),
|
||||
body: JSON.stringify({
|
||||
...body,
|
||||
stream: true,
|
||||
...this.extraBodyProperties(),
|
||||
}),
|
||||
signal,
|
||||
});
|
||||
|
||||
for await (const evt of streamSse(response)) {
|
||||
try {
|
||||
const msg = fromResponsesChunk(evt);
|
||||
if (Array.isArray(msg)) {
|
||||
for (const m of msg) {
|
||||
if (m) yield m;
|
||||
}
|
||||
} else if (msg) {
|
||||
yield msg;
|
||||
}
|
||||
} catch {
|
||||
// ignore malformed chunks
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected async _responses(
|
||||
messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
): Promise<ChatMessage | ChatMessage[]> {
|
||||
if (!this.isOSeriesOrGpt5Model(options.model)) {
|
||||
// Minimal draft: only handle supported models for now
|
||||
return { role: "assistant", content: "" };
|
||||
}
|
||||
|
||||
const body: any = this._convertArgsResponses(options, messages);
|
||||
|
||||
const response = await this.fetch(this._getEndpoint("responses"), {
|
||||
method: "POST",
|
||||
headers: this._getHeaders(),
|
||||
body: JSON.stringify({
|
||||
...body,
|
||||
stream: false,
|
||||
...this.extraBodyProperties(),
|
||||
}),
|
||||
signal,
|
||||
});
|
||||
|
||||
if ((response as any).status === 499) {
|
||||
return { role: "assistant", content: "" };
|
||||
}
|
||||
|
||||
const data: any = await response.json().catch(() => ({}));
|
||||
const msg = fromResponsesChunk(data);
|
||||
if (msg) return msg;
|
||||
return { role: "assistant", content: "" };
|
||||
}
|
||||
|
||||
protected async *_streamFim(
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
|
|
|
|||
|
|
@ -7,6 +7,8 @@ import OpenAI from "./OpenAI.js";
|
|||
|
||||
class OpenRouter extends OpenAI {
|
||||
static providerName = "openrouter";
|
||||
protected supportsReasoningField = true;
|
||||
protected supportsReasoningDetailsField = true;
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://openrouter.ai/api/v1/",
|
||||
model: "gpt-4o-mini",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import ReplicateClient from "replicate";
|
||||
|
||||
import { CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { BaseLLM } from "../index.js";
|
||||
|
||||
class Replicate extends BaseLLM {
|
||||
|
|
@ -33,6 +34,7 @@ class Replicate extends BaseLLM {
|
|||
"tomasmcm/neural-chat-7b-v3-1:acb450496b49e19a1e410b50c574a34acacd54820bc36c19cbfe05148de2ba57",
|
||||
"deepseek-7b": "kcaverly/deepseek-coder-33b-instruct-gguf" as any,
|
||||
"phind-codellama-34b": "kcaverly/phind-codellama-34b-v2-gguf" as any,
|
||||
"claude-4-sonnet-latest": "anthropic/claude-4-sonnet" as any,
|
||||
};
|
||||
|
||||
static providerName = "replicate";
|
||||
|
|
@ -42,12 +44,55 @@ class Replicate extends BaseLLM {
|
|||
options: CompletionOptions,
|
||||
prompt: string,
|
||||
signal: AbortSignal,
|
||||
): [`${string}/${string}:${string}`, { input: any; signal: AbortSignal }] {
|
||||
): [`${string}/${string}:${string}`, { input: any }] {
|
||||
return [
|
||||
Replicate.MODEL_IDS[options.model] || (options.model as any),
|
||||
{
|
||||
input: { prompt, message: prompt },
|
||||
signal,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
private _convertChatArgs(
|
||||
options: CompletionOptions,
|
||||
messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
): [`${string}/${string}:${string}`, { input: any }] {
|
||||
let prompt = "";
|
||||
let system_prompt = "";
|
||||
|
||||
for (const message of messages) {
|
||||
const content =
|
||||
typeof message.content === "string"
|
||||
? message.content
|
||||
: renderChatMessage(message);
|
||||
|
||||
if (message.role === "system") {
|
||||
system_prompt += `System: ${content}\n\n`;
|
||||
} else if (message.role === "user") {
|
||||
prompt += `Human: ${content}\n\n`;
|
||||
} else if (message.role === "assistant") {
|
||||
prompt += `Assistant: ${content}\n\n`;
|
||||
}
|
||||
}
|
||||
|
||||
if (!prompt.endsWith("Assistant: ")) {
|
||||
prompt += "Assistant: ";
|
||||
}
|
||||
|
||||
// Construct the input
|
||||
const input: any = {
|
||||
prompt: prompt,
|
||||
system_prompt: system_prompt,
|
||||
max_tokens: options.maxTokens || 2048,
|
||||
extended_thinking: options.reasoning,
|
||||
thinking_budget_tokens: options.reasoningBudgetTokens || 1024,
|
||||
};
|
||||
|
||||
return [
|
||||
Replicate.MODEL_IDS[options.model] || (options.model as any),
|
||||
{
|
||||
input,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
|
@ -80,6 +125,43 @@ class Replicate extends BaseLLM {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected async *_streamChat(
|
||||
messages: ChatMessage[],
|
||||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
if (!this.apiKey || this.apiKey === "") {
|
||||
throw new Error("You need to use an API key");
|
||||
}
|
||||
|
||||
const [model, args] = this._convertChatArgs(options, messages, signal);
|
||||
|
||||
try {
|
||||
for await (const event of this._replicate.stream(model, args)) {
|
||||
if (event.event === "output") {
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: event.data,
|
||||
};
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes("authentication")) {
|
||||
throw new Error(
|
||||
"Replicate API authentication failed. Please check your API key",
|
||||
);
|
||||
}
|
||||
if (error.message.includes("model not found")) {
|
||||
throw new Error(
|
||||
`Model "${options.model}" not found on Replicate. Please check the model name or use another model.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default Replicate;
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import {
|
|||
Chunk,
|
||||
CompletionOptions,
|
||||
LLMOptions,
|
||||
TextMessagePart,
|
||||
ToolCallDelta,
|
||||
ToolResultChatMessage,
|
||||
} from "../../index.js";
|
||||
|
|
@ -103,11 +104,30 @@ class WatsonX extends BaseLLM {
|
|||
}));
|
||||
delete message_.toolCalls;
|
||||
delete message_.content;
|
||||
} else if (
|
||||
message_.role === "user" &&
|
||||
typeof message_.content === "string"
|
||||
) {
|
||||
message_.content = [{ type: "text", text: message_.content }];
|
||||
} else if (message_.role === "user") {
|
||||
if (typeof message.content === "string") {
|
||||
message_.content = [{ type: "text", text: message_.content }];
|
||||
} else {
|
||||
return {
|
||||
role: "user",
|
||||
content: !message.content.some((item) => item.type !== "text")
|
||||
? message.content
|
||||
.map((item) => (item as TextMessagePart).text)
|
||||
.join("") || " "
|
||||
: message.content.map((part) => {
|
||||
if (part.type === "imageUrl") {
|
||||
return {
|
||||
type: "image_url" as const,
|
||||
image_url: {
|
||||
url: part.imageUrl.url,
|
||||
detail: "auto" as const,
|
||||
},
|
||||
};
|
||||
}
|
||||
return part;
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
return message_;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -192,6 +192,7 @@ export type GeminiFunctionCallContentPart = {
|
|||
name: string;
|
||||
args: JSONSchema7Object;
|
||||
};
|
||||
thoughtSignature?: string;
|
||||
};
|
||||
|
||||
export type GeminiFunctionResponseContentPart = {
|
||||
|
|
|
|||
|
|
@ -101,9 +101,18 @@ class ContinueProxy extends OpenAI {
|
|||
protected _getHeaders() {
|
||||
const headers: any = super._getHeaders();
|
||||
headers["x-continue-unique-id"] = Telemetry.uniqueId;
|
||||
headers["user-agent"] = this._getUserAgent();
|
||||
return headers;
|
||||
}
|
||||
|
||||
private _getUserAgent(): string {
|
||||
const ideInfo = Telemetry.ideInfo;
|
||||
const extensionVersion = ideInfo?.extensionVersion ?? "unknown";
|
||||
const ideName = ideInfo?.name ?? "unknown";
|
||||
const ideType = ideInfo?.ideType ?? "unknown";
|
||||
return `Continue/${extensionVersion} (${ideName}; ${ideType})`;
|
||||
}
|
||||
|
||||
supportsCompletions(): boolean {
|
||||
// This was a hotfix and contains duplicate logic from class-specific completion support methods
|
||||
if (this.underlyingProviderName === "vllm") {
|
||||
|
|
@ -129,6 +138,7 @@ class ContinueProxy extends OpenAI {
|
|||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
"user-agent": this._getUserAgent(),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
query,
|
||||
|
|
|
|||
|
|
@ -4,15 +4,97 @@ import {
|
|||
ChatCompletionAssistantMessageParam,
|
||||
ChatCompletionChunk,
|
||||
ChatCompletionCreateParams,
|
||||
ChatCompletionMessage,
|
||||
ChatCompletionMessageParam,
|
||||
CompletionCreateParams,
|
||||
} from "openai/resources/index";
|
||||
import type {
|
||||
EasyInputMessage,
|
||||
Response as OpenAIResponse,
|
||||
ResponseFunctionToolCall,
|
||||
ResponseInput,
|
||||
ResponseInputItem,
|
||||
ResponseInputMessageContentList,
|
||||
ResponseOutputMessage,
|
||||
ResponseOutputText,
|
||||
ResponseReasoningItem,
|
||||
ResponseReasoningSummaryTextDeltaEvent,
|
||||
ResponseReasoningSummaryTextDoneEvent,
|
||||
ResponseReasoningTextDeltaEvent,
|
||||
ResponseReasoningTextDoneEvent,
|
||||
ResponseStreamEvent,
|
||||
ResponseTextDeltaEvent,
|
||||
} from "openai/resources/responses/responses.mjs";
|
||||
|
||||
import { ChatMessage, CompletionOptions, TextMessagePart } from "..";
|
||||
import {
|
||||
AssistantChatMessage,
|
||||
ChatMessage,
|
||||
CompletionOptions,
|
||||
MessageContent,
|
||||
MessagePart,
|
||||
TextMessagePart,
|
||||
ThinkingChatMessage,
|
||||
ToolCallDelta,
|
||||
} from "..";
|
||||
|
||||
function appendReasoningFieldsIfSupported(
|
||||
msg: ChatCompletionAssistantMessageParam & {
|
||||
reasoning?: string;
|
||||
reasoning_details?: any[];
|
||||
},
|
||||
options: CompletionOptions,
|
||||
prevMessage?: ChatMessage,
|
||||
providerFlags?: {
|
||||
includeReasoningField?: boolean;
|
||||
includeReasoningDetailsField?: boolean;
|
||||
},
|
||||
) {
|
||||
if (!prevMessage || prevMessage.role !== "thinking") return;
|
||||
|
||||
const includeReasoning = !!providerFlags?.includeReasoningField;
|
||||
const includeReasoningDetails = !!providerFlags?.includeReasoningDetailsField;
|
||||
if (!includeReasoning && !includeReasoningDetails) return;
|
||||
|
||||
const reasoningDetailsValue =
|
||||
prevMessage.reasoning_details ||
|
||||
(prevMessage.signature
|
||||
? [{ signature: prevMessage.signature }]
|
||||
: undefined);
|
||||
|
||||
// Claude-specific safeguard: prevent errors when switching to Claude after another model.
|
||||
// Claude requires a signed reasoning_details block; if missing, we must omit both fields.
|
||||
// This check is done before adding any fields to avoid deletes.
|
||||
if (
|
||||
includeReasoningDetails &&
|
||||
options.model.includes("claude") &&
|
||||
!(
|
||||
Array.isArray(reasoningDetailsValue) &&
|
||||
reasoningDetailsValue.some((d) => d && d.signature)
|
||||
)
|
||||
) {
|
||||
console.warn(
|
||||
"Omitting reasoning fields for Claude: no signature present in reasoning_details",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (includeReasoningDetails && reasoningDetailsValue) {
|
||||
msg.reasoning_details = reasoningDetailsValue || [];
|
||||
}
|
||||
if (includeReasoning) {
|
||||
msg.reasoning = prevMessage.content as string;
|
||||
}
|
||||
}
|
||||
|
||||
export function toChatMessage(
|
||||
message: ChatMessage,
|
||||
): ChatCompletionMessageParam {
|
||||
options: CompletionOptions,
|
||||
prevMessage?: ChatMessage,
|
||||
providerFlags?: {
|
||||
includeReasoningField?: boolean;
|
||||
includeReasoningDetailsField?: boolean;
|
||||
},
|
||||
): ChatCompletionMessageParam | null {
|
||||
if (message.role === "tool") {
|
||||
return {
|
||||
role: "tool",
|
||||
|
|
@ -26,18 +108,30 @@ export function toChatMessage(
|
|||
content: message.content,
|
||||
};
|
||||
}
|
||||
if (message.role === "thinking") {
|
||||
// Return null - thinking messages are merged into following assistant messages
|
||||
return null;
|
||||
}
|
||||
|
||||
if (message.role === "assistant") {
|
||||
const msg: ChatCompletionAssistantMessageParam = {
|
||||
// Base assistant message
|
||||
const msg: ChatCompletionAssistantMessageParam & {
|
||||
reasoning?: string;
|
||||
reasoning_details?: {
|
||||
[key: string]: any;
|
||||
signature?: string | undefined;
|
||||
}[];
|
||||
} = {
|
||||
role: "assistant",
|
||||
content:
|
||||
typeof message.content === "string"
|
||||
? message.content || " " // LM Studio (and other providers) don't accept empty content
|
||||
: message.content
|
||||
.filter((part) => part.type === "text")
|
||||
.map((part) => part as TextMessagePart), // can remove with newer typescript version
|
||||
.map((part) => part as TextMessagePart),
|
||||
};
|
||||
|
||||
// Add tool calls if present
|
||||
if (message.toolCalls) {
|
||||
msg.tool_calls = message.toolCalls.map((toolCall) => ({
|
||||
id: toolCall.id!,
|
||||
|
|
@ -48,7 +142,16 @@ export function toChatMessage(
|
|||
},
|
||||
}));
|
||||
}
|
||||
return msg;
|
||||
|
||||
// Preserving reasoning blocks
|
||||
appendReasoningFieldsIfSupported(
|
||||
msg as any,
|
||||
options,
|
||||
prevMessage,
|
||||
providerFlags,
|
||||
);
|
||||
|
||||
return msg as ChatCompletionMessageParam;
|
||||
} else {
|
||||
if (typeof message.content === "string") {
|
||||
return {
|
||||
|
|
@ -62,11 +165,8 @@ export function toChatMessage(
|
|||
// that don't support multi-media format
|
||||
return {
|
||||
role: "user",
|
||||
content: !message.content.some((item) => item.type !== "text")
|
||||
? message.content
|
||||
.map((item) => (item as TextMessagePart).text)
|
||||
.join("") || " "
|
||||
: message.content.map((part) => {
|
||||
content: message.content.some((item) => item.type !== "text")
|
||||
? message.content.map((part) => {
|
||||
if (part.type === "imageUrl") {
|
||||
return {
|
||||
type: "image_url" as const,
|
||||
|
|
@ -77,7 +177,10 @@ export function toChatMessage(
|
|||
};
|
||||
}
|
||||
return part;
|
||||
}),
|
||||
})
|
||||
: message.content
|
||||
.map((item) => (item as TextMessagePart).text)
|
||||
.join("") || " ",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -85,9 +188,17 @@ export function toChatMessage(
|
|||
export function toChatBody(
|
||||
messages: ChatMessage[],
|
||||
options: CompletionOptions,
|
||||
providerFlags?: {
|
||||
includeReasoningField?: boolean;
|
||||
includeReasoningDetailsField?: boolean;
|
||||
},
|
||||
): ChatCompletionCreateParams {
|
||||
const params: ChatCompletionCreateParams = {
|
||||
messages: messages.map(toChatMessage),
|
||||
messages: messages
|
||||
.map((m, index) =>
|
||||
toChatMessage(m, options, messages[index - 1], providerFlags),
|
||||
)
|
||||
.filter((m) => m !== null) as ChatCompletionMessageParam[],
|
||||
model: options.model,
|
||||
max_tokens: options.maxTokens,
|
||||
temperature: options.temperature,
|
||||
|
|
@ -153,11 +264,40 @@ export function toFimBody(
|
|||
} as any;
|
||||
}
|
||||
|
||||
export function fromChatResponse(response: ChatCompletion): ChatMessage {
|
||||
const message = response.choices[0].message;
|
||||
export function fromChatResponse(response: ChatCompletion): ChatMessage[] {
|
||||
const messages: ChatMessage[] = [];
|
||||
const message = response.choices[0].message as ChatCompletionMessage & {
|
||||
reasoning?: string;
|
||||
reasoning_content?: string;
|
||||
reasoning_details?: {
|
||||
signature?: string;
|
||||
[key: string]: any;
|
||||
}[];
|
||||
};
|
||||
|
||||
// Check for reasoning content first (similar to fromChatCompletionChunk)
|
||||
if (message.reasoning_content || message.reasoning) {
|
||||
const thinkingMessage: ChatMessage = {
|
||||
role: "thinking",
|
||||
content: (message as any).reasoning_content || (message as any).reasoning,
|
||||
};
|
||||
|
||||
// Preserve reasoning_details if present
|
||||
if (message.reasoning_details) {
|
||||
thinkingMessage.reasoning_details = message.reasoning_details;
|
||||
// Extract signature from reasoning_details if available
|
||||
if (message.reasoning_details[0]?.signature) {
|
||||
thinkingMessage.signature = message.reasoning_details[0].signature;
|
||||
}
|
||||
}
|
||||
|
||||
messages.push(thinkingMessage);
|
||||
}
|
||||
|
||||
// Then add the assistant message
|
||||
const toolCall = message.tool_calls?.[0];
|
||||
if (toolCall) {
|
||||
return {
|
||||
messages.push({
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls: message.tool_calls
|
||||
|
|
@ -170,19 +310,29 @@ export function fromChatResponse(response: ChatCompletion): ChatMessage {
|
|||
arguments: (tc as any).function?.arguments,
|
||||
},
|
||||
})),
|
||||
};
|
||||
});
|
||||
} else {
|
||||
messages.push({
|
||||
role: "assistant",
|
||||
content: message.content ?? "",
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
role: "assistant",
|
||||
content: message.content ?? "",
|
||||
};
|
||||
return messages;
|
||||
}
|
||||
|
||||
export function fromChatCompletionChunk(
|
||||
chunk: ChatCompletionChunk,
|
||||
): ChatMessage | undefined {
|
||||
const delta = chunk.choices?.[0]?.delta;
|
||||
const delta = chunk.choices?.[0]?.delta as
|
||||
| (ChatCompletionChunk.Choice.Delta & {
|
||||
reasoning?: string;
|
||||
reasoning_content?: string;
|
||||
reasoning_details?: {
|
||||
signature?: string;
|
||||
}[];
|
||||
})
|
||||
| undefined;
|
||||
|
||||
if (delta?.content) {
|
||||
return {
|
||||
|
|
@ -208,11 +358,568 @@ export function fromChatCompletionChunk(
|
|||
toolCalls,
|
||||
};
|
||||
}
|
||||
} else if (
|
||||
delta?.reasoning_content ||
|
||||
delta?.reasoning ||
|
||||
delta?.reasoning_details?.length
|
||||
) {
|
||||
const message: ThinkingChatMessage = {
|
||||
role: "thinking",
|
||||
content: delta.reasoning_content || delta.reasoning || "",
|
||||
signature: delta?.reasoning_details?.[0]?.signature,
|
||||
reasoning_details: delta?.reasoning_details as any[],
|
||||
};
|
||||
return message;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function handleTextDeltaEvent(
|
||||
e: ResponseTextDeltaEvent,
|
||||
): ChatMessage | undefined {
|
||||
return e.delta ? { role: "assistant", content: e.delta } : undefined;
|
||||
}
|
||||
|
||||
function handleFunctionCallArgsDelta(e: any): ChatMessage | undefined {
|
||||
const ev: any = e as any;
|
||||
const item = ev.item || {};
|
||||
const name = item && typeof item.name === "string" ? item.name : undefined;
|
||||
const argDelta =
|
||||
typeof ev.delta === "string"
|
||||
? ev.delta
|
||||
: (ev.delta?.arguments ?? ev.arguments);
|
||||
if (typeof argDelta === "string" && argDelta.length > 0) {
|
||||
const call_id =
|
||||
(item?.call_id as string | undefined) ||
|
||||
(item?.id as string | undefined) ||
|
||||
"";
|
||||
const toolCalls: ToolCallDelta[] = [
|
||||
{
|
||||
id: call_id,
|
||||
type: "function",
|
||||
function: { name: name || "", arguments: argDelta },
|
||||
},
|
||||
];
|
||||
const assistant: AssistantChatMessage = {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls,
|
||||
};
|
||||
return assistant;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function handleOutputItemAdded(
|
||||
e: ResponseStreamEvent,
|
||||
): ChatMessage | undefined {
|
||||
const item = (e as any).item as {
|
||||
type?: string;
|
||||
id?: string;
|
||||
name?: string;
|
||||
arguments?: string;
|
||||
call_id?: string;
|
||||
summary?: Array<{ type: string; text: string }>;
|
||||
encrypted_content?: string;
|
||||
};
|
||||
if (!item || !item.type) return undefined;
|
||||
if (item.type === "reasoning") {
|
||||
const details: Array<{ [k: string]: unknown }> = [];
|
||||
if (item.id) details.push({ type: "reasoning_id", id: item.id });
|
||||
if (typeof item.encrypted_content === "string" && item.encrypted_content) {
|
||||
details.push({
|
||||
type: "encrypted_content",
|
||||
encrypted_content: item.encrypted_content,
|
||||
});
|
||||
}
|
||||
if (Array.isArray(item.summary)) {
|
||||
for (const part of item.summary) {
|
||||
if (part?.type === "summary_text" && typeof part.text === "string") {
|
||||
details.push({ type: "summary_text", text: part.text });
|
||||
}
|
||||
}
|
||||
}
|
||||
const thinking: ThinkingChatMessage = {
|
||||
role: "thinking",
|
||||
content: "",
|
||||
reasoning_details: details,
|
||||
metadata: {
|
||||
reasoningId: item.id as string,
|
||||
encrypted_content: item.encrypted_content as string | undefined,
|
||||
},
|
||||
};
|
||||
return thinking;
|
||||
}
|
||||
if (item.type === "message" && typeof item.id === "string") {
|
||||
return {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
metadata: { responsesOutputItemId: item.id },
|
||||
};
|
||||
}
|
||||
if (item.type === "function_call" && typeof item.id === "string") {
|
||||
const name = item.name as string | undefined;
|
||||
const args = typeof item.arguments === "string" ? item.arguments : "";
|
||||
const call_id = item.call_id as string | undefined;
|
||||
const toolCalls: ToolCallDelta[] = name
|
||||
? [
|
||||
{
|
||||
id: call_id || (item.id as string),
|
||||
type: "function",
|
||||
function: { name, arguments: args },
|
||||
},
|
||||
]
|
||||
: [];
|
||||
const assistant: AssistantChatMessage = {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls,
|
||||
metadata: { responsesOutputItemId: item.id as string },
|
||||
};
|
||||
return assistant;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function handleReasoningSummaryDelta(
|
||||
e: ResponseReasoningSummaryTextDeltaEvent,
|
||||
): ChatMessage | undefined {
|
||||
const details: Array<{ [k: string]: unknown }> = [
|
||||
{ type: "summary_text", text: e.delta },
|
||||
];
|
||||
if ((e as any).item_id)
|
||||
details.push({ type: "reasoning_id", id: (e as any).item_id });
|
||||
const thinking: ThinkingChatMessage = {
|
||||
role: "thinking",
|
||||
content: e.delta,
|
||||
reasoning_details: details,
|
||||
};
|
||||
return thinking;
|
||||
}
|
||||
|
||||
function handleReasoningSummaryDone(
|
||||
e: ResponseReasoningSummaryTextDoneEvent,
|
||||
): ChatMessage | undefined {
|
||||
const details: Array<{ [k: string]: unknown }> = [];
|
||||
if (e.text) details.push({ type: "summary_text", text: e.text });
|
||||
if ((e as any).item_id)
|
||||
details.push({ type: "reasoning_id", id: (e as any).item_id });
|
||||
const thinking: ThinkingChatMessage = {
|
||||
role: "thinking",
|
||||
content: e.text,
|
||||
reasoning_details: details,
|
||||
};
|
||||
return thinking;
|
||||
}
|
||||
|
||||
function handleReasoningTextDelta(
|
||||
e: ResponseReasoningTextDeltaEvent,
|
||||
): ChatMessage | undefined {
|
||||
const details: Array<{ [k: string]: unknown }> = [
|
||||
{ type: "reasoning_text", text: e.delta },
|
||||
];
|
||||
if ((e as any).item_id)
|
||||
details.push({ type: "reasoning_id", id: (e as any).item_id });
|
||||
const thinking: ThinkingChatMessage = {
|
||||
role: "thinking",
|
||||
content: e.delta,
|
||||
reasoning_details: details,
|
||||
};
|
||||
return thinking;
|
||||
}
|
||||
|
||||
function handleReasoningTextDone(
|
||||
e: ResponseReasoningTextDoneEvent,
|
||||
): ChatMessage | undefined {
|
||||
const details: Array<{ [k: string]: unknown }> = [];
|
||||
if (e.text) details.push({ type: "reasoning_text", text: e.text });
|
||||
if ((e as any).item_id)
|
||||
details.push({ type: "reasoning_id", id: (e as any).item_id });
|
||||
const thinking: ThinkingChatMessage = {
|
||||
role: "thinking",
|
||||
content: e.text,
|
||||
reasoning_details: details,
|
||||
};
|
||||
return thinking;
|
||||
}
|
||||
|
||||
function handleResponsesStreamEvent(
|
||||
e: ResponseStreamEvent,
|
||||
): ChatMessage | undefined {
|
||||
const t = (e as any).type as string;
|
||||
if (t === "response.output_text.delta") {
|
||||
return handleTextDeltaEvent(e as ResponseTextDeltaEvent);
|
||||
}
|
||||
if (t === "response.output_text.done") {
|
||||
return undefined; // avoid duplicate final text
|
||||
}
|
||||
if (t === "response.function_call_arguments.delta") {
|
||||
return handleFunctionCallArgsDelta(e);
|
||||
}
|
||||
if (t === "response.function_call_arguments.done") {
|
||||
return undefined;
|
||||
}
|
||||
if (t === "response.output_item.added") {
|
||||
return handleOutputItemAdded(e);
|
||||
}
|
||||
if (t === "response.reasoning_summary_text.delta") {
|
||||
return handleReasoningSummaryDelta(
|
||||
e as ResponseReasoningSummaryTextDeltaEvent,
|
||||
);
|
||||
}
|
||||
if (t === "response.reasoning_summary_text.done") {
|
||||
return handleReasoningSummaryDone(
|
||||
e as ResponseReasoningSummaryTextDoneEvent,
|
||||
);
|
||||
}
|
||||
if (t === "response.reasoning_text.delta") {
|
||||
return handleReasoningTextDelta(e as ResponseReasoningTextDeltaEvent);
|
||||
}
|
||||
if (t === "response.reasoning_text.done") {
|
||||
return handleReasoningTextDone(e as ResponseReasoningTextDoneEvent);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function handleResponsesFinal(
|
||||
resp: OpenAIResponse,
|
||||
): ChatMessage | ChatMessage[] | undefined {
|
||||
// Prefer structured output items when present
|
||||
if (Array.isArray(resp.output) && resp.output.length > 0) {
|
||||
const result: ChatMessage[] = [];
|
||||
for (const raw of resp.output as any[]) {
|
||||
const item = raw as any;
|
||||
if (!item || typeof item !== "object") continue;
|
||||
if (item.type === "reasoning") {
|
||||
const details: Array<{ [k: string]: unknown }> = [];
|
||||
if (typeof item.id === "string") {
|
||||
details.push({ type: "reasoning_id", id: item.id });
|
||||
}
|
||||
if (Array.isArray(item.summary)) {
|
||||
for (const s of item.summary) {
|
||||
if (s?.type === "summary_text" && typeof s.text === "string") {
|
||||
details.push({ type: "summary_text", text: s.text });
|
||||
}
|
||||
}
|
||||
}
|
||||
if (Array.isArray(item.content)) {
|
||||
for (const c of item.content) {
|
||||
if (c?.type === "reasoning_text" && typeof c.text === "string") {
|
||||
details.push({ type: "reasoning_text", text: c.text });
|
||||
}
|
||||
}
|
||||
}
|
||||
if (
|
||||
typeof item.encrypted_content === "string" &&
|
||||
item.encrypted_content
|
||||
) {
|
||||
details.push({
|
||||
type: "encrypted_content",
|
||||
encrypted_content: item.encrypted_content,
|
||||
});
|
||||
}
|
||||
const thinking: ThinkingChatMessage = {
|
||||
role: "thinking",
|
||||
content: "",
|
||||
reasoning_details: details,
|
||||
metadata: {
|
||||
reasoningId: item.id as string,
|
||||
encrypted_content: item.encrypted_content as string | undefined,
|
||||
},
|
||||
};
|
||||
result.push(thinking);
|
||||
continue;
|
||||
}
|
||||
if (item.type === "message") {
|
||||
let text = "";
|
||||
if (Array.isArray(item.content)) {
|
||||
text = (item.content as any[])
|
||||
.map((c) => (typeof c?.text === "string" ? c.text : ""))
|
||||
.join("");
|
||||
} else if (typeof item.content === "string") {
|
||||
text = item.content;
|
||||
}
|
||||
const assistant: AssistantChatMessage = {
|
||||
role: "assistant",
|
||||
content: text || "",
|
||||
metadata:
|
||||
typeof item.id === "string"
|
||||
? { responsesOutputItemId: item.id }
|
||||
: undefined,
|
||||
};
|
||||
result.push(assistant);
|
||||
continue;
|
||||
}
|
||||
if (item.type === "function_call") {
|
||||
const name = item.name as string | undefined;
|
||||
const args =
|
||||
typeof item.arguments === "string"
|
||||
? item.arguments
|
||||
: JSON.stringify(item.arguments ?? "");
|
||||
const call_id =
|
||||
(item.call_id as string | undefined) ||
|
||||
(item.id as string | undefined) ||
|
||||
"";
|
||||
const toolCalls: ToolCallDelta[] = name
|
||||
? [
|
||||
{
|
||||
id: call_id,
|
||||
type: "function",
|
||||
function: { name, arguments: args || "" },
|
||||
},
|
||||
]
|
||||
: [];
|
||||
const assistant: AssistantChatMessage = {
|
||||
role: "assistant",
|
||||
content: "",
|
||||
toolCalls,
|
||||
metadata:
|
||||
typeof item.id === "string"
|
||||
? { responsesOutputItemId: item.id }
|
||||
: undefined,
|
||||
};
|
||||
result.push(assistant);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (result.length > 0) return result;
|
||||
}
|
||||
|
||||
// Fallback to output_text when no structured output is present
|
||||
if (typeof resp.output_text === "string" && resp.output_text.length > 0) {
|
||||
return { role: "assistant", content: resp.output_text };
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function fromResponsesChunk(
|
||||
event: ResponseStreamEvent | OpenAIResponse,
|
||||
): ChatMessage | ChatMessage[] | undefined {
|
||||
if (typeof (event as any).type === "string") {
|
||||
return handleResponsesStreamEvent(event as ResponseStreamEvent);
|
||||
}
|
||||
return handleResponsesFinal(event as OpenAIResponse);
|
||||
}
|
||||
|
||||
export function mergeReasoningDetails(
|
||||
existing: any[] | undefined,
|
||||
delta: any[] | undefined,
|
||||
): any[] | undefined {
|
||||
if (!delta) return existing;
|
||||
if (!existing) return delta;
|
||||
|
||||
const result = [...existing];
|
||||
|
||||
for (const deltaItem of delta) {
|
||||
// Skip items without a type
|
||||
if (!deltaItem.type) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Find existing item with the same type
|
||||
const existingIndex = result.findIndex(
|
||||
(item) => item.type === deltaItem.type,
|
||||
);
|
||||
|
||||
if (existingIndex === -1) {
|
||||
// No existing item with this type, add new item
|
||||
result.push({ ...deltaItem });
|
||||
} else {
|
||||
// Merge with existing item of the same type
|
||||
const existingItem = result[existingIndex];
|
||||
|
||||
for (const [key, value] of Object.entries(deltaItem)) {
|
||||
if (value === null || value === undefined) continue;
|
||||
|
||||
if (key === "text" || key === "signature" || key === "summary") {
|
||||
// Concatenate text and signature fields
|
||||
existingItem[key] = (existingItem[key] || "") + value;
|
||||
} else if (key !== "type") {
|
||||
// Don't overwrite type
|
||||
// Overwrite other fields
|
||||
existingItem[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function getTextFromMessageContent(content: MessageContent): string {
|
||||
if (typeof content === "string") return content;
|
||||
return content
|
||||
.filter((p): p is TextMessagePart => p.type === "text")
|
||||
.map((p) => p.text)
|
||||
.join("");
|
||||
}
|
||||
|
||||
function toResponseInputContentList(
|
||||
parts: MessagePart[],
|
||||
): ResponseInputMessageContentList {
|
||||
const list: ResponseInputMessageContentList = [];
|
||||
for (const part of parts) {
|
||||
if (part.type === "text") {
|
||||
list.push({ type: "input_text", text: part.text });
|
||||
} else if (part.type === "imageUrl") {
|
||||
list.push({
|
||||
type: "input_image",
|
||||
image_url: part.imageUrl.url,
|
||||
detail: "auto",
|
||||
});
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
export function toResponsesInput(messages: ChatMessage[]): ResponseInput {
|
||||
const input: ResponseInput = [];
|
||||
|
||||
const pushMessage = (
|
||||
role: "user" | "assistant" | "system" | "developer",
|
||||
content: string | ResponseInputMessageContentList,
|
||||
) => {
|
||||
const normalizedRole: "user" | "assistant" | "system" | "developer" =
|
||||
role === "system" ? "developer" : role;
|
||||
const easyMsg: EasyInputMessage = {
|
||||
role: normalizedRole,
|
||||
content,
|
||||
type: "message",
|
||||
};
|
||||
input.push(easyMsg as ResponseInputItem);
|
||||
};
|
||||
|
||||
for (let i = 0; i < messages.length; i++) {
|
||||
const msg = messages[i];
|
||||
switch (msg.role) {
|
||||
case "system": {
|
||||
const content = getTextFromMessageContent(msg.content);
|
||||
pushMessage("developer", content || "");
|
||||
break;
|
||||
}
|
||||
case "user": {
|
||||
if (typeof msg.content === "string") {
|
||||
pushMessage("user", msg.content);
|
||||
} else if (Array.isArray(msg.content)) {
|
||||
const parts = toResponseInputContentList(
|
||||
msg.content as MessagePart[],
|
||||
);
|
||||
pushMessage("user", parts.length ? parts : "");
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "assistant": {
|
||||
const text = getTextFromMessageContent(msg.content);
|
||||
|
||||
const respId = msg.metadata?.responsesOutputItemId as
|
||||
| string
|
||||
| undefined;
|
||||
const toolCalls = msg.toolCalls as ToolCallDelta[] | undefined;
|
||||
|
||||
if (respId && Array.isArray(toolCalls) && toolCalls.length > 0) {
|
||||
// Emit full function_call output item
|
||||
const tc = toolCalls[0];
|
||||
const name = tc?.function?.name as string | undefined;
|
||||
const args = tc?.function?.arguments as string | undefined;
|
||||
const call_id = tc?.id as string | undefined;
|
||||
const functionCallItem: ResponseFunctionToolCall = {
|
||||
id: respId,
|
||||
type: "function_call",
|
||||
name: name || "",
|
||||
arguments: typeof args === "string" ? args : "{}",
|
||||
call_id: call_id || respId,
|
||||
};
|
||||
input.push(functionCallItem);
|
||||
} else if (respId) {
|
||||
// Emit full assistant output message item
|
||||
const outputMessageItem: ResponseOutputMessage = {
|
||||
id: respId,
|
||||
role: "assistant",
|
||||
type: "message",
|
||||
status: "completed",
|
||||
content: [
|
||||
{
|
||||
type: "output_text",
|
||||
text: text || "",
|
||||
annotations: [],
|
||||
} satisfies ResponseOutputText,
|
||||
],
|
||||
};
|
||||
input.push(outputMessageItem);
|
||||
} else {
|
||||
// Fallback to EasyInput assistant message
|
||||
pushMessage("assistant", text || "");
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "tool": {
|
||||
const call_id = msg.toolCallId;
|
||||
const output =
|
||||
typeof msg.content === "string"
|
||||
? msg.content
|
||||
: JSON.stringify(msg.content);
|
||||
const functionCallOutput: ResponseInputItem = {
|
||||
type: "function_call_output",
|
||||
call_id,
|
||||
output,
|
||||
} as ResponseInputItem;
|
||||
input.push(functionCallOutput);
|
||||
break;
|
||||
}
|
||||
case "thinking": {
|
||||
const details = (msg as ThinkingChatMessage).reasoning_details ?? [];
|
||||
if (details.length) {
|
||||
let id: string | undefined;
|
||||
let summaryText = "";
|
||||
let encrypted: string | undefined;
|
||||
let reasoningText = "";
|
||||
for (const raw of details as Array<Record<string, unknown>>) {
|
||||
const d = raw as {
|
||||
type?: string;
|
||||
id?: string;
|
||||
text?: string;
|
||||
encrypted_content?: string;
|
||||
};
|
||||
if (d.type === "reasoning_id" && d.id) id = d.id;
|
||||
else if (d.type === "encrypted_content" && d.encrypted_content)
|
||||
encrypted = d.encrypted_content;
|
||||
else if (d.type === "summary_text" && typeof d.text === "string")
|
||||
summaryText += d.text;
|
||||
else if (d.type === "reasoning_text" && typeof d.text === "string")
|
||||
reasoningText += d.text;
|
||||
}
|
||||
if (id) {
|
||||
const reasoningItem: ResponseReasoningItem = {
|
||||
id,
|
||||
type: "reasoning",
|
||||
summary: [],
|
||||
} as ResponseReasoningItem;
|
||||
if (summaryText) {
|
||||
reasoningItem.summary = [
|
||||
{ type: "summary_text", text: summaryText },
|
||||
];
|
||||
}
|
||||
if (reasoningText) {
|
||||
reasoningItem.content = [
|
||||
{ type: "reasoning_text", text: reasoningText },
|
||||
];
|
||||
}
|
||||
if (encrypted) {
|
||||
reasoningItem.encrypted_content = encrypted;
|
||||
}
|
||||
input.push(reasoningItem as ResponseInputItem);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return input;
|
||||
}
|
||||
|
||||
export type LlmApiRequestType =
|
||||
| "chat"
|
||||
| "streamChat"
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { minimatch } from "minimatch";
|
||||
import {
|
||||
ContextItemWithId,
|
||||
RuleMetadata,
|
||||
RuleWithSource,
|
||||
ToolResultChatMessage,
|
||||
UserChatMessage,
|
||||
|
|
@ -324,7 +325,7 @@ export const getApplicableRules = (
|
|||
return applicableRules;
|
||||
};
|
||||
|
||||
export function getRuleId(rule: RuleWithSource): string {
|
||||
export function getRuleId(rule: RuleMetadata): string {
|
||||
return rule.slug ?? rule.sourceFile ?? rule.name ?? rule.source;
|
||||
}
|
||||
|
||||
|
|
@ -342,7 +343,7 @@ export const getSystemMessageWithRules = ({
|
|||
rulePolicies?: RulePolicies;
|
||||
}): {
|
||||
systemMessage: string;
|
||||
appliedRules: RuleWithSource[];
|
||||
appliedRules: RuleMetadata[];
|
||||
} => {
|
||||
const appliedRules = getApplicableRules(
|
||||
userMessage,
|
||||
|
|
@ -359,8 +360,10 @@ export const getSystemMessageWithRules = ({
|
|||
systemMessage += rule.rule;
|
||||
}
|
||||
|
||||
const ruleMetadata = appliedRules.map(({ rule, ...rest }) => rest);
|
||||
|
||||
return {
|
||||
systemMessage,
|
||||
appliedRules,
|
||||
appliedRules: ruleMetadata,
|
||||
};
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,14 +1,14 @@
|
|||
import { RuleWithSource } from "../..";
|
||||
import { RuleMetadata } from "../..";
|
||||
import { getLastNPathParts } from "../../util/uri";
|
||||
|
||||
export function getRuleDisplayName(rule: RuleWithSource): string {
|
||||
export function getRuleDisplayName(rule: RuleMetadata): string {
|
||||
if (rule.name) {
|
||||
return rule.name;
|
||||
}
|
||||
return getRuleSourceDisplayName(rule);
|
||||
}
|
||||
|
||||
export function getRuleSourceDisplayName(rule: RuleWithSource): string {
|
||||
export function getRuleSourceDisplayName(rule: RuleMetadata): string {
|
||||
switch (rule.source) {
|
||||
case ".continuerules":
|
||||
return "Project rules";
|
||||
|
|
|
|||
|
|
@ -60,13 +60,6 @@ export async function* llmStreamChat(
|
|||
if (!slashCommand) {
|
||||
throw new Error(`Unknown slash command ${command.name}`);
|
||||
}
|
||||
void Telemetry.capture(
|
||||
"useSlashCommand",
|
||||
{
|
||||
name: command.name,
|
||||
},
|
||||
true,
|
||||
);
|
||||
if (!slashCommand.run) {
|
||||
console.error(
|
||||
`Slash command ${command.name} (${command.source}) has no run function`,
|
||||
|
|
|
|||
|
|
@ -7,19 +7,7 @@ const simplifiedEditPrompt = `Consider the following code:
|
|||
\`\`\`
|
||||
Edit the code to perfectly satisfy the following user request:
|
||||
{{{userInput}}}
|
||||
Output nothing except for the code. No code block, no English explanation, no start/end tags.`;
|
||||
|
||||
const simplestEditPrompt = `Here is the code before editing:
|
||||
\`\`\`{{{language}}}
|
||||
{{{codeToEdit}}}
|
||||
\`\`\`
|
||||
|
||||
Here is the edit requested:
|
||||
"{{{userInput}}}"
|
||||
|
||||
Here is the code after editing:`;
|
||||
|
||||
const codellamaInfillEditPrompt = "{{filePrefix}}<FILL>{{fileSuffix}}";
|
||||
Output nothing except for the code. No code block, no English explanation, no start/end tags. Leave existing comments in place unless changes require modifying them.`;
|
||||
|
||||
const START_TAG = "<START EDITING HERE>";
|
||||
const osModelsEditPrompt: PromptTemplate = (history, otherData) => {
|
||||
|
|
@ -55,7 +43,7 @@ ${otherData.codeToEdit}
|
|||
${suffixTag}
|
||||
\`\`\`
|
||||
|
||||
Please rewrite the entire code block above in order to satisfy the following request: "${otherData.userInput}". You should rewrite the entire code block without leaving placeholders, even if the code is the same as before.${suffixExplanation}`,
|
||||
Please rewrite the entire code block above in order to satisfy the following request: "${otherData.userInput}". You should rewrite the entire code block without leaving placeholders, even if the code is the same as before. Leave existing comments in place unless changes require modifying them.${suffixExplanation}`,
|
||||
},
|
||||
{
|
||||
role: "assistant",
|
||||
|
|
@ -75,7 +63,7 @@ ${otherData.codeToEdit}
|
|||
${suffixTag}
|
||||
\`\`\`
|
||||
|
||||
Please rewrite the entire code block above, editing the portion below "${START_TAG}" in order to satisfy the following request: "${otherData.userInput}". You should rewrite the entire code block without leaving placeholders, even if the code is the same as before.${suffixExplanation}
|
||||
Please rewrite the entire code block above, editing the portion below "${START_TAG}" in order to satisfy the following request: "${otherData.userInput}". You should rewrite the entire code block without leaving placeholders, even if the code is the same as before. Leave existing comments in place unless changes require modifying them.${suffixExplanation}
|
||||
`,
|
||||
},
|
||||
{
|
||||
|
|
@ -93,12 +81,12 @@ const mistralEditPrompt = `[INST] You are a helpful code assistant. Your task is
|
|||
{{{codeToEdit}}}
|
||||
\`\`\`
|
||||
|
||||
Just rewrite the code without explanations: [/INST]
|
||||
Leave existing comments in place unless changes require modifying them. Just rewrite the code without explanations: [/INST]
|
||||
\`\`\`{{{language}}}`;
|
||||
|
||||
const alpacaEditPrompt = `Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
|
||||
|
||||
### Instruction: Rewrite the code to satisfy this request: "{{{userInput}}}"
|
||||
### Instruction: Leave existing comments in place unless changes require modifying them. Rewrite the code to satisfy this request: "{{{userInput}}}"
|
||||
|
||||
### Input:
|
||||
|
||||
|
|
@ -116,7 +104,7 @@ const phindEditPrompt = `### System Prompt
|
|||
You are an expert programmer and write code on the first attempt without any errors or fillers.
|
||||
|
||||
### User Message:
|
||||
Rewrite the code to satisfy this request: "{{{userInput}}}"
|
||||
Leave existing comments in place unless changes require modifying them. Rewrite the code to satisfy this request: "{{{userInput}}}"
|
||||
|
||||
\`\`\`{{{language}}}
|
||||
{{{codeToEdit}}}
|
||||
|
|
@ -131,7 +119,7 @@ Sure! Here's the code you requested:
|
|||
const deepseekEditPrompt = `### System Prompt
|
||||
You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and your role is to assist with questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will not answer.
|
||||
### Instruction:
|
||||
Rewrite the code to satisfy this request: "{{{userInput}}}"
|
||||
Leave existing comments in place unless changes require modifying them. Rewrite the code to satisfy this request: "{{{userInput}}}"
|
||||
|
||||
\`\`\`{{{language}}}
|
||||
{{{codeToEdit}}}
|
||||
|
|
@ -145,7 +133,7 @@ Sure! Here's the code you requested:
|
|||
const zephyrEditPrompt = `<|system|>
|
||||
You are an expert programmer and write code on the first attempt without any errors or fillers.</s>
|
||||
<|user|>
|
||||
Rewrite the code to satisfy this request: "{{{userInput}}}"
|
||||
Leave existing comments in place unless changes require modifying them. Rewrite the code to satisfy this request: "{{{userInput}}}"
|
||||
|
||||
\`\`\`{{{language}}}
|
||||
{{{codeToEdit}}}
|
||||
|
|
@ -160,12 +148,12 @@ const openchatEditPrompt = `GPT4 Correct User: You are an expert programmer and
|
|||
\`\`\`{{{language}}}
|
||||
{{{codeToEdit}}}
|
||||
\`\`\`
|
||||
Please only respond with code and put it inside of a markdown code block. Do not give any explanation, but your code should perfectly satisfy the user request.<|end_of_turn|>GPT4 Correct Assistant: Sure thing! Here is the rewritten code that you requested:
|
||||
Please only respond with code and put it inside of a markdown code block. Do not give any explanation, but your code should perfectly satisfy the user request. Leave existing comments in place unless changes require modifying them.<|end_of_turn|>GPT4 Correct Assistant: Sure thing! Here is the rewritten code that you requested:
|
||||
\`\`\`{{{language}}}
|
||||
`;
|
||||
|
||||
const xWinCoderEditPrompt = `<system>: You are an AI coding agent that helps people with programming. Write a response that appropriately completes the user's request.
|
||||
<user>: Please rewrite the following code with these instructions: "{{{userInput}}}"
|
||||
<user>: Please rewrite the following code (without changing existing code comments) with these instructions: "{{{userInput}}}"
|
||||
\`\`\`{{{language}}}
|
||||
{{{codeToEdit}}}
|
||||
\`\`\`
|
||||
|
|
@ -177,7 +165,7 @@ Just rewrite the code without explanations:
|
|||
const neuralChatEditPrompt = `### System:
|
||||
You are an expert programmer and write code on the first attempt without any errors or fillers.
|
||||
### User:
|
||||
Rewrite the code to satisfy this request: "{{{userInput}}}"
|
||||
Rewrite the code (without changing existing code comments) to satisfy this request: "{{{userInput}}}"
|
||||
|
||||
\`\`\`{{{language}}}
|
||||
{{{codeToEdit}}}
|
||||
|
|
@ -188,7 +176,7 @@ Sure! Here's the code you requested:
|
|||
\`\`\`{{{language}}}
|
||||
`;
|
||||
|
||||
const codeLlama70bEditPrompt = `<s>Source: system\n\n You are an expert programmer and write code on the first attempt without any errors or fillers. <step> Source: user\n\n Rewrite the code to satisfy this request: "{{{userInput}}}"
|
||||
const codeLlama70bEditPrompt = `<s>Source: system\n\n You are an expert programmer and write code on the first attempt without any errors or fillers. <step> Source: user\n\n Rewrite the code (without changing existing code comments) to satisfy this request: "{{{userInput}}}"
|
||||
|
||||
\`\`\`{{{language}}}
|
||||
{{{codeToEdit}}}
|
||||
|
|
@ -209,7 +197,7 @@ You are an expert programmer. You will rewrite the above code to do the followin
|
|||
|
||||
${otherData.userInput}
|
||||
|
||||
Output only a code block with the rewritten code:
|
||||
Leave existing comments in place unless changes require modifying them. Output only a code block with the rewritten code:
|
||||
`,
|
||||
},
|
||||
{
|
||||
|
|
@ -224,12 +212,12 @@ const llama3EditPrompt: PromptTemplate = `<|begin_of_text|><|start_header_id|>us
|
|||
{{{codeToEdit}}}
|
||||
\`\`\`
|
||||
|
||||
Rewrite the above code to satisfy this request: "{{{userInput}}}"<|eot_id|><|start_header_id|>assistant<|end_header_id|>
|
||||
Rewrite the above code to satisfy this request (without changing existing code comments): "{{{userInput}}}"<|eot_id|><|start_header_id|>assistant<|end_header_id|>
|
||||
Sure! Here's the code you requested:
|
||||
\`\`\`{{{language}}}`;
|
||||
|
||||
const gemmaEditPrompt = `<start_of_turn>user
|
||||
You are an expert programmer and write code on the first attempt without any errors or fillers. Rewrite the code to satisfy this request: "{{{userInput}}}"
|
||||
You are an expert programmer and write code on the first attempt without any errors or fillers. Rewrite the code to satisfy this request (without changing existing code comments): "{{{userInput}}}"
|
||||
|
||||
\`\`\`{{{language}}}
|
||||
{{{codeToEdit}}}
|
||||
|
|
@ -244,7 +232,6 @@ export {
|
|||
alpacaEditPrompt,
|
||||
claudeEditPrompt,
|
||||
codeLlama70bEditPrompt,
|
||||
codellamaInfillEditPrompt,
|
||||
deepseekEditPrompt,
|
||||
gemmaEditPrompt,
|
||||
gptEditPrompt,
|
||||
|
|
@ -254,7 +241,6 @@ export {
|
|||
openchatEditPrompt,
|
||||
osModelsEditPrompt,
|
||||
phindEditPrompt,
|
||||
simplestEditPrompt,
|
||||
simplifiedEditPrompt,
|
||||
xWinCoderEditPrompt,
|
||||
zephyrEditPrompt,
|
||||
|
|
|
|||
|
|
@ -76,5 +76,5 @@ export const defaultApplyPrompt: PromptTemplateFunction = (
|
|||
history,
|
||||
otherData,
|
||||
) => {
|
||||
return `${otherData.original_code}\n\nThe following code was suggested as an edit:\n\`\`\`\n${otherData.new_code}\n\`\`\`\nPlease apply it to the previous code.`;
|
||||
return `${otherData.original_code}\n\nThe following code was suggested as an edit:\n\`\`\`\n${otherData.new_code}\n\`\`\`\nPlease apply it to the previous code. Leave existing comments in place unless changes require modifying them.`;
|
||||
};
|
||||
|
|
|
|||
|
|
@ -124,6 +124,10 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
|
|||
describe("cohere", () => {
|
||||
const supportsFn = PROVIDER_TOOL_SUPPORT["cohere"];
|
||||
|
||||
it("should return false for Command A Vision models", () => {
|
||||
expect(supportsFn("command-a-vision")).toBe(false);
|
||||
});
|
||||
|
||||
it("should return true for Command models", () => {
|
||||
expect(supportsFn("command-r")).toBe(true);
|
||||
expect(supportsFn("command-a")).toBe(true);
|
||||
|
|
|
|||
|
|
@ -22,7 +22,6 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
|||
if (["claude"].some((part) => model.toLowerCase().startsWith(part))) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
azure: (model) => {
|
||||
|
|
@ -76,7 +75,11 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
|||
return false;
|
||||
},
|
||||
cohere: (model) => {
|
||||
return model.toLowerCase().startsWith("command");
|
||||
const lower = model.toLowerCase();
|
||||
if (lower.startsWith("command-a-vision")) {
|
||||
return false;
|
||||
}
|
||||
return lower.startsWith("command");
|
||||
},
|
||||
gemini: (model) => {
|
||||
// All gemini models support function calling
|
||||
|
|
@ -92,7 +95,9 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
|||
},
|
||||
xAI: (model) => {
|
||||
const lowerCaseModel = model.toLowerCase();
|
||||
return ["grok-3", "grok-4"].some((val) => lowerCaseModel.includes(val));
|
||||
return ["grok-3", "grok-4", "grok-4-1", "grok-code"].some((val) =>
|
||||
lowerCaseModel.includes(val),
|
||||
);
|
||||
},
|
||||
bedrock: (model) => {
|
||||
if (
|
||||
|
|
@ -169,6 +174,8 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
|||
"llama3-groq",
|
||||
"granite3",
|
||||
"granite-3",
|
||||
"granite4",
|
||||
"granite-4",
|
||||
"aya-expanse",
|
||||
"firefunction-v2",
|
||||
"mistral",
|
||||
|
|
@ -360,9 +367,12 @@ export function isRecommendedAgentModel(modelName: string): boolean {
|
|||
[/o[134]/],
|
||||
[/deepseek/, /r1|reasoner/],
|
||||
[/gemini/, /2\.5/, /pro/],
|
||||
[/gpt-5/],
|
||||
[/gpt/, /-5|5\.1/],
|
||||
[/claude/, /sonnet/, /3\.7|3-7|-4/],
|
||||
[/claude/, /opus/, /-4/],
|
||||
[/grok-code/],
|
||||
[/grok-4-1|grok-4\.1/],
|
||||
[/claude/, /4-5/],
|
||||
];
|
||||
for (const combo of recs) {
|
||||
if (combo.every((regex) => modelName.toLowerCase().match(regex))) {
|
||||
|
|
|
|||
|
|
@ -461,9 +461,13 @@ export class NextEditProvider {
|
|||
// prompts[1] extracts the user prompt from the system-user prompt pair.
|
||||
// NOTE: Stream is currently set to false, but this should ideally be a per-model flag.
|
||||
// Mercury Coder currently does not support streaming.
|
||||
const msg: ChatMessage = await llm.chat([prompts[1]], token, {
|
||||
stream: false,
|
||||
});
|
||||
const msg: ChatMessage = await llm.chat(
|
||||
this.endpointType === "fineTuned" ? [prompts[1]] : prompts,
|
||||
token,
|
||||
{
|
||||
stream: false,
|
||||
},
|
||||
);
|
||||
|
||||
if (typeof msg.content !== "string") {
|
||||
return undefined;
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { IDE, Position } from "../..";
|
||||
import { GetLspDefinitionsFunction } from "../../autocomplete/types";
|
||||
import { ConfigHandler } from "../../config/ConfigHandler";
|
||||
import { isSecurityConcern } from "../../indexing/ignore.js";
|
||||
import { NextEditProvider } from "../NextEditProvider";
|
||||
import { EditAggregator } from "./aggregateEdits";
|
||||
import { BeforeAfterDiff, createDiff, DiffFormatType } from "./diffFormatting";
|
||||
|
|
@ -23,16 +24,18 @@ export const processSmallEdit = async (
|
|||
recentlyVisitedRanges: [],
|
||||
};
|
||||
|
||||
NextEditProvider.getInstance().addDiffToContext(
|
||||
createDiff({
|
||||
beforeContent: beforeAfterdiff.beforeContent,
|
||||
afterContent: beforeAfterdiff.afterContent,
|
||||
filePath: beforeAfterdiff.filePath,
|
||||
diffType: DiffFormatType.Unified,
|
||||
contextLines: 3, // NOTE: This can change depending on experiments!
|
||||
workspaceDir: currentData.workspaceDir,
|
||||
}),
|
||||
);
|
||||
if (!isSecurityConcern(beforeAfterdiff.filePath)) {
|
||||
NextEditProvider.getInstance().addDiffToContext(
|
||||
createDiff({
|
||||
beforeContent: beforeAfterdiff.beforeContent,
|
||||
afterContent: beforeAfterdiff.afterContent,
|
||||
filePath: beforeAfterdiff.filePath,
|
||||
diffType: DiffFormatType.Unified,
|
||||
contextLines: 3, // NOTE: This can change depending on experiments!
|
||||
workspaceDir: currentData.workspaceDir,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
void processNextEditData({
|
||||
filePath: beforeAfterdiff.filePath,
|
||||
|
|
|
|||
728
core/package-lock.json
generated
728
core/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -85,7 +85,7 @@
|
|||
"fastest-levenshtein": "^1.0.16",
|
||||
"filtrex": "^3.1.0",
|
||||
"follow-redirects": "^1.15.5",
|
||||
"google-auth-library": "^9.14.2",
|
||||
"google-auth-library": "^10.4.1",
|
||||
"handlebars": "^4.7.8",
|
||||
"http-proxy-agent": "^7.0.1",
|
||||
"https-proxy-agent": "^7.0.3",
|
||||
|
|
@ -109,7 +109,7 @@
|
|||
"pg": "^8.11.3",
|
||||
"plist": "^3.1.0",
|
||||
"posthog-node": "^3.6.3",
|
||||
"puppeteer": "^22.4.0",
|
||||
"puppeteer": "^24.15.0",
|
||||
"puppeteer-chromium-resolver": "^23.0.0",
|
||||
"quick-lru": "^7.0.0",
|
||||
"replicate": "^0.26.0",
|
||||
|
|
@ -121,6 +121,7 @@
|
|||
"system-ca": "^1.0.3",
|
||||
"tar": "^7.4.3",
|
||||
"tree-sitter-wasms": "^0.1.11",
|
||||
"untildify": "^6.0.0",
|
||||
"uuid": "^9.0.1",
|
||||
"vectordb": "^0.4.20",
|
||||
"web-tree-sitter": "^0.21.0",
|
||||
|
|
@ -129,7 +130,7 @@
|
|||
"winston": "^3.17.0",
|
||||
"workerpool": "^9.1.3",
|
||||
"yaml": "^2.4.2",
|
||||
"zod": "^3.24.2"
|
||||
"zod": "^3.25.76"
|
||||
},
|
||||
"engine-strict": true,
|
||||
"engines": {
|
||||
|
|
|
|||
|
|
@ -24,7 +24,9 @@ export async function getPromptFilesFromDir(
|
|||
const uris = await walkDir(dir, ide, {
|
||||
source: "get dir prompt files",
|
||||
});
|
||||
const promptFilePaths = uris.filter((p) => p.endsWith(".prompt"));
|
||||
const promptFilePaths = uris.filter(
|
||||
(p) => p.endsWith(".prompt") || p.endsWith(".md"),
|
||||
);
|
||||
const results = promptFilePaths.map(async (uri) => {
|
||||
const content = await ide.readFile(uri); // make a try catch
|
||||
return { path: uri, content };
|
||||
|
|
@ -68,10 +70,11 @@ export async function getAllPromptFiles(
|
|||
);
|
||||
promptFiles.push(...promptFilesFromRulesDirectory);
|
||||
|
||||
return await Promise.all(
|
||||
const result = await Promise.all(
|
||||
promptFiles.map(async (file) => {
|
||||
const content = await ide.readFile(file.path);
|
||||
return { path: file.path, content };
|
||||
}),
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -90,8 +90,11 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
},
|
||||
void,
|
||||
];
|
||||
"config/addLocalWorkspaceBlock": [{ blockType: BlockType }, void];
|
||||
"config/addGlobalRule": [undefined, void];
|
||||
"config/addLocalWorkspaceBlock": [
|
||||
{ blockType: BlockType; baseFilename?: string },
|
||||
void,
|
||||
];
|
||||
"config/addGlobalRule": [undefined | { baseFilename?: string }, void];
|
||||
"config/newPromptFile": [undefined, void];
|
||||
"config/newAssistantFile": [undefined, void];
|
||||
"config/ideSettingsUpdate": [IdeSettings, void];
|
||||
|
|
@ -241,6 +244,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
AsyncGenerator<ChatMessage, PromptLog>,
|
||||
];
|
||||
streamDiffLines: [StreamDiffLinesPayload, AsyncGenerator<DiffLine>];
|
||||
getDiffLines: [{ oldContent: string; newContent: string }, DiffLine[]];
|
||||
"llm/compileChat": [
|
||||
{ messages: ChatMessage[]; options: LLMFullCompletionOptions },
|
||||
CompiledMessagesResult,
|
||||
|
|
@ -314,7 +318,12 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
},
|
||||
];
|
||||
"tools/evaluatePolicy": [
|
||||
{ toolName: string; basePolicy: ToolPolicy; args: Record<string, unknown> },
|
||||
{
|
||||
toolName: string;
|
||||
basePolicy: ToolPolicy;
|
||||
parsedArgs: Record<string, unknown>;
|
||||
processedArgs?: Record<string, unknown>;
|
||||
},
|
||||
{ policy: ToolPolicy; displayValue?: string },
|
||||
];
|
||||
"tools/preprocessArgs": [
|
||||
|
|
|
|||
|
|
@ -78,6 +78,12 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
|
|||
totalCount: number;
|
||||
},
|
||||
];
|
||||
openAgentLocally: [
|
||||
{
|
||||
agentSessionId: string;
|
||||
},
|
||||
void,
|
||||
];
|
||||
};
|
||||
|
||||
export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
|
||||
|
|
@ -94,6 +100,7 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
|
|||
|
||||
focusContinueSessionId: [{ sessionId: string | undefined }, void];
|
||||
newSession: [undefined, void];
|
||||
loadAgentSession: [{ session: any }, void];
|
||||
setTheme: [{ theme: any }, void];
|
||||
setColors: [{ [key: string]: string }, void];
|
||||
"jetbrains/editorInsetRefresh": [undefined, void];
|
||||
|
|
|
|||
|
|
@ -1,5 +1,8 @@
|
|||
import { ToolPolicy } from "@continuedev/terminal-security";
|
||||
import { Tool } from "../..";
|
||||
import { ResolvedPath, resolveInputPath } from "../../util/pathResolver";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import { evaluateFileAccessPolicy } from "../policies/fileAccess";
|
||||
|
||||
export const createNewFileTool: Tool = {
|
||||
type: "function",
|
||||
|
|
@ -21,7 +24,7 @@ export const createNewFileTool: Tool = {
|
|||
filepath: {
|
||||
type: "string",
|
||||
description:
|
||||
"The path where the new file should be created, relative to the root of the workspace",
|
||||
"The path where the new file should be created. Can be a relative path (from workspace root), absolute path, tilde path (~/...), or file:// URI.",
|
||||
},
|
||||
contents: {
|
||||
type: "string",
|
||||
|
|
@ -38,4 +41,26 @@ export const createNewFileTool: Tool = {
|
|||
["contents", "Contents of the file"],
|
||||
],
|
||||
},
|
||||
preprocessArgs: async (args, { ide }) => {
|
||||
const filepath = args.filepath as string;
|
||||
const resolvedPath = await resolveInputPath(ide, filepath);
|
||||
|
||||
// Store the resolved path info in args for policy evaluation
|
||||
return {
|
||||
resolvedPath,
|
||||
};
|
||||
},
|
||||
evaluateToolCallPolicy: (
|
||||
basePolicy: ToolPolicy,
|
||||
_: Record<string, unknown>,
|
||||
processedArgs?: Record<string, unknown>,
|
||||
): ToolPolicy => {
|
||||
const resolvedPath = processedArgs?.resolvedPath as
|
||||
| ResolvedPath
|
||||
| null
|
||||
| undefined;
|
||||
if (!resolvedPath) return basePolicy;
|
||||
|
||||
return evaluateFileAccessPolicy(basePolicy, resolvedPath.isWithinWorkspace);
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ export const grepSearchTool: Tool = {
|
|||
function: {
|
||||
name: BuiltInToolNames.GrepSearch,
|
||||
description:
|
||||
"Perform a search over the repository using ripgrep. Will not include results for many build, cache, secrets dirs/files. Output may be truncated, so use targeted queries",
|
||||
"Performs a regex search over the repository using ripgrep. Will not include results for many build, cache, secrets dirs/files. Output may be truncated, so use targeted queries",
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["query"],
|
||||
|
|
@ -21,7 +21,7 @@ export const grepSearchTool: Tool = {
|
|||
query: {
|
||||
type: "string",
|
||||
description:
|
||||
"The search query to use. Must be a valid ripgrep regex expression, escaped where needed",
|
||||
"The search query to use. Must be the exact string to be searched or a valid ripgrep expression. Use regex with alternation (e.g., 'word1|word2|word3) or character classes to find multiple potential words in a single search.",
|
||||
},
|
||||
},
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
import { Tool } from "../..";
|
||||
|
||||
import { ToolPolicy } from "@continuedev/terminal-security";
|
||||
import { ResolvedPath, resolveInputPath } from "../../util/pathResolver";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import { evaluateFileAccessPolicy } from "../policies/fileAccess";
|
||||
|
||||
export const lsTool: Tool = {
|
||||
type: "function",
|
||||
|
|
@ -20,7 +23,7 @@ export const lsTool: Tool = {
|
|||
dirPath: {
|
||||
type: "string",
|
||||
description:
|
||||
"The directory path relative to the root of the project. Use forward slash paths like '/'. rather than e.g. '.'",
|
||||
"The directory path. Can be relative to project root, absolute path, tilde path (~/...), or file:// URI. Use forward slash paths",
|
||||
},
|
||||
recursive: {
|
||||
type: "boolean",
|
||||
|
|
@ -39,4 +42,28 @@ export const lsTool: Tool = {
|
|||
],
|
||||
},
|
||||
toolCallIcon: "FolderIcon",
|
||||
preprocessArgs: async (args, { ide }) => {
|
||||
const dirPath = args.dirPath as string;
|
||||
|
||||
// Default to current directory if no path provided
|
||||
const pathToResolve = dirPath || ".";
|
||||
const resolvedPath = await resolveInputPath(ide, pathToResolve);
|
||||
|
||||
return {
|
||||
resolvedPath,
|
||||
};
|
||||
},
|
||||
evaluateToolCallPolicy: (
|
||||
basePolicy: ToolPolicy,
|
||||
_: Record<string, unknown>,
|
||||
processedArgs?: Record<string, unknown>,
|
||||
): ToolPolicy => {
|
||||
const resolvedPath = processedArgs?.resolvedPath as
|
||||
| ResolvedPath
|
||||
| null
|
||||
| undefined;
|
||||
if (!resolvedPath) return basePolicy;
|
||||
|
||||
return evaluateFileAccessPolicy(basePolicy, resolvedPath.isWithinWorkspace);
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,5 +1,8 @@
|
|||
import { ToolPolicy } from "@continuedev/terminal-security";
|
||||
import { Tool } from "../..";
|
||||
import { ResolvedPath, resolveInputPath } from "../../util/pathResolver";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import { evaluateFileAccessPolicy } from "../policies/fileAccess";
|
||||
|
||||
export const readFileTool: Tool = {
|
||||
type: "function",
|
||||
|
|
@ -21,7 +24,7 @@ export const readFileTool: Tool = {
|
|||
filepath: {
|
||||
type: "string",
|
||||
description:
|
||||
"The path of the file to read, relative to the root of the workspace (NOT uri or absolute path)",
|
||||
"The path of the file to read. Can be a relative path (from workspace root), absolute path, tilde path (~/...), or file:// URI",
|
||||
},
|
||||
},
|
||||
},
|
||||
|
|
@ -32,4 +35,26 @@ export const readFileTool: Tool = {
|
|||
},
|
||||
defaultToolPolicy: "allowedWithoutPermission",
|
||||
toolCallIcon: "DocumentIcon",
|
||||
preprocessArgs: async (args, { ide }) => {
|
||||
const filepath = args.filepath as string;
|
||||
const resolvedPath = await resolveInputPath(ide, filepath);
|
||||
|
||||
// Store the resolved path info in args for policy evaluation
|
||||
return {
|
||||
resolvedPath,
|
||||
};
|
||||
},
|
||||
evaluateToolCallPolicy: (
|
||||
basePolicy: ToolPolicy,
|
||||
_: Record<string, unknown>,
|
||||
processedArgs?: Record<string, unknown>,
|
||||
): ToolPolicy => {
|
||||
const resolvedPath = processedArgs?.resolvedPath as
|
||||
| ResolvedPath
|
||||
| null
|
||||
| undefined;
|
||||
if (!resolvedPath) return basePolicy;
|
||||
|
||||
return evaluateFileAccessPolicy(basePolicy, resolvedPath.isWithinWorkspace);
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,5 +1,8 @@
|
|||
import { ToolPolicy } from "@continuedev/terminal-security";
|
||||
import { Tool } from "../..";
|
||||
import { ResolvedPath, resolveInputPath } from "../../util/pathResolver";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import { evaluateFileAccessPolicy } from "../policies/fileAccess";
|
||||
|
||||
export const readFileRangeTool: Tool = {
|
||||
type: "function",
|
||||
|
|
@ -49,4 +52,25 @@ export const readFileRangeTool: Tool = {
|
|||
},
|
||||
defaultToolPolicy: "allowedWithoutPermission",
|
||||
toolCallIcon: "DocumentIcon",
|
||||
preprocessArgs: async (args, { ide }) => {
|
||||
const filepath = args.filepath as string;
|
||||
const resolvedPath = await resolveInputPath(ide, filepath);
|
||||
|
||||
return {
|
||||
resolvedPath,
|
||||
};
|
||||
},
|
||||
evaluateToolCallPolicy: (
|
||||
basePolicy: ToolPolicy,
|
||||
_: Record<string, unknown>,
|
||||
processedArgs?: Record<string, unknown>,
|
||||
): ToolPolicy => {
|
||||
const resolvedPath = processedArgs?.resolvedPath as
|
||||
| ResolvedPath
|
||||
| null
|
||||
| undefined;
|
||||
if (!resolvedPath) return basePolicy;
|
||||
|
||||
return evaluateFileAccessPolicy(basePolicy, resolvedPath.isWithinWorkspace);
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@ const RUN_COMMAND_NOTES = `The shell is not stateful and will not remember any p
|
|||
When a command is run in the background ALWAYS suggest using shell commands to stop it; NEVER suggest using Ctrl+C.\
|
||||
When suggesting subsequent shell commands ALWAYS format them in shell command blocks.\
|
||||
Do NOT perform actions requiring special/admin privileges.\
|
||||
IMPORTANT: To edit files, use Edit/MultiEdit tools instead of bash commands (sed, awk, etc).\
|
||||
${PLATFORM_INFO}`;
|
||||
|
||||
export const runTerminalCommandTool: Tool = {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,8 @@
|
|||
import { ToolPolicy } from "@continuedev/terminal-security";
|
||||
import { Tool } from "../..";
|
||||
import { ResolvedPath, resolveInputPath } from "../../util/pathResolver";
|
||||
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
|
||||
import { evaluateFileAccessPolicy } from "../policies/fileAccess";
|
||||
|
||||
export const viewSubdirectoryTool: Tool = {
|
||||
type: "function",
|
||||
|
|
@ -31,4 +34,25 @@ export const viewSubdirectoryTool: Tool = {
|
|||
},
|
||||
defaultToolPolicy: "allowedWithPermission",
|
||||
toolCallIcon: "FolderOpenIcon",
|
||||
preprocessArgs: async (args, { ide }) => {
|
||||
const directoryPath = args.directory_path as string;
|
||||
const resolvedPath = await resolveInputPath(ide, directoryPath);
|
||||
|
||||
return {
|
||||
resolvedPath,
|
||||
};
|
||||
},
|
||||
evaluateToolCallPolicy: (
|
||||
basePolicy: ToolPolicy,
|
||||
_: Record<string, unknown>,
|
||||
processedArgs?: Record<string, unknown>,
|
||||
): ToolPolicy => {
|
||||
const resolvedPath = processedArgs?.resolvedPath as
|
||||
| ResolvedPath
|
||||
| null
|
||||
| undefined;
|
||||
if (!resolvedPath) return basePolicy;
|
||||
|
||||
return evaluateFileAccessPolicy(basePolicy, resolvedPath.isWithinWorkspace);
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -89,3 +89,13 @@ test("fetchUrlContent should add truncation warning with multiple truncated item
|
|||
expect(result[1].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT);
|
||||
expect(result[2].name).toBe("Truncation warning");
|
||||
});
|
||||
|
||||
test("fetchUrlContent should propagate errors when URL fetch fails", async () => {
|
||||
const errorMessage = "HTTP 404 Not Found";
|
||||
|
||||
(getUrlContextItems as any).mockRejectedValue(new Error(errorMessage));
|
||||
|
||||
await expect(
|
||||
fetchUrlContentImpl({ url: "https://example.com/404" }, mockExtras),
|
||||
).rejects.toThrow(errorMessage);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -2,14 +2,15 @@ import ignore from "ignore";
|
|||
|
||||
import { ToolImpl } from ".";
|
||||
import { walkDir } from "../../indexing/walkDir";
|
||||
import { resolveRelativePathInDir } from "../../util/ideUtils";
|
||||
import { resolveInputPath } from "../../util/pathResolver";
|
||||
import { ContinueError, ContinueErrorReason } from "../../util/errors";
|
||||
|
||||
export function resolveLsToolDirPath(dirPath: string | undefined) {
|
||||
if (!dirPath || dirPath === ".") {
|
||||
return "/";
|
||||
}
|
||||
if (dirPath.startsWith(".")) {
|
||||
// Don't strip leading slash from absolute paths - let the resolver handle it
|
||||
if (dirPath.startsWith(".") && !dirPath.startsWith("./")) {
|
||||
return dirPath.slice(1);
|
||||
}
|
||||
return dirPath.replace(/\\/g, "/");
|
||||
|
|
@ -19,15 +20,15 @@ const MAX_LS_TOOL_LINES = 200;
|
|||
|
||||
export const lsToolImpl: ToolImpl = async (args, extras) => {
|
||||
const dirPath = resolveLsToolDirPath(args?.dirPath);
|
||||
const uri = await resolveRelativePathInDir(dirPath, extras.ide);
|
||||
if (!uri) {
|
||||
const resolvedPath = await resolveInputPath(extras.ide, dirPath);
|
||||
if (!resolvedPath) {
|
||||
throw new ContinueError(
|
||||
ContinueErrorReason.DirectoryNotFound,
|
||||
`Directory ${args.dirPath} not found. Make sure to use forward-slash paths`,
|
||||
`Directory ${args.dirPath} not found or is not accessible. You can use absolute paths, relative paths, or paths starting with ~`,
|
||||
);
|
||||
}
|
||||
|
||||
const entries = await walkDir(uri, extras.ide, {
|
||||
const entries = await walkDir(resolvedPath.uri, extras.ide, {
|
||||
returnRelativeUrisPaths: true,
|
||||
include: "both",
|
||||
recursive: args?.recursive ?? false,
|
||||
|
|
@ -39,12 +40,12 @@ export const lsToolImpl: ToolImpl = async (args, extras) => {
|
|||
let content =
|
||||
lines.length > 0
|
||||
? lines.join("\n")
|
||||
: `No files/folders found in ${dirPath}`;
|
||||
: `No files/folders found in ${resolvedPath.displayPath}`;
|
||||
|
||||
const contextItems = [
|
||||
{
|
||||
name: "File/folder list",
|
||||
description: `Files/folders in ${dirPath}`,
|
||||
description: `Files/folders in ${resolvedPath.displayPath}`,
|
||||
content,
|
||||
},
|
||||
];
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue