Merge branch 'main' into core-vitest/config
This commit is contained in:
commit
35029e2409
221 changed files with 15205 additions and 4212 deletions
7
.continue/rules/github-pr-documentation-updater.md
Normal file
7
.continue/rules/github-pr-documentation-updater.md
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
---
|
||||
name: Update docs from GitHub PR
|
||||
description: Provide a PR link to update docs based on
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
When provided with a GitHub PR URL, use the GitHub CLI (`gh pr view <PR_URL> --json title,body,commits,files,additions,deletions,changedFiles`) to fetch comprehensive PR details including title, description, commits, changed files, and diff statistics. Analyze the PR content to identify what documentation in the `docs` folder needs to be updated, created, or modified. Update relevant documentation files to reflect the changes, new features, bug fixes, or improvements described in the PR. Ensure documentation changes are accurate, well-structured, and maintain consistency with existing docs formatting and style.
|
||||
4
.continue/rules/navigating-responses.md
Normal file
4
.continue/rules/navigating-responses.md
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
If the user's request is vague and you don't have enough information to confidently answer, you can either
|
||||
|
||||
- In Chat OR Agent mode, stop and ask questions to clarify before proceeding
|
||||
- In Agent mode, use tools to discover more information, starting with the glob/grep tools if available.
|
||||
35
.continue/rules/new-protocol-message.md
Normal file
35
.continue/rules/new-protocol-message.md
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
---
|
||||
name: New protocol message
|
||||
description: Create a new protocol message from core/gui/ide to core/gui/ide
|
||||
---
|
||||
|
||||
Create a new protocol message by taking the following steps:
|
||||
|
||||
## 1. Define the message type
|
||||
|
||||
Add your new message type definition to the appropriate file in the `protocol/` directory with correct TypeScript typing.
|
||||
|
||||
## 2. Check for duplicates
|
||||
|
||||
Verify that no existing message type already provides the same functionality.
|
||||
|
||||
## 3. Add to passThrough (if webview ↔ core)
|
||||
|
||||
If your message is between webview and core, add it to `core/protocol/passThrough.ts`.
|
||||
|
||||
## 4. Add to IntelliJ constants (if webview ↔ core)
|
||||
|
||||
If your message is between webview and core, add it to `extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt`.
|
||||
|
||||
## 5. Implement the message handler
|
||||
|
||||
Implement the message in the appropriate location:
|
||||
|
||||
- **Messages to core**: `core/core.ts`
|
||||
- **Messages to GUI**: `useWebviewListener` hook
|
||||
- **Messages to VS Code IDE**: `VsCodeMessenger.ts`
|
||||
- **Messages to JetBrains IDE**: `IdeProtocolClient.kt`
|
||||
|
||||
## 6. Test the implementation
|
||||
|
||||
Verify that your message works correctly in both VS Code and JetBrains IDEs if applicable.
|
||||
5
.continue/rules/overeager.md
Normal file
5
.continue/rules/overeager.md
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
---
|
||||
name: Don't be overeager
|
||||
---
|
||||
|
||||
Avoid over-eagerly adding new features. You should solve the problem at hand and then can propose further work.
|
||||
6
.continue/rules/programming-principles.md
Normal file
6
.continue/rules/programming-principles.md
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
---
|
||||
name: Programming principles
|
||||
description: Guidelines for coding fundamentals in this project
|
||||
---
|
||||
|
||||
Use functional programming paradigms whenever possible. Modifying existing classes or creating singletons where needed is acceptable. but otherwise, use functions.
|
||||
1
.continue/rules/pure-function-unit-tests.md
Normal file
1
.continue/rules/pure-function-unit-tests.md
Normal file
|
|
@ -0,0 +1 @@
|
|||
Always create comprehensive unit tests for new pure functions. Tests should cover normal cases, edge cases, and boundary conditions.
|
||||
|
|
@ -6,25 +6,23 @@ rules:
|
|||
rule: >-
|
||||
For unit testing in this project:
|
||||
|
||||
1. The project uses Vitest and Jest for testing. Prefer Vitest
|
||||
|
||||
1. The project uses Jest as the testing framework
|
||||
2. Run tests from within the specific package directory (e.g., `cd core && ..`
|
||||
|
||||
2. Run tests using `npm test` from within the specific package/module
|
||||
directory
|
||||
3. For vitest tests,
|
||||
- Test files follow the pattern `*.vitest.ts`
|
||||
- Run tests using `vitest` from within the specific package/module
|
||||
directory: `cd [directory] && vitest -- [test file path]`
|
||||
|
||||
3. Command structure: `cd [directory] && npm test -- [test file path]`
|
||||
4. For jest tests,
|
||||
- Test files follow the pattern `*.test.ts`
|
||||
- Run tests using `npm test` from within the specific package/module
|
||||
directory: `cd [directory] && npm test -- [test file path]`
|
||||
- The test script uses experimental VM modules via NODE_OPTIONS flag
|
||||
|
||||
4. The test script uses experimental VM modules via NODE_OPTIONS flag
|
||||
|
||||
5. Test files follow the pattern `*.test.ts`
|
||||
|
||||
6. Tests must import Jest with `import { jest } from "@jest/globals";`
|
||||
|
||||
7. Run tests from within the specific package directory (e.g., `cd core`
|
||||
for core module tests)
|
||||
|
||||
8. Write tests as top-level `test()` functions - DO NOT use `describe()`
|
||||
5. For both
|
||||
- Write tests as top-level `test()` functions - DO NOT use `describe()`
|
||||
blocks
|
||||
|
||||
9. Include the function name being tested in the test description for
|
||||
- Include the function name being tested in the test description for
|
||||
clarity
|
||||
|
|
|
|||
5
.continue/rules/vs-code-commands-helper-functions.md
Normal file
5
.continue/rules/vs-code-commands-helper-functions.md
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
---
|
||||
globs: "extensions/vscode/src/commands.ts"
|
||||
---
|
||||
|
||||
When adding new commands to the commands map, always create a separate helper function for the command logic instead of defining it inline. Follow the pattern of existing commands like `streamInlineEdit` - define the helper function below the commands map, then call it from within the command entry.
|
||||
8
.github/workflows/main.yaml
vendored
8
.github/workflows/main.yaml
vendored
|
|
@ -104,6 +104,14 @@ jobs:
|
|||
path: gui/node_modules
|
||||
key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }}
|
||||
|
||||
- name: Build packages (Windows)
|
||||
run: ./scripts/build-packages.ps1
|
||||
if: matrix.os == 'windows-latest'
|
||||
|
||||
- name: Build packages (Unix)
|
||||
run: ./scripts/build-packages.sh
|
||||
if: matrix.os != 'windows-latest'
|
||||
|
||||
- name: Install extension Dependencies
|
||||
run: |
|
||||
cd extensions/vscode
|
||||
|
|
|
|||
187
.github/workflows/pr_checks.yaml
vendored
187
.github/workflows/pr_checks.yaml
vendored
|
|
@ -75,6 +75,33 @@ jobs:
|
|||
cd packages/config-yaml
|
||||
npm ci
|
||||
|
||||
install-openai-adapters:
|
||||
needs: install-root
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: node_modules
|
||||
key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: openai-adapters-cache
|
||||
with:
|
||||
path: packages/openai-adapters/node_modules
|
||||
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
|
||||
|
||||
- name: Install openai-adapters dependencies
|
||||
if: steps.openai-adapters-cache.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
cd packages/openai-adapters
|
||||
npm ci
|
||||
|
||||
config-yaml-checks:
|
||||
needs: install-config-yaml
|
||||
runs-on: ubuntu-latest
|
||||
|
|
@ -133,7 +160,7 @@ jobs:
|
|||
npm ci
|
||||
|
||||
core-checks:
|
||||
needs: [install-core, install-config-yaml]
|
||||
needs: [install-core, install-config-yaml, install-openai-adapters]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
|
@ -160,11 +187,21 @@ jobs:
|
|||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: openai-adapters-cache
|
||||
with:
|
||||
path: packages/openai-adapters/node_modules
|
||||
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Build openai-adapters
|
||||
run: |
|
||||
cd packages/openai-adapters
|
||||
npm run build
|
||||
- name: Type check and lint
|
||||
run: |
|
||||
cd core
|
||||
|
|
@ -174,7 +211,8 @@ jobs:
|
|||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
|
||||
install-gui:
|
||||
needs: [install-root, install-core, install-config-yaml]
|
||||
needs:
|
||||
[install-root, install-core, install-config-yaml, install-openai-adapters]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
|
@ -205,11 +243,22 @@ jobs:
|
|||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: openai-adapters-cache
|
||||
with:
|
||||
path: packages/openai-adapters/node_modules
|
||||
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Build openai-adapters
|
||||
run: |
|
||||
cd packages/openai-adapters
|
||||
npm run build
|
||||
|
||||
- name: Install gui dependencies
|
||||
if: steps.gui-cache.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
|
|
@ -221,7 +270,6 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
|
@ -242,6 +290,12 @@ jobs:
|
|||
path: gui/node_modules
|
||||
key: ${{ runner.os }}-gui-node-modules-${{ hashFiles('gui/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: openai-adapters-cache
|
||||
with:
|
||||
path: packages/openai-adapters/node_modules
|
||||
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: config-yaml-cache
|
||||
with:
|
||||
|
|
@ -253,6 +307,11 @@ jobs:
|
|||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Build openai-adapters
|
||||
run: |
|
||||
cd packages/openai-adapters
|
||||
npm run build
|
||||
|
||||
- name: Type check and lint
|
||||
run: |
|
||||
cd gui
|
||||
|
|
@ -260,7 +319,8 @@ jobs:
|
|||
npm run lint
|
||||
|
||||
binary-checks:
|
||||
needs: [install-root, install-core, install-config-yaml]
|
||||
needs:
|
||||
[install-root, install-core, install-config-yaml, install-openai-adapters]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
|
@ -291,11 +351,22 @@ jobs:
|
|||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: openai-adapters-cache
|
||||
with:
|
||||
path: packages/openai-adapters/node_modules
|
||||
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Build openai-adapters
|
||||
run: |
|
||||
cd packages/openai-adapters
|
||||
npm run build
|
||||
|
||||
- name: Install binary dependencies
|
||||
if: steps.binary-cache.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
|
|
@ -308,7 +379,8 @@ jobs:
|
|||
npx tsc --noEmit
|
||||
|
||||
install-vscode:
|
||||
needs: [install-root, install-core, install-config-yaml]
|
||||
needs:
|
||||
[install-root, install-core, install-config-yaml, install-openai-adapters]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
|
@ -339,11 +411,22 @@ jobs:
|
|||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: openai-adapters-cache
|
||||
with:
|
||||
path: packages/openai-adapters/node_modules
|
||||
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Build openai-adapters
|
||||
run: |
|
||||
cd packages/openai-adapters
|
||||
npm run build
|
||||
|
||||
- name: Install vscode dependencies
|
||||
if: steps.vscode-cache.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
|
|
@ -384,11 +467,22 @@ jobs:
|
|||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: openai-adapters-cache
|
||||
with:
|
||||
path: packages/openai-adapters/node_modules
|
||||
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Build openai-adapters
|
||||
run: |
|
||||
cd packages/openai-adapters
|
||||
npm run build
|
||||
|
||||
- name: Type check and lint
|
||||
run: |
|
||||
cd extensions/vscode
|
||||
|
|
@ -402,7 +496,7 @@ jobs:
|
|||
npm run vitest
|
||||
|
||||
core-tests:
|
||||
needs: [install-core, install-config-yaml]
|
||||
needs: [install-core, install-config-yaml, install-openai-adapters]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
|
@ -422,11 +516,22 @@ jobs:
|
|||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: openai-adapters-cache
|
||||
with:
|
||||
path: packages/openai-adapters/node_modules
|
||||
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Build openai-adapters
|
||||
run: |
|
||||
cd packages/openai-adapters
|
||||
npm run build
|
||||
|
||||
- name: Run core tests
|
||||
run: |
|
||||
cd core
|
||||
|
|
@ -476,7 +581,7 @@ jobs:
|
|||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Cache node modules
|
||||
uses: actions/cache@v3
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: extensions/vscode/node_modules
|
||||
key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }}
|
||||
|
|
@ -515,7 +620,13 @@ jobs:
|
|||
|
||||
vscode-package-extension:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [install-vscode, install-core, install-config-yaml]
|
||||
needs:
|
||||
[
|
||||
install-vscode,
|
||||
install-core,
|
||||
install-config-yaml,
|
||||
install-openai-adapters,
|
||||
]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
|
|
@ -541,11 +652,22 @@ jobs:
|
|||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: openai-adapters-cache
|
||||
with:
|
||||
path: packages/openai-adapters/node_modules
|
||||
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Build openai-adapters
|
||||
run: |
|
||||
cd packages/openai-adapters
|
||||
npm run build
|
||||
|
||||
- name: Package extension
|
||||
run: |
|
||||
cd extensions/vscode
|
||||
|
|
@ -559,7 +681,13 @@ jobs:
|
|||
|
||||
vscode-download-e2e-dependencies:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [install-vscode, install-core, install-config-yaml]
|
||||
needs:
|
||||
[
|
||||
install-vscode,
|
||||
install-core,
|
||||
install-config-yaml,
|
||||
install-openai-adapters,
|
||||
]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
|
|
@ -612,6 +740,7 @@ jobs:
|
|||
install-vscode,
|
||||
install-core,
|
||||
install-config-yaml,
|
||||
install-openai-adapters,
|
||||
]
|
||||
runs-on: ubuntu-latest
|
||||
# Tests requiring secrets need approval from maintainers
|
||||
|
|
@ -658,11 +787,22 @@ jobs:
|
|||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: openai-adapters-cache
|
||||
with:
|
||||
path: packages/openai-adapters/node_modules
|
||||
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Build openai-adapters
|
||||
run: |
|
||||
cd packages/openai-adapters
|
||||
npm run build
|
||||
|
||||
- name: Fix VSCode binary permissions
|
||||
run: |
|
||||
chmod +x extensions/vscode/e2e/storage/VSCode-linux-x64/code
|
||||
|
|
@ -726,7 +866,8 @@ jobs:
|
|||
path: extensions/vscode/e2e.log
|
||||
|
||||
gui-tests:
|
||||
needs: [install-gui, install-core, install-config-yaml]
|
||||
needs:
|
||||
[install-gui, install-core, install-config-yaml, install-openai-adapters]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
|
@ -752,11 +893,22 @@ jobs:
|
|||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: openai-adapters-cache
|
||||
with:
|
||||
path: packages/openai-adapters/node_modules
|
||||
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Build openai-adapters
|
||||
run: |
|
||||
cd packages/openai-adapters
|
||||
npm run build
|
||||
|
||||
- name: Install GUI dependencies
|
||||
if: steps.gui-cache.outputs.cache-hit != 'true'
|
||||
run: cd gui && npm ci
|
||||
|
|
@ -769,7 +921,8 @@ jobs:
|
|||
npm test
|
||||
|
||||
jetbrains-tests:
|
||||
needs: [install-root, core-checks, install-config-yaml]
|
||||
needs:
|
||||
[install-root, core-checks, install-config-yaml, install-openai-adapters]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
|
@ -784,11 +937,22 @@ jobs:
|
|||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: openai-adapters-cache
|
||||
with:
|
||||
path: packages/openai-adapters/node_modules
|
||||
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Build openai-adapters
|
||||
run: |
|
||||
cd packages/openai-adapters
|
||||
npm run build
|
||||
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v4.5.0
|
||||
with:
|
||||
|
|
@ -903,6 +1067,7 @@ jobs:
|
|||
- jetbrains-tests
|
||||
- config-yaml-checks
|
||||
- install-config-yaml
|
||||
- install-openai-adapters
|
||||
|
||||
steps:
|
||||
- name: Decide whether the needed jobs succeeded or failed
|
||||
|
|
|
|||
8
.github/workflows/preview.yaml
vendored
8
.github/workflows/preview.yaml
vendored
|
|
@ -99,6 +99,14 @@ jobs:
|
|||
path: gui/node_modules
|
||||
key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }}
|
||||
|
||||
- name: Build packages (Windows)
|
||||
run: ./scripts/build-packages.ps1
|
||||
if: matrix.os == 'windows-latest'
|
||||
|
||||
- name: Build packages (Unix)
|
||||
run: ./scripts/build-packages.sh
|
||||
if: matrix.os != 'windows-latest'
|
||||
|
||||
- name: Install extension Dependencies
|
||||
run: |
|
||||
cd extensions/vscode
|
||||
|
|
|
|||
42
.github/workflows/release-config-yaml.yml
vendored
42
.github/workflows/release-config-yaml.yml
vendored
|
|
@ -9,38 +9,10 @@ on:
|
|||
|
||||
jobs:
|
||||
release:
|
||||
name: Release
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Use Node.js from .nvmrc
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm ci
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Run tests
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm test
|
||||
|
||||
- name: Release
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npx semantic-release
|
||||
uses: ./.github/workflows/reusable-release.yml
|
||||
with:
|
||||
package-name: "config-yaml"
|
||||
package-path: "packages/config-yaml"
|
||||
secrets:
|
||||
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
|
||||
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
|
||||
|
|
|
|||
18
.github/workflows/release-fetch.yml
vendored
Normal file
18
.github/workflows/release-fetch.yml
vendored
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
name: Release @continuedev/fetch
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "packages/fetch/**"
|
||||
|
||||
jobs:
|
||||
release:
|
||||
uses: ./.github/workflows/reusable-release.yml
|
||||
with:
|
||||
package-name: "fetch"
|
||||
package-path: "packages/fetch"
|
||||
secrets:
|
||||
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
|
||||
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
|
||||
18
.github/workflows/release-llm-info.yml
vendored
Normal file
18
.github/workflows/release-llm-info.yml
vendored
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
name: Release @continuedev/llm-info
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "packages/llm-info/**"
|
||||
|
||||
jobs:
|
||||
release:
|
||||
uses: ./.github/workflows/reusable-release.yml
|
||||
with:
|
||||
package-name: "llm-info"
|
||||
package-path: "packages/llm-info"
|
||||
secrets:
|
||||
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
|
||||
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
|
||||
18
.github/workflows/release-openai-adapters.yml
vendored
Normal file
18
.github/workflows/release-openai-adapters.yml
vendored
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
name: Release @continuedev/openai-adapters
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "packages/openai-adapters/**"
|
||||
|
||||
jobs:
|
||||
release:
|
||||
uses: ./.github/workflows/reusable-release.yml
|
||||
with:
|
||||
package-name: "openai-adapters"
|
||||
package-path: "packages/openai-adapters"
|
||||
secrets:
|
||||
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
|
||||
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
|
||||
55
.github/workflows/reusable-release.yml
vendored
Normal file
55
.github/workflows/reusable-release.yml
vendored
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
name: Reusable Release Workflow
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
package-name:
|
||||
required: true
|
||||
type: string
|
||||
package-path:
|
||||
required: true
|
||||
type: string
|
||||
secrets:
|
||||
SEMANTIC_RELEASE_GITHUB_TOKEN:
|
||||
required: true
|
||||
SEMANTIC_RELEASE_NPM_TOKEN:
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
release:
|
||||
name: Release ${{ inputs.package-name }}
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: ${{ inputs.package-path }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Use Node.js from .nvmrc
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
|
||||
- name: Run tests
|
||||
run: npm test
|
||||
|
||||
- name: Release
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
|
||||
NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
|
||||
NODE_AUTH_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
|
||||
run: npx semantic-release
|
||||
26
.vscode/launch.json
vendored
26
.vscode/launch.json
vendored
|
|
@ -73,32 +73,6 @@
|
|||
"sourceMaps": true
|
||||
// "preLaunchTask": "gui:dev"
|
||||
},
|
||||
// Has to be run after starting the server (separately or using the compound configuration)
|
||||
{
|
||||
"name": "Run tests",
|
||||
"type": "extensionHost",
|
||||
"request": "launch",
|
||||
"cwd": "${workspaceFolder}/extensions/vscode",
|
||||
"runtimeExecutable": "${execPath}",
|
||||
"args": [
|
||||
// Pass a directory to run tests in
|
||||
"${workspaceFolder}/extensions/vscode/manual-testing-sandbox",
|
||||
"--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode",
|
||||
"--extensionTestsPath=${workspaceFolder}/extensions/vscode/out/test/runner/mochaRunner"
|
||||
],
|
||||
"outFiles": [
|
||||
// Allows setting breakpoints in test suites across the /src folder
|
||||
"${workspaceFolder}/extensions/vscode/out/test/test-suites/**/*.js",
|
||||
// Allows setting breakpoints in mocha test runner file
|
||||
"${workspaceFolder}/extensions/vscode/out/test/runner/**/*.js"
|
||||
],
|
||||
"internalConsoleOptions": "openOnSessionStart",
|
||||
"preLaunchTask": "vscode-extension:tests:build",
|
||||
"env": {
|
||||
// Avoid timing out when stopping on breakpoints during debugging in VSCode
|
||||
"MOCHA_TIMEOUT": "0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "[Core] Jest Test Debugger, Current Open File",
|
||||
"type": "node",
|
||||
|
|
|
|||
36
.vscode/tasks.json
vendored
36
.vscode/tasks.json
vendored
|
|
@ -103,42 +103,12 @@
|
|||
"clear": true
|
||||
},
|
||||
"options": {
|
||||
"env": {
|
||||
"SKIP_INSTALLS": "true"
|
||||
},
|
||||
"cwd": "${workspaceFolder}/extensions/vscode"
|
||||
}
|
||||
},
|
||||
//
|
||||
// Compile and bundle tests
|
||||
{
|
||||
"label": "vscode-extension:tests:build",
|
||||
"dependsOn": [
|
||||
// Build the extension
|
||||
"vscode-extension:build",
|
||||
// To detect compile errors - this type checks both the extension and the tests
|
||||
"tsc:watch",
|
||||
"vscode-extension:tests:esbuild"
|
||||
]
|
||||
},
|
||||
{
|
||||
"label": "vscode-extension:tests:esbuild",
|
||||
"type": "npm",
|
||||
"script": "build-test",
|
||||
"path": "extensions/vscode",
|
||||
"problemMatcher": [
|
||||
{
|
||||
"pattern": [
|
||||
{
|
||||
"regexp": "> (.*?):([0-9]+):([0-9]+): (warning|error): (.+)$",
|
||||
"file": 1,
|
||||
"line": 2,
|
||||
"column": 3,
|
||||
"severity": 4,
|
||||
"message": 5
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
//
|
||||
// Install or update all dependencies for all projects in the monrepo
|
||||
{
|
||||
"label": "install-all-dependencies",
|
||||
|
|
|
|||
170
binary/build.js
170
binary/build.js
|
|
@ -3,13 +3,13 @@ const fs = require("fs");
|
|||
const path = require("path");
|
||||
const ncp = require("ncp").ncp;
|
||||
const { rimrafSync } = require("rimraf");
|
||||
const {
|
||||
validateFilesPresent,
|
||||
execCmdSync,
|
||||
autodetectPlatformAndArch,
|
||||
} = require("../scripts/util");
|
||||
const { downloadRipgrep } = require("./utils/ripgrep");
|
||||
const { validateFilesPresent } = require("../scripts/util");
|
||||
const { ALL_TARGETS, TARGET_TO_LANCEDB } = require("./utils/targets");
|
||||
const { fork } = require("child_process");
|
||||
const {
|
||||
installAndCopyNodeModules,
|
||||
} = require("../extensions/vscode/scripts/install-copy-nodemodule");
|
||||
const { bundleBinary } = require("./utils/bundle-binary");
|
||||
|
||||
const bin = path.join(__dirname, "bin");
|
||||
const out = path.join(__dirname, "out");
|
||||
|
|
@ -29,8 +29,6 @@ function cleanSlate() {
|
|||
const esbuildOutputFile = "out/index.js";
|
||||
let targets = [...ALL_TARGETS];
|
||||
|
||||
const [currentPlatform, currentArch] = autodetectPlatformAndArch();
|
||||
|
||||
const assetBackups = [
|
||||
"node_modules/win-ca/lib/crypt32-ia32.node.bak",
|
||||
"node_modules/win-ca/lib/crypt32-x64.node.bak",
|
||||
|
|
@ -78,85 +76,6 @@ async function buildWithEsbuild() {
|
|||
});
|
||||
}
|
||||
|
||||
async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
|
||||
console.log(`Copying ${packageName} to ${toCopy}`);
|
||||
// This is a way to install only one package without npm trying to install all the dependencies
|
||||
// Create a temporary directory for installing the package
|
||||
const adjustedName = packageName.replace(/@/g, "").replace("/", "-");
|
||||
const tempDir = path.join(
|
||||
__dirname,
|
||||
"tmp",
|
||||
`continue-node_modules-${adjustedName}`,
|
||||
);
|
||||
const currentDir = process.cwd();
|
||||
|
||||
// // Remove the dir we will be copying to
|
||||
// rimrafSync(`node_modules/${toCopy}`);
|
||||
|
||||
// // Ensure the temporary directory exists
|
||||
fs.mkdirSync(tempDir, { recursive: true });
|
||||
|
||||
try {
|
||||
// Move to the temporary directory
|
||||
process.chdir(tempDir);
|
||||
|
||||
// Initialize a new package.json and install the package
|
||||
execCmdSync(`npm init -y && npm i -f ${packageName} --no-save`);
|
||||
|
||||
console.log(
|
||||
`Contents of: ${packageName}`,
|
||||
fs.readdirSync(path.join(tempDir, "node_modules", toCopy)),
|
||||
);
|
||||
|
||||
// Without this it seems the file isn't completely written to disk
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||
|
||||
// Copy the installed package back to the current directory
|
||||
await new Promise((resolve, reject) => {
|
||||
ncp(
|
||||
path.join(tempDir, "node_modules", toCopy),
|
||||
path.join(currentDir, "node_modules", toCopy),
|
||||
{ dereference: true },
|
||||
(error) => {
|
||||
if (error) {
|
||||
console.error(
|
||||
`[error] Error copying ${packageName} package`,
|
||||
error,
|
||||
);
|
||||
reject(error);
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
} finally {
|
||||
// Clean up the temporary directory
|
||||
// rimrafSync(tempDir);
|
||||
|
||||
// Return to the original directory
|
||||
process.chdir(currentDir);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Downloads and installs ripgrep binaries for the specified target
|
||||
*
|
||||
* @param {string} target - Target platform-arch (e.g., 'darwin-x64')
|
||||
* @param {string} targetDir - Directory to install ripgrep to
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function downloadRipgrepForTarget(target, targetDir) {
|
||||
console.log(`[info] Downloading ripgrep for ${target}...`);
|
||||
try {
|
||||
await downloadRipgrep(target, targetDir);
|
||||
console.log(`[info] Successfully installed ripgrep for ${target}`);
|
||||
} catch (error) {
|
||||
console.error(`[error] Failed to download ripgrep for ${target}:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
(async () => {
|
||||
if (esbuildOnly) {
|
||||
await buildWithEsbuild();
|
||||
|
|
@ -181,16 +100,21 @@ async function downloadRipgrepForTarget(target, targetDir) {
|
|||
),
|
||||
);
|
||||
|
||||
console.log("[info] Downloading prebuilt lancedb...");
|
||||
const copyLanceDBPromises = [];
|
||||
for (const target of targets) {
|
||||
if (TARGET_TO_LANCEDB[target]) {
|
||||
console.log(`[info] Downloading for ${target}...`);
|
||||
await installNodeModuleInTempDirAndCopyToCurrent(
|
||||
TARGET_TO_LANCEDB[target],
|
||||
"@lancedb",
|
||||
);
|
||||
if (!TARGET_TO_LANCEDB[target]) {
|
||||
continue;
|
||||
}
|
||||
console.log(`[info] Downloading for ${target}...`);
|
||||
copyLanceDBPromises.push(
|
||||
installAndCopyNodeModules(TARGET_TO_LANCEDB[target], "@lancedb"),
|
||||
);
|
||||
}
|
||||
await Promise.all(copyLanceDBPromises).catch(() => {
|
||||
console.error("[error] Failed to copy LanceDB");
|
||||
process.exit(1);
|
||||
});
|
||||
console.log("[info] Copied all LanceDB");
|
||||
|
||||
// tree-sitter-wasm
|
||||
const treeSitterWasmsDir = path.join(out, "tree-sitter-wasms");
|
||||
|
|
@ -252,59 +176,16 @@ async function downloadRipgrepForTarget(target, targetDir) {
|
|||
"out/llamaTokenizerWorkerPool.mjs",
|
||||
);
|
||||
|
||||
const buildBinaryPromises = [];
|
||||
console.log("[info] Building binaries with pkg...");
|
||||
for (const target of targets) {
|
||||
const targetDir = `bin/${target}`;
|
||||
fs.mkdirSync(targetDir, { recursive: true });
|
||||
console.log(`[info] Building ${target}...`);
|
||||
execCmdSync(
|
||||
`npx pkg --no-bytecode --public-packages "*" --public --compress GZip pkgJson/${target} --out-path ${targetDir}`,
|
||||
);
|
||||
|
||||
// Download and unzip prebuilt sqlite3 binary for the target
|
||||
console.log("[info] Downloading node-sqlite3");
|
||||
|
||||
const downloadUrl =
|
||||
// node-sqlite3 doesn't have a pre-built binary for win32-arm64
|
||||
target === "win32-arm64"
|
||||
? "https://continue-server-binaries.s3.us-west-1.amazonaws.com/win32-arm64/node_sqlite3.tar.gz"
|
||||
: `https://github.com/TryGhost/node-sqlite3/releases/download/v5.1.7/sqlite3-v5.1.7-napi-v6-${
|
||||
target
|
||||
}.tar.gz`;
|
||||
|
||||
execCmdSync(`curl -L -o ${targetDir}/build.tar.gz ${downloadUrl}`);
|
||||
execCmdSync(`cd ${targetDir} && tar -xvzf build.tar.gz`);
|
||||
|
||||
// Copy to build directory for testing
|
||||
try {
|
||||
const [platform, arch] = target.split("-");
|
||||
if (platform === currentPlatform && arch === currentArch) {
|
||||
fs.copyFileSync(
|
||||
`${targetDir}/build/Release/node_sqlite3.node`,
|
||||
`build/node_sqlite3.node`,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.log("[warn] Could not copy node_sqlite to build");
|
||||
console.log(error);
|
||||
}
|
||||
|
||||
fs.unlinkSync(`${targetDir}/build.tar.gz`);
|
||||
|
||||
// copy @lancedb to bin folders
|
||||
console.log("[info] Copying @lancedb files to bin");
|
||||
fs.copyFileSync(
|
||||
`node_modules/${TARGET_TO_LANCEDB[target]}/index.node`,
|
||||
`${targetDir}/index.node`,
|
||||
);
|
||||
|
||||
// Download and install ripgrep for the target
|
||||
await downloadRipgrepForTarget(target, targetDir);
|
||||
|
||||
// Informs the `continue-binary` of where to look for node_sqlite3.node
|
||||
// https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found
|
||||
fs.writeFileSync(`${targetDir}/package.json`, "");
|
||||
buildBinaryPromises.push(bundleBinary(target));
|
||||
}
|
||||
await Promise.all(buildBinaryPromises).catch(() => {
|
||||
console.error("[error] Failed to build binaries");
|
||||
process.exit(1);
|
||||
});
|
||||
console.log("[info] All binaries built");
|
||||
|
||||
// Cleanup - this is needed when running locally
|
||||
fs.rmSync("out/package.json");
|
||||
|
|
@ -331,4 +212,5 @@ async function downloadRipgrepForTarget(target, targetDir) {
|
|||
validateFilesPresent(pathsToVerify);
|
||||
|
||||
console.log("[info] Done!");
|
||||
process.exit(0);
|
||||
})();
|
||||
|
|
|
|||
6
binary/package-lock.json
generated
6
binary/package-lock.json
generated
|
|
@ -53,9 +53,9 @@
|
|||
"@aws-sdk/credential-providers": "^3.778.0",
|
||||
"@continuedev/config-types": "^1.0.13",
|
||||
"@continuedev/config-yaml": "file:../packages/config-yaml",
|
||||
"@continuedev/fetch": "^1.0.13",
|
||||
"@continuedev/fetch": "^1.0.14",
|
||||
"@continuedev/llm-info": "^1.0.8",
|
||||
"@continuedev/openai-adapters": "^1.0.32",
|
||||
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
|
||||
"@modelcontextprotocol/sdk": "^1.12.0",
|
||||
"@mozilla/readability": "^0.5.0",
|
||||
"@octokit/rest": "^20.1.1",
|
||||
|
|
@ -106,7 +106,6 @@
|
|||
"sqlite3": "^5.1.7",
|
||||
"system-ca": "^1.0.3",
|
||||
"tar": "^7.4.3",
|
||||
"tree-sitter-structured-text": "^0.0.1",
|
||||
"tree-sitter-wasms": "^0.1.11",
|
||||
"uuid": "^9.0.1",
|
||||
"vectordb": "^0.4.20",
|
||||
|
|
@ -145,7 +144,6 @@
|
|||
"myers-diff": "^2.1.0",
|
||||
"onnxruntime-common": "1.14.0",
|
||||
"onnxruntime-web": "1.14.0",
|
||||
"tree-sitter-cli": "^0.22.5",
|
||||
"ts-jest": "^29.1.1",
|
||||
"typescript": "^5.6.3",
|
||||
"vitest": "^3.1.4"
|
||||
|
|
|
|||
103
binary/utils/bundle-binary.js
Normal file
103
binary/utils/bundle-binary.js
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
/**
|
||||
* @file Builds the binary for the specified target. It is also intended to run as a child process.
|
||||
*/
|
||||
|
||||
const {
|
||||
execCmdSync,
|
||||
autodetectPlatformAndArch,
|
||||
} = require("../../scripts/util");
|
||||
const { downloadRipgrep } = require("./ripgrep");
|
||||
const { TARGET_TO_LANCEDB } = require("../utils/targets");
|
||||
const fs = require("fs");
|
||||
const {
|
||||
downloadSqlite,
|
||||
} = require("../../extensions/vscode/scripts/download-copy-sqlite-esbuild");
|
||||
const { fork } = require("child_process");
|
||||
|
||||
async function downloadNodeSqlite(target, targetDir) {
|
||||
const [currentPlatform, currentArch] = autodetectPlatformAndArch();
|
||||
|
||||
// Download and unzip prebuilt sqlite3 binary for the target
|
||||
console.log("[info] Downloading node-sqlite3");
|
||||
|
||||
await downloadSqlite(target, `${targetDir}/build.tar.gz`);
|
||||
|
||||
execCmdSync(`cd ${targetDir} && tar -xvzf build.tar.gz`);
|
||||
|
||||
// Copy to build directory for testing
|
||||
try {
|
||||
const [platform, arch] = target.split("-");
|
||||
if (platform === currentPlatform && arch === currentArch) {
|
||||
fs.copyFileSync(
|
||||
`${targetDir}/build/Release/node_sqlite3.node`,
|
||||
`build/node_sqlite3.node`,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.log("[warn] Could not copy node_sqlite to build");
|
||||
console.log(error);
|
||||
}
|
||||
fs.unlinkSync(`${targetDir}/build.tar.gz`);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} target the platform to build for
|
||||
*/
|
||||
async function bundleForBinary(target) {
|
||||
const targetDir = `bin/${target}`;
|
||||
fs.mkdirSync(targetDir, { recursive: true });
|
||||
console.log(`[info] Building ${target}...`);
|
||||
execCmdSync(
|
||||
`npx pkg --no-bytecode --public-packages "*" --public --compress GZip pkgJson/${target} --out-path ${targetDir}`,
|
||||
);
|
||||
|
||||
// copy @lancedb to bin folders
|
||||
console.log("[info] Copying @lancedb files to bin");
|
||||
fs.copyFileSync(
|
||||
`node_modules/${TARGET_TO_LANCEDB[target]}/index.node`,
|
||||
`${targetDir}/index.node`,
|
||||
);
|
||||
|
||||
const downloadPromises = [];
|
||||
downloadPromises.push(downloadRipgrep(target, targetDir));
|
||||
downloadPromises.push(downloadNodeSqlite(target, targetDir));
|
||||
await Promise.all(downloadPromises);
|
||||
|
||||
// Informs the `continue-binary` of where to look for node_sqlite3.node
|
||||
// https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found
|
||||
fs.writeFileSync(`${targetDir}/package.json`, "");
|
||||
}
|
||||
|
||||
process.on("message", (msg) => {
|
||||
bundleForBinary(msg.payload.target)
|
||||
.then(() => process.send({ done: true }))
|
||||
.catch((error) => {
|
||||
console.error(error); // show the error in the parent process
|
||||
process.send({ error: true });
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* @param {string} target the platform to bundle for
|
||||
*/
|
||||
async function bundleBinary(target) {
|
||||
const child = fork(__filename, { stdio: "inherit" });
|
||||
child.send({
|
||||
payload: {
|
||||
target,
|
||||
},
|
||||
});
|
||||
return new Promise((resolve, reject) => {
|
||||
child.on("message", (msg) => {
|
||||
if (msg.error) {
|
||||
reject();
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
bundleBinary,
|
||||
};
|
||||
|
|
@ -1,88 +0,0 @@
|
|||
import { CustomCommand, SlashCommand, SlashCommandDescription } from "../";
|
||||
import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString";
|
||||
import { replaceSlashCommandWithPromptInChatHistory } from "../promptFiles/v1/updateChatHistory";
|
||||
import { renderPromptFileV2 } from "../promptFiles/v2/renderPromptFile";
|
||||
import { renderChatMessage } from "../util/messageContent";
|
||||
|
||||
import SlashCommands from "./slash";
|
||||
|
||||
export function slashFromCustomCommand(
|
||||
customCommand: CustomCommand,
|
||||
): SlashCommand {
|
||||
const commandName = customCommand.name.startsWith("/")
|
||||
? customCommand.name.substring(1)
|
||||
: customCommand.name;
|
||||
return {
|
||||
name: commandName,
|
||||
description: customCommand.description ?? "",
|
||||
prompt: customCommand.prompt,
|
||||
run: async function* ({
|
||||
input,
|
||||
llm,
|
||||
history,
|
||||
ide,
|
||||
completionOptions,
|
||||
config,
|
||||
selectedCode,
|
||||
fetch,
|
||||
abortController,
|
||||
}) {
|
||||
// Render prompt template
|
||||
let renderedPrompt: string;
|
||||
if (customCommand.prompt.includes("{{{ input }}}")) {
|
||||
renderedPrompt = await renderTemplatedString(
|
||||
customCommand.prompt,
|
||||
ide.readFile.bind(ide),
|
||||
{ input },
|
||||
);
|
||||
} else {
|
||||
const renderedPromptFile = await renderPromptFileV2(
|
||||
customCommand.prompt,
|
||||
{
|
||||
config,
|
||||
llm,
|
||||
ide,
|
||||
selectedCode,
|
||||
fetch,
|
||||
fullInput: input,
|
||||
embeddingsProvider: config.modelsByRole.embed[0],
|
||||
reranker: config.modelsByRole.rerank[0],
|
||||
},
|
||||
);
|
||||
|
||||
renderedPrompt = renderedPromptFile[1];
|
||||
}
|
||||
|
||||
// Replaces slash command messages with the rendered prompt
|
||||
// which INCLUDES the input
|
||||
const messages = replaceSlashCommandWithPromptInChatHistory(
|
||||
history,
|
||||
commandName,
|
||||
renderedPrompt,
|
||||
undefined,
|
||||
);
|
||||
|
||||
for await (const chunk of llm.streamChat(
|
||||
messages,
|
||||
abortController.signal,
|
||||
completionOptions,
|
||||
)) {
|
||||
yield renderChatMessage(chunk);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function slashCommandFromDescription(
|
||||
desc: SlashCommandDescription,
|
||||
): SlashCommand | undefined {
|
||||
const cmd = SlashCommands.find((cmd) => cmd.name === desc.name);
|
||||
if (!cmd) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
...cmd,
|
||||
params: desc.params,
|
||||
description: desc.description ?? cmd.description,
|
||||
};
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import { streamLines } from "../../diff/util.js";
|
||||
import { SlashCommand } from "../../index.js";
|
||||
import { removeQuotesAndEscapes } from "../../util/index.js";
|
||||
import { streamLines } from "../../../diff/util.js";
|
||||
import { SlashCommand } from "../../../index.js";
|
||||
import { removeQuotesAndEscapes } from "../../../util/index.js";
|
||||
|
||||
function commandIsPotentiallyDangerous(command: string) {
|
||||
return (
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import { SlashCommand } from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { SlashCommand } from "../../../index.js";
|
||||
import { renderChatMessage } from "../../../util/messageContent.js";
|
||||
|
||||
const CommitMessageCommand: SlashCommand = {
|
||||
name: "commit",
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import { ChatMessage, SlashCommand } from "../../index.js";
|
||||
import { removeQuotesAndEscapes } from "../../util/index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { ChatMessage, SlashCommand } from "../../../index.js";
|
||||
import { removeQuotesAndEscapes } from "../../../util/index.js";
|
||||
import { renderChatMessage } from "../../../util/messageContent.js";
|
||||
|
||||
const PROMPT = (
|
||||
input: string,
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import { streamResponse } from "@continuedev/fetch";
|
||||
import { SlashCommand } from "../../index.js";
|
||||
import { removeQuotesAndEscapes } from "../../util/index.js";
|
||||
import { SlashCommand } from "../../../index.js";
|
||||
import { removeQuotesAndEscapes } from "../../../util/index.js";
|
||||
|
||||
const HttpSlashCommand: SlashCommand = {
|
||||
name: "http",
|
||||
37
core/commands/slash/built-in-legacy/index.ts
Normal file
37
core/commands/slash/built-in-legacy/index.ts
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import {
|
||||
SlashCommand,
|
||||
SlashCommandDescription,
|
||||
SlashCommandWithSource,
|
||||
} from "../../..";
|
||||
import GenerateTerminalCommand from "./cmd";
|
||||
import CommitMessageCommand from "./commit";
|
||||
import DraftIssueCommand from "./draftIssue";
|
||||
import HttpSlashCommand from "./http";
|
||||
import OnboardSlashCommand from "./onboard";
|
||||
import ReviewMessageCommand from "./review";
|
||||
import ShareSlashCommand from "./share";
|
||||
|
||||
const LegacyBuiltInSlashCommands: SlashCommand[] = [
|
||||
DraftIssueCommand,
|
||||
ShareSlashCommand,
|
||||
GenerateTerminalCommand,
|
||||
HttpSlashCommand,
|
||||
CommitMessageCommand,
|
||||
ReviewMessageCommand,
|
||||
OnboardSlashCommand,
|
||||
];
|
||||
|
||||
export function getLegacyBuiltInSlashCommandFromDescription(
|
||||
desc: SlashCommandDescription,
|
||||
): SlashCommandWithSource | undefined {
|
||||
const cmd = LegacyBuiltInSlashCommands.find((cmd) => cmd.name === desc.name);
|
||||
if (!cmd) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
...cmd,
|
||||
params: desc.params,
|
||||
description: desc.description ?? cmd.description,
|
||||
source: "built-in-legacy",
|
||||
};
|
||||
}
|
||||
|
|
@ -1,17 +1,17 @@
|
|||
import ignore from "ignore";
|
||||
|
||||
import type { FileType, IDE, SlashCommand } from "../..";
|
||||
import type { FileType, IDE, SlashCommand } from "../../..";
|
||||
import {
|
||||
DEFAULT_IGNORE,
|
||||
getGlobalContinueIgArray,
|
||||
gitIgArrayFromFile,
|
||||
} from "../../indexing/ignore";
|
||||
import { renderChatMessage } from "../../util/messageContent";
|
||||
} from "../../../indexing/ignore";
|
||||
import { renderChatMessage } from "../../../util/messageContent";
|
||||
import {
|
||||
findUriInDirs,
|
||||
getUriPathBasename,
|
||||
joinPathsToUri,
|
||||
} from "../../util/uri";
|
||||
} from "../../../util/uri";
|
||||
|
||||
const LANGUAGE_DEP_MGMT_FILENAMES = [
|
||||
"package.json", // JavaScript (Node.js)
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import { ChatMessage, SlashCommand } from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { ChatMessage, SlashCommand } from "../../../index.js";
|
||||
import { renderChatMessage } from "../../../util/messageContent.js";
|
||||
|
||||
const prompt = `
|
||||
Review the following code, focusing on Readability, Maintainability, Code Smells, Speed, and Memory Performance. Provide feedback with these guidelines:
|
||||
|
|
@ -3,10 +3,10 @@ import { homedir } from "node:os";
|
|||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import path from "path";
|
||||
|
||||
import { languageForFilepath } from "../../autocomplete/constants/AutocompleteLanguageInfo.js";
|
||||
import { SlashCommand } from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { getContinueGlobalPath } from "../../util/paths.js";
|
||||
import { languageForFilepath } from "../../../autocomplete/constants/AutocompleteLanguageInfo.js";
|
||||
import { SlashCommand } from "../../../index.js";
|
||||
import { renderChatMessage } from "../../../util/messageContent.js";
|
||||
import { getContinueGlobalPath } from "../../../util/paths.js";
|
||||
|
||||
// If useful elsewhere, helper funcs should move to core/util/index.ts or similar
|
||||
function getOffsetDatetime(date: Date): Date {
|
||||
15
core/commands/slash/customSlashCommand.ts
Normal file
15
core/commands/slash/customSlashCommand.ts
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import { CustomCommand, SlashCommandWithSource } from "../..";
|
||||
|
||||
export function convertCustomCommandToSlashCommand(
|
||||
customCommand: CustomCommand,
|
||||
): SlashCommandWithSource {
|
||||
const commandName = customCommand.name.startsWith("/")
|
||||
? customCommand.name.substring(1)
|
||||
: customCommand.name;
|
||||
return {
|
||||
name: commandName,
|
||||
description: customCommand.description ?? "",
|
||||
prompt: customCommand.prompt,
|
||||
source: "json-custom-command",
|
||||
};
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
import GenerateTerminalCommand from "./cmd";
|
||||
import CommitMessageCommand from "./commit";
|
||||
import DraftIssueCommand from "./draftIssue";
|
||||
import HttpSlashCommand from "./http";
|
||||
import OnboardSlashCommand from "./onboard";
|
||||
import ReviewMessageCommand from "./review";
|
||||
import ShareSlashCommand from "./share";
|
||||
|
||||
export default [
|
||||
DraftIssueCommand,
|
||||
ShareSlashCommand,
|
||||
GenerateTerminalCommand,
|
||||
HttpSlashCommand,
|
||||
CommitMessageCommand,
|
||||
ReviewMessageCommand,
|
||||
OnboardSlashCommand,
|
||||
];
|
||||
|
|
@ -1,70 +0,0 @@
|
|||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
|
||||
import { PromptMessage } from "@modelcontextprotocol/sdk/types.js";
|
||||
import { ChatMessage, SlashCommand } from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
export function constructMcpSlashCommand(
|
||||
client: Client,
|
||||
name: string,
|
||||
description?: string,
|
||||
args?: string[],
|
||||
): SlashCommand {
|
||||
return {
|
||||
name,
|
||||
description: description ?? "MCP Prompt",
|
||||
params: {},
|
||||
run: async function* (context) {
|
||||
const argsObject: { [key: string]: string } = {};
|
||||
const userInput = context.input.split(" ").slice(1).join(" ");
|
||||
if (args) {
|
||||
args.forEach((arg, i) => {
|
||||
argsObject[arg] = ""; // userInput
|
||||
});
|
||||
}
|
||||
|
||||
const result = await client.getPrompt({ name, arguments: argsObject });
|
||||
const mcpMessages: PromptMessage[] = result.messages;
|
||||
const messages: ChatMessage[] = mcpMessages.map((msg) => {
|
||||
if (msg.content.type !== "text") {
|
||||
throw new Error(
|
||||
"Continue currently only supports text prompts through MCP",
|
||||
);
|
||||
}
|
||||
return {
|
||||
content: msg.content.text,
|
||||
role: msg.role,
|
||||
};
|
||||
});
|
||||
|
||||
if (messages.length === 0) {
|
||||
yield "The MCP prompt returned no messages";
|
||||
return;
|
||||
}
|
||||
|
||||
if (userInput) {
|
||||
const lastMessage = messages.at(-1);
|
||||
if (!lastMessage || lastMessage.role !== "user") {
|
||||
messages.push({
|
||||
role: "user",
|
||||
content: userInput,
|
||||
});
|
||||
} else {
|
||||
let newContent = renderChatMessage(lastMessage);
|
||||
if (newContent) {
|
||||
newContent += "\n\n";
|
||||
}
|
||||
newContent += userInput;
|
||||
lastMessage.content = newContent;
|
||||
}
|
||||
}
|
||||
|
||||
for await (const chunk of context.llm.streamChat(
|
||||
messages,
|
||||
context.abortController.signal,
|
||||
context.completionOptions,
|
||||
)) {
|
||||
yield renderChatMessage(chunk);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
34
core/commands/slash/mcpSlashCommand.ts
Normal file
34
core/commands/slash/mcpSlashCommand.ts
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
|
||||
import { SlashCommandWithSource } from "../../index.js";
|
||||
|
||||
export function constructMcpSlashCommand(
|
||||
client: Client,
|
||||
name: string,
|
||||
description?: string,
|
||||
args?: string[],
|
||||
): SlashCommandWithSource {
|
||||
return {
|
||||
name,
|
||||
description: description ?? "MCP Prompt",
|
||||
source: "mcp-prompt",
|
||||
params: {},
|
||||
};
|
||||
}
|
||||
|
||||
export function stringifyMcpPrompt(
|
||||
prompt: Awaited<ReturnType<typeof Client.prototype.getPrompt>>,
|
||||
): string {
|
||||
const { messages } = prompt;
|
||||
let stringified = "";
|
||||
for (const message of messages) {
|
||||
if (message.content.type === "text") {
|
||||
stringified += `<${message.content.role}/>\n${message.content.text}\n<${message.content.role}/>`;
|
||||
} else {
|
||||
console.warn(
|
||||
`MCP Prompt conversion warning: ${message.content.type} content is not yet supported, message skipped`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return stringified;
|
||||
}
|
||||
13
core/commands/slash/promptBlockSlashCommand.ts
Normal file
13
core/commands/slash/promptBlockSlashCommand.ts
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import { Prompt } from "@continuedev/config-yaml";
|
||||
import { SlashCommandWithSource } from "../..";
|
||||
|
||||
export function convertPromptBlockToSlashCommand(
|
||||
prompt: Prompt,
|
||||
): SlashCommandWithSource {
|
||||
return {
|
||||
name: prompt.name,
|
||||
description: prompt.description ?? "",
|
||||
prompt: prompt.prompt,
|
||||
source: "yaml-prompt-block",
|
||||
};
|
||||
}
|
||||
21
core/commands/slash/promptFileSlashCommand.ts
Normal file
21
core/commands/slash/promptFileSlashCommand.ts
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import { SlashCommandWithSource } from "../..";
|
||||
import { parsePromptFile } from "../../promptFiles/parsePromptFile";
|
||||
|
||||
export function slashCommandFromPromptFile(
|
||||
path: string,
|
||||
content: string,
|
||||
): SlashCommandWithSource | null {
|
||||
const { name, description, systemMessage, prompt, version } = parsePromptFile(
|
||||
path,
|
||||
content,
|
||||
);
|
||||
|
||||
return {
|
||||
name,
|
||||
description,
|
||||
prompt,
|
||||
source: version === 1 ? "prompt-file-v1" : "prompt-file-v2",
|
||||
promptFile: path,
|
||||
overrideSystemMessage: systemMessage,
|
||||
};
|
||||
}
|
||||
|
|
@ -16,7 +16,7 @@ export function rifWithContentsToContextItem(
|
|||
return {
|
||||
content: rif.contents,
|
||||
name: `${basename} ${rangeStr}`,
|
||||
description: `${relativePathOrBasename} ${rangeStr}`, // This is passed to the LLM - do not pass full URI
|
||||
description: `${relativePathOrBasename} ${rangeStr}`,
|
||||
id: {
|
||||
providerTitle: "code",
|
||||
itemId: uuidv4(),
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { ctxItemToRifWithContents } from "./util";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { ContextItemWithId, RangeInFileWithContents } from "../index";
|
||||
import { ctxItemToRifWithContents } from "./util";
|
||||
|
||||
describe("ctxItemToRifWithContents", () => {
|
||||
it("should parse start and end lines from the item name when format is valid", () => {
|
||||
|
|
@ -30,12 +30,11 @@ import {
|
|||
ModelDescription,
|
||||
RerankerDescription,
|
||||
SerializedContinueConfig,
|
||||
SlashCommand,
|
||||
SlashCommandWithSource,
|
||||
} from "..";
|
||||
import {
|
||||
slashCommandFromDescription,
|
||||
slashFromCustomCommand,
|
||||
} from "../commands/index";
|
||||
import { getLegacyBuiltInSlashCommandFromDescription } from "../commands/slash/built-in-legacy";
|
||||
import { convertCustomCommandToSlashCommand } from "../commands/slash/customSlashCommand";
|
||||
import { slashCommandFromPromptFile } from "../commands/slash/promptFileSlashCommand";
|
||||
import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton";
|
||||
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider";
|
||||
import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider";
|
||||
|
|
@ -48,8 +47,7 @@ import { LLMClasses, llmFromDescription } from "../llm/llms";
|
|||
import CustomLLMClass from "../llm/llms/CustomLLM";
|
||||
import { LLMReranker } from "../llm/llms/llm";
|
||||
import TransformersJsEmbeddingsProvider from "../llm/llms/TransformersJsEmbeddingsProvider";
|
||||
import { slashCommandFromPromptFileV1 } from "../promptFiles/v1/slashCommandFromPromptFile";
|
||||
import { getAllPromptFiles } from "../promptFiles/v2/getPromptFiles";
|
||||
import { getAllPromptFiles } from "../promptFiles/getPromptFiles";
|
||||
import { copyOf } from "../util";
|
||||
import { GlobalContext } from "../util/GlobalContext";
|
||||
import mergeJson from "../util/merge";
|
||||
|
|
@ -66,6 +64,7 @@ import {
|
|||
import { localPathToUri } from "../util/pathToUri";
|
||||
|
||||
import { baseToolDefinitions } from "../tools";
|
||||
import { resolveRelativePathInDir } from "../util/ideUtils";
|
||||
import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
|
||||
import {
|
||||
getModelByRole,
|
||||
|
|
@ -174,15 +173,15 @@ async function serializedToIntermediateConfig(
|
|||
ide: IDE,
|
||||
): Promise<Config> {
|
||||
// DEPRECATED - load custom slash commands
|
||||
const slashCommands: SlashCommand[] = [];
|
||||
const slashCommands: SlashCommandWithSource[] = [];
|
||||
for (const command of initial.slashCommands || []) {
|
||||
const newCommand = slashCommandFromDescription(command);
|
||||
const newCommand = getLegacyBuiltInSlashCommandFromDescription(command);
|
||||
if (newCommand) {
|
||||
slashCommands.push(newCommand);
|
||||
}
|
||||
}
|
||||
for (const command of initial.customCommands || []) {
|
||||
slashCommands.push(slashFromCustomCommand(command));
|
||||
slashCommands.push(convertCustomCommandToSlashCommand(command));
|
||||
}
|
||||
|
||||
// DEPRECATED - load slash commands from v1 prompt files
|
||||
|
|
@ -194,7 +193,7 @@ async function serializedToIntermediateConfig(
|
|||
);
|
||||
|
||||
for (const file of promptFiles) {
|
||||
const slashCommand = slashCommandFromPromptFileV1(file.path, file.content);
|
||||
const slashCommand = slashCommandFromPromptFile(file.path, file.content);
|
||||
if (slashCommand) {
|
||||
slashCommands.push(slashCommand);
|
||||
}
|
||||
|
|
@ -254,7 +253,10 @@ async function intermediateToFinalConfig({
|
|||
loadPromptFiles?: boolean;
|
||||
}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
|
||||
const errors: ConfigValidationError[] = [];
|
||||
|
||||
const workspaceDirs = await ide.getWorkspaceDirs();
|
||||
const getUriFromPath = (path: string) => {
|
||||
return resolveRelativePathInDir(path, ide, workspaceDirs);
|
||||
};
|
||||
// Auto-detect models
|
||||
let models: BaseLLM[] = [];
|
||||
await Promise.all(
|
||||
|
|
@ -263,6 +265,7 @@ async function intermediateToFinalConfig({
|
|||
const llm = await llmFromDescription(
|
||||
desc,
|
||||
ide.readFile.bind(ide),
|
||||
getUriFromPath,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
|
|
@ -284,6 +287,7 @@ async function intermediateToFinalConfig({
|
|||
title: modelName,
|
||||
},
|
||||
ide.readFile.bind(ide),
|
||||
getUriFromPath,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
|
|
@ -360,6 +364,7 @@ async function intermediateToFinalConfig({
|
|||
const llm = await llmFromDescription(
|
||||
desc,
|
||||
ide.readFile.bind(ide),
|
||||
getUriFromPath,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
|
|
@ -529,7 +534,7 @@ async function intermediateToFinalConfig({
|
|||
contextProviders,
|
||||
tools: [...baseToolDefinitions],
|
||||
mcpServerStatuses: [],
|
||||
slashCommands: config.slashCommands ?? [],
|
||||
slashCommands: [],
|
||||
modelsByRole: {
|
||||
chat: models,
|
||||
edit: models,
|
||||
|
|
@ -551,6 +556,17 @@ async function intermediateToFinalConfig({
|
|||
rules: [],
|
||||
};
|
||||
|
||||
for (const cmd of config.slashCommands ?? []) {
|
||||
if ("source" in cmd) {
|
||||
continueConfig.slashCommands.push(cmd);
|
||||
} else {
|
||||
continueConfig.slashCommands.push({
|
||||
...cmd,
|
||||
source: "config-ts-slash-command",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (config.systemMessage) {
|
||||
continueConfig.rules.unshift({
|
||||
rule: config.systemMessage,
|
||||
|
|
@ -651,9 +667,10 @@ async function finalToBrowserConfig(
|
|||
return {
|
||||
allowAnonymousTelemetry: final.allowAnonymousTelemetry,
|
||||
completionOptions: final.completionOptions,
|
||||
slashCommands: final.slashCommands?.map(
|
||||
({ run, ...slashCommandDescription }) => slashCommandDescription,
|
||||
),
|
||||
slashCommands: final.slashCommands?.map(({ run, ...rest }) => ({
|
||||
...rest,
|
||||
isLegacy: !!run,
|
||||
})),
|
||||
contextProviders: final.contextProviders?.map((c) => c.description),
|
||||
disableIndexing: final.disableIndexing,
|
||||
disableSessionTitles: final.disableSessionTitles,
|
||||
|
|
@ -975,7 +992,6 @@ async function loadContinueConfigFromJson(
|
|||
|
||||
export {
|
||||
finalToBrowserConfig,
|
||||
intermediateToFinalConfig,
|
||||
loadContinueConfigFromJson,
|
||||
type BrowserSerializedContinueConfig,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -16,9 +16,9 @@ import {
|
|||
ILLMLogger,
|
||||
RuleWithSource,
|
||||
SerializedContinueConfig,
|
||||
SlashCommandDescWithSource,
|
||||
Tool,
|
||||
} from "../../";
|
||||
import { constructMcpSlashCommand } from "../../commands/slash/mcp";
|
||||
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
|
||||
import MCPContextProvider from "../../context/providers/MCPContextProvider";
|
||||
import RulesContextProvider from "../../context/providers/RulesContextProvider";
|
||||
|
|
@ -190,14 +190,15 @@ export default async function doLoadConfig(options: {
|
|||
}));
|
||||
newConfig.tools.push(...serverTools);
|
||||
|
||||
const serverSlashCommands = server.prompts.map((prompt) =>
|
||||
constructMcpSlashCommand(
|
||||
server.client,
|
||||
prompt.name,
|
||||
prompt.description,
|
||||
prompt.arguments?.map((a: any) => a.name),
|
||||
),
|
||||
);
|
||||
const serverSlashCommands: SlashCommandDescWithSource[] =
|
||||
server.prompts.map((prompt) => ({
|
||||
name: prompt.name,
|
||||
description: prompt.description ?? "MCP Prompt",
|
||||
source: "mcp-prompt",
|
||||
isLegacy: false,
|
||||
mcpServerName: server.name, // Used in client to retrieve prompt
|
||||
mcpArgs: prompt.arguments,
|
||||
}));
|
||||
newConfig.slashCommands.push(...serverSlashCommands);
|
||||
|
||||
const submenuItems = server.resources
|
||||
|
|
|
|||
|
|
@ -25,7 +25,6 @@ import {
|
|||
ILLMLogger,
|
||||
RuleWithSource,
|
||||
} from "../..";
|
||||
import { slashFromCustomCommand } from "../../commands";
|
||||
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
|
||||
import CodebaseContextProvider from "../../context/providers/CodebaseContextProvider";
|
||||
import DocsContextProvider from "../../context/providers/DocsContextProvider";
|
||||
|
|
@ -33,13 +32,14 @@ import FileContextProvider from "../../context/providers/FileContextProvider";
|
|||
import { contextProviderClassFromName } from "../../context/providers/index";
|
||||
import { ControlPlaneClient } from "../../control-plane/client";
|
||||
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
|
||||
import { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandFromPromptFile";
|
||||
import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles";
|
||||
import { getAllPromptFiles } from "../../promptFiles/getPromptFiles";
|
||||
import { GlobalContext } from "../../util/GlobalContext";
|
||||
import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
|
||||
|
||||
import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand";
|
||||
import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand";
|
||||
import { getControlPlaneEnvSync } from "../../control-plane/env";
|
||||
import { baseToolDefinitions } from "../../tools";
|
||||
import { getToolsForIde } from "../../tools";
|
||||
import { getCleanUriPath } from "../../util/uri";
|
||||
import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
|
||||
import { LocalPlatformClient } from "./LocalPlatformClient";
|
||||
|
|
@ -187,7 +187,7 @@ async function configYamlToContinueConfig(options: {
|
|||
|
||||
const continueConfig: ContinueConfig = {
|
||||
slashCommands: [],
|
||||
tools: [...baseToolDefinitions],
|
||||
tools: await getToolsForIde(ide),
|
||||
mcpServerStatuses: [],
|
||||
contextProviders: [],
|
||||
modelsByRole: {
|
||||
|
|
@ -263,7 +263,7 @@ async function configYamlToContinueConfig(options: {
|
|||
|
||||
promptFiles.forEach((file) => {
|
||||
try {
|
||||
const slashCommand = slashCommandFromPromptFileV1(
|
||||
const slashCommand = slashCommandFromPromptFile(
|
||||
file.path,
|
||||
file.content,
|
||||
);
|
||||
|
|
@ -286,7 +286,7 @@ async function configYamlToContinueConfig(options: {
|
|||
|
||||
config.prompts?.forEach((prompt) => {
|
||||
try {
|
||||
const slashCommand = slashFromCustomCommand(prompt);
|
||||
const slashCommand = convertPromptBlockToSlashCommand(prompt);
|
||||
continueConfig.slashCommands?.push(slashCommand);
|
||||
} catch (e) {
|
||||
localErrors.push({
|
||||
|
|
|
|||
|
|
@ -161,4 +161,21 @@ export class MCPManagerSingleton {
|
|||
client: connection.client,
|
||||
}));
|
||||
}
|
||||
|
||||
async getPrompt(
|
||||
serverName: string,
|
||||
promptName: string,
|
||||
args: Record<string, string> = {},
|
||||
) {
|
||||
const connection = this.connections.get(serverName);
|
||||
if (!connection) {
|
||||
throw new Error(
|
||||
`Error getting prompt: MCP Connection ${serverName} not found`,
|
||||
);
|
||||
}
|
||||
return await connection.client.getPrompt({
|
||||
name: promptName,
|
||||
arguments: args,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -56,7 +56,9 @@ class MCPContextProvider extends BaseContextProvider {
|
|||
private insertInputToUriTemplate(uri: string, query: string): string {
|
||||
const TEMPLATE_VAR = "query";
|
||||
if (uri.includes(`{${TEMPLATE_VAR}}`)) {
|
||||
return uri.replace(`{${TEMPLATE_VAR}}`, encodeURIComponent(query));
|
||||
// Sending an empty string will result in an error, so we instead send "null"
|
||||
const queryOrNull = query.trim() === "" ? "null" : query;
|
||||
return uri.replace(`{${TEMPLATE_VAR}}`, encodeURIComponent(queryOrNull));
|
||||
}
|
||||
return uri;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,7 +21,9 @@ class TerminalContextProvider extends BaseContextProvider {
|
|||
return [
|
||||
{
|
||||
description: "The contents of the terminal",
|
||||
content: `Current terminal contents:\n\n${content}`,
|
||||
content: `Current terminal contents:\n\n${
|
||||
content || "The terminal is empty."
|
||||
}`,
|
||||
name: "Terminal",
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import * as crypto from "crypto";
|
||||
import { expect, test } from "vitest";
|
||||
import { LicenseKeyData, validateLicenseKey } from "./mdm";
|
||||
|
||||
// We'll create a real key pair once for all tests
|
||||
16
core/core.ts
16
core/core.ts
|
|
@ -21,7 +21,7 @@ import { CodebaseIndexer } from "./indexing/CodebaseIndexer";
|
|||
import DocsService from "./indexing/docs/DocsService";
|
||||
import { countTokens } from "./llm/countTokens";
|
||||
import Ollama from "./llm/llms/Ollama";
|
||||
import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile";
|
||||
import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile";
|
||||
import { callTool } from "./tools/callTool";
|
||||
import { ChatDescriber } from "./util/chatDescriber";
|
||||
import { clipboardCache } from "./util/clipboardCache";
|
||||
|
|
@ -50,6 +50,7 @@ import {
|
|||
|
||||
import { BLOCK_TYPES, ConfigYaml } from "@continuedev/config-yaml";
|
||||
import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache";
|
||||
import { stringifyMcpPrompt } from "./commands/slash/mcpSlashCommand";
|
||||
import { isLocalDefinitionFile } from "./config/loadLocalAssistants";
|
||||
import {
|
||||
setupLocalConfig,
|
||||
|
|
@ -381,6 +382,19 @@ export class Core {
|
|||
on("mcp/reloadServer", async (msg) => {
|
||||
await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
|
||||
});
|
||||
on("mcp/getPrompt", async (msg) => {
|
||||
const { serverName, promptName, args } = msg.data;
|
||||
const prompt = await MCPManagerSingleton.getInstance().getPrompt(
|
||||
serverName,
|
||||
promptName,
|
||||
args,
|
||||
);
|
||||
const stringifiedPrompt = stringifyMcpPrompt(prompt);
|
||||
return {
|
||||
prompt: stringifiedPrompt,
|
||||
description: prompt.description,
|
||||
};
|
||||
});
|
||||
// Context providers
|
||||
on("context/addDocs", async (msg) => {
|
||||
void this.docsService.indexAndAdd(msg.data);
|
||||
|
|
|
|||
|
|
@ -1,13 +1,22 @@
|
|||
import { DevDataLogEvent } from "@continuedev/config-yaml";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import {
|
||||
afterAll,
|
||||
beforeAll,
|
||||
beforeEach,
|
||||
describe,
|
||||
expect,
|
||||
it,
|
||||
vi,
|
||||
} from "vitest";
|
||||
import { IdeInfo, IdeSettings } from "..";
|
||||
import { Core } from "../core";
|
||||
import { getDevDataFilePath } from "../util/paths";
|
||||
import { DataLogger } from "./log";
|
||||
|
||||
// Only mock fetch, not fs
|
||||
jest.mock("@continuedev/fetch");
|
||||
vi.mock("@continuedev/fetch");
|
||||
|
||||
const TEST_EVENT: DevDataLogEvent = {
|
||||
name: "tokensGenerated",
|
||||
|
|
@ -54,7 +63,7 @@ describe("DataLogger", () => {
|
|||
|
||||
beforeEach(() => {
|
||||
// Reset mocks
|
||||
jest.clearAllMocks();
|
||||
vi.clearAllMocks();
|
||||
|
||||
// Remove test file if it exists
|
||||
if (fs.existsSync(testFilePath)) {
|
||||
|
|
@ -67,7 +76,7 @@ describe("DataLogger", () => {
|
|||
// Mock core and required promises
|
||||
dataLogger.core = {
|
||||
configHandler: {
|
||||
loadConfig: jest.fn().mockResolvedValue({
|
||||
loadConfig: vi.fn().mockResolvedValue({
|
||||
config: {
|
||||
data: [],
|
||||
},
|
||||
|
|
@ -78,7 +87,7 @@ describe("DataLogger", () => {
|
|||
},
|
||||
},
|
||||
controlPlaneClient: {
|
||||
getAccessToken: jest.fn().mockResolvedValue("test-access-token"),
|
||||
getAccessToken: vi.fn().mockResolvedValue("test-access-token"),
|
||||
},
|
||||
},
|
||||
} as unknown as Core;
|
||||
|
|
@ -184,7 +193,6 @@ describe("DataLogger", () => {
|
|||
|
||||
// Read file contents and verify
|
||||
const fileContent = fs.readFileSync(filepath, "utf8");
|
||||
console.log("debug1 filecontent", fileContent);
|
||||
expect(fileContent).toContain('"eventName":"chatInteraction"');
|
||||
expect(fileContent).toContain('"prompt":"Hello, world!"');
|
||||
expect(fileContent).toContain('"completion":"Hello, world!"');
|
||||
|
|
@ -195,10 +203,10 @@ describe("DataLogger", () => {
|
|||
describe("logDevData", () => {
|
||||
it("should log data locally and to configured destinations", async () => {
|
||||
// Spy on logLocalData and logToOneDestination
|
||||
const logLocalDataSpy = jest
|
||||
const logLocalDataSpy = vi
|
||||
.spyOn(dataLogger, "logLocalData")
|
||||
.mockResolvedValue();
|
||||
const logToOneDestinationSpy = jest
|
||||
const logToOneDestinationSpy = vi
|
||||
.spyOn(dataLogger, "logToOneDestination")
|
||||
.mockResolvedValue();
|
||||
|
||||
|
|
@ -212,7 +220,7 @@ describe("DataLogger", () => {
|
|||
},
|
||||
};
|
||||
|
||||
dataLogger.core!.configHandler.loadConfig = jest
|
||||
dataLogger.core!.configHandler.loadConfig = vi
|
||||
.fn()
|
||||
.mockResolvedValue(mockConfig);
|
||||
|
||||
|
|
@ -1,3 +1,5 @@
|
|||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { dedent } from "../util";
|
||||
|
||||
import { myersDiff } from "./myers";
|
||||
|
|
@ -1,6 +1,8 @@
|
|||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
// @ts-ignore no typings available
|
||||
import { changed, diff as myersDiff } from "myers-diff";
|
||||
import { streamDiff } from "../diff/streamDiff.js";
|
||||
|
|
@ -54,12 +56,7 @@ function displayDiff(diff: DiffLine[]) {
|
|||
}
|
||||
|
||||
async function expectDiff(file: string) {
|
||||
const testFilePath = path.join(
|
||||
__dirname,
|
||||
"diff",
|
||||
"test-examples",
|
||||
file + ".diff",
|
||||
);
|
||||
const testFilePath = path.join(__dirname, "test-examples", file + ".diff");
|
||||
const testFileContents = fs.readFileSync(testFilePath, "utf-8");
|
||||
const [oldText, newText, expectedDiff] = testFileContents
|
||||
.split("\n---\n")
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
// Generated by continue
|
||||
|
||||
import { matchLine, streamLines, generateLines } from "./util";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { ChatMessage } from "../index";
|
||||
import { jest } from "@jest/globals";
|
||||
import { generateLines, matchLine, streamLines } from "./util";
|
||||
|
||||
describe.skip("matchLine", () => {
|
||||
it("should match empty lines if the first old line is also empty", () => {
|
||||
|
|
@ -146,7 +146,7 @@ describe("streamLines", () => {
|
|||
content: "line4",
|
||||
};
|
||||
|
||||
// const spy = jest.spyOn(messageContentModule, "renderChatMessage");
|
||||
// const spy = vi.spyOn(messageContentModule, "renderChatMessage");
|
||||
|
||||
async function* streamCompletion(): AsyncGenerator<ChatMessage> {
|
||||
yield messageChunk1;
|
||||
|
|
@ -164,7 +164,7 @@ describe("streamLines", () => {
|
|||
});
|
||||
|
||||
it("should log lines if log parameter is true", async () => {
|
||||
const consoleSpy = jest.spyOn(console, "log").mockImplementation(() => {});
|
||||
const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
|
||||
async function* streamCompletion(): AsyncGenerator<string> {
|
||||
yield "line1\nline2\n";
|
||||
57
core/index.d.ts
vendored
57
core/index.d.ts
vendored
|
|
@ -731,6 +731,8 @@ export interface IDE {
|
|||
|
||||
isTelemetryEnabled(): Promise<boolean>;
|
||||
|
||||
isWorkspaceRemote(): Promise<boolean>;
|
||||
|
||||
getUniqueId(): Promise<string>;
|
||||
|
||||
getTerminalContents(): Promise<string>;
|
||||
|
|
@ -836,15 +838,44 @@ export interface ContinueSDK {
|
|||
abortController: AbortController;
|
||||
}
|
||||
|
||||
export interface SlashCommand {
|
||||
/* Be careful changing SlashCommand or SlashCommandDescription, config.ts can break */
|
||||
export interface SlashCommandDescription {
|
||||
name: string;
|
||||
description: string;
|
||||
prompt?: string;
|
||||
params?: { [key: string]: any };
|
||||
promptFile?: string;
|
||||
}
|
||||
|
||||
export interface SlashCommand extends SlashCommandDescription {
|
||||
run: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>;
|
||||
}
|
||||
|
||||
export interface SlashCommandWithSource extends SlashCommandDescription {
|
||||
run?: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>; // Optional - only needed for legacy
|
||||
source: SlashCommandSource;
|
||||
promptFile?: string;
|
||||
overrideSystemMessage?: string;
|
||||
}
|
||||
|
||||
export type SlashCommandSource =
|
||||
| "built-in-legacy"
|
||||
| "built-in"
|
||||
| "json-custom-command"
|
||||
| "config-ts-slash-command"
|
||||
| "yaml-prompt-block"
|
||||
| "mcp-prompt"
|
||||
| "prompt-file-v1"
|
||||
| "prompt-file-v2"
|
||||
| "invokable-rule";
|
||||
|
||||
export interface SlashCommandDescWithSource extends SlashCommandDescription {
|
||||
isLegacy: boolean; // Maps to if slashcommand.run exists
|
||||
source: SlashCommandSource;
|
||||
promptFile?: string;
|
||||
mcpServerName?: string;
|
||||
mcpArgs?: MCPPromptArgs;
|
||||
}
|
||||
|
||||
// Config
|
||||
|
||||
export type StepName =
|
||||
|
|
@ -945,8 +976,6 @@ export interface ContextProviderWithParams {
|
|||
params: { [key: string]: any };
|
||||
}
|
||||
|
||||
export type SlashCommandDescription = Omit<SlashCommand, "run">;
|
||||
|
||||
export interface CustomCommand {
|
||||
name: string;
|
||||
prompt: string;
|
||||
|
|
@ -1170,14 +1199,16 @@ export type MCPConnectionStatus =
|
|||
| "error"
|
||||
| "not-connected";
|
||||
|
||||
export type MCPPromptArgs = {
|
||||
name: string;
|
||||
description?: string;
|
||||
required?: boolean;
|
||||
}[];
|
||||
|
||||
export interface MCPPrompt {
|
||||
name: string;
|
||||
description?: string;
|
||||
arguments?: {
|
||||
name: string;
|
||||
description?: string;
|
||||
required?: boolean;
|
||||
}[];
|
||||
arguments?: MCPPromptArgs;
|
||||
}
|
||||
|
||||
// Leaving here to ideate on
|
||||
|
|
@ -1442,7 +1473,7 @@ export interface Config {
|
|||
/** Request options that will be applied to all models and context providers */
|
||||
requestOptions?: RequestOptions;
|
||||
/** The list of slash commands that will be available in the sidebar */
|
||||
slashCommands?: SlashCommand[];
|
||||
slashCommands?: (SlashCommand | SlashCommandWithSource)[];
|
||||
/** Each entry in this array will originally be a ContextProviderWithParams, the same object from your config.json, but you may add CustomContextProviders.
|
||||
* A CustomContextProvider requires you only to define a title and getContextItems function. When you type '@title <query>', Continue will call `getContextItems(query)`.
|
||||
*/
|
||||
|
|
@ -1479,7 +1510,7 @@ export interface ContinueConfig {
|
|||
// systemMessage?: string;
|
||||
completionOptions?: BaseCompletionOptions;
|
||||
requestOptions?: RequestOptions;
|
||||
slashCommands: SlashCommand[];
|
||||
slashCommands: SlashCommandWithSource[];
|
||||
contextProviders: IContextProvider[];
|
||||
disableSessionTitles?: boolean;
|
||||
disableIndexing?: boolean;
|
||||
|
|
@ -1502,7 +1533,7 @@ export interface BrowserSerializedContinueConfig {
|
|||
// systemMessage?: string;
|
||||
completionOptions?: BaseCompletionOptions;
|
||||
requestOptions?: RequestOptions;
|
||||
slashCommands: SlashCommandDescription[];
|
||||
slashCommands: SlashCommandDescWithSource[];
|
||||
contextProviders: ContextProviderDescription[];
|
||||
disableIndexing?: boolean;
|
||||
disableSessionTitles?: boolean;
|
||||
|
|
@ -1577,12 +1608,12 @@ export interface RuleWithSource {
|
|||
slug?: string;
|
||||
source: RuleSource;
|
||||
globs?: string | string[];
|
||||
regex?: string | string[];
|
||||
rule: string;
|
||||
description?: string;
|
||||
ruleFile?: string;
|
||||
alwaysApply?: boolean;
|
||||
}
|
||||
|
||||
export interface CompleteOnboardingPayload {
|
||||
mode: OnboardingModes;
|
||||
provider?: string;
|
||||
|
|
|
|||
|
|
@ -124,14 +124,6 @@ describe("CodebaseIndexer", () => {
|
|||
return updates;
|
||||
}
|
||||
|
||||
async function refreshIndexFiles(files: string[]) {
|
||||
const updates = [];
|
||||
for await (const update of codebaseIndexer.refreshFiles(files)) {
|
||||
updates.push(update);
|
||||
}
|
||||
return updates;
|
||||
}
|
||||
|
||||
async function getAllIndexedFiles() {
|
||||
const files = await testIndex.getIndexedFilesForTags(
|
||||
await testIde.getTags(testIndex.artifactId),
|
||||
|
|
@ -197,7 +189,7 @@ describe("CodebaseIndexer", () => {
|
|||
test("should successfuly re-index specific files", async () => {
|
||||
// Could add more specific tests for this but uses similar logic
|
||||
const before = await getAllIndexedFiles();
|
||||
await refreshIndexFiles(before);
|
||||
await codebaseIndexer.refreshCodebaseIndexFiles(before);
|
||||
|
||||
const after = await getAllIndexedFiles();
|
||||
expect(after.length).toBe(before.length);
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@ export class CodebaseIndexer {
|
|||
* - To limit memory usage for indexes that perform computations locally, e.g. FTS
|
||||
* - To make as few requests as possible to the embeddings providers
|
||||
*/
|
||||
filesPerBatch = 500;
|
||||
filesPerBatch = 200;
|
||||
private indexingCancellationController: AbortController | undefined;
|
||||
private codebaseIndexingState: IndexingProgressUpdate;
|
||||
private readonly pauseToken: PauseToken;
|
||||
|
|
@ -75,16 +75,10 @@ export class CodebaseIndexer {
|
|||
this.pauseToken = new PauseToken(initialPaused);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the paused state of the indexer
|
||||
*/
|
||||
set paused(value: boolean) {
|
||||
this.pauseToken.paused = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current paused state of the indexer
|
||||
*/
|
||||
get paused(): boolean {
|
||||
return this.pauseToken.paused;
|
||||
}
|
||||
|
|
@ -235,7 +229,9 @@ export class CodebaseIndexer {
|
|||
}
|
||||
}
|
||||
|
||||
async *refreshFiles(files: string[]): AsyncGenerator<IndexingProgressUpdate> {
|
||||
private async *refreshFiles(
|
||||
files: string[],
|
||||
): AsyncGenerator<IndexingProgressUpdate> {
|
||||
let progress = 0;
|
||||
if (files.length === 0) {
|
||||
yield {
|
||||
|
|
@ -525,7 +521,7 @@ export class CodebaseIndexer {
|
|||
repoName,
|
||||
)) {
|
||||
yield {
|
||||
progress: progress,
|
||||
progress,
|
||||
desc,
|
||||
status: "indexing",
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
const DEFAULT_MAX_TOKENS = 4096;
|
||||
const DEFAULT_CONTEXT_LENGTH = 8192;
|
||||
const DEFAULT_CONTEXT_LENGTH = 32_768;
|
||||
const DEFAULT_TEMPERATURE = 0.5;
|
||||
|
||||
const DEFAULT_ARGS = {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,10 @@
|
|||
import { ChatMessage, LLMOptions } from "..";
|
||||
|
||||
import { allModelProviders } from "@continuedev/llm-info";
|
||||
import { LlmInfo } from "@continuedev/llm-info/dist/types";
|
||||
import { BaseLLM } from ".";
|
||||
import { DEFAULT_CONTEXT_LENGTH } from "./constants";
|
||||
import { LLMClasses } from "./llms";
|
||||
import { LLMLogger } from "./logger";
|
||||
|
||||
class DummyLLM extends BaseLLM {
|
||||
|
|
@ -140,4 +144,31 @@ describe("BaseLLM", () => {
|
|||
describe("*streamChat", () => {
|
||||
// TODO: Implement tests for *streamChat method
|
||||
});
|
||||
|
||||
describe("default context length", () => {
|
||||
allModelProviders.map((modelProvider) => {
|
||||
const LLMClass = LLMClasses.find(
|
||||
(llm) => llm.providerName === modelProvider.id,
|
||||
);
|
||||
if (!LLMClass) {
|
||||
throw new Error(`did not find LLM provider for ${modelProvider.id}`);
|
||||
}
|
||||
const testContextLength = (llmInfo: LlmInfo) => () => {
|
||||
const llm = new LLMClass({ model: llmInfo.model });
|
||||
if (llmInfo.contextLength) {
|
||||
expect(llm.contextLength).toEqual(llmInfo.contextLength);
|
||||
} else {
|
||||
expect(llm.contextLength).toEqual(DEFAULT_CONTEXT_LENGTH);
|
||||
}
|
||||
};
|
||||
describe(`${modelProvider.id}`, () => {
|
||||
modelProvider.models.forEach((llmInfo) => {
|
||||
test(
|
||||
`should have correct context length for ${llmInfo.model}`,
|
||||
testContextLength(llmInfo),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -292,6 +292,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
apiKey: this.apiKey ?? "",
|
||||
apiBase: this.apiBase,
|
||||
requestOptions: this.requestOptions,
|
||||
env: this._llmOptions.env,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -8,7 +8,6 @@ class Anthropic extends BaseLLM {
|
|||
static providerName = "anthropic";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
contextLength: 200_000,
|
||||
completionOptions: {
|
||||
model: "claude-3-5-sonnet-latest",
|
||||
maxTokens: 8192,
|
||||
|
|
|
|||
|
|
@ -48,7 +48,6 @@ class Bedrock extends BaseLLM {
|
|||
static defaultOptions: Partial<LLMOptions> = {
|
||||
region: "us-east-1",
|
||||
model: "anthropic.claude-3-sonnet-20240229-v1:0",
|
||||
contextLength: 200_000,
|
||||
profile: "bedrock",
|
||||
};
|
||||
|
||||
|
|
@ -547,7 +546,7 @@ class Bedrock extends BaseLLM {
|
|||
}
|
||||
|
||||
// EMBED //
|
||||
async embed(chunks: string[]): Promise<number[][]> {
|
||||
async _embed(chunks: string[]): Promise<number[][]> {
|
||||
const credentials = await this._getCredentials();
|
||||
const client = new BedrockRuntimeClient({
|
||||
region: this.region,
|
||||
|
|
|
|||
|
|
@ -25,16 +25,7 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseLLM {
|
|||
});
|
||||
}
|
||||
|
||||
async embed(chunks: string[]) {
|
||||
const batchedChunks = this.getBatchedChunks(chunks);
|
||||
|
||||
const results = await Promise.all(
|
||||
batchedChunks.map((batch) => this.doEmbedRequest(batch)),
|
||||
);
|
||||
return results.flat();
|
||||
}
|
||||
|
||||
async doEmbedRequest(batch: string[]): Promise<number[][]> {
|
||||
async _embed(batch: string[]): Promise<number[][]> {
|
||||
const headers: Record<string, string> = {
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
|
|
|
|||
|
|
@ -405,7 +405,6 @@ class Ollama extends BaseLLM implements ModelInstaller {
|
|||
parameters: tool.function.parameters,
|
||||
},
|
||||
}));
|
||||
chatOptions.stream = false; // Cannot set stream = true for tools calls
|
||||
}
|
||||
const headers: Record<string, string> = {
|
||||
"Content-Type": "application/json",
|
||||
|
|
|
|||
|
|
@ -141,7 +141,7 @@ class SageMaker extends BaseLLM {
|
|||
}
|
||||
}
|
||||
|
||||
async embed(chunks: string[]) {
|
||||
async _embed(chunks: string[]) {
|
||||
const credentials = await this._getCredentials();
|
||||
const client = new SageMakerRuntimeClient({
|
||||
region: this.region,
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import Handlebars from "handlebars";
|
||||
import {
|
||||
BaseCompletionOptions,
|
||||
IdeSettings,
|
||||
|
|
@ -6,10 +7,9 @@ import {
|
|||
JSONModelDescription,
|
||||
LLMOptions,
|
||||
} from "../..";
|
||||
import { renderTemplatedString } from "../../promptFiles/v1/renderTemplatedString";
|
||||
import { renderTemplatedString } from "../../util/handlebars/renderTemplatedString";
|
||||
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../constructMessages";
|
||||
import { BaseLLM } from "../index";
|
||||
|
||||
import Anthropic from "./Anthropic";
|
||||
import Asksage from "./Asksage";
|
||||
import Azure from "./Azure";
|
||||
|
|
@ -121,6 +121,7 @@ export const LLMClasses = [
|
|||
export async function llmFromDescription(
|
||||
desc: JSONModelDescription,
|
||||
readFile: (filepath: string) => Promise<string>,
|
||||
getUriFromPath: (path: string) => Promise<string | undefined>,
|
||||
uniqueId: string,
|
||||
ideSettings: IdeSettings,
|
||||
llmLogger: ILLMLogger,
|
||||
|
|
@ -142,9 +143,12 @@ export async function llmFromDescription(
|
|||
baseChatSystemMessage = DEFAULT_CHAT_SYSTEM_MESSAGE;
|
||||
baseChatSystemMessage += "\n\n";
|
||||
baseChatSystemMessage += await renderTemplatedString(
|
||||
Handlebars,
|
||||
desc.systemMessage,
|
||||
readFile,
|
||||
{},
|
||||
[],
|
||||
readFile,
|
||||
getUriFromPath,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import {
|
|||
} from "../..";
|
||||
import { renderChatMessage } from "../../util/messageContent";
|
||||
import { getCleanUriPath } from "../../util/uri";
|
||||
import { extractContentFromCodeBlock } from "../utils/extractContentFromCodeBlocks";
|
||||
import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks";
|
||||
import { RulePolicies } from "./types";
|
||||
|
||||
|
|
@ -52,6 +53,47 @@ const matchesGlobs = (
|
|||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Checks if file content matches any of the provided regex regex
|
||||
*
|
||||
* @param fileContent - The content of the file to check
|
||||
* @param regex - A single regex pattern string or array of regex pattern strings
|
||||
* @returns true if the content matches any pattern (or if no regex is provided), false otherwise
|
||||
*/
|
||||
const contentMatchesRegex = (
|
||||
fileContent: string,
|
||||
regex: string | string[],
|
||||
): boolean => {
|
||||
// Handle single string pattern
|
||||
if (typeof regex === "string") {
|
||||
try {
|
||||
const expression = new RegExp(regex);
|
||||
return expression.test(fileContent);
|
||||
} catch (e) {
|
||||
console.error(`Invalid regex pattern: ${regex}`, e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle array of regex
|
||||
if (Array.isArray(regex)) {
|
||||
if (regex.length === 0) return true;
|
||||
|
||||
// Content must match at least one pattern
|
||||
return regex.some((pattern) => {
|
||||
try {
|
||||
const regex = new RegExp(pattern);
|
||||
return regex.test(fileContent);
|
||||
} catch (e) {
|
||||
console.error(`Invalid regex pattern: ${pattern}`, e);
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Determines if a file path is within a specific directory or its subdirectories
|
||||
*
|
||||
|
|
@ -103,25 +145,67 @@ const isGlobalRule = (rule: RuleWithSource): boolean => {
|
|||
return true;
|
||||
}
|
||||
|
||||
// Root-level rules with no globs are implicitly global
|
||||
if (isRootLevelRule(rule) && !rule.globs && rule.alwaysApply !== false) {
|
||||
// Root-level rules with no globs or regex are implicitly global
|
||||
if (
|
||||
isRootLevelRule(rule) &&
|
||||
!rule.globs &&
|
||||
!rule.regex &&
|
||||
rule.alwaysApply !== false
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
const checkGlobsAndRegex = ({
|
||||
rule,
|
||||
filePaths,
|
||||
fileContents,
|
||||
}: {
|
||||
rule: RuleWithSource;
|
||||
filePaths: string[];
|
||||
fileContents: Record<string, string>;
|
||||
}) => {
|
||||
const matchingFiles = rule.globs
|
||||
? filePaths.filter((filePath) => matchesGlobs(filePath, rule.globs))
|
||||
: filePaths;
|
||||
|
||||
// If no files match the globs, don't apply the rule
|
||||
if (matchingFiles.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Now check for pattern matches in file contents if regex are specified
|
||||
if (rule.regex) {
|
||||
// Check if any of the matching files also match the content regex
|
||||
return matchingFiles.some((filePath) => {
|
||||
const content = fileContents[filePath];
|
||||
// If we don't have the content, we can't check regex
|
||||
if (!content) return false;
|
||||
return contentMatchesRegex(content, rule.regex!);
|
||||
});
|
||||
}
|
||||
|
||||
// If we have no regex or if we couldn't check regex (no content),
|
||||
// just go with the glob matches
|
||||
return matchingFiles.length > 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Determines if a rule should be applied based on its alwaysApply property and file path matching
|
||||
* Determines if a rule should be applied based on its properties and file matching
|
||||
*
|
||||
* @param rule - The rule to check
|
||||
* @param filePaths - Array of file paths to check against the rule's globs
|
||||
* @param fileContents - Map of file paths to their contents for pattern matching
|
||||
* @param rulePolicies - Optional policies that can override normal rule behavior
|
||||
* @returns true if the rule should be applied, false otherwise
|
||||
*/
|
||||
export const shouldApplyRule = (
|
||||
rule: RuleWithSource,
|
||||
filePaths: string[],
|
||||
rulePolicies: RulePolicies = {},
|
||||
fileContents: Record<string, string> = {},
|
||||
): boolean => {
|
||||
const policy = rulePolicies[rule.name || ""];
|
||||
|
||||
|
|
@ -157,40 +241,27 @@ export const shouldApplyRule = (
|
|||
isFileInDirectory(filePath, ruleDirPath),
|
||||
);
|
||||
|
||||
// If no files are in this directory, don't apply the rule
|
||||
if (filesInRuleDirectory.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// If we have globs, check if any files in this directory match them
|
||||
if (rule.globs) {
|
||||
return filesInRuleDirectory.some((filePath) =>
|
||||
matchesGlobs(filePath, rule.globs),
|
||||
);
|
||||
}
|
||||
|
||||
// No globs but files are in this directory, so apply the rule
|
||||
return true;
|
||||
return checkGlobsAndRegex({
|
||||
filePaths: filesInRuleDirectory,
|
||||
fileContents,
|
||||
rule,
|
||||
});
|
||||
}
|
||||
|
||||
// For root-level rules:
|
||||
|
||||
// If alwaysApply is explicitly false, only apply if there are globs AND they match
|
||||
if (rule.alwaysApply === false) {
|
||||
if (!rule.globs) {
|
||||
return false;
|
||||
}
|
||||
return filePaths.some((path) => matchesGlobs(path, rule.globs));
|
||||
// If alwaysApply is explicitly false, we need to check globs and/or regex
|
||||
if (
|
||||
rule.alwaysApply === false &&
|
||||
rule.globs === undefined &&
|
||||
rule.regex === undefined
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Default behavior for root rules with globs:
|
||||
// - Only apply if they match the globs
|
||||
if (rule.globs) {
|
||||
return filePaths.some((path) => matchesGlobs(path, rule.globs));
|
||||
}
|
||||
|
||||
// This point should not be reached as we've handled all cases above
|
||||
return false;
|
||||
return checkGlobsAndRegex({
|
||||
filePaths,
|
||||
fileContents,
|
||||
rule,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
|
|
@ -220,10 +291,34 @@ export const getApplicableRules = (
|
|||
// Combine file paths from both sources
|
||||
const allFilePaths = [...filePathsFromMessage, ...filePathsFromContextItems];
|
||||
|
||||
// Create a map of file paths to their contents for pattern matching
|
||||
const fileContents: Record<string, string> = {};
|
||||
|
||||
// Extract contents from context items with file URIs
|
||||
contextItems.forEach((item) => {
|
||||
if (item.uri?.type === "file" && item.uri?.value) {
|
||||
fileContents[item.uri.value] = item.content;
|
||||
}
|
||||
});
|
||||
|
||||
// Extract contents from code blocks in the message for paths that don't have content yet
|
||||
if (userMessage) {
|
||||
const messageContent = renderChatMessage(userMessage);
|
||||
filePathsFromMessage.forEach((path) => {
|
||||
// Only extract content if we don't already have it from context items
|
||||
if (!fileContents[path]) {
|
||||
const blockContent = extractContentFromCodeBlock(messageContent, path);
|
||||
if (blockContent) {
|
||||
fileContents[path] = blockContent;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Apply shouldApplyRule to all rules - this will handle global rules, rule policies,
|
||||
// and path matching in a consistent way
|
||||
const applicableRules = rules.filter((rule) =>
|
||||
shouldApplyRule(rule, allFilePaths, rulePolicies),
|
||||
shouldApplyRule(rule, allFilePaths, rulePolicies, fileContents),
|
||||
);
|
||||
|
||||
return applicableRules;
|
||||
|
|
|
|||
|
|
@ -1,6 +1,14 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import { RuleWithSource } from "../..";
|
||||
import { shouldApplyRule } from "./getSystemMessageWithRules";
|
||||
import {
|
||||
ContextItemId,
|
||||
ContextItemWithId,
|
||||
RuleWithSource,
|
||||
UserChatMessage,
|
||||
} from "../..";
|
||||
import {
|
||||
getApplicableRules,
|
||||
shouldApplyRule,
|
||||
} from "./getSystemMessageWithRules";
|
||||
import { RulePolicies } from "./types";
|
||||
|
||||
describe("Rule colocation glob matching", () => {
|
||||
|
|
@ -244,3 +252,228 @@ describe("Rule policies", () => {
|
|||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Content pattern matching", () => {
|
||||
it("should apply rules when file content matches pattern", () => {
|
||||
// Rule with pattern to match React component files
|
||||
const reactComponentRule: RuleWithSource = {
|
||||
name: "React Component Rule",
|
||||
rule: "Follow React component standards",
|
||||
regex: "export (function|const) \\w+.*\\(",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/components/rules.md",
|
||||
};
|
||||
|
||||
// File that matches the pattern
|
||||
const filePath = "src/components/Button.tsx";
|
||||
const fileContents = {
|
||||
[filePath]:
|
||||
"export function Button() { return <button>Click me</button> }",
|
||||
};
|
||||
|
||||
expect(
|
||||
shouldApplyRule(reactComponentRule, [filePath], {}, fileContents),
|
||||
).toBe(true);
|
||||
|
||||
// File that doesn't match the pattern
|
||||
const nonMatchingContents = {
|
||||
[filePath]:
|
||||
"import React from 'react'; // Just an import, not a component",
|
||||
};
|
||||
|
||||
expect(
|
||||
shouldApplyRule(reactComponentRule, [filePath], {}, nonMatchingContents),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should support multiple regex regex as an array", () => {
|
||||
// Rule with multiple regex
|
||||
const multiPatternRule: RuleWithSource = {
|
||||
name: "Multi-Pattern Rule",
|
||||
rule: "Apply to functions or classes",
|
||||
regex: ["function\\s+\\w+", "class\\s+\\w+"],
|
||||
source: "rules-block",
|
||||
ruleFile: "src/utils/rules.md",
|
||||
};
|
||||
|
||||
const filePath = "src/utils/helper.ts";
|
||||
|
||||
// Content with function - should match
|
||||
const functionContent = {
|
||||
[filePath]: "function formatDate(date) { return date.toISOString(); }",
|
||||
};
|
||||
expect(
|
||||
shouldApplyRule(multiPatternRule, [filePath], {}, functionContent),
|
||||
).toBe(true);
|
||||
|
||||
// Content with class - should match
|
||||
const classContent = {
|
||||
[filePath]:
|
||||
"class DateFormatter { format(date) { return date.toISOString(); } }",
|
||||
};
|
||||
expect(
|
||||
shouldApplyRule(multiPatternRule, [filePath], {}, classContent),
|
||||
).toBe(true);
|
||||
|
||||
// Content with neither - should not match
|
||||
const nonMatchingContent = {
|
||||
[filePath]: "const PI = 3.14159;",
|
||||
};
|
||||
expect(
|
||||
shouldApplyRule(multiPatternRule, [filePath], {}, nonMatchingContent),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should apply rules based on both globs and regex when both are specified", () => {
|
||||
// Rule with both glob and pattern restrictions
|
||||
const typescriptClassRule: RuleWithSource = {
|
||||
name: "TypeScript Class Rule",
|
||||
rule: "Follow class standards in TypeScript",
|
||||
globs: "**/*.ts",
|
||||
regex: "class\\s+\\w+",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/models/rules.md",
|
||||
};
|
||||
|
||||
const tsFilePath = "src/models/User.ts";
|
||||
const jsFilePath = "src/models/Product.js";
|
||||
|
||||
// TypeScript file with class - should match
|
||||
const tsClassContent = {
|
||||
[tsFilePath]: "export class User { constructor(public name: string) {} }",
|
||||
};
|
||||
expect(
|
||||
shouldApplyRule(typescriptClassRule, [tsFilePath], {}, tsClassContent),
|
||||
).toBe(true);
|
||||
|
||||
// TypeScript file without class - should not match
|
||||
const tsNonClassContent = {
|
||||
[tsFilePath]: "export const createUser = (name: string) => ({ name });",
|
||||
};
|
||||
expect(
|
||||
shouldApplyRule(typescriptClassRule, [tsFilePath], {}, tsNonClassContent),
|
||||
).toBe(false);
|
||||
|
||||
// JavaScript file with class - should not match due to glob
|
||||
const jsClassContent = {
|
||||
[jsFilePath]:
|
||||
"export class Product { constructor(name) { this.name = name; } }",
|
||||
};
|
||||
expect(
|
||||
shouldApplyRule(typescriptClassRule, [jsFilePath], {}, jsClassContent),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should extract file content from messages for pattern matching", () => {
|
||||
// Rule with pattern
|
||||
const arrowFunctionRule: RuleWithSource = {
|
||||
name: "Arrow Function Rule",
|
||||
rule: "Use arrow functions for better this binding",
|
||||
regex: "const\\s+\\w+\\s*=\\s*\\(",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/utils/rules.md",
|
||||
};
|
||||
|
||||
// Message with code block containing a matching pattern
|
||||
const messageWithArrowFn: UserChatMessage = {
|
||||
role: "user",
|
||||
content:
|
||||
"Can you check this code?\n```typescript src/utils/formatter.ts\nconst format = (date) => {\n return date.toISOString();\n};\n```",
|
||||
};
|
||||
|
||||
// Create context item to match the file in the message
|
||||
const contextItem: ContextItemWithId = {
|
||||
id: { providerTitle: "file", itemId: "formatter" } as ContextItemId,
|
||||
uri: { type: "file", value: "src/utils/formatter.ts" },
|
||||
content: "const format = (date) => {\n return date.toISOString();\n};",
|
||||
name: "formatter.ts",
|
||||
description: "Utility formatter",
|
||||
};
|
||||
|
||||
// Should match the pattern
|
||||
const applicableRules = getApplicableRules(
|
||||
messageWithArrowFn,
|
||||
[arrowFunctionRule],
|
||||
[contextItem],
|
||||
);
|
||||
|
||||
expect(applicableRules).toHaveLength(1);
|
||||
expect(applicableRules[0].name).toBe("Arrow Function Rule");
|
||||
|
||||
// Message with code block that doesn't match the pattern
|
||||
const messageWithoutArrowFn: UserChatMessage = {
|
||||
role: "user",
|
||||
content:
|
||||
"Can you check this code?\n```typescript src/utils/formatter.ts\nfunction format(date) {\n return date.toISOString();\n}\n```",
|
||||
};
|
||||
|
||||
// Context item with non-matching content
|
||||
const nonMatchingContextItem: ContextItemWithId = {
|
||||
id: { providerTitle: "file", itemId: "formatter2" } as ContextItemId,
|
||||
uri: { type: "file", value: "src/utils/formatter.ts" },
|
||||
content: "function format(date) {\n return date.toISOString();\n}",
|
||||
name: "formatter.ts",
|
||||
description: "Utility formatter",
|
||||
};
|
||||
|
||||
// Should not match the pattern
|
||||
const nonApplicableRules = getApplicableRules(
|
||||
messageWithoutArrowFn,
|
||||
[arrowFunctionRule],
|
||||
[nonMatchingContextItem],
|
||||
);
|
||||
|
||||
expect(nonApplicableRules).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("should handle invalid regex regex gracefully", () => {
|
||||
// Rule with invalid regex pattern
|
||||
const invalidRegexRule: RuleWithSource = {
|
||||
name: "Invalid Regex Rule",
|
||||
rule: "This rule has an invalid regex pattern",
|
||||
regex: "([unclosed parenthesis",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/utils/rules.md",
|
||||
};
|
||||
|
||||
const filePath = "src/utils/helper.ts";
|
||||
const fileContents = {
|
||||
[filePath]: "function helper() { return true; }",
|
||||
};
|
||||
|
||||
// Should not throw an error but gracefully not apply the rule
|
||||
expect(
|
||||
shouldApplyRule(invalidRegexRule, [filePath], {}, fileContents),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("should respect directory restrictions for pattern rules", () => {
|
||||
// Rule with pattern in a nested directory
|
||||
const nestedPatternRule: RuleWithSource = {
|
||||
name: "Nested Pattern Rule",
|
||||
rule: "Apply only to model files with interfaces",
|
||||
regex: "interface\\s+\\w+",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/models/rules.md",
|
||||
};
|
||||
|
||||
// File in the correct directory with matching content
|
||||
const modelFilePath = "src/models/User.ts";
|
||||
const modelContents = {
|
||||
[modelFilePath]: "export interface User { id: string; name: string; }",
|
||||
};
|
||||
expect(
|
||||
shouldApplyRule(nestedPatternRule, [modelFilePath], {}, modelContents),
|
||||
).toBe(true);
|
||||
|
||||
// File outside the directory with matching content - should not match
|
||||
const utilFilePath = "src/utils/types.ts";
|
||||
const utilContents = {
|
||||
[utilFilePath]:
|
||||
"export interface Config { apiUrl: string; timeout: number; }",
|
||||
};
|
||||
expect(
|
||||
shouldApplyRule(nestedPatternRule, [utilFilePath], {}, utilContents),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -59,6 +59,12 @@ export async function* llmStreamChat(
|
|||
},
|
||||
true,
|
||||
);
|
||||
if (!slashCommand.run) {
|
||||
console.error(
|
||||
`Slash command ${command.name} (${command.source}) has no run function`,
|
||||
);
|
||||
throw new Error(`Slash command not found`);
|
||||
}
|
||||
|
||||
const gen = slashCommand.run({
|
||||
input,
|
||||
|
|
|
|||
94
core/llm/utils/extractContentFromCodeBlocks.test.ts
Normal file
94
core/llm/utils/extractContentFromCodeBlocks.test.ts
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
import { extractContentFromCodeBlock } from "./extractContentFromCodeBlocks";
|
||||
|
||||
describe("extractContentFromCodeBlock", () => {
|
||||
it("should extract content from code block with language and filepath", () => {
|
||||
const content = "```typescript src/main.ts\nconst x = 1;\n```";
|
||||
expect(extractContentFromCodeBlock(content, "src/main.ts")).toBe(
|
||||
"const x = 1;",
|
||||
);
|
||||
});
|
||||
|
||||
it("should extract content from code block with filepath only (no language)", () => {
|
||||
const content = "```test.js\nclass Calculator { }\n```";
|
||||
expect(extractContentFromCodeBlock(content, "test.js")).toBe(
|
||||
"class Calculator { }",
|
||||
);
|
||||
});
|
||||
|
||||
it("should extract content from code block with line ranges", () => {
|
||||
const content = "```js test.js (19-25)\nfunction test() {}\n```";
|
||||
expect(extractContentFromCodeBlock(content, "test.js")).toBe(
|
||||
"function test() {}",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle multiple code blocks and find the right one", () => {
|
||||
const content =
|
||||
"```typescript src/main.ts\nconst x = 1;\n```\n" +
|
||||
"```test.js\nclass Calculator { }\n```\n" +
|
||||
"```js utils.js (19-25)\nfunction test() {}\n```";
|
||||
|
||||
expect(extractContentFromCodeBlock(content, "src/main.ts")).toBe(
|
||||
"const x = 1;",
|
||||
);
|
||||
expect(extractContentFromCodeBlock(content, "test.js")).toBe(
|
||||
"class Calculator { }",
|
||||
);
|
||||
expect(extractContentFromCodeBlock(content, "utils.js")).toBe(
|
||||
"function test() {}",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle paths with special regex characters", () => {
|
||||
const content =
|
||||
"```typescript src/special+chars.ts[123]\nconst special = true;\n```";
|
||||
expect(
|
||||
extractContentFromCodeBlock(content, "src/special+chars.ts[123]"),
|
||||
).toBe("const special = true;");
|
||||
});
|
||||
|
||||
it("should handle multiline content", () => {
|
||||
const content =
|
||||
"```typescript src/multi-line.ts\n" +
|
||||
"function example() {\n" +
|
||||
" const x = 1;\n" +
|
||||
" return x + 2;\n" +
|
||||
"}\n" +
|
||||
"```";
|
||||
|
||||
const expected =
|
||||
"function example() {\n" + " const x = 1;\n" + " return x + 2;\n" + "}";
|
||||
|
||||
expect(extractContentFromCodeBlock(content, "src/multi-line.ts")).toBe(
|
||||
expected,
|
||||
);
|
||||
});
|
||||
|
||||
it("should return undefined when path doesn't exist in any code block", () => {
|
||||
const content = "```typescript src/main.ts\nconst x = 1;\n```";
|
||||
expect(
|
||||
extractContentFromCodeBlock(content, "nonexistent.ts"),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should extract content when the path has directory structure", () => {
|
||||
const content =
|
||||
"```js src/components/Button.jsx\nconst Button = () => <button>Click me</button>;\n```";
|
||||
expect(
|
||||
extractContentFromCodeBlock(content, "src/components/Button.jsx"),
|
||||
).toBe("const Button = () => <button>Click me</button>;");
|
||||
});
|
||||
|
||||
it("should match exact paths only", () => {
|
||||
const content =
|
||||
"```typescript src/utils.ts\nconst util = {};\n```\n" +
|
||||
"```typescript src/utils/index.ts\nconst index = {};\n```";
|
||||
|
||||
expect(extractContentFromCodeBlock(content, "src/utils.ts")).toBe(
|
||||
"const util = {};",
|
||||
);
|
||||
expect(extractContentFromCodeBlock(content, "src/utils/index.ts")).toBe(
|
||||
"const index = {};",
|
||||
);
|
||||
});
|
||||
});
|
||||
33
core/llm/utils/extractContentFromCodeBlocks.ts
Normal file
33
core/llm/utils/extractContentFromCodeBlocks.ts
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
/**
|
||||
* Extracts content from code blocks with given path
|
||||
* @param content The full message content
|
||||
* @param path The file path to look for
|
||||
* @returns The content of the code block if found, undefined otherwise
|
||||
*/
|
||||
export function extractContentFromCodeBlock(
|
||||
content: string,
|
||||
path: string,
|
||||
): string | undefined {
|
||||
// Escape special characters in the path for regex
|
||||
const escapedPath = path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
|
||||
// Match the code block with this path
|
||||
// This regex looks for:
|
||||
// 1. Code block start with the path (```[language] path)
|
||||
// 2. The content until the closing ```
|
||||
// The path can be:
|
||||
// - With language: ```typescript src/main.ts
|
||||
// - Without language: ```src/main.ts
|
||||
// - With line ranges: ```js src/main.ts (1-10)
|
||||
const regex = new RegExp(
|
||||
`\`\`\`[^\\n]*\\b${escapedPath}(?:\\s+\\([\\d-]+\\))?[^\\n]*\\n([\\s\\S]*?)\\n\`\`\``,
|
||||
"m",
|
||||
);
|
||||
|
||||
const match = content.match(regex);
|
||||
if (match && match[1]) {
|
||||
return match[1];
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
70
core/package-lock.json
generated
70
core/package-lock.json
generated
|
|
@ -14,9 +14,9 @@
|
|||
"@aws-sdk/credential-providers": "^3.778.0",
|
||||
"@continuedev/config-types": "^1.0.13",
|
||||
"@continuedev/config-yaml": "file:../packages/config-yaml",
|
||||
"@continuedev/fetch": "^1.0.13",
|
||||
"@continuedev/fetch": "^1.0.14",
|
||||
"@continuedev/llm-info": "^1.0.8",
|
||||
"@continuedev/openai-adapters": "^1.0.32",
|
||||
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
|
||||
"@modelcontextprotocol/sdk": "^1.12.0",
|
||||
"@mozilla/readability": "^0.5.0",
|
||||
"@octokit/rest": "^20.1.1",
|
||||
|
|
@ -139,7 +139,7 @@
|
|||
},
|
||||
"../packages/config-yaml": {
|
||||
"name": "@continuedev/config-yaml",
|
||||
"version": "1.0.88",
|
||||
"version": "1.0.95",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@continuedev/config-types": "^1.0.14",
|
||||
|
|
@ -150,15 +150,44 @@
|
|||
"config-yaml": "dist/cli.js"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@semantic-release/changelog": "^6.0.3",
|
||||
"@semantic-release/git": "^10.0.1",
|
||||
"@semantic-release/github": "^9.2.6",
|
||||
"@semantic-release/npm": "^10.0.6",
|
||||
"@types/jest": "^29.5.14",
|
||||
"@types/node": "^20.0.0",
|
||||
"cross-env": "^7.0.3",
|
||||
"jest": "^29.7.0",
|
||||
"semantic-release": "^21.1.2",
|
||||
"ts-jest": "^29.2.3",
|
||||
"ts-node": "^10.9.2",
|
||||
"zod-to-json-schema": "^3.24.5"
|
||||
}
|
||||
},
|
||||
"../packages/openai-adapters": {
|
||||
"name": "@continuedev/openai-adapters",
|
||||
"version": "1.0.42",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@continuedev/config-types": "^1.0.5",
|
||||
"@continuedev/config-yaml": "^1.0.51",
|
||||
"@continuedev/fetch": "^1.0.11",
|
||||
"dotenv": "^16.5.0",
|
||||
"json-schema": "^0.4.0",
|
||||
"node-fetch": "^3.3.2",
|
||||
"openai": "^4.76.0",
|
||||
"uuid": "^11.1.0",
|
||||
"zod": "^3.24.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/follow-redirects": "^1.14.4",
|
||||
"@types/jest": "^29.5.14",
|
||||
"@types/json-schema": "^7.0.15",
|
||||
"cross-env": "^7.0.3",
|
||||
"ts-jest": "^29.2.3",
|
||||
"ts-node": "^10.9.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@75lb/deep-merge": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/@75lb/deep-merge/-/deep-merge-1.1.2.tgz",
|
||||
|
|
@ -2883,9 +2912,10 @@
|
|||
"link": true
|
||||
},
|
||||
"node_modules/@continuedev/fetch": {
|
||||
"version": "1.0.13",
|
||||
"resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.13.tgz",
|
||||
"integrity": "sha512-7vwsefFBozsutv355zD7mEhFfl6UT4KXRH1QXRzjdbCaYneiRdFLe6UAwV2wGnH71Lj76gOLnTlcGoTV357OZg==",
|
||||
"version": "1.0.14",
|
||||
"resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.14.tgz",
|
||||
"integrity": "sha512-r/CUwW0tt7VrjLVNeowA281aq7VQvToE+Ro9+0EhfINBMNre4eU2MbNOgbRmYCr5VkIuSnltPUDI357Kns7uCw==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@continuedev/config-types": "^1.0.5",
|
||||
"follow-redirects": "^1.15.6",
|
||||
|
|
@ -2900,32 +2930,8 @@
|
|||
"integrity": "sha512-/htL7p4li3zQSwn9bXkI23WRpZNklWTPzRSSG3Fd5gvYW8cizjhlf7OzeDdKxBfi1S0lpqMm0VwHlx3KjMKLpw=="
|
||||
},
|
||||
"node_modules/@continuedev/openai-adapters": {
|
||||
"version": "1.0.32",
|
||||
"resolved": "https://registry.npmjs.org/@continuedev/openai-adapters/-/openai-adapters-1.0.32.tgz",
|
||||
"integrity": "sha512-teNzbpcsa7Y0eBk+dxlLDo0m43sWI5txTYMIk6ezyS0cZAKFJODDB0Gkp3aEHXbD8mDE7H5dDSlM23ohKCirAA==",
|
||||
"dependencies": {
|
||||
"@continuedev/config-types": "^1.0.5",
|
||||
"@continuedev/config-yaml": "^1.0.51",
|
||||
"@continuedev/fetch": "^1.0.11",
|
||||
"dotenv": "^16.5.0",
|
||||
"json-schema": "^0.4.0",
|
||||
"node-fetch": "^3.3.2",
|
||||
"openai": "^4.76.0",
|
||||
"uuid": "^11.1.0",
|
||||
"zod": "^3.24.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@continuedev/openai-adapters/node_modules/uuid": {
|
||||
"version": "11.1.0",
|
||||
"resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz",
|
||||
"integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==",
|
||||
"funding": [
|
||||
"https://github.com/sponsors/broofa",
|
||||
"https://github.com/sponsors/ctavan"
|
||||
],
|
||||
"bin": {
|
||||
"uuid": "dist/esm/bin/uuid"
|
||||
}
|
||||
"resolved": "../packages/openai-adapters",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@dabh/diagnostics": {
|
||||
"version": "2.0.3",
|
||||
|
|
|
|||
|
|
@ -51,9 +51,9 @@
|
|||
"@aws-sdk/credential-providers": "^3.778.0",
|
||||
"@continuedev/config-types": "^1.0.13",
|
||||
"@continuedev/config-yaml": "file:../packages/config-yaml",
|
||||
"@continuedev/fetch": "^1.0.13",
|
||||
"@continuedev/fetch": "^1.0.14",
|
||||
"@continuedev/llm-info": "^1.0.8",
|
||||
"@continuedev/openai-adapters": "^1.0.32",
|
||||
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
|
||||
"@modelcontextprotocol/sdk": "^1.12.0",
|
||||
"@mozilla/readability": "^0.5.0",
|
||||
"@octokit/rest": "^20.1.1",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { IDE } from "../..";
|
||||
import { GlobalContext } from "../../util/GlobalContext";
|
||||
import { joinPathsToUri } from "../../util/uri";
|
||||
import { IDE } from "..";
|
||||
import { GlobalContext } from "../util/GlobalContext";
|
||||
import { joinPathsToUri } from "../util/uri";
|
||||
|
||||
const FIRST_TIME_DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file
|
||||
# It is used to define and reuse prompts within Continue
|
||||
|
|
@ -1,10 +1,9 @@
|
|||
import { IDE } from "../..";
|
||||
import { walkDir } from "../../indexing/walkDir";
|
||||
import { readAllGlobalPromptFiles } from "../../util/paths";
|
||||
import { joinPathsToUri } from "../../util/uri";
|
||||
import { DEFAULT_PROMPTS_FOLDER_V1 } from "../v1";
|
||||
import { DEFAULT_PROMPTS_FOLDER_V1, DEFAULT_PROMPTS_FOLDER_V2 } from ".";
|
||||
import { IDE } from "..";
|
||||
import { walkDir } from "../indexing/walkDir";
|
||||
import { readAllGlobalPromptFiles } from "../util/paths";
|
||||
import { joinPathsToUri } from "../util/uri";
|
||||
|
||||
export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts";
|
||||
export async function getPromptFilesFromDir(
|
||||
ide: IDE,
|
||||
dir: string,
|
||||
19
core/promptFiles/index.ts
Normal file
19
core/promptFiles/index.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import { ContextProviderName } from "..";
|
||||
|
||||
export const DEFAULT_PROMPTS_FOLDER_V1 = ".prompts";
|
||||
export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts";
|
||||
|
||||
export const SUPPORTED_PROMPT_CONTEXT_PROVIDERS: ContextProviderName[] = [
|
||||
"file",
|
||||
"clipboard",
|
||||
"repo-map",
|
||||
"currentFile",
|
||||
"os",
|
||||
"problems",
|
||||
"codebase",
|
||||
"tree",
|
||||
"open",
|
||||
"debugger",
|
||||
"terminal",
|
||||
"diff",
|
||||
];
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
import * as YAML from "yaml";
|
||||
|
||||
import { getLastNPathParts } from "../../util/uri";
|
||||
import { getLastNPathParts } from "../util/uri";
|
||||
|
||||
export function parsePromptFileV1V2(path: string, content: string) {
|
||||
export function parsePromptFile(path: string, content: string) {
|
||||
let [preambleRaw, prompt] = content.split("\n---\n");
|
||||
if (prompt === undefined) {
|
||||
prompt = preambleRaw;
|
||||
|
|
@ -1,38 +0,0 @@
|
|||
import Handlebars from "handlebars";
|
||||
import { ContextItem, ContinueSDK, IContextProvider } from "../..";
|
||||
|
||||
function createContextItem(item: ContextItem, provider: IContextProvider) {
|
||||
return {
|
||||
...item,
|
||||
id: {
|
||||
itemId: item.description,
|
||||
providerTitle: provider.description.title,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function getContextProviderHelpers(
|
||||
context: ContinueSDK,
|
||||
): Array<[string, Handlebars.HelperDelegate]> | undefined {
|
||||
return context.config.contextProviders?.map((provider: IContextProvider) => [
|
||||
provider.description.title,
|
||||
async (helperContext: any) => {
|
||||
const items = await provider.getContextItems(helperContext, {
|
||||
config: context.config,
|
||||
embeddingsProvider: context.config.selectedModelByRole.embed,
|
||||
fetch: context.fetch,
|
||||
fullInput: context.input,
|
||||
ide: context.ide,
|
||||
llm: context.llm,
|
||||
reranker: context.config.selectedModelByRole.rerank,
|
||||
selectedCode: context.selectedCode,
|
||||
});
|
||||
|
||||
items.forEach((item) =>
|
||||
context.addContextItem(createContextItem(item, provider)),
|
||||
);
|
||||
|
||||
return items.map((item) => item.content).join("\n\n");
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
|
@ -1,117 +0,0 @@
|
|||
import Handlebars from "handlebars";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
function convertToLetter(num: number): string {
|
||||
let result = "";
|
||||
while (num > 0) {
|
||||
const remainder = (num - 1) % 26;
|
||||
result = String.fromCharCode(97 + remainder) + result;
|
||||
num = Math.floor((num - 1) / 26);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* We replace filepaths with alphabetic characters to handle
|
||||
* escaping issues.
|
||||
*/
|
||||
const replaceFilepaths = (
|
||||
value: string,
|
||||
ctxProviderNames: string[],
|
||||
): [string, { [key: string]: string }] => {
|
||||
const ast = Handlebars.parse(value);
|
||||
|
||||
const keysToFilepath: { [key: string]: string } = {};
|
||||
|
||||
let keyIndex = 1;
|
||||
|
||||
for (const i in ast.body) {
|
||||
const node = ast.body[i] as any;
|
||||
|
||||
if (node.type === "MustacheStatement") {
|
||||
const originalNodeVal = node.path.original;
|
||||
const isFilepath = !ctxProviderNames.includes(originalNodeVal);
|
||||
|
||||
if (isFilepath) {
|
||||
const letter = convertToLetter(keyIndex);
|
||||
|
||||
keysToFilepath[letter] = originalNodeVal;
|
||||
|
||||
value = value.replace(
|
||||
new RegExp(`{{\\s*${originalNodeVal}\\s*}}`),
|
||||
`{{${letter}}}`,
|
||||
);
|
||||
|
||||
keyIndex++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [value, keysToFilepath];
|
||||
};
|
||||
|
||||
export function registerHelpers(
|
||||
helpers: Array<[string, Handlebars.HelperDelegate]>,
|
||||
): {
|
||||
[key: string]: Promise<string>;
|
||||
} {
|
||||
const promises: { [key: string]: Promise<string> } = {};
|
||||
|
||||
for (const [name, helper] of helpers) {
|
||||
Handlebars.registerHelper(name, (...args) => {
|
||||
const id = uuidv4();
|
||||
promises[id] = helper(...args);
|
||||
return `__${id}__`;
|
||||
});
|
||||
}
|
||||
|
||||
return promises;
|
||||
}
|
||||
|
||||
export async function prepareTemplateAndData(
|
||||
template: string,
|
||||
readFile: (filepath: string) => Promise<string>,
|
||||
inputData: Record<string, string>,
|
||||
ctxProviderNames: string[],
|
||||
): Promise<[string, any]> {
|
||||
const [newTemplate, vars] = replaceFilepaths(template, ctxProviderNames);
|
||||
|
||||
const data: any = { ...inputData };
|
||||
|
||||
for (const [replacedName, originalCtxProviderName] of Object.entries(vars)) {
|
||||
data[replacedName] =
|
||||
inputData[originalCtxProviderName] ?? originalCtxProviderName;
|
||||
|
||||
// If it's not a context provider, assume it's a filepath.
|
||||
if (!ctxProviderNames.includes(originalCtxProviderName)) {
|
||||
const fileContents = await readFile(vars[replacedName]);
|
||||
|
||||
if (fileContents) {
|
||||
data[replacedName] = fileContents;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [newTemplate, data];
|
||||
}
|
||||
|
||||
export function compileAndRenderTemplate(
|
||||
template: string,
|
||||
data: Record<string, string>,
|
||||
): string {
|
||||
const templateFn = Handlebars.compile(template);
|
||||
return templateFn(data);
|
||||
}
|
||||
|
||||
export async function resolveHelperPromises(
|
||||
renderedString: string,
|
||||
promises: { [key: string]: Promise<string> },
|
||||
): Promise<string> {
|
||||
await Promise.all(Object.values(promises));
|
||||
|
||||
for (const id in promises) {
|
||||
renderedString = renderedString.replace(`__${id}__`, await promises[id]);
|
||||
}
|
||||
|
||||
return renderedString;
|
||||
}
|
||||
|
|
@ -1 +0,0 @@
|
|||
export const DEFAULT_PROMPTS_FOLDER_V1 = ".prompts";
|
||||
|
|
@ -1,89 +0,0 @@
|
|||
import { ContinueSDK, SlashCommand } from "../..";
|
||||
import { getDiffsFromCache } from "../../autocomplete/snippets/gitDiffCache";
|
||||
import { renderChatMessage } from "../../util/messageContent";
|
||||
import { getLastNPathParts } from "../../util/uri";
|
||||
import { parsePromptFileV1V2 } from "../v2/parsePromptFileV1V2";
|
||||
import { renderPromptFileV2 } from "../v2/renderPromptFile";
|
||||
|
||||
import { getContextProviderHelpers } from "./getContextProviderHelpers";
|
||||
import { renderTemplatedString } from "./renderTemplatedString";
|
||||
import { replaceSlashCommandWithPromptInChatHistory } from "./updateChatHistory";
|
||||
|
||||
export function extractName(preamble: { name?: string }, path: string): string {
|
||||
return preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0];
|
||||
}
|
||||
|
||||
async function renderPromptV1(
|
||||
prompt: string,
|
||||
context: ContinueSDK,
|
||||
userInput: string,
|
||||
) {
|
||||
const helpers = getContextProviderHelpers(context);
|
||||
|
||||
const inputData: Record<string, string> = {
|
||||
input: userInput,
|
||||
};
|
||||
|
||||
// A few context providers that don't need to be in config.json to work in .prompt files
|
||||
if (helpers?.find((helper) => helper[0] === "diff")) {
|
||||
const diffs = await getDiffsFromCache(context.ide);
|
||||
inputData.diff = diffs.join("\n");
|
||||
}
|
||||
if (helpers?.find((helper) => helper[0] === "currentFile")) {
|
||||
const currentFile = await context.ide.getCurrentFile();
|
||||
if (currentFile) {
|
||||
inputData.currentFile = currentFile.path;
|
||||
}
|
||||
}
|
||||
|
||||
return renderTemplatedString(
|
||||
prompt,
|
||||
context.ide.readFile.bind(context.ide),
|
||||
inputData,
|
||||
helpers,
|
||||
);
|
||||
}
|
||||
|
||||
export function slashCommandFromPromptFileV1(
|
||||
path: string,
|
||||
content: string,
|
||||
): SlashCommand | null {
|
||||
const { name, description, systemMessage, prompt } = parsePromptFileV1V2(
|
||||
path,
|
||||
content,
|
||||
);
|
||||
|
||||
return {
|
||||
name,
|
||||
description,
|
||||
prompt,
|
||||
promptFile: path,
|
||||
run: async function* (context) {
|
||||
const [_, renderedPrompt] = await renderPromptFileV2(prompt, {
|
||||
config: context.config,
|
||||
fullInput: context.input,
|
||||
embeddingsProvider: context.config.modelsByRole.embed[0],
|
||||
reranker: context.config.modelsByRole.rerank[0],
|
||||
llm: context.llm,
|
||||
ide: context.ide,
|
||||
selectedCode: context.selectedCode,
|
||||
fetch: context.fetch,
|
||||
});
|
||||
|
||||
const messages = replaceSlashCommandWithPromptInChatHistory(
|
||||
context.history,
|
||||
name,
|
||||
renderedPrompt,
|
||||
systemMessage,
|
||||
);
|
||||
|
||||
for await (const chunk of context.llm.streamChat(
|
||||
messages,
|
||||
context.abortController.signal,
|
||||
context.completionOptions,
|
||||
)) {
|
||||
yield renderChatMessage(chunk);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
@ -1,64 +0,0 @@
|
|||
import { ChatMessage } from "../..";
|
||||
|
||||
export function replaceSlashCommandWithPromptInChatHistory(
|
||||
history: ChatMessage[],
|
||||
commandName: string,
|
||||
renderedPrompt: string,
|
||||
systemMessageOverride?: string,
|
||||
): ChatMessage[] {
|
||||
const messages = [...history];
|
||||
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
const { role, content } = messages[i];
|
||||
if (role !== "user") {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Array.isArray(content)) {
|
||||
if (
|
||||
content.some(
|
||||
(part) =>
|
||||
part.type === "text" && part.text?.startsWith(`/${commandName}`),
|
||||
)
|
||||
) {
|
||||
messages[i] = updateArrayContent(
|
||||
messages[i],
|
||||
commandName,
|
||||
renderedPrompt,
|
||||
);
|
||||
break;
|
||||
}
|
||||
} else if (
|
||||
typeof content === "string" &&
|
||||
content.startsWith(`/${commandName}`)
|
||||
) {
|
||||
messages[i] = { ...messages[i], content: renderedPrompt };
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (systemMessageOverride) {
|
||||
if (messages[0]?.role === "system") {
|
||||
messages[0].content = systemMessageOverride;
|
||||
} else {
|
||||
messages.unshift({ role: "system", content: systemMessageOverride });
|
||||
}
|
||||
}
|
||||
|
||||
return messages;
|
||||
}
|
||||
|
||||
function updateArrayContent(
|
||||
message: any,
|
||||
commandName: string,
|
||||
renderedPrompt: string,
|
||||
) {
|
||||
return {
|
||||
...message,
|
||||
content: message.content.map((part: any) =>
|
||||
part.text?.startsWith(`/${commandName}`)
|
||||
? { ...part, text: renderedPrompt }
|
||||
: part,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
|
@ -1,34 +0,0 @@
|
|||
import * as YAML from "yaml";
|
||||
|
||||
import { getLastNPathParts } from "../../util/uri";
|
||||
|
||||
export function extractName(preamble: { name?: string }, path: string): string {
|
||||
return preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0];
|
||||
}
|
||||
|
||||
export function getPreambleAndBody(content: string): [string, string] {
|
||||
let [preamble, body] = content.split("\n---\n");
|
||||
if (body === undefined) {
|
||||
// This means there is no preamble
|
||||
body = preamble;
|
||||
preamble = "";
|
||||
}
|
||||
return [preamble, body];
|
||||
}
|
||||
|
||||
export function parsePreamble(
|
||||
path: string,
|
||||
content: string,
|
||||
): { [key: string]: any; name: string; description: string } {
|
||||
const [preambleRaw, _] = getPreambleAndBody(content);
|
||||
|
||||
const preamble = YAML.parse(preambleRaw) ?? {};
|
||||
const name = extractName(preamble, path);
|
||||
const description = preamble.description ?? name;
|
||||
|
||||
return {
|
||||
...preamble,
|
||||
name,
|
||||
description,
|
||||
};
|
||||
}
|
||||
|
|
@ -1,84 +0,0 @@
|
|||
import { ContextItem, ContextProviderExtras } from "../..";
|
||||
import { contextProviderClassFromName } from "../../context/providers";
|
||||
import { getUrlContextItems } from "../../context/providers/URLContextProvider";
|
||||
import { resolveRelativePathInDir } from "../../util/ideUtils";
|
||||
import { getUriPathBasename } from "../../util/uri";
|
||||
|
||||
import { getPreambleAndBody } from "./parse";
|
||||
|
||||
async function resolveAttachment(
|
||||
name: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
// Context providers
|
||||
const contextProvider = extras.config.contextProviders?.find(
|
||||
(provider) => provider.description.title === name,
|
||||
);
|
||||
if (contextProvider) {
|
||||
const items = await contextProvider.getContextItems("", extras);
|
||||
return items;
|
||||
} else {
|
||||
// Just instantiate it here
|
||||
const providerClass = contextProviderClassFromName(name) as any;
|
||||
if (providerClass) {
|
||||
const providerInstance = new providerClass({});
|
||||
return providerInstance.getContextItems("", extras);
|
||||
}
|
||||
}
|
||||
|
||||
// Files
|
||||
const resolvedFileUri = await resolveRelativePathInDir(name, extras.ide);
|
||||
if (resolvedFileUri) {
|
||||
let subItems: ContextItem[] = [];
|
||||
if (name.endsWith(".prompt")) {
|
||||
// Recurse
|
||||
const [items, _] = await renderPromptFileV2(
|
||||
await extras.ide.readFile(resolvedFileUri),
|
||||
extras,
|
||||
);
|
||||
subItems.push(...items);
|
||||
}
|
||||
|
||||
const content = `\`\`\`${name}\n${await extras.ide.readFile(resolvedFileUri)}\n\`\`\``;
|
||||
return [
|
||||
...subItems,
|
||||
{
|
||||
name: getUriPathBasename(resolvedFileUri),
|
||||
content,
|
||||
description: resolvedFileUri,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
// URLs
|
||||
if (name.startsWith("http")) {
|
||||
const items = getUrlContextItems(name, extras.fetch);
|
||||
return items;
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
export async function renderPromptFileV2(
|
||||
rawContent: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<[ContextItem[], string]> {
|
||||
const [_, body] = getPreambleAndBody(rawContent);
|
||||
|
||||
const contextItemsPromises: Promise<ContextItem[]>[] = [];
|
||||
const renderedBody = body.replace(/@([^\s]+)/g, (match, name) => {
|
||||
contextItemsPromises.push(resolveAttachment(name, extras));
|
||||
return match;
|
||||
});
|
||||
|
||||
const contextItems = (await Promise.all(contextItemsPromises)).flat();
|
||||
const renderedPrompt = [
|
||||
...contextItems.map((item) => item.content),
|
||||
renderedBody,
|
||||
extras.fullInput,
|
||||
]
|
||||
.join("\n\n")
|
||||
.trim();
|
||||
|
||||
return [contextItems, renderedPrompt];
|
||||
}
|
||||
|
|
@ -1,175 +0,0 @@
|
|||
import { ContextProviderExtras, ILLM, RangeInFile } from "../..";
|
||||
import { testConfigHandler, testIde } from "../../test/fixtures";
|
||||
import {
|
||||
addToTestDir,
|
||||
setUpTestDir,
|
||||
tearDownTestDir,
|
||||
} from "../../test/testDir";
|
||||
import { renderPromptFileV2 } from "./renderPromptFile";
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock(
|
||||
import("../../context/providers/URLContextProvider"),
|
||||
async (importOriginal) => {
|
||||
const actual = await importOriginal();
|
||||
return {
|
||||
...actual,
|
||||
getUrlContextItems: vi.fn().mockResolvedValue([
|
||||
{
|
||||
description: "https://example.com",
|
||||
content: "Example Content",
|
||||
name: "Example site",
|
||||
uri: {
|
||||
type: "url",
|
||||
value: "https://example.com",
|
||||
},
|
||||
},
|
||||
]),
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
describe("renderPromptFileV2", () => {
|
||||
let extras: ContextProviderExtras;
|
||||
const mockGetContextItems = vi.fn().mockResolvedValue([
|
||||
{
|
||||
name: "custom",
|
||||
content: "Custom provider content",
|
||||
description: "Custom provider",
|
||||
},
|
||||
]);
|
||||
beforeEach(async () => {
|
||||
const { config } = await testConfigHandler.loadConfig();
|
||||
|
||||
// Setup mock extras
|
||||
extras = {
|
||||
config: {
|
||||
...config!,
|
||||
contextProviders: [
|
||||
{
|
||||
description: {
|
||||
type: "normal",
|
||||
title: "CustomProvider",
|
||||
displayTitle: "Custom Provider",
|
||||
description: "A custom context provider",
|
||||
},
|
||||
loadSubmenuItems: vi.fn().mockResolvedValue([]),
|
||||
getContextItems: mockGetContextItems,
|
||||
},
|
||||
],
|
||||
},
|
||||
fullInput: "User input",
|
||||
embeddingsProvider: null,
|
||||
reranker: null,
|
||||
llm: {} as ILLM,
|
||||
ide: testIde,
|
||||
selectedCode: [] as RangeInFile[],
|
||||
fetch: vi.fn(),
|
||||
};
|
||||
|
||||
// Clear all mocks
|
||||
vi.clearAllMocks();
|
||||
setUpTestDir();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
tearDownTestDir();
|
||||
});
|
||||
|
||||
it("should render a prompt file with no attachments", async () => {
|
||||
const rawContent = "Simple prompt with no attachments";
|
||||
const [contextItems, renderedPrompt] = await renderPromptFileV2(
|
||||
rawContent,
|
||||
extras,
|
||||
);
|
||||
|
||||
expect(contextItems).toHaveLength(0);
|
||||
expect(renderedPrompt).toBe(
|
||||
"Simple prompt with no attachments\n\nUser input",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle URL attachments", async () => {
|
||||
const rawContent = "Content with URL @https://example.com";
|
||||
|
||||
const [contextItems, renderedPrompt] = await renderPromptFileV2(
|
||||
rawContent,
|
||||
extras,
|
||||
);
|
||||
|
||||
expect(contextItems).toHaveLength(1);
|
||||
expect(renderedPrompt).toContain("Example Content");
|
||||
});
|
||||
|
||||
it("should resolve file attachments", async () => {
|
||||
const rawContent = "Content with file attachment @test.txt";
|
||||
|
||||
addToTestDir([["test.txt", "File content"]]);
|
||||
|
||||
const [contextItems, renderedPrompt] = await renderPromptFileV2(
|
||||
rawContent,
|
||||
extras,
|
||||
);
|
||||
|
||||
expect(contextItems).toHaveLength(1);
|
||||
expect(renderedPrompt).toContain("```test.txt\nFile content\n```");
|
||||
expect(renderedPrompt).toContain("Content with file attachment @test.txt");
|
||||
});
|
||||
|
||||
it("should handle nested prompt files", async () => {
|
||||
const rawContent = "Main prompt with nested @nested.prompt";
|
||||
addToTestDir([
|
||||
["nested.prompt", "Nested prompt content with @CustomProvider"],
|
||||
]);
|
||||
|
||||
const [contextItems, renderedPrompt] = await renderPromptFileV2(
|
||||
rawContent,
|
||||
extras,
|
||||
);
|
||||
|
||||
expect(renderedPrompt).toContain("Custom provider content");
|
||||
});
|
||||
|
||||
it("should handle custom context providers", async () => {
|
||||
const rawContent = "Content with custom provider @CustomProvider";
|
||||
|
||||
const [contextItems, renderedPrompt] = await renderPromptFileV2(
|
||||
rawContent,
|
||||
extras,
|
||||
);
|
||||
|
||||
expect(contextItems).toHaveLength(1);
|
||||
expect(renderedPrompt).toContain("Custom provider content");
|
||||
expect(mockGetContextItems).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle multiple attachments", async () => {
|
||||
const rawContent = "Content with @file1.txt and @file2.txt";
|
||||
addToTestDir([
|
||||
["file1.txt", "Content 1"],
|
||||
["file2.txt", "Content 2"],
|
||||
]);
|
||||
|
||||
const [contextItems, renderedPrompt] = await renderPromptFileV2(
|
||||
rawContent,
|
||||
extras,
|
||||
);
|
||||
|
||||
expect(contextItems).toHaveLength(2);
|
||||
expect(renderedPrompt).toContain("```file1.txt\nContent 1\n```");
|
||||
expect(renderedPrompt).toContain("```file2.txt\nContent 2\n```");
|
||||
});
|
||||
|
||||
it("should handle failed attachment resolutions gracefully", async () => {
|
||||
const rawContent = "Content with @nonexistent";
|
||||
|
||||
const [contextItems, renderedPrompt] = await renderPromptFileV2(
|
||||
rawContent,
|
||||
extras,
|
||||
);
|
||||
|
||||
expect(contextItems).toHaveLength(0);
|
||||
expect(renderedPrompt).toBe("Content with @nonexistent\n\nUser input");
|
||||
});
|
||||
});
|
||||
|
|
@ -29,7 +29,7 @@ import {
|
|||
Session,
|
||||
SessionMetadata,
|
||||
SiteIndexingConfig,
|
||||
SlashCommandDescription,
|
||||
SlashCommandDescWithSource,
|
||||
StreamDiffLinesPayload,
|
||||
ToolCall,
|
||||
} from "../";
|
||||
|
|
@ -118,6 +118,17 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
},
|
||||
void,
|
||||
];
|
||||
"mcp/getPrompt": [
|
||||
{
|
||||
serverName: string;
|
||||
promptName: string;
|
||||
args?: Record<string, string>;
|
||||
},
|
||||
{
|
||||
prompt: string;
|
||||
description: string | undefined;
|
||||
},
|
||||
];
|
||||
"context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap];
|
||||
"context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]];
|
||||
"autocomplete/complete": [AutocompleteInput, string[]];
|
||||
|
|
@ -141,7 +152,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
completionOptions: LLMFullCompletionOptions;
|
||||
title: string;
|
||||
legacySlashCommandData?: {
|
||||
command: SlashCommandDescription;
|
||||
command: SlashCommandDescWithSource;
|
||||
input: string;
|
||||
contextItems: ContextItemWithId[];
|
||||
historyIndex: number;
|
||||
|
|
|
|||
|
|
@ -70,6 +70,7 @@ export type ToIdeFromWebviewOrCoreProtocol = {
|
|||
];
|
||||
getAvailableThreads: [undefined, Thread[]];
|
||||
isTelemetryEnabled: [undefined, boolean];
|
||||
isWorkspaceRemote: [undefined, boolean];
|
||||
getUniqueId: [undefined, string];
|
||||
getTags: [string, IndexTag[]];
|
||||
readSecrets: [{ keys: string[] }, Record<string, string>];
|
||||
|
|
|
|||
|
|
@ -106,6 +106,10 @@ export class MessageIde implements IDE {
|
|||
return this.request("isTelemetryEnabled", undefined);
|
||||
}
|
||||
|
||||
isWorkspaceRemote(): Promise<boolean> {
|
||||
return this.request("isWorkspaceRemote", undefined);
|
||||
}
|
||||
|
||||
getUniqueId(): Promise<string> {
|
||||
return this.request("getUniqueId", undefined);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
"config/updateSharedConfig",
|
||||
"config/updateSelectedModel",
|
||||
"mcp/reloadServer",
|
||||
"mcp/getPrompt",
|
||||
"context/getContextItems",
|
||||
"context/getSymbolsForFiles",
|
||||
"context/loadSubmenuItems",
|
||||
|
|
|
|||
10
core/rules.md
Normal file
10
core/rules.md
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
# `core` rules
|
||||
|
||||
Whenever a new protocol message is added to the `protocol/` directory, check the following:
|
||||
|
||||
- It's type is defined correctly
|
||||
- If it is a message from webview to core or vice versa:
|
||||
- It has been added to `core/protocol/passThrough.ts`
|
||||
- It has been added to `extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt`
|
||||
- It is implemented in either `core/core.ts` (for messages to the core), in a `useWebviewListener` (for messages to the gui), or in `VsCodeMessenger.ts` for VS Code or `IdeProtocolClient.kt` for JetBriains (for messages to the IDE).
|
||||
- It does not duplicate functionality from another message type that already exists.
|
||||
|
|
@ -13,10 +13,10 @@ export const createRuleBlock: Tool = {
|
|||
function: {
|
||||
name: BuiltInToolNames.CreateRuleBlock,
|
||||
description:
|
||||
"Creates a persistent rule for all future conversations. For establishing code standards or preferences that should be applied consistently. To modify existing rules, use the edit tool instead.",
|
||||
'Creates a "rule" that can be referenced in future conversations. This should be used whenever you want to establish code standards / preferences that should be applied consistently, or when you want to avoid making a mistake again. To modify existing rules, use the edit tool instead.',
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["name", "rule", "alwaysApply", "description"],
|
||||
required: ["name", "rule", "description"],
|
||||
properties: {
|
||||
name: {
|
||||
type: "string",
|
||||
|
|
@ -37,6 +37,11 @@ export const createRuleBlock: Tool = {
|
|||
description:
|
||||
"Optional file patterns to which this rule applies (e.g. ['**/*.{ts,tsx}'] or ['src/**/*.ts', 'tests/**/*.ts'])",
|
||||
},
|
||||
regex: {
|
||||
type: "string",
|
||||
description:
|
||||
"Optional regex patterns to match against file content. Rule applies only to files whose content matches the pattern (e.g. 'useEffect' for React hooks or '\\bclass\\b' for class definitions)",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
|
|
|||
|
|
@ -7,16 +7,24 @@ export type CreateRuleBlockArgs = Pick<
|
|||
Required<RuleWithSource>,
|
||||
"rule" | "description" | "alwaysApply" | "name"
|
||||
> &
|
||||
Pick<RuleWithSource, "globs">;
|
||||
Pick<RuleWithSource, "globs" | "regex">;
|
||||
|
||||
export const createRuleBlockImpl: ToolImpl = async (
|
||||
args: CreateRuleBlockArgs,
|
||||
extras,
|
||||
) => {
|
||||
const fileContent = createRuleMarkdown(args.name, args.rule, {
|
||||
// Create options object with the fields that createRuleMarkdown expects
|
||||
const options: any = {
|
||||
description: args.description,
|
||||
globs: args.globs,
|
||||
});
|
||||
};
|
||||
|
||||
// Add regex if provided
|
||||
if (args.regex) {
|
||||
options.regex = args.regex;
|
||||
}
|
||||
|
||||
const fileContent = createRuleMarkdown(args.name, args.rule, options);
|
||||
|
||||
const [localContinueDir] = await extras.ide.getWorkspaceDirs();
|
||||
const ruleFilePath = createRuleFilePath(localContinueDir, args.name);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { ConfigDependentToolParams, Tool } from "..";
|
||||
import { ConfigDependentToolParams, IDE, Tool } from "..";
|
||||
import { createNewFileTool } from "./definitions/createNewFile";
|
||||
import { createRuleBlock } from "./definitions/createRuleBlock";
|
||||
import { editFileTool } from "./definitions/editFile";
|
||||
|
|
@ -13,12 +13,14 @@ import { runTerminalCommandTool } from "./definitions/runTerminalCommand";
|
|||
import { searchWebTool } from "./definitions/searchWeb";
|
||||
import { viewDiffTool } from "./definitions/viewDiff";
|
||||
|
||||
// missing support for remote os calls: https://github.com/microsoft/vscode/issues/252269
|
||||
export const localOnlyToolDefinitions = [grepSearchTool];
|
||||
|
||||
export const baseToolDefinitions = [
|
||||
readFileTool,
|
||||
editFileTool,
|
||||
createNewFileTool,
|
||||
runTerminalCommandTool,
|
||||
grepSearchTool,
|
||||
globSearchTool,
|
||||
searchWebTool,
|
||||
viewDiffTool,
|
||||
|
|
@ -34,3 +36,8 @@ export const baseToolDefinitions = [
|
|||
export const getConfigDependentToolDefinitions = (
|
||||
params: ConfigDependentToolParams,
|
||||
): Tool[] => [requestRuleTool(params)];
|
||||
|
||||
export const getToolsForIde = async (ide: IDE) =>
|
||||
(await ide.isWorkspaceRemote())
|
||||
? baseToolDefinitions
|
||||
: [...baseToolDefinitions, ...localOnlyToolDefinitions];
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ export function safeParseToolCallArgs(
|
|||
toolCall: ToolCallDelta,
|
||||
): Record<string, any> {
|
||||
try {
|
||||
return JSON.parse(toolCall.function?.arguments ?? "{}");
|
||||
return JSON.parse(toolCall.function?.arguments?.trim() || "{}");
|
||||
} catch (e) {
|
||||
console.error(
|
||||
`Failed to parse tool call arguments:\nTool call: ${toolCall.function?.name + " " + toolCall.id}\nArgs:${toolCall.function?.arguments}\n`,
|
||||
|
|
|
|||
|
|
@ -48,6 +48,10 @@ class FileSystemIde implements IDE {
|
|||
return;
|
||||
}
|
||||
|
||||
isWorkspaceRemote(): Promise<boolean> {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
|
||||
async getIdeSettings(): Promise<IdeSettings> {
|
||||
return {
|
||||
remoteConfigServerUrl: undefined,
|
||||
|
|
|
|||
111
core/util/handlebars/handlebarUtils.ts
Normal file
111
core/util/handlebars/handlebarUtils.ts
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
export type HandlebarsType = typeof import("handlebars");
|
||||
|
||||
function convertToLetter(num: number): string {
|
||||
let result = "";
|
||||
while (num > 0) {
|
||||
const remainder = (num - 1) % 26;
|
||||
result = String.fromCharCode(97 + remainder) + result;
|
||||
num = Math.floor((num - 1) / 26);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function registerHelpers(
|
||||
handlebars: HandlebarsType,
|
||||
helpers: Array<[string, Handlebars.HelperDelegate]>,
|
||||
): {
|
||||
[key: string]: Promise<string>;
|
||||
} {
|
||||
const promises: { [key: string]: Promise<string> } = {};
|
||||
|
||||
for (const [name, helper] of helpers) {
|
||||
handlebars.registerHelper(name, (...args) => {
|
||||
const id = uuidv4();
|
||||
promises[id] = helper(...args);
|
||||
return `__${id}__`;
|
||||
});
|
||||
}
|
||||
|
||||
return promises;
|
||||
}
|
||||
|
||||
export async function prepareTemplatedFilepaths(
|
||||
handlebars: HandlebarsType,
|
||||
template: string,
|
||||
inputData: Record<string, string>,
|
||||
ctxProviderNames: string[],
|
||||
readFile: (filepath: string) => Promise<string>,
|
||||
getUriFromPath: (path: string) => Promise<string | undefined>,
|
||||
) {
|
||||
// First, replace filepaths with letters to avoid escaping issues
|
||||
const ast = handlebars.parse(template);
|
||||
|
||||
const filepathLetters: Map<string, string> = new Map();
|
||||
const requiredContextProviders: Set<string> = new Set();
|
||||
let withLetterKeys = template;
|
||||
|
||||
let letterIndex = 1;
|
||||
|
||||
for (const i in ast.body) {
|
||||
const node = ast.body[i] as any;
|
||||
|
||||
if (node.type === "MustacheStatement") {
|
||||
const originalNodeVal = node.path.original;
|
||||
if (originalNodeVal.toLowerCase() === "input") {
|
||||
continue;
|
||||
}
|
||||
const isFilepath = !ctxProviderNames.includes(originalNodeVal);
|
||||
|
||||
if (isFilepath) {
|
||||
const letter = convertToLetter(letterIndex);
|
||||
|
||||
filepathLetters.set(letter, originalNodeVal);
|
||||
|
||||
withLetterKeys = withLetterKeys.replace(
|
||||
new RegExp(`{{\\s*${originalNodeVal}\\s*}}`),
|
||||
`{{${letter}}}`,
|
||||
);
|
||||
|
||||
letterIndex++;
|
||||
} else {
|
||||
requiredContextProviders.add(originalNodeVal);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Then, resolve the filepaths to their actual content and add to template data
|
||||
// Fallback to simple error string if file read fails
|
||||
const templateData = { ...inputData };
|
||||
|
||||
for (const [letter, filepath] of filepathLetters.entries()) {
|
||||
try {
|
||||
const uri = await getUriFromPath(filepath);
|
||||
if (uri) {
|
||||
const fileContents = await readFile(uri);
|
||||
templateData[letter] = fileContents;
|
||||
} else {
|
||||
throw new Error(`File not found: ${filepath}`);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(`Error reading file in prompt file ${filepath}:`, e);
|
||||
templateData[letter] = `[Error reading file "${filepath}"]`;
|
||||
}
|
||||
}
|
||||
|
||||
return { withLetterKeys, templateData, requiredContextProviders };
|
||||
}
|
||||
|
||||
export async function resolveHelperPromises(
|
||||
renderedString: string,
|
||||
promises: { [key: string]: Promise<string> },
|
||||
): Promise<string> {
|
||||
await Promise.all(Object.values(promises));
|
||||
|
||||
for (const id in promises) {
|
||||
renderedString = renderedString.replace(`__${id}__`, await promises[id]);
|
||||
}
|
||||
|
||||
return renderedString;
|
||||
}
|
||||
|
|
@ -1,30 +1,35 @@
|
|||
import {
|
||||
compileAndRenderTemplate,
|
||||
prepareTemplateAndData,
|
||||
prepareTemplatedFilepaths,
|
||||
registerHelpers,
|
||||
resolveHelperPromises,
|
||||
type HandlebarsType,
|
||||
} from "./handlebarUtils";
|
||||
|
||||
export async function renderTemplatedString(
|
||||
handlebars: HandlebarsType,
|
||||
template: string,
|
||||
readFile: (filepath: string) => Promise<string>,
|
||||
inputData: Record<string, string>,
|
||||
availableHelpers?: Array<[string, Handlebars.HelperDelegate]>,
|
||||
availableHelpers: Array<[string, Handlebars.HelperDelegate]>,
|
||||
readFile: (filepath: string) => Promise<string>,
|
||||
getUriFromPath: (path: string) => Promise<string | undefined>,
|
||||
): Promise<string> {
|
||||
const helperPromises = availableHelpers
|
||||
? registerHelpers(availableHelpers)
|
||||
? registerHelpers(handlebars, availableHelpers)
|
||||
: {};
|
||||
|
||||
const ctxProviderNames = availableHelpers?.map((h) => h[0]) ?? [];
|
||||
|
||||
const [newTemplate, data] = await prepareTemplateAndData(
|
||||
const { withLetterKeys, templateData } = await prepareTemplatedFilepaths(
|
||||
handlebars,
|
||||
template,
|
||||
readFile,
|
||||
inputData,
|
||||
ctxProviderNames,
|
||||
readFile,
|
||||
getUriFromPath,
|
||||
);
|
||||
|
||||
let renderedString = compileAndRenderTemplate(newTemplate, data);
|
||||
const templateFn = handlebars.compile(withLetterKeys);
|
||||
const renderedString = templateFn(templateData);
|
||||
|
||||
return resolveHelperPromises(renderedString, helperPromises);
|
||||
}
|
||||
|
|
@ -188,6 +188,7 @@ export function getUriDescription(uri: string, dirUriCandidates: string[]) {
|
|||
dirUriCandidates,
|
||||
);
|
||||
const baseName = getUriPathBasename(uri);
|
||||
const extension = getFileExtensionFromBasename(baseName);
|
||||
const last2Parts = getLastNUriRelativePathParts(dirUriCandidates, uri, 2);
|
||||
return {
|
||||
uri,
|
||||
|
|
@ -195,5 +196,6 @@ export function getUriDescription(uri: string, dirUriCandidates: string[]) {
|
|||
foundInDir,
|
||||
last2Parts,
|
||||
baseName,
|
||||
extension,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,93 +5,54 @@ title: Prompts
|
|||
Prompts are reusable instructions that can be referenced at any time during chat. They are especially useful as context for repetitive and/or complex tasks.
|
||||
|
||||
:::info
|
||||
Visit the Hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=prompts)
|
||||
Prompts were previously defined in a `.prompt` file format, but for consistency we now recommend using the same Markdown format as [rules](./rules.mdx) and adding `alwaysApply: false` to the frontmatter so that they are manually triggered.
|
||||
:::
|
||||
|
||||
## Examples
|
||||
|
||||
Below are some examples to get you started.
|
||||
|
||||
### Security review
|
||||
|
||||
```text title="Security best practices review"
|
||||
@open - Review these files for the following security best practices:
|
||||
- Does the architecture follow security-by-design principles?
|
||||
- Are there potential security vulnerabilities in the system design?
|
||||
- Is sensitive data handled appropriately throughout the lifecycle?
|
||||
```
|
||||
|
||||
### Reference best practice guides
|
||||
|
||||
```text title="Redux best practices review"
|
||||
@https://redux.js.org/style-guide/
|
||||
@currentFile
|
||||
|
||||
Review this code for adherence to Redux best practices.
|
||||
```
|
||||
|
||||
### Pull in commonly used files for tasks
|
||||
|
||||
```text title="Generate a new TypeORM entity"
|
||||
@src/db/dataSource.ts @src/db/entity/SampleEntity.ts
|
||||
|
||||
Use these files to generate a new TypeORM entity based on the following requirements:
|
||||
```
|
||||
|
||||
## Including Context Providers in your prompts
|
||||
|
||||
Many [context providers](../context-providers.mdx) can be referenced by typing "@" followed by the name of the context provider. The currently supported list is:
|
||||
|
||||
- `@terminal` - The contents of the terminal
|
||||
- `@currentFile` - The currently active file
|
||||
- `@open` - All open files
|
||||
- `@os` - Information about the operating system
|
||||
- `@problems` - Problems reported by the language server in the active file
|
||||
- `@repo-map` - A map of files in the repository
|
||||
- `@tree` - A tree view of the repository structure
|
||||
|
||||
Or you can directly type URLs and file paths:
|
||||
|
||||
- `@https://github.com/continuedev/continue` - The contents of a URL
|
||||
- `@src/index.ts` - The contents of a file (VS Code only)
|
||||
|
||||
All references will be attached as context items, rather than injected directly inline.
|
||||
|
||||
## Local `.prompt` files
|
||||
|
||||
In addition to Prompt blocks on the Hub, you can also define prompts in local `.prompt` files, located in the `.continue/prompts` folder at the top level of your workspace. This is useful for quick iteration on prompts to test them out before pushing up to the Hub.
|
||||
|
||||
### Quick Start
|
||||
|
||||
Below is a quick example of setting up a prompt file:
|
||||
|
||||
1. Create a folder called `.continue/prompts` at the top level of your workspace
|
||||
2. Add a file called `test.prompt` to this folder.
|
||||
3. Write the following contents to `test.prompt` and save.
|
||||
1. Create a folder called `.continue/rules` at the top level of your workspace
|
||||
2. Add a file called `review-prompt.md` to this folder.
|
||||
3. Write the following contents to `review-prompt.md` and save.
|
||||
|
||||
```.prompt
|
||||
name: Current file prompt
|
||||
description: A test prompt using the current file context provider
|
||||
```md title="review-prompt.md"
|
||||
---
|
||||
@currentFile
|
||||
name: Redux best practices review
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
Review the currently open file for adherence to Redux best practices, as explained in their style guide at https://redux.js.org/style-guide/.
|
||||
```
|
||||
|
||||
Now to use this prompt, you can open Chat, type <kbd>/</kbd>, select the prompt, and add type out some additional text such as "Review the code for any issues".
|
||||
Now to use this prompt, you can open Chat, type <kbd>/</kbd>, select the prompt, and type out any additional instructions you'd like to add.
|
||||
|
||||
### Format
|
||||
## Further Examples
|
||||
|
||||
The format is inspired by [HumanLoops's .prompt file](https://docs.humanloop.com/docs/prompt-file-format), with additional templating to reference files, URLs, and context providers.
|
||||
Below are more examples to get you started. You can also visit the Hub to [explore prompts](https://hub.continue.dev/explore/prompts) or [create your own](https://hub.continue.dev/new?type=block&blockType=prompts).
|
||||
|
||||
:::info
|
||||
The current state of this format is experimental and subject to change
|
||||
:::
|
||||
### Security review
|
||||
|
||||
### Preamble
|
||||
```md title="security-review.md"
|
||||
---
|
||||
name: Security best practices review
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
The "preamble" is everything above the `---` separator, and lets you specify model parameters. It uses YAML syntax and currently supports the following parameters:
|
||||
Review the changes in the current git diff for these security best practices:
|
||||
|
||||
- `name` - The display title
|
||||
- `description` - The description you will see in the dropdown
|
||||
- `version` - Can be either "1" (for legacy prompt files) or "2" (this is the default and does not need to be set)
|
||||
- Does the architecture follow security-by-design principles?
|
||||
- Are there potential security vulnerabilities in the system design?
|
||||
- Is sensitive data handled appropriately throughout the lifecycle?
|
||||
```
|
||||
|
||||
If you don't need any of these parameters, you can leave out the preamble and do not need to include the `---` separator.
|
||||
### Pull in commonly used files for tasks
|
||||
|
||||
```md title="typeorm-entity-generator.md"
|
||||
---
|
||||
name: Generate a new TypeORM entity
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
Referencing `src/db/dataSource.ts` and `src/db/entity/SampleEntity.ts`, generate a new TypeORM entity based on the following requirements:
|
||||
```
|
||||
|
|
|
|||
|
|
@ -55,18 +55,26 @@ For example, you can say "Create a rule for this", and a rule will be created fo
|
|||
|
||||
Rules can also be added to an Assistant on the Continue Hub.
|
||||
|
||||
Explore available rules [here](https://hub.continue.dev/explore/rules), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub. These blocks are defined using the [`config.yaml` syntax](../../reference.md#rules) and can also be created locally.
|
||||
Explore available rules [here](https://hub.continue.dev), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub.
|
||||
|
||||
### Syntax
|
||||
|
||||
:::info
|
||||
|
||||
Rules were originally defined in YAML format (demonstrated below), but we introduced Markdown for easier editing. While both are still supported, we recommend Markdown.
|
||||
|
||||
:::
|
||||
|
||||
Rules blocks can be simple text, written in YAML configuration files, or as Markdown (`.md`) files. They can have the following properties:
|
||||
|
||||
- `name` (**required** for YAML): A display name/title for the rule
|
||||
- `globs` (optional): When files are provided as context that match this glob pattern, the rule will be included. This can be either a single pattern (e.g., `"**/*.{ts,tsx}"`) or an array of patterns (e.g., `["src/**/*.ts", "tests/**/*.ts"]`).
|
||||
- `regex` (optional): When files are provided as context and their content matches this regex pattern, the rule will be included. This can be either a single pattern (e.g., `"^import .* from '.*';$"`) or an array of patterns (e.g., `["^import .* from '.*';$", "^export .* from '.*';$"]`).
|
||||
- `description` (optional): A description for the rule. Agents may read this description when `alwaysApply` is false to determine whether the rule should be pulled into context.
|
||||
- `alwaysApply`: true - Always include the rule, regardless of file context
|
||||
- `alwaysApply`: false - Included if globs exist AND match file context, or the agent decides to pull the rule into context based on it's description
|
||||
- `alwaysApply`: undefined - Default behavior: include if no globs exist OR globs exist and match
|
||||
- `alwaysApply`: Determines whether the rule is always included. Behavior is described below:
|
||||
- `true`: Always included, regardless of file context
|
||||
- `false`: Included if globs exist AND match file context, or the agent decides to pull the rule into context based on it's description
|
||||
- `undefined` (default behavior): Included if no globs exist OR globs exist and match
|
||||
|
||||
<Tabs groupId="rules-example">
|
||||
<TabItem value="md" label="Markdown">
|
||||
|
|
@ -96,10 +104,13 @@ Rules blocks can be simple text, written in YAML configuration files, or as Mark
|
|||
|
||||
```yaml title="doc-standards.yaml"
|
||||
name: Documentation Standards
|
||||
globs: docs/**/*.{md,mdx}
|
||||
alwaysApply: false
|
||||
version: 1.0.0
|
||||
schema: v1
|
||||
|
||||
rules:
|
||||
- name: Documentation Standards
|
||||
globs: docs/**/*.{md,mdx}
|
||||
alwaysApply: false
|
||||
rule: >
|
||||
- Follow Docusaurus documentation standards
|
||||
- Include YAML frontmatter with title, description, and keywords
|
||||
|
|
@ -163,7 +174,7 @@ Whenever you are writing React code, make sure to
|
|||
|
||||
Continue includes a simple default system message for [Chat](../../chat/how-to-use-it.md) and [Agent](../../agent/how-to-use-it.md) requests, to help the model provide reliable codeblock formats in its output.
|
||||
|
||||
This can be viewed in the rules section of the toolbar (see above), or visit the source code [here](https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts#L4)
|
||||
This can be viewed in the rules section of the toolbar (see above), or in the source code [here](https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts#L4).
|
||||
|
||||
Advanced users can override this system message for a specific model if needed by using `chatOptions.baseSystemMessage`. See the [`config.yaml` reference](../../reference.md#models).
|
||||
|
||||
|
|
@ -171,7 +182,7 @@ Advanced users can override this system message for a specific model if needed b
|
|||
|
||||
:::warning
|
||||
|
||||
`.contninuerules` will be deprecated in a future release. Please use the `.continue/rules` folder instead.
|
||||
`.continuerules` will be deprecated in a future release. Please use the `.continue/rules` folder instead.
|
||||
|
||||
:::
|
||||
|
||||
|
|
|
|||
|
|
@ -211,6 +211,15 @@ const config = {
|
|||
enableInDevelopment: false,
|
||||
},
|
||||
],
|
||||
[
|
||||
"docusaurus-plugin-llms-txt",
|
||||
{
|
||||
// Optional configuration
|
||||
outputPath: "static/llms.txt",
|
||||
includePatterns: ["docs/**"],
|
||||
excludePatterns: ["**/node_modules/**"],
|
||||
},
|
||||
],
|
||||
[
|
||||
"@docusaurus/plugin-client-redirects",
|
||||
{
|
||||
|
|
|
|||
18
docs/package-lock.json
generated
18
docs/package-lock.json
generated
|
|
@ -14,6 +14,7 @@
|
|||
"@docusaurus/preset-classic": "^3.7.0",
|
||||
"@mdx-js/react": "^3.0.0",
|
||||
"clsx": "^2.1.0",
|
||||
"docusaurus-plugin-llms-txt": "^0.1.3",
|
||||
"posthog-docusaurus": "^2.0.4",
|
||||
"prism-react-renderer": "^2.3.1",
|
||||
"react": "^18.2.0",
|
||||
|
|
@ -7604,6 +7605,23 @@
|
|||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/docusaurus-plugin-llms-txt": {
|
||||
"version": "0.1.3",
|
||||
"resolved": "https://registry.npmjs.org/docusaurus-plugin-llms-txt/-/docusaurus-plugin-llms-txt-0.1.3.tgz",
|
||||
"integrity": "sha512-X/Dqf1/soHFjvELWXtfa9C023498HsWWwNPdVZEu0OoznI2Gzf+VCB/4obwpBSV9OeDeI8D94/dK/ETq534k9A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"fs-extra": "^11.2.0",
|
||||
"gray-matter": "^4.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16.14"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@docusaurus/core": ">=2.0.0",
|
||||
"react": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/dom-converter": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/dom-converter/-/dom-converter-0.2.0.tgz",
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@
|
|||
"@docusaurus/preset-classic": "^3.7.0",
|
||||
"@mdx-js/react": "^3.0.0",
|
||||
"clsx": "^2.1.0",
|
||||
"docusaurus-plugin-llms-txt": "^0.1.3",
|
||||
"posthog-docusaurus": "^2.0.4",
|
||||
"prism-react-renderer": "^2.3.1",
|
||||
"react": "^18.2.0",
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension
|
|||
pluginName=continue-intellij-extension
|
||||
pluginRepositoryUrl=https://github.com/continuedev/continue
|
||||
# SemVer format -> https://semver.org
|
||||
pluginVersion=1.0.25
|
||||
pluginVersion=1.0.26
|
||||
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
|
||||
pluginSinceBuild=223
|
||||
# IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue