diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index b8c473604..9b79be9c1 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -6,7 +6,13 @@ name: JetBrains Release on: release: - types: [prereleased] + types: [ prereleased ] + workflow_dispatch: + inputs: + publish_build: + description: 'Whether or not to publish the built extension to the JetBrains marketplace' + required: true + default: false defaults: run: @@ -34,7 +40,7 @@ jobs: # Prepare and publish the plugin to JetBrains Marketplace repository build: needs: check_release_name - if: needs.check_release_name.outputs.should_run == 'true' + if: needs.check_release_name.outputs.should_run == 'true' || github.event_name == 'workflow_dispatch' name: Build Plugin runs-on: macos-latest permissions: @@ -175,6 +181,7 @@ jobs: # Publish the plugin to JetBrains Marketplace - name: Publish EAP Plugin + if: github.event_name == 'release' || github.event.inputs.publish_build == 'true' env: PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }} CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }} @@ -184,6 +191,7 @@ jobs: run: ./gradlew publishPlugin - name: Publish Stable Plugin + if: github.event_name == 'release' || github.event.inputs.publish_build == 'true' env: PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }} CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }} @@ -337,7 +345,7 @@ jobs: # Run tests and upload a code coverage report test: name: Test - needs: [build] + needs: [ build ] runs-on: ubuntu-latest steps: # Check out current repository @@ -379,7 +387,7 @@ jobs: inspectCode: if: false name: Inspect code - needs: [build] + needs: [ build ] runs-on: ubuntu-latest permissions: contents: write @@ -414,7 +422,7 @@ jobs: verify: if: false name: Verify plugin - needs: [build] + needs: [ build ] runs-on: ubuntu-latest steps: # Free GitHub Actions Environment Disk Space diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index ae0359027..d10d58ef1 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -4,6 +4,13 @@ on: release: types: [released] + workflow_dispatch: + inputs: + publish_build: + description: "Whether or not to publish the built extension to the VS Code marketplace" + required: true + default: false + jobs: check_release_name: runs-on: ubuntu-latest @@ -21,7 +28,7 @@ jobs: build: needs: check_release_name - if: needs.check_release_name.outputs.should_run == 'true' + if: needs.check_release_name.outputs.should_run == 'true' || github.event_name == 'workflow_dispatch' strategy: matrix: include: @@ -201,6 +208,7 @@ jobs: runs-on: ubuntu-latest needs: - build + if: github.event.inputs.publish_build == 'true' permissions: contents: write steps: diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index c41c57f72..ccc9e8a44 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -1,10 +1,11 @@ name: PR checks on: - pull_request: + pull_request_target: branches: - main paths: + - "extensions/intellij/**" - "extensions/vscode/**" - "core/**" - "gui/**" @@ -21,10 +22,22 @@ on: - ".github/workflows/**" jobs: + validate-pr: + runs-on: ubuntu-latest + environment: tests-requiring-secrets + steps: + - uses: actions/checkout@v4 + install-root: + needs: validate-pr runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + # This is important - it switches from the base repo to the fork + repository: ${{ github.event.pull_request.head.repo.full_name }} + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -44,6 +57,10 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -69,8 +86,13 @@ jobs: core-checks: needs: install-core runs-on: ubuntu-latest + environment: tests-requiring-secrets steps: - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -96,10 +118,14 @@ jobs: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} install-gui: - needs: [ install-root, install-core ] + needs: [install-root, install-core] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -131,6 +157,10 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -157,10 +187,14 @@ jobs: npx tsc --noEmit binary-checks: - needs: [ install-root, install-core ] + needs: [install-root, install-core] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -193,10 +227,14 @@ jobs: npx tsc --noEmit install-vscode: - needs: [ install-root, install-core ] + needs: [install-root, install-core] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -230,6 +268,10 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -261,6 +303,10 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -274,14 +320,22 @@ jobs: run: | cd core npm test + env: + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} + MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }} vscode-get-test-file-matrix: runs-on: ubuntu-latest - needs: [ install-root, install-vscode ] + needs: [install-root, install-vscode] outputs: test_file_matrix: ${{ steps.vscode-get-test-file-matrix.outputs.test_file_matrix }} steps: - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + repository: ${{ github.event.pull_request.head.repo.full_name }} - name: Cache node modules uses: actions/cache@v3 @@ -306,9 +360,13 @@ jobs: vscode-package-extension: runs-on: ubuntu-latest - needs: [ install-vscode, install-core ] + needs: [install-vscode, install-core] steps: - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -338,9 +396,13 @@ jobs: vscode-download-e2e-dependencies: runs-on: ubuntu-latest - needs: [ install-vscode, install-core ] + needs: [install-vscode, install-core] steps: - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -370,7 +432,7 @@ jobs: path: extensions/vscode/e2e/storage vscode-e2e-tests: - name: ${{ matrix.test_file }}" + name: ${{ matrix.test_file }} (${{ matrix.command }}) needs: [ vscode-download-e2e-dependencies, @@ -380,12 +442,19 @@ jobs: install-core, ] runs-on: ubuntu-latest + # Tests requiring secrets need approval from maintainers + environment: tests-requiring-secrets strategy: fail-fast: false matrix: test_file: ${{ fromJson(needs.vscode-get-test-file-matrix.outputs.test_file_matrix) }} + command: ["e2e:ci:run", "e2e:ci:run-yaml"] steps: - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -432,8 +501,7 @@ jobs: - name: Run e2e tests run: | cd extensions/vscode - TEST_FILE="${{ matrix.test_file }}" npm run e2e:ci:run - + TEST_FILE="${{ matrix.test_file }}" npm run ${{ matrix.command }} env: DISPLAY: :99 @@ -445,10 +513,14 @@ jobs: path: extensions/vscode/e2e/storage/screenshots gui-tests: - needs: [ install-gui, install-core ] + needs: [install-gui, install-core] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + - uses: actions/setup-node@v4 with: node-version-file: ".nvmrc" @@ -476,10 +548,13 @@ jobs: npm test jetbrains-tests: - needs: [ install-root, core-checks ] + needs: [install-root, core-checks] runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + repository: ${{ github.event.pull_request.head.repo.full_name }} - uses: actions/cache@v4 with: @@ -546,7 +621,7 @@ jobs: with: url: http://127.0.0.1:8082 max-attempts: 15 - retry-delay: 5s + retry-delay: 30s - name: Run tests run: | @@ -574,4 +649,33 @@ jobs: path: | ${{ github.workspace }}/extensions/intellij/build/reports + # GitHub does not have a way of requiring that all checks pass (you must manually select each job) + # This action at least lets us manage the list of required tests via source control + # so that creators of new jobs can add them to this list + require-all-checks-to-pass: + if: always() + runs-on: ubuntu-latest + needs: + - install-root + - install-core + - core-checks + - install-gui + - gui-checks + - binary-checks + - install-vscode + - vscode-checks + - core-tests + - vscode-get-test-file-matrix + - vscode-package-extension + - vscode-download-e2e-dependencies + - vscode-e2e-tests + - gui-tests + - jetbrains-tests + steps: + - name: Decide whether the needed jobs succeeded or failed + uses: re-actors/alls-green@release/v1 + with: + allowed-failures: + allowed-skips: + jobs: ${{ toJSON(needs) }} diff --git a/.vscode/launch.json b/.vscode/launch.json index dfe474f40..7a5161729 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -20,10 +20,10 @@ "outFiles": ["${workspaceFolder}/extensions/vscode/out/extension.js"], "preLaunchTask": "vscode-extension:build", "env": { + // "CONTROL_PLANE_ENV": "local", "CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug" // "staging" for the preview deployment "CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug" // "local" for entirely local development of control plane/proxy - // "CONTROL_PLANE_ENV": "staging" } }, { @@ -38,6 +38,7 @@ "internalConsoleOptions": "openOnSessionStart", "cwd": "${workspaceFolder}/binary", "env": { + // "CONTROL_PLANE_ENV": "test", "CONTINUE_DEVELOPMENT": "true", "CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug" } diff --git a/.vscode/settings.json b/.vscode/settings.json index 97782cdcc..dd446726a 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -42,5 +42,6 @@ "extensions/.continue-debug": true // "sync/**": true }, - "eslint.workingDirectories": ["./core"] + "eslint.workingDirectories": ["./core"], + "typescript.tsdk": "node_modules/typescript/lib" } diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ca26d38fe..b69b1fd44 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -49,7 +49,7 @@ If you find a bug, please [create an issue](https://github.com/continuedev/conti ## ✨ Suggest Enhancements -Continue is quickly adding features, and we'd love to hear which are the most important to you. The best ways to suggest an enhancement are +Continue is quickly adding features, and we'd love to hear which are the most important to you. The best ways to suggest an enhancement are: - Create an issue @@ -192,7 +192,7 @@ Continue has support for more than a dozen different LLM "providers", making it 1. Create a new file in the `core/llm/llms` directory. The name of the file should be the name of the provider, and it should export a class that extends `BaseLLM`. This class should contain the following minimal implementation. We recommend viewing pre-existing providers for more details. The [LlamaCpp Provider](./core/llm/llms/LlamaCpp.ts) is a good simple example. -- `providerName` - the identifier for your provider +- `providerName` - the identifier for your provider. - At least one of `_streamComplete` or `_streamChat` - This is the function that makes the request to the API and returns the streamed response. You only need to implement one because Continue can automatically convert between "chat" and "raw completion". 2. Add your provider to the `LLMs` array in [core/llm/llms/index.ts](./core/llm/llms/index.ts). diff --git a/binary/build.js b/binary/build.js index 045fb64f2..11aaf5c59 100644 --- a/binary/build.js +++ b/binary/build.js @@ -118,6 +118,22 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { } (async () => { + // Informs of where to look for node_sqlite3.node https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found + // This is only needed for our `pkg` command at build time + fs.writeFileSync( + "out/package.json", + JSON.stringify( + { + name: "binary", + version: "1.0.0", + author: "Continue Dev, Inc", + license: "Apache-2.0", + }, + undefined, + 2, + ), + ); + console.log("[info] Downloading prebuilt lancedb..."); for (const target of targets) { if (targetToLanceDb[target]) { @@ -263,9 +279,12 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) { // 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`, ""); + // fs.writeFileSync(`${targetDir}/package.json`, ""); } + // Cleanup - this is needed when running locally + fs.rmSync("out/package.json"); + const pathsToVerify = []; for (const target of targets) { const exe = target.startsWith("win") ? ".exe" : ""; diff --git a/binary/package-lock.json b/binary/package-lock.json index 158342e0b..316fddcd2 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -48,7 +48,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.0", + "@continuedev/config-yaml": "^1.0.16", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", diff --git a/binary/src/IpcMessenger.ts b/binary/src/IpcMessenger.ts index ec6f160c7..e90fbeb84 100644 --- a/binary/src/IpcMessenger.ts +++ b/binary/src/IpcMessenger.ts @@ -33,14 +33,46 @@ class IPCMessengerBase< response && typeof response[Symbol.asyncIterator] === "function" ) { - for await (const update of response) { - this.send(msg.messageType, update, msg.messageId); + let next = await response.next(); + while (!next.done) { + this.send( + msg.messageType, + { + done: false, + content: next.value, + status: "success", + }, + msg.messageId, + ); + next = await response.next(); } - this.send(msg.messageType, { done: true }, msg.messageId); + this.send( + msg.messageType, + { + done: true, + content: next.value, + status: "success", + }, + msg.messageId, + ); } else { - this.send(msg.messageType, response, msg.messageId); + this.send( + msg.messageType, + { + done: true, + content: response, + status: "success", + }, + msg.messageId, + ); } } catch (e: any) { + this.send( + msg.messageType, + { done: true, error: e.message, status: "error" }, + msg.messageId, + ); + console.warn(`Error running handler for "${msg.messageType}": `, e); this._onErrorHandlers.forEach((handler) => { handler(e); @@ -62,6 +94,7 @@ class IPCMessengerBase< } private _unfinishedLine: string | undefined = undefined; + protected _handleData(data: Buffer) { const d = data.toString(); const lines = d.split(/\r\n/).filter((line) => line.trim() !== ""); @@ -169,6 +202,7 @@ export class IpcMessenger< process.exit(1); }); } + _sendMsg(msg: Message) { const d = JSON.stringify(msg); // console.log("[info] Sending message: ", d); diff --git a/binary/src/TcpMessenger.ts b/binary/src/TcpMessenger.ts index ecd5d0d70..ad4713473 100644 --- a/binary/src/TcpMessenger.ts +++ b/binary/src/TcpMessenger.ts @@ -69,14 +69,46 @@ export class TcpMessenger< response && typeof response[Symbol.asyncIterator] === "function" ) { - for await (const update of response) { - this.send(msg.messageType, update, msg.messageId); + let next = await response.next(); + while (!next.done) { + this.send( + msg.messageType, + { + done: false, + content: next.value, + status: "success", + }, + msg.messageId, + ); + next = await response.next(); } - this.send(msg.messageType, { done: true }, msg.messageId); + this.send( + msg.messageType, + { + done: true, + content: next.value, + status: "success", + }, + msg.messageId, + ); } else { - this.send(msg.messageType, response || {}, msg.messageId); + this.send( + msg.messageType, + { + done: true, + content: response, + status: "success", + }, + msg.messageId, + ); } } catch (e: any) { + this.send( + msg.messageType, + { done: true, error: e.message, status: "error" }, + msg.messageId, + ); + console.warn(`Error running handler for "${msg.messageType}": `, e); this._onErrorHandlers.forEach((handler) => { handler(e); @@ -98,6 +130,7 @@ export class TcpMessenger< } private _unfinishedLine: string | undefined = undefined; + private _handleData(data: Buffer) { const d = data.toString(); const lines = d.split(/\r\n/).filter((line) => line.trim() !== ""); @@ -151,6 +184,7 @@ export class TcpMessenger< data, }); } + request( messageType: T, data: FromProtocol[T][0], diff --git a/core/autocomplete/README.md b/core/autocomplete/README.md deleted file mode 100644 index ab6e9adfb..000000000 --- a/core/autocomplete/README.md +++ /dev/null @@ -1,158 +0,0 @@ -# Tab Autocomplete (beta) - -Continue now provides support for tab autocomplete in [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains IDEs](https://plugins.jetbrains.com/plugin/22707-continue/edit). We will be greatly improving the experience over the next few releases, and it is always helpful to hear feedback. If you have any problems or suggestions, please let us know in our [Discord](https://discord.gg/vapESyrFmJ). - -## Setting up with Ollama (default) - -We recommend setting up tab-autocomplete with a local Ollama instance. To do this, first download the latest version of Ollama from [here](https://ollama.ai). Then, run the following command to download our recommended model: - -```bash -ollama run qwen2.5-coder:1.5b-base -``` - -Once it has been downloaded, you should begin to see completions in VS Code. - -## Setting up with LM Studio - -You can also set up tab-autocomplete with a local LM Studio instance by following these steps: - -1. Download the latest version of LM Studio from [here](https://lmstudio.ai/) -2. Download a model (e.g. search for `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF` and choose one of the options there) -3. Go to the server section (button is on the left), select your model from the dropdown at the top, and click "Start Server" -4. Go to the "My Models" section (button is on the left), find your selected model, and copy the name the path (example: `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF/qwen2.5-coder-1.5b-instruct-q4_k_m.gguf`); this will be used as the "model" attribute in Continue -5. Go to Continue and modify the configurations for a [custom model](#setting-up-a-custom-model) -6. Set the "provider" to `lmstudio` and the "model" to the path copied earlier - -Example: - -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Qwen2.5-Coder 1.5b", - "model": "Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF", - "provider": "lmstudio" - } -} -``` - -## Setting up a custom model - -All of the configuration options available for chat models are available to use for tab-autocomplete. For example, if you wanted to use a remote vLLM instance you would edit your `config.json` like this (note that it is not inside the models array), filling in the correct model name and vLLM endpoint: - -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Tab Autocomplete Model", - "provider": "openai", - "model": "", - "apiBase": "" - }, - ... -} -``` - -As another example, say you want to use a different model, `deepseek-coder:6.7b-base`, with Ollama: - -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Tab Autocomplete Model", - "provider": "ollama", - "model": "deepseek-coder:6.7b-base" - }, - ... -} -``` - -If you aren't yet familiar with the available options, you can learn more in our [overview](../setup/overview.md). - -### What model should I use? - -If you are running the model locally, we recommend `qwen2.5-coder:1.5b`. - -If you have a bit more compute, or are running a model in the cloud, you can upgrade to `qwen2.5-coder:7b`. - -Regardless of what you are willing to spend, we do not recommend using GPT or Claude for autocomplete. Learn why [below](#i-want-better-completions-should-i-use-gpt-4). - -## Configuration Options - -The following can be configured in `config.json`: - -### `tabAutocompleteModel` - -This is just another object like the ones in the `"models"` array of `config.json`. You can choose and configure any model you would like, but we strongly suggest using a small model made for tab-autocomplete, such as `deepseek-1b`, `qwen2.5-coder:1.5b`, or `starcoder-3b`. - -### `tabAutocompleteOptions` - -This object allows you to customize the behavior of tab-autocomplete. The available options are: - -- `useFileSuffix`: Determines whether to use the file suffix in the prompt. (Boolean) -- `maxPromptTokens`: The maximum number of prompt tokens to use. A smaller number will yield faster completions, but less context. (Number) -- `debounceDelay`: The delay in milliseconds before triggering autocomplete after a keystroke. (Number) -- `maxSuffixPercentage`: The maximum percentage of the prompt that can be dedicated to the suffix. (Number) -- `prefixPercentage`: The percentage of the input that should be dedicated to the prefix. (Number) -- `template`: An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables. (String) -- `multilineCompletions`: Whether to enable multiline completions ("always", "never", or "auto"). Defaults to "auto". - -### Full example - -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Tab Autocomplete Model", - "provider": "ollama", - "model": "qwen2.5-coder:1.5b-base", - "apiBase": "https://" - }, - "tabAutocompleteOptions": { - "maxPromptTokens": 400, - "prefixPercentage": 0.5 - } -} -``` - -## Troubleshooting - -### I want better completions, should I use GPT-4? - -Perhaps surprisingly, the answer is no. The models that we suggest for autocomplete are trained with a highly specific prompt format, which allows them to respond to requests for completing code (see examples of these prompts [here](https://github.com/continuedev/continue/blob/main/core/autocomplete/templates.ts)). Some of the best commercial models like GPT-4 or Claude are not trained with this prompt format, which means that they won't generate useful completions. Luckily, a huge model is not required for great autocomplete. Most of the state-of-the-art autocomplete models are no more than 10b parameters, and increasing beyond this does not significantly improve performance. - -### I'm not seeing any completions - -Follow these steps to ensure that everything is set up correctly: - -1. Make sure you have the "Enable Tab Autocomplete" setting checked (in VS Code, you can toggle by clicking the "Continue" button in the status bar). -2. Make sure you have downloaded Ollama. -3. Run `ollama run qwen2.5-coder:1.5b-base` to verify that the model is downloaded. -4. Make sure that any other completion providers are disabled (e.g. Copilot), as they may interfere. -5. If you are using another Ollama model for chat and your resources are limited, this will cause Ollama to constantly load and unload the models from memory, resulting in slow responses (or none at all) for both. A resolution for this could be using the same model for chat and autocomplete. -6. Check the output of the logs to find any potential errors (cmd/ctrl+shift+p -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/logs/core.log in JetBrains). -7. If you are still having issues, please let us know in our [Discord](https://discord.gg/vapESyrFmJ) and we'll help as soon as possible. - -### Completions are slow - -Depending on your hardware, you may want to try a smaller, faster model. If 3b isn't working for you we recommend trying `deepseek-coder:1.3b-base`. - -### Completions don't know about my code - -We are working on this! Right now Continue uses the Language Server Protocol to add definitions to the prompt, as well as using similarity search over recently edited files. We will be improving the accuracy of this system greatly over the next few weeks. - -### Completions contain formatting errors - -If you're seeing a common pattern of mistake that might be helpful to report, please share in Discord. We will do our best to fix it as soon as possible. - -## How to turn off autocomplete - -### VS Code - -Click the "Continue" button in the status panel at the bottom right of the screen. The checkmark will become a "cancel" symbol and you will no longer see completions. You can click again to turn it back on. - -Alternatively, open VS Code settings, search for "Continue" and uncheck the box for "Enable Tab Autocomplete". - -### JetBrains - -Open Settings -> Tools -> Continue and uncheck the box for "Enable Tab Autocomplete". - -### Feedback - -If you're turning off autocomplete, we'd love to hear how we can improve! Please let us know in our [Discord](https://discord.gg/vapESyrFmJ) or file an issue on GitHub. diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts index 6bfc6cfe1..1bd90c503 100644 --- a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -76,7 +76,6 @@ export class StreamTransformPipeline { const timeoutValue = await Telemetry.getValueForFeatureFlag( PosthogFeatureFlag.AutocompleteTimeout, ); - // helper.options.showWhateverWeHaveAtXMs ?? DEFAULT_AUTOCOMPLETE_OPTS.showWhateverWeHaveAtXMs lineGenerator = showWhateverWeHaveAtXMs(lineGenerator, timeoutValue!); diff --git a/core/commands/index.ts b/core/commands/index.ts index 492b7f90a..f4a0084da 100644 --- a/core/commands/index.ts +++ b/core/commands/index.ts @@ -9,7 +9,7 @@ export function slashFromCustomCommand( ): SlashCommand { return { name: customCommand.name, - description: customCommand.description, + description: customCommand.description ?? "", run: async function* ({ input, llm, history, ide }) { // Remove slash command prefix from input let userInput = input; @@ -37,16 +37,21 @@ export function slashFromCustomCommand( if ( Array.isArray(content) && - content.some((part) => - part.text?.startsWith(`/${customCommand.name}`), + content.some( + (part) => + "text" in part && part.text?.startsWith(`/${customCommand.name}`), ) ) { messages[i] = { ...message, content: content.map((part) => { - return part.text?.startsWith(`/${customCommand.name}`) - ? { ...part, text: promptUserInput } - : part; + if ( + "text" in part && + part.text.startsWith(`/${customCommand.name}`) + ) { + return { type: "text", text: promptUserInput }; + } + return part; }), }; break; diff --git a/core/config/ConfigHandler.test.ts b/core/config/ConfigHandler.test.ts index 5a25e71fc..deb1deded 100644 --- a/core/config/ConfigHandler.test.ts +++ b/core/config/ConfigHandler.test.ts @@ -14,7 +14,7 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => { expect(profiles[0].id).toBe("local"); const currentProfile = testConfigHandler.currentProfile; - expect(currentProfile.profileId).toBe("local"); + expect(currentProfile.profileDescription.id).toBe("local"); }); test("should load the default config successfully", async () => { diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 2c91148ba..edcf62071 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -1,3 +1,5 @@ +import * as fs from "node:fs"; + import { ControlPlaneClient, ControlPlaneSessionInfo, @@ -12,20 +14,28 @@ import { } from "../index.js"; import Ollama from "../llm/llms/Ollama.js"; import { GlobalContext } from "../util/GlobalContext.js"; -import { getConfigJsonPath } from "../util/paths.js"; +import { getConfigJsonPath, getConfigYamlPath } from "../util/paths.js"; -import { ConfigResult } from "./load.js"; +import { + AssistantUnrolled, + ConfigResult, + FullSlug, +} from "@continuedev/config-yaml"; +import * as YAML from "yaml"; +import { getControlPlaneEnv, useHub } from "../control-plane/env.js"; +import { localPathToUri } from "../util/pathToUri.js"; import { LOCAL_ONBOARDING_CHAT_MODEL, ONBOARDING_LOCAL_MODEL_TITLE, } from "./onboarding.js"; import ControlPlaneProfileLoader from "./profile/ControlPlaneProfileLoader.js"; import LocalProfileLoader from "./profile/LocalProfileLoader.js"; +import PlatformProfileLoader from "./profile/PlatformProfileLoader.js"; import { ProfileDescription, ProfileLifecycleManager, } from "./ProfileLifecycleManager.js"; -import { pathToFileURL } from "url"; +import { clientRenderHelper } from "./yaml/clientRender.js"; export type { ProfileDescription }; @@ -56,8 +66,8 @@ export class ConfigHandler { controlPlaneClient, writeLog, ); - this.profiles = [new ProfileLifecycleManager(localProfileLoader)]; - this.selectedProfileId = localProfileLoader.profileId; + this.profiles = [new ProfileLifecycleManager(localProfileLoader, this.ide)]; + this.selectedProfileId = localProfileLoader.description.id; // Always load local profile immediately in case control plane doesn't load try { @@ -77,47 +87,72 @@ export class ConfigHandler { get currentProfile() { return ( - this.profiles.find((p) => p.profileId === this.selectedProfileId) ?? - this.fallbackProfile + this.profiles.find( + (p) => p.profileDescription.id === this.selectedProfileId, + ) ?? this.fallbackProfile ); } get inactiveProfiles() { - return this.profiles.filter((p) => p.profileId !== this.selectedProfileId); + return this.profiles.filter( + (p) => p.profileDescription.id !== this.selectedProfileId, + ); } async openConfigProfile(profileId?: string) { let openProfileId = profileId || this.selectedProfileId; if (openProfileId === "local") { - await this.ide.openFile(pathToFileURL(getConfigJsonPath()).toString()); + const ideInfo = await this.ide.getIdeInfo(); + const configYamlPath = getConfigYamlPath(ideInfo.ideType); + if (fs.existsSync(configYamlPath)) { + await this.ide.openFile(localPathToUri(configYamlPath)); + } else { + await this.ide.openFile(localPathToUri(getConfigJsonPath())); + } } else { - await this.ide.openUrl( - "https://app.continue.dev/", - // `https://app.continue.dev/workspaces/${openProfileId}/chat`, - ); + const env = await getControlPlaneEnv(this.ide.getIdeSettings()); + await this.ide.openUrl(`${env.APP_URL}platform/${openProfileId}`); } } - private async fetchControlPlaneProfiles() { + private async loadPlatformProfiles() { // Get the profiles and create their lifecycle managers this.controlPlaneClient - .listWorkspaces() - .then(async (workspaces) => { - this.profiles = this.profiles.filter( - (profile) => profile.profileId === "local", + .listAssistants() + .then(async (assistants) => { + const hubProfiles = await Promise.all( + assistants.map(async (assistant) => { + let renderedConfig: AssistantUnrolled | undefined = undefined; + if (assistant.configResult.config) { + renderedConfig = await clientRenderHelper( + YAML.stringify(assistant.configResult.config), + this.ide, + this.controlPlaneClient, + ); + } + + const profileLoader = new PlatformProfileLoader( + { ...assistant.configResult, config: renderedConfig }, + assistant.ownerSlug, + assistant.packageSlug, + assistant.configResult.config?.version ?? "latest", + this.controlPlaneClient, + this.ide, + this.ideSettingsPromise, + this.writeLog, + this.reloadConfig.bind(this), + ); + + return new ProfileLifecycleManager(profileLoader, this.ide); + }), ); - workspaces.forEach((workspace) => { - const profileLoader = new ControlPlaneProfileLoader( - workspace.id, - workspace.name, - this.controlPlaneClient, - this.ide, - this.ideSettingsPromise, - this.writeLog, - this.reloadConfig.bind(this), - ); - this.profiles.push(new ProfileLifecycleManager(profileLoader)); - }); + + this.profiles = [ + ...this.profiles.filter( + (profile) => profile.profileDescription.id === "local", + ), + ...hubProfiles, + ]; this.notifyProfileListeners( this.profiles.map((profile) => profile.profileDescription), @@ -141,10 +176,103 @@ export class ConfigHandler { } }) .catch((e) => { - console.error(e); + console.error("Failed to list assistants: ", e); }); } + private platformProfilesRefreshInterval: NodeJS.Timeout | undefined; + // We use this to keep track of whether we should reload the assistants + private lastFullSlugsList: FullSlug[] = []; + + private fullSlugsListsDiffer(a: FullSlug[], b: FullSlug[]): boolean { + if (a.length !== b.length) { + return true; + } + for (let i = 0; i < a.length; i++) { + if (a[i].ownerSlug !== b[i].ownerSlug) { + return true; + } + if (a[i].packageSlug !== b[i].packageSlug) { + return true; + } + if (a[i].versionSlug !== b[i].versionSlug) { + return true; + } + } + return false; + } + + private async fetchControlPlaneProfiles() { + if (await useHub(this.ideSettingsPromise)) { + clearInterval(this.platformProfilesRefreshInterval); + await this.loadPlatformProfiles(); + + // Every 5 seconds we ask the platform whether there are any assistant updates in the last 5 seconds + // If so, we do the full (more expensive) reload + this.platformProfilesRefreshInterval = setInterval(async () => { + const newFullSlugsList = + await this.controlPlaneClient.listAssistantFullSlugs(); + + if (newFullSlugsList) { + const shouldReload = this.fullSlugsListsDiffer( + newFullSlugsList, + this.lastFullSlugsList, + ); + if (shouldReload) { + await this.loadPlatformProfiles(); + } + this.lastFullSlugsList = newFullSlugsList; + } + }, PlatformProfileLoader.RELOAD_INTERVAL); + } else { + this.controlPlaneClient + .listWorkspaces() + .then(async (workspaces) => { + this.profiles = this.profiles.filter( + (profile) => profile.profileDescription.id === "local", + ); + workspaces.forEach((workspace) => { + const profileLoader = new ControlPlaneProfileLoader( + workspace.id, + workspace.name, + this.controlPlaneClient, + this.ide, + this.ideSettingsPromise, + this.writeLog, + this.reloadConfig.bind(this), + ); + this.profiles.push( + new ProfileLifecycleManager(profileLoader, this.ide), + ); + }); + + this.notifyProfileListeners( + this.profiles.map((profile) => profile.profileDescription), + ); + + // Check the last selected workspace, and reload if it isn't local + const workspaceId = await this.getWorkspaceId(); + const lastSelectedWorkspaceIds = + this.globalContext.get("lastSelectedProfileForWorkspace") ?? {}; + const selectedWorkspaceId = lastSelectedWorkspaceIds[workspaceId]; + if (selectedWorkspaceId) { + this.selectedProfileId = selectedWorkspaceId; + await this.loadConfig(); + } else { + // Otherwise we stick with local profile, and record choice + lastSelectedWorkspaceIds[workspaceId] = this.selectedProfileId; + this.globalContext.update( + "lastSelectedProfileForWorkspace", + lastSelectedWorkspaceIds, + ); + } + }) + .catch((e) => { + console.error(e); + }); + } + } + async setSelectedProfile(profileId: string) { this.selectedProfileId = profileId; const result = await this.loadConfig(); @@ -170,11 +298,12 @@ export class ConfigHandler { void this.reloadConfig(); } - updateControlPlaneSessionInfo( + async updateControlPlaneSessionInfo( sessionInfo: ControlPlaneSessionInfo | undefined, ) { this.controlPlaneClient = new ControlPlaneClient( Promise.resolve(sessionInfo), + this.ideSettingsPromise, ); this.fetchControlPlaneProfiles().catch((e) => { console.error("Failed to fetch control plane profiles: ", e); diff --git a/core/config/ProfileLifecycleManager.ts b/core/config/ProfileLifecycleManager.ts index c5ae16f91..fa76c6b55 100644 --- a/core/config/ProfileLifecycleManager.ts +++ b/core/config/ProfileLifecycleManager.ts @@ -1,15 +1,24 @@ +import { + ConfigResult, + ConfigValidationError, + FullSlug, +} from "@continuedev/config-yaml"; import { BrowserSerializedContinueConfig, ContinueConfig, IContextProvider, + IDE, } from "../index.js"; -import { ConfigResult, finalToBrowserConfig } from "./load.js"; +import { finalToBrowserConfig } from "./load.js"; import { IProfileLoader } from "./profile/IProfileLoader.js"; export interface ProfileDescription { + fullSlug: FullSlug; + profileType: "control-plane" | "local" | "platform"; title: string; id: string; + errors: ConfigValidationError[] | undefined; } export class ProfileLifecycleManager { @@ -17,21 +26,13 @@ export class ProfileLifecycleManager { private savedBrowserConfigResult?: ConfigResult; private pendingConfigPromise?: Promise>; - constructor(private readonly profileLoader: IProfileLoader) {} - - get profileId() { - return this.profileLoader.profileId; - } - - get profileTitle() { - return this.profileLoader.profileTitle; - } + constructor( + private readonly profileLoader: IProfileLoader, + private readonly ide: IDE, + ) {} get profileDescription(): ProfileDescription { - return { - title: this.profileTitle, - id: this.profileId, - }; + return this.profileLoader.description; } clearConfig() { @@ -71,14 +72,10 @@ export class ProfileLifecycleManager { result.config.contextProviders = ( result.config.contextProviders ?? [] ).concat(additionalContextProviders); - - this.savedConfigResult = result; - resolve(result); - } else if (result.errors) { - reject( - `Error in config.json: ${result.errors.map((item) => item.message).join(" | ")}`, - ); } + + this.savedConfigResult = result; + resolve(result); }); // Wait for the config promise to resolve @@ -100,7 +97,10 @@ export class ProfileLifecycleManager { config: undefined, }; } - const serializedConfig = finalToBrowserConfig(result.config); + const serializedConfig = await finalToBrowserConfig( + result.config, + this.ide, + ); return { ...result, config: serializedConfig, diff --git a/core/config/load.ts b/core/config/load.ts index 9a6599608..da95ec5a8 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -62,6 +62,7 @@ import { getEsbuildBinaryPath, } from "../util/paths"; +import { ConfigResult, ConfigValidationError } from "@continuedev/config-yaml"; import { defaultContextProvidersJetBrains, defaultContextProvidersVsCode, @@ -69,16 +70,14 @@ import { defaultSlashCommandsVscode, } from "./default"; import { getSystemPromptDotFile } from "./getSystemPromptDotFile"; -// import { isSupportedLanceDbCpuTarget } from "./util"; -import { ConfigValidationError, validateConfig } from "./validation.js"; +import { useHub } from "../control-plane/env"; +import { localPathToUri } from "../util/pathToUri"; +import { modifyContinueConfigWithSharedConfig } from "./sharedConfig"; +import { validateConfig } from "./validation.js"; -export interface ConfigResult { - config: T | undefined; - errors: ConfigValidationError[] | undefined; - configLoadInterrupted: boolean; -} - -function resolveSerializedConfig(filepath: string): SerializedContinueConfig { +export function resolveSerializedConfig( + filepath: string, +): SerializedContinueConfig { let content = fs.readFileSync(filepath, "utf8"); const config = JSONC.parse(content) as unknown as SerializedContinueConfig; if (config.env && Array.isArray(config.env)) { @@ -114,11 +113,10 @@ function loadSerializedConfig( overrideConfigJson: SerializedContinueConfig | undefined, ide: IDE, ): ConfigResult { - const configPath = getConfigJsonPath(ideType); let config: SerializedContinueConfig = overrideConfigJson!; if (!config) { try { - config = resolveSerializedConfig(configPath); + config = resolveSerializedConfig(getConfigJsonPath(ideType)); } catch (e) { throw new Error(`Failed to parse config.json: ${e}`); } @@ -138,13 +136,6 @@ function loadSerializedConfig( config.allowAnonymousTelemetry = true; } - if (config.ui?.getChatTitles === undefined) { - config.ui = { - ...config.ui, - getChatTitles: true, - }; - } - if (ideSettings.remoteConfigServerUrl) { try { const remoteConfigJson = resolveSerializedConfig( @@ -229,7 +220,7 @@ function isModelDescription( return (llm as ModelDescription).title !== undefined; } -function isContextProviderWithParams( +export function isContextProviderWithParams( contextProvider: CustomContextProvider | ContextProviderWithParams, ): contextProvider is ContextProviderWithParams { return (contextProvider as ContextProviderWithParams).name !== undefined; @@ -547,9 +538,10 @@ async function intermediateToFinalConfig( return { config: continueConfig, errors }; } -function finalToBrowserConfig( +async function finalToBrowserConfig( final: ContinueConfig, -): BrowserSerializedContinueConfig { + ide: IDE, +): Promise { return { allowAnonymousTelemetry: final.allowAnonymousTelemetry, models: final.models.map((m) => ({ @@ -582,6 +574,8 @@ function finalToBrowserConfig( experimental: final.experimental, docs: final.docs, tools: final.tools, + tabAutocompleteOptions: final.tabAutocompleteOptions, + usePlatform: await useHub(ide.getIdeSettings()), }; } @@ -765,7 +759,7 @@ async function buildConfigTsandReadConfigJs(ide: IDE, ideType: IdeType) { return readConfigJs(); } -async function loadFullConfigNode( +async function loadContinueConfigFromJson( ide: IDE, workspaceConfigs: ContinueRcJson[], ideSettings: IdeSettings, @@ -797,8 +791,16 @@ async function loadFullConfigNode( serialized.systemMessage = systemPromptDotFile; } + // Apply shared config + // TODO: override several of these values with user/org shared config + const sharedConfig = new GlobalContext().getSharedConfig(); + const withShared = modifyContinueConfigWithSharedConfig( + serialized, + sharedConfig, + ); + // Convert serialized to intermediate config - let intermediate = await serializedToIntermediateConfig(serialized, ide); + let intermediate = await serializedToIntermediateConfig(withShared, ide); // Apply config.ts to modify intermediate config const configJsContents = await buildConfigTsandReadConfigJs(ide, ideType); @@ -816,7 +818,7 @@ async function loadFullConfigNode( "Could not load config.ts as absolute path, retrying as file url ...", ); try { - module = await import(`file://${configJsPath}`); + module = await import(localPathToUri(configJsPath)); } catch (e) { throw new Error("Could not load config.ts as file url either", { cause: e, @@ -875,6 +877,6 @@ async function loadFullConfigNode( export { finalToBrowserConfig, intermediateToFinalConfig, - loadFullConfigNode, + loadContinueConfigFromJson, type BrowserSerializedContinueConfig, }; diff --git a/core/config/migrateSharedConfig.ts b/core/config/migrateSharedConfig.ts new file mode 100644 index 000000000..b68e3adec --- /dev/null +++ b/core/config/migrateSharedConfig.ts @@ -0,0 +1,212 @@ +import * as fs from "fs"; + +import * as JSONC from "comment-json"; + +import { IDE, SerializedContinueConfig } from ".."; +import { SharedConfigSchema } from "./sharedConfig"; +import { GlobalContext } from "../util/GlobalContext"; +import { editConfigJson } from "../util/paths"; +import { resolveSerializedConfig } from "./load"; +import { deduplicateArray } from "../util"; + +/* + This migration function eliminates deprecated values from the json file + And writes them to the shared config +*/ +export function migrateJsonSharedConfig(filepath: string, ide: IDE): void { + const globalContext = new GlobalContext(); + const currentSharedConfig = globalContext.getSharedConfig(); // for merging security concerns + + try { + let config = resolveSerializedConfig(filepath); + const shareConfigUpdates: SharedConfigSchema = {}; + + let effected = false; + + const { allowAnonymousTelemetry, ...withoutAllowTelemetry } = config; + if (allowAnonymousTelemetry !== undefined) { + if (currentSharedConfig.allowAnonymousTelemetry !== false) { + // safe merge for security + shareConfigUpdates.allowAnonymousTelemetry = allowAnonymousTelemetry; + } + config = withoutAllowTelemetry; + effected = true; + } + + const { disableIndexing, ...withoutDisableIndexing } = config; + if (disableIndexing !== undefined) { + if (currentSharedConfig.disableIndexing !== true) { + // safe merge for security + shareConfigUpdates.disableIndexing = disableIndexing; + } + config = withoutDisableIndexing; + effected = true; + } + + const { disableSessionTitles, ...withoutDisableSessionTitles } = config; + if (config.disableSessionTitles !== undefined) { + if (currentSharedConfig.disableSessionTitles !== true) { + // safe merge for security + shareConfigUpdates.disableSessionTitles = config.disableSessionTitles; + } + config = withoutDisableSessionTitles; + effected = true; + } + + const { tabAutocompleteOptions, ...withoutAutocompleteOptions } = config; + if (tabAutocompleteOptions !== undefined) { + let migratedAutocomplete = { ...tabAutocompleteOptions }; + + const { useCache, ...withoutUseCache } = migratedAutocomplete; + if (useCache !== undefined) { + shareConfigUpdates.useAutocompleteCache = useCache; + migratedAutocomplete = withoutUseCache; + effected = true; + } + + const { multilineCompletions, ...withoutMultiline } = + migratedAutocomplete; + if (multilineCompletions !== undefined) { + shareConfigUpdates.useAutocompleteMultilineCompletions = + multilineCompletions; + migratedAutocomplete = withoutMultiline; + effected = true; + } + + const { disableInFiles, ...withoutDisableInFiles } = migratedAutocomplete; + if (disableInFiles !== undefined) { + if (currentSharedConfig.disableAutocompleteInFiles !== undefined) { + // safe merge for security + shareConfigUpdates.disableAutocompleteInFiles = deduplicateArray( + [ + ...currentSharedConfig.disableAutocompleteInFiles, + ...disableInFiles, + ], + (a, b) => a === b, + ); + } else { + shareConfigUpdates.disableAutocompleteInFiles = disableInFiles; + } + shareConfigUpdates.disableAutocompleteInFiles = disableInFiles; + migratedAutocomplete = withoutDisableInFiles; + effected = true; + } + + if (Object.keys(migratedAutocomplete).length > 0) { + config = { + ...withoutAutocompleteOptions, + tabAutocompleteOptions: migratedAutocomplete, + }; + } else { + config = withoutAutocompleteOptions; + } + } + + const { experimental, ...withoutExperimental } = config; + if (experimental !== undefined) { + let migratedExperimental = { ...experimental }; + + const { useChromiumForDocsCrawling, ...rest10 } = migratedExperimental; + if (useChromiumForDocsCrawling !== undefined) { + shareConfigUpdates.useChromiumForDocsCrawling = + useChromiumForDocsCrawling; + migratedExperimental = rest10; + effected = true; + } + + const { promptPath, ...withoutPromptPath } = migratedExperimental; + if (promptPath !== undefined) { + shareConfigUpdates.promptPath = promptPath; + migratedExperimental = withoutPromptPath; + effected = true; + } + + const { readResponseTTS, ...withoutReadTTS } = migratedExperimental; + if (readResponseTTS !== undefined) { + shareConfigUpdates.readResponseTTS = readResponseTTS; + migratedExperimental = withoutReadTTS; + effected = true; + } + + if (Object.keys(migratedExperimental).length > 0) { + config = { + ...withoutExperimental, + experimental: migratedExperimental, + }; + } else { + config = withoutExperimental; + } + } + + const { ui, ...withoutUI } = config; + if (ui !== undefined) { + let migratedUI = { ...ui }; + + const { codeBlockToolbarPosition, ...withoutToolbarPosition } = + migratedUI; + if (codeBlockToolbarPosition !== undefined) { + shareConfigUpdates.codeBlockToolbarPosition = codeBlockToolbarPosition; + migratedUI = withoutToolbarPosition; + effected = true; + } + + const { fontSize, ...withoutFontSize } = migratedUI; + if (fontSize !== undefined) { + shareConfigUpdates.fontSize = fontSize; + migratedUI = withoutFontSize; + effected = true; + } + + const { codeWrap, ...withoutCodeWrap } = migratedUI; + if (codeWrap !== undefined) { + shareConfigUpdates.codeWrap = codeWrap; + migratedUI = withoutCodeWrap; + effected = true; + } + + const { displayRawMarkdown, ...withoutMD } = migratedUI; + if (displayRawMarkdown !== undefined) { + shareConfigUpdates.displayRawMarkdown = displayRawMarkdown; + migratedUI = withoutMD; + effected = true; + } + + const { showChatScrollbar, ...withoutShowChatScrollbar } = migratedUI; + if (showChatScrollbar !== undefined) { + shareConfigUpdates.showChatScrollbar = showChatScrollbar; + migratedUI = withoutShowChatScrollbar; + effected = true; + } + + // Ancient param to overwrite disableSessionTitles + if ("getChatTitles" in migratedUI) { + const { getChatTitles, ...withoutChatTitles } = migratedUI; + if (getChatTitles === false) { + shareConfigUpdates.disableSessionTitles = true; + migratedUI = withoutChatTitles; + effected = true; + } + } + + if (Object.keys(migratedUI).length > 0) { + config = { + ...withoutUI, + ui: migratedUI, + }; + } else { + config = withoutUI; + } + } + + if (effected) { + new GlobalContext().updateSharedConfig(shareConfigUpdates); + editConfigJson(() => config); + void ide.showToast( + "warning", + "Migrated deprecated Continue JSON settings. Edit in the Settings Page", + ); + } + } catch (e) { + throw new Error(`Migration: Failed to parse config.json: ${e}`); + } +} diff --git a/core/config/profile/ControlPlaneProfileLoader.ts b/core/config/profile/ControlPlaneProfileLoader.ts index 448dbdb42..dfb111e1f 100644 --- a/core/config/profile/ControlPlaneProfileLoader.ts +++ b/core/config/profile/ControlPlaneProfileLoader.ts @@ -7,16 +7,16 @@ import { IdeSettings, SerializedContinueConfig, } from "../../index.js"; -import { ConfigResult } from "../load.js"; +import { ConfigResult } from "@continuedev/config-yaml"; +import { ProfileDescription } from "../ProfileLifecycleManager.js"; import doLoadConfig from "./doLoadConfig.js"; import { IProfileLoader } from "./IProfileLoader.js"; export default class ControlPlaneProfileLoader implements IProfileLoader { private static RELOAD_INTERVAL = 1000 * 60 * 15; // every 15 minutes - readonly profileId: string; - profileTitle: string; + description: ProfileDescription; workspaceSettings: ConfigJson | undefined; @@ -29,12 +29,23 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { private writeLog: (message: string) => Promise, private readonly onReload: () => void, ) { - this.profileId = workspaceId; - this.profileTitle = workspaceTitle; + this.description = { + id: workspaceId, + profileType: "control-plane", + fullSlug: { + ownerSlug: "", + packageSlug: "", + versionSlug: "", + }, + title: workspaceTitle, + errors: undefined, + }; setInterval(async () => { this.workspaceSettings = - await this.controlPlaneClient.getSettingsForWorkspace(this.profileId); + await this.controlPlaneClient.getSettingsForWorkspace( + this.description.id, + ); this.onReload(); }, ControlPlaneProfileLoader.RELOAD_INTERVAL); } @@ -43,7 +54,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { const settings = this.workspaceSettings ?? ((await this.controlPlaneClient.getSettingsForWorkspace( - this.profileId, + this.description.id, )) as any); const serializedConfig: SerializedContinueConfig = settings; @@ -53,6 +64,8 @@ export default class ControlPlaneProfileLoader implements IProfileLoader { this.controlPlaneClient, this.writeLog, serializedConfig, + undefined, + undefined, this.workspaceId, ); diff --git a/core/config/profile/IProfileLoader.ts b/core/config/profile/IProfileLoader.ts index 2d22a821e..5d0717252 100644 --- a/core/config/profile/IProfileLoader.ts +++ b/core/config/profile/IProfileLoader.ts @@ -1,12 +1,12 @@ // ProfileHandlers manage the loading of a config, allowing us to abstract over different ways of getting to a ContinueConfig +import { ConfigResult } from "@continuedev/config-yaml"; import { ContinueConfig } from "../../index.js"; -import { ConfigResult } from "../load.js"; +import { ProfileDescription } from "../ProfileLifecycleManager.js"; // After we have the ContinueConfig, the ConfigHandler takes care of everything else (loading models, lifecycle, etc.) export interface IProfileLoader { - profileTitle: string; - profileId: string; + description: ProfileDescription; doLoadConfig(): Promise>; setIsActive(isActive: boolean): void; } diff --git a/core/config/profile/LocalProfileLoader.ts b/core/config/profile/LocalProfileLoader.ts index 0705c8745..cb8694bbc 100644 --- a/core/config/profile/LocalProfileLoader.ts +++ b/core/config/profile/LocalProfileLoader.ts @@ -1,14 +1,24 @@ +import { ConfigResult } from "@continuedev/config-yaml"; import { ControlPlaneClient } from "../../control-plane/client.js"; import { ContinueConfig, IDE, IdeSettings } from "../../index.js"; -import { ConfigResult } from "../load.js"; +import { ProfileDescription } from "../ProfileLifecycleManager.js"; import doLoadConfig from "./doLoadConfig.js"; import { IProfileLoader } from "./IProfileLoader.js"; export default class LocalProfileLoader implements IProfileLoader { static ID = "local"; - profileId = LocalProfileLoader.ID; - profileTitle = "Local Config"; + description: ProfileDescription = { + id: LocalProfileLoader.ID, + profileType: "local", + fullSlug: { + ownerSlug: "", + packageSlug: "", + versionSlug: "", + }, + title: "Local Config", + errors: undefined, + }; constructor( private ide: IDE, @@ -18,13 +28,19 @@ export default class LocalProfileLoader implements IProfileLoader { ) {} async doLoadConfig(): Promise> { - return doLoadConfig( + const result = await doLoadConfig( this.ide, this.ideSettingsPromise, this.controlPlaneClient, this.writeLog, undefined, + undefined, + undefined, ); + + this.description.errors = result.errors; + + return result; } setIsActive(isActive: boolean): void {} diff --git a/core/config/profile/PlatformProfileLoader.ts b/core/config/profile/PlatformProfileLoader.ts new file mode 100644 index 000000000..12e166c2d --- /dev/null +++ b/core/config/profile/PlatformProfileLoader.ts @@ -0,0 +1,79 @@ +import { AssistantUnrolled } from "@continuedev/config-yaml/dist/schemas/index.js"; + +import { ControlPlaneClient } from "../../control-plane/client.js"; +import { ContinueConfig, IDE, IdeSettings } from "../../index.js"; + +import { ConfigResult } from "@continuedev/config-yaml"; +import { ProfileDescription } from "../ProfileLifecycleManager.js"; +import doLoadConfig from "./doLoadConfig.js"; +import { IProfileLoader } from "./IProfileLoader.js"; + +/** + * Metadata about the package that is currently being loaded + * If this is `undefined`, it's not a config from the platform, + * could be local for example. + */ +export interface PlatformConfigMetadata { + ownerSlug: string; + packageSlug: string; +} + +export default class PlatformProfileLoader implements IProfileLoader { + static RELOAD_INTERVAL = 1000 * 5; // 5 seconds + + description: ProfileDescription; + + constructor( + private configResult: ConfigResult, + private readonly ownerSlug: string, + private readonly packageSlug: string, + versionSlug: string, + private readonly controlPlaneClient: ControlPlaneClient, + private readonly ide: IDE, + private ideSettingsPromise: Promise, + private writeLog: (message: string) => Promise, + private readonly onReload: () => void, + ) { + this.description = { + id: `${ownerSlug}/${packageSlug}`, + profileType: "platform", + fullSlug: { + ownerSlug, + packageSlug, + versionSlug, + }, + title: `${ownerSlug}/${packageSlug}@${versionSlug}`, + errors: configResult.errors, + }; + } + + async doLoadConfig(): Promise> { + if (this.configResult.errors?.length) { + return { + config: undefined, + errors: this.configResult.errors, + configLoadInterrupted: false, + }; + } + + const results = await doLoadConfig( + this.ide, + this.ideSettingsPromise, + this.controlPlaneClient, + this.writeLog, + undefined, + this.configResult.config, + { + ownerSlug: this.ownerSlug, + packageSlug: this.packageSlug, + }, + ); + + return { + ...results, + errors: [], // Don't do config validation here, it happens in admin panel + }; + } + + setIsActive(isActive: boolean): void {} +} diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index a82dd896d..5ee0620a6 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -1,5 +1,10 @@ import fs from "fs"; +import { + AssistantUnrolled, + ConfigResult, + ConfigValidationError, +} from "@continuedev/config-yaml"; import { ContinueConfig, ContinueRcJson, @@ -9,15 +14,16 @@ import { } from "../../"; import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js"; import { ControlPlaneClient } from "../../control-plane/client.js"; -import { controlPlaneEnv } from "../../control-plane/env.js"; +import { getControlPlaneEnv } from "../../control-plane/env.js"; import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js"; import ContinueProxy from "../../llm/llms/stubs/ContinueProxy"; -import { getConfigYamlPath } from "../../util/paths"; +import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths"; import { Telemetry } from "../../util/posthog"; import { TTS } from "../../util/tts"; -import { ConfigResult, loadFullConfigNode } from "../load"; -import { ConfigValidationError } from "../validation"; +import { loadContinueConfigFromJson } from "../load"; import { loadContinueConfigFromYaml } from "../yaml/loadYaml"; +import { PlatformConfigMetadata } from "./PlatformProfileLoader"; +import { migrateJsonSharedConfig } from "../migrateSharedConfig"; export default async function doLoadConfig( ide: IDE, @@ -25,6 +31,8 @@ export default async function doLoadConfig( controlPlaneClient: ControlPlaneClient, writeLog: (message: string) => Promise, overrideConfigJson: SerializedContinueConfig | undefined, + overrideConfigYaml: AssistantUnrolled | undefined, + platformConfigMetadata: PlatformConfigMetadata | undefined, workspaceId?: string, ): Promise> { const workspaceConfigs = await getWorkspaceConfigs(ide); @@ -33,13 +41,20 @@ export default async function doLoadConfig( const ideSettings = await ideSettingsPromise; const workOsAccessToken = await controlPlaneClient.getAccessToken(); + // Migrations for old config files + // Removes + const configJsonPath = getConfigJsonPath(ideInfo.ideType); + if (fs.existsSync(configJsonPath)) { + migrateJsonSharedConfig(configJsonPath, ide); + } + const configYamlPath = getConfigYamlPath(ideInfo.ideType); let newConfig: ContinueConfig | undefined; let errors: ConfigValidationError[] | undefined; let configLoadInterrupted = false; - if (fs.existsSync(configYamlPath)) { + if (overrideConfigYaml || fs.existsSync(configYamlPath)) { const result = await loadContinueConfigFromYaml( ide, workspaceConfigs.map((c) => JSON.stringify(c)), @@ -48,14 +63,15 @@ export default async function doLoadConfig( uniqueId, writeLog, workOsAccessToken, - undefined, - // overrideConfigYaml, TODO + overrideConfigYaml, + platformConfigMetadata, + controlPlaneClient, ); newConfig = result.config; errors = result.errors; configLoadInterrupted = result.configLoadInterrupted; } else { - const result = await loadFullConfigNode( + const result = await loadContinueConfigFromJson( ide, workspaceConfigs, ideSettings, @@ -91,9 +107,11 @@ export default async function doLoadConfig( const controlPlane = (newConfig as any).controlPlane; const useOnPremProxy = controlPlane?.useContinueForTeamsProxy === false && controlPlane?.proxyUrl; + + const env = await getControlPlaneEnv(ideSettingsPromise); let controlPlaneProxyUrl: string = useOnPremProxy ? controlPlane?.proxyUrl - : controlPlaneEnv.DEFAULT_CONTROL_PLANE_PROXY_URL; + : env.DEFAULT_CONTROL_PLANE_PROXY_URL; if (!controlPlaneProxyUrl.endsWith("/")) { controlPlaneProxyUrl += "/"; diff --git a/core/config/sharedConfig.ts b/core/config/sharedConfig.ts new file mode 100644 index 000000000..9f2335243 --- /dev/null +++ b/core/config/sharedConfig.ts @@ -0,0 +1,162 @@ +import z from "zod"; +import { + BrowserSerializedContinueConfig, + ContinueConfig, + Config, + SerializedContinueConfig, +} from ".."; + +export const sharedConfigSchema = z + .object({ + allowAnonymousTelemetry: z.boolean(), + disableIndexing: z.boolean(), + disableSessionTitles: z.boolean(), + + // `experimental` in `ContinueConfig` + useChromiumForDocsCrawling: z.boolean(), + readResponseTTS: z.boolean(), + promptPath: z.string(), + + // `ui` in `ContinueConfig` + codeBlockToolbarPosition: z.enum(["top", "bottom"]), + fontSize: z.number(), + codeWrap: z.boolean(), + displayRawMarkdown: z.boolean(), + showChatScrollbar: z.boolean(), + + // `tabAutocompleteOptions` in `ContinueConfig` + useAutocompleteCache: z.boolean(), + useAutocompleteMultilineCompletions: z.enum(["always", "never", "auto"]), + disableAutocompleteInFiles: z.array(z.string()), + }) + .partial(); + +export type SharedConfigSchema = z.infer; + +// For security in case of damaged config file, try to salvage any security-related values +export function salvageSharedConfig(sharedConfig: object): SharedConfigSchema { + const salvagedConfig: SharedConfigSchema = {}; + if ("allowAnonymousTelemetry" in sharedConfig) { + const val = z.boolean().safeParse(sharedConfig.allowAnonymousTelemetry); + if (val.success) { + salvagedConfig.allowAnonymousTelemetry = val.data; + } + } + if ("disableIndexing" in sharedConfig) { + const val = z.boolean().safeParse(sharedConfig.disableIndexing); + if (val.success) { + salvagedConfig.disableIndexing = val.data; + } + } + if ("disableSessionTitles" in sharedConfig) { + const val = z.boolean().safeParse(sharedConfig.disableSessionTitles); + if (val.success) { + salvagedConfig.disableSessionTitles = val.data; + } + } + if ("disableAutocompleteInFiles" in sharedConfig) { + const val = sharedConfigSchema.shape.disableAutocompleteInFiles.safeParse( + sharedConfig.disableAutocompleteInFiles, + ); + if (val.success) { + salvagedConfig.disableAutocompleteInFiles = val.data; + } + } + return salvagedConfig; +} + +export function modifyContinueConfigWithSharedConfig< + T extends + | ContinueConfig + | BrowserSerializedContinueConfig + | Config + | SerializedContinueConfig, +>(continueConfig: T, sharedConfig: SharedConfigSchema): T { + const configCopy = { ...continueConfig }; + configCopy.tabAutocompleteOptions = { + ...configCopy.tabAutocompleteOptions, + }; + if (sharedConfig.useAutocompleteCache !== undefined) { + configCopy.tabAutocompleteOptions.useCache = + sharedConfig.useAutocompleteCache; + } + if (sharedConfig.useAutocompleteMultilineCompletions !== undefined) { + configCopy.tabAutocompleteOptions.multilineCompletions = + sharedConfig.useAutocompleteMultilineCompletions; + } + if (sharedConfig.disableAutocompleteInFiles !== undefined) { + configCopy.tabAutocompleteOptions.disableInFiles = + sharedConfig.disableAutocompleteInFiles; + } + + configCopy.ui = { + ...configCopy.ui, + }; + if (sharedConfig.codeBlockToolbarPosition !== undefined) { + configCopy.ui.codeBlockToolbarPosition = + sharedConfig.codeBlockToolbarPosition; + } + if (sharedConfig.fontSize !== undefined) { + configCopy.ui.fontSize = sharedConfig.fontSize; + } + if (sharedConfig.codeWrap !== undefined) { + configCopy.ui.codeWrap = sharedConfig.codeWrap; + } + if (sharedConfig.displayRawMarkdown !== undefined) { + configCopy.ui.displayRawMarkdown = sharedConfig.displayRawMarkdown; + } + if (sharedConfig.showChatScrollbar !== undefined) { + configCopy.ui.showChatScrollbar = sharedConfig.showChatScrollbar; + } + + if (sharedConfig.allowAnonymousTelemetry !== undefined) { + configCopy.allowAnonymousTelemetry = sharedConfig.allowAnonymousTelemetry; + } + if (sharedConfig.disableIndexing !== undefined) { + configCopy.disableIndexing = sharedConfig.disableIndexing; + } + if (sharedConfig.disableSessionTitles !== undefined) { + configCopy.disableSessionTitles = sharedConfig.disableSessionTitles; + } + + configCopy.experimental = { + ...configCopy.experimental, + }; + if (sharedConfig.promptPath !== undefined) { + configCopy.experimental.promptPath = sharedConfig.promptPath; + } + if (sharedConfig.useChromiumForDocsCrawling !== undefined) { + configCopy.experimental.useChromiumForDocsCrawling = + sharedConfig.useChromiumForDocsCrawling; + } + if (sharedConfig.readResponseTTS !== undefined) { + configCopy.experimental.readResponseTTS = sharedConfig.readResponseTTS; + } + + return configCopy; +} + +// continueConfig.tabAutocompleteOptions = { +// ...continueConfig.tabAutocompleteOptions, +// useCache: sharedConfig.useAutocompleteCache, +// disableInFiles: sharedConfig.disableAutocompleteInFiles, +// multilineCompletions: sharedConfig.useAutocompleteMultilineCompletions, +// }; +// continueConfig.ui = { +// ...continueConfig.ui, +// codeBlockToolbarPosition: sharedConfig.codeBlockToolbarPosition, +// fontSize: sharedConfig.fontSize, +// codeWrap: sharedConfig.codeWrap, +// displayRawMarkdown: sharedConfig.displayRawMarkdown, +// showChatScrollbar: sharedConfig.showChatScrollbar, +// }; +// continueConfig.allowAnonymousTelemetry = sharedConfig.allowAnonymousTelemetry; +// continueConfig.disableIndexing = sharedConfig.disableIndexing; +// continueConfig.disableIndexing = sharedConfig.disableIndexing; +// continueConfig.disableSessionTitles = sharedConfig.disableSessionTitles; +// continueConfig.experimental = { +// ...continueConfig.experimental, +// useChromiumForDocsCrawling: sharedConfig.useChromiumForDocsCrawling, +// readResponseTTS: sharedConfig.readResponseTTS, +// promptPath: sharedConfig.promptPath, +// }; diff --git a/core/config/types.ts b/core/config/types.ts index aa1873894..384da0c8f 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -220,18 +220,10 @@ declare global { export interface SiteIndexingConfig { title: string; startUrl: string; - rootUrl?: string; maxDepth?: number; faviconUrl?: string; } - export interface SiteIndexingConfig { - startUrl: string; - rootUrl?: string; - title: string; - maxDepth?: number; - } - export interface IContextProvider { get description(): ContextProviderDescription; @@ -580,7 +572,6 @@ declare global { userToken: string; enableControlServerBeta: boolean; pauseCodebaseIndexOnStart: boolean; - enableDebugLogs: boolean; } export interface IDE { @@ -910,7 +901,6 @@ declare global { export interface TabAutocompleteOptions { disable: boolean; - useFileSuffix: boolean; maxPromptTokens: number; debounceDelay: number; maxSuffixPercentage: number; @@ -955,7 +945,6 @@ declare global { fontSize?: number; displayRawMarkdown?: boolean; showChatScrollbar?: boolean; - getChatTitles?: boolean; codeWrap?: boolean; } diff --git a/core/config/validation.ts b/core/config/validation.ts index e10b3f523..d28bb7809 100644 --- a/core/config/validation.ts +++ b/core/config/validation.ts @@ -1,11 +1,7 @@ +import { ConfigValidationError } from "@continuedev/config-yaml"; import { ModelDescription, SerializedContinueConfig } from "../"; import { Telemetry } from "../util/posthog"; -export interface ConfigValidationError { - fatal: boolean; - message: string; -} - /** * Validates a SerializedContinueConfig object to ensure all properties are correctly formed. * @param config The configuration object to validate. diff --git a/core/config/yaml/clientRender.ts b/core/config/yaml/clientRender.ts new file mode 100644 index 000000000..8cb727456 --- /dev/null +++ b/core/config/yaml/clientRender.ts @@ -0,0 +1,40 @@ +import { + clientRender, + PlatformClient, + SecretStore, +} from "@continuedev/config-yaml"; + +import { IDE } from "../.."; +import { ControlPlaneClient } from "../../control-plane/client"; + +export async function clientRenderHelper( + unrolledAssistant: string, + ide: IDE, + controlPlaneClient: ControlPlaneClient, +) { + const ideSecretStore: SecretStore = { + get: async function (secretName: string): Promise { + const results = await ide.readSecrets([secretName]); + return results[secretName]; + }, + set: async function ( + secretName: string, + secretValue: string, + ): Promise { + return await ide.writeSecrets({ + [secretName]: secretValue, + }); + }, + }; + + const platformClient: PlatformClient = { + resolveFQSNs: controlPlaneClient.resolveFQSNs.bind(controlPlaneClient), + }; + + const userId = await controlPlaneClient.userId; + return await clientRender( + unrolledAssistant, + ideSecretStore, + userId ? platformClient : undefined, + ); +} diff --git a/core/config/yaml/convertFromJson.ts b/core/config/yaml/convertFromJson.ts index 59482b5c3..576e196c8 100644 --- a/core/config/yaml/convertFromJson.ts +++ b/core/config/yaml/convertFromJson.ts @@ -1,13 +1,14 @@ import { ModelConfig } from "@continuedev/config-yaml"; -import { ConfigYaml } from "@continuedev/config-yaml/dist/schemas"; +import { AssistantUnrolled } from "@continuedev/config-yaml/dist/schemas"; import { SerializedContinueConfig } from "../.."; export function convertConfigJsonToConfigYaml( configJson: SerializedContinueConfig, -): ConfigYaml { +): AssistantUnrolled { return { name: "Local Config", + version: "1.0.0", models: [ ...configJson.models.map( (model): ModelConfig => ({ @@ -23,8 +24,8 @@ export function convertConfigJsonToConfigYaml( // rerankModels ], context: configJson.contextProviders?.map((provider) => ({ - uses: provider.name, - with: provider.params, + provider: provider.name, + params: provider.params, })), }; } diff --git a/core/config/yaml/default.ts b/core/config/yaml/default.ts index f991561df..0bc872f88 100644 --- a/core/config/yaml/default.ts +++ b/core/config/yaml/default.ts @@ -1,14 +1,16 @@ -import { ConfigYaml } from "@continuedev/config-yaml/dist/schemas"; +import { AssistantUnrolled } from "@continuedev/config-yaml/dist/schemas"; // TODO -export const defaultConfigYaml: ConfigYaml = { +export const defaultConfigYaml: AssistantUnrolled = { models: [], context: [], name: "Local Config", + version: "1.0.0", }; -export const defaultConfigYamlJetBrains: ConfigYaml = { +export const defaultConfigYamlJetBrains: AssistantUnrolled = { models: [], context: [], name: "Local Config", + version: "1.0.0", }; diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index ad33ea4d8..9503c0865 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -1,15 +1,11 @@ import fs from "node:fs"; -import path from "path"; import { - extendConfig, - fillTemplateVariables, + AssistantUnrolled, + ConfigResult, validateConfigYaml, } from "@continuedev/config-yaml"; -import { ConfigYaml } from "@continuedev/config-yaml/dist/schemas"; -import { ValidationLevel } from "@continuedev/config-yaml/dist/validation"; import { fetchwithRequestOptions } from "@continuedev/fetch"; -import * as YAML from "yaml"; import { BrowserSerializedContinueConfig, @@ -22,74 +18,53 @@ import { } from "../.."; import { AllRerankers } from "../../context/allRerankers"; import { MCPManagerSingleton } from "../../context/mcp"; +import CodebaseContextProvider from "../../context/providers/CodebaseContextProvider"; +import FileContextProvider from "../../context/providers/FileContextProvider"; import { contextProviderClassFromName } from "../../context/providers/index"; +import PromptFilesContextProvider from "../../context/providers/PromptFilesContextProvider"; +import { ControlPlaneClient } from "../../control-plane/client"; import { allEmbeddingsProviders } from "../../indexing/allEmbeddingsProviders"; import FreeTrial from "../../llm/llms/FreeTrial"; import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider"; -import { - getConfigYamlPath, - getContinueDotEnv, - readAllGlobalPromptFiles, -} from "../../util/paths"; -import { getSystemPromptDotFile } from "../getSystemPromptDotFile"; -import { ConfigValidationError } from "../validation.js"; - -import { llmsFromModelConfig } from "./models"; -import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles"; import { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandFromPromptFile"; +import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles"; +import { getConfigYamlPath } from "../../util/paths"; +import { getSystemPromptDotFile } from "../getSystemPromptDotFile"; +import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader"; -export interface ConfigResult { - config: T | undefined; - errors: ConfigValidationError[] | undefined; - configLoadInterrupted: boolean; -} +import { slashFromCustomCommand } from "../../commands"; +import { allTools } from "../../tools"; +import { clientRenderHelper } from "./clientRender"; +import { llmsFromModelConfig } from "./models"; +import { GlobalContext } from "../../util/GlobalContext"; +import { modifyContinueConfigWithSharedConfig } from "../sharedConfig"; -function renderTemplateVars(configYaml: string): string { - const data: Record = {}; - - // env.* - const envVars = getContinueDotEnv(); - Object.entries(envVars).forEach(([key, value]) => { - data[`env.${key}`] = value; - }); - - // secrets.* not filled in - - return fillTemplateVariables(configYaml, data); -} - -function loadConfigYaml( +async function loadConfigYaml( workspaceConfigs: string[], - ideSettings: IdeSettings, - ideType: IdeType, rawYaml: string, -): ConfigResult { - const renderedYaml = renderTemplateVars(rawYaml); - let config = YAML.parse(renderedYaml) as ConfigYaml; + overrideConfigYaml: AssistantUnrolled | undefined, + ide: IDE, + controlPlaneClient: ControlPlaneClient, +): Promise> { + let config = + overrideConfigYaml ?? + (await clientRenderHelper(rawYaml, ide, controlPlaneClient)); const errors = validateConfigYaml(config); - if (errors?.some((error) => error.level === ValidationLevel.Error)) { + if (errors?.some((error) => error.fatal)) { return { - errors: errors.map((error) => ({ - message: error.message, - fatal: error.level === ValidationLevel.Error, - })), + errors, config: undefined, configLoadInterrupted: true, }; } - for (const workspaceConfig of workspaceConfigs) { - const rendered = renderTemplateVars(workspaceConfig); - config = extendConfig(config, YAML.parse(rendered) as ConfigYaml); - } - // Set defaults if undefined (this lets us keep config.json uncluttered for new users) return { config, errors: errors.map((error) => ({ message: error.message, - fatal: error.level === ValidationLevel.Error, + fatal: error.fatal, })), configLoadInterrupted: false, }; @@ -113,23 +88,42 @@ async function slashCommandsFromV1PromptFiles( } async function configYamlToContinueConfig( - config: ConfigYaml, + config: AssistantUnrolled, ide: IDE, ideSettings: IdeSettings, uniqueId: string, writeLog: (log: string) => Promise, workOsAccessToken: string | undefined, + platformConfigMetadata: PlatformConfigMetadata | undefined, allowFreeTrial: boolean = true, ): Promise { const continueConfig: ContinueConfig = { - slashCommands: await slashCommandsFromV1PromptFiles(ide), + slashCommands: [ + ...(await slashCommandsFromV1PromptFiles(ide)), + ...(config.prompts?.map(slashFromCustomCommand) ?? []), + ], models: [], tabAutocompleteModels: [], - tools: [], + tools: allTools, + systemMessage: config.rules?.join("\n"), embeddingsProvider: new TransformersJsEmbeddingsProvider(), experimental: { - modelContextProtocolServers: [], + modelContextProtocolServers: config.mcpServers?.map((mcpServer) => ({ + transport: { + type: "stdio", + command: mcpServer.command, + args: mcpServer.args ?? [], + env: mcpServer.env, + }, + })), }, + docs: config.docs?.map((doc) => ({ + title: doc.name, + startUrl: doc.startUrl, + rootUrl: doc.rootUrl, + faviconUrl: doc.faviconUrl, + })), + contextProviders: [], }; // Models @@ -146,9 +140,13 @@ async function configYamlToContinueConfig( uniqueId, ideSettings, writeLog, + platformConfigMetadata, + continueConfig.systemMessage, ); continueConfig.models.push(...llms); - } else if (model.roles?.includes("autocomplete")) { + } + + if (model.roles?.includes("autocomplete")) { // Autocomplete models array const llms = await llmsFromModelConfig( model, @@ -156,6 +154,8 @@ async function configYamlToContinueConfig( uniqueId, ideSettings, writeLog, + platformConfigMetadata, + continueConfig.systemMessage, ); continueConfig.tabAutocompleteModels?.push(...llms); } @@ -181,18 +181,34 @@ async function configYamlToContinueConfig( // TODO: Split into model roles. - // Context - continueConfig.contextProviders = config.context + // Context providers + const codebaseContextParams: IContextProvider[] = + (config.context || []).find((cp) => cp.provider === "codebase")?.params || + {}; + const DEFAULT_CONTEXT_PROVIDERS = [ + new FileContextProvider({}), + new CodebaseContextProvider(codebaseContextParams), + new PromptFilesContextProvider({}), + ]; + + const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map( + ({ description: { title } }) => title, + ); + + continueConfig.contextProviders = (config.context ?.map((context) => { - const cls = contextProviderClassFromName(context.uses) as any; + const cls = contextProviderClassFromName(context.provider) as any; if (!cls) { - console.warn(`Unknown context provider ${context.uses}`); + if (!DEFAULT_CONTEXT_PROVIDERS_TITLES.includes(context.provider)) { + console.warn(`Unknown context provider ${context.provider}`); + } return undefined; } - const instance: IContextProvider = new cls(context.with ?? {}); + const instance: IContextProvider = new cls(context.params ?? {}); return instance; }) - .filter((p) => !!p) as IContextProvider[]; + .filter((p) => !!p) ?? []) as IContextProvider[]; + continueConfig.contextProviders.push(...DEFAULT_CONTEXT_PROVIDERS); // Embeddings Provider const embedConfig = config.models?.find((model) => @@ -283,16 +299,21 @@ export async function loadContinueConfigFromYaml( uniqueId: string, writeLog: (log: string) => Promise, workOsAccessToken: string | undefined, - overrideConfigYaml: string | undefined, + overrideConfigYaml: AssistantUnrolled | undefined, + platformConfigMetadata: PlatformConfigMetadata | undefined, + controlPlaneClient: ControlPlaneClient, ): Promise> { - const configYamlPath = getConfigYamlPath(ideType); - const rawYaml = fs.readFileSync(configYamlPath, "utf-8"); + const rawYaml = + overrideConfigYaml === undefined + ? fs.readFileSync(getConfigYamlPath(ideType), "utf-8") + : ""; const configYamlResult = await loadConfigYaml( workspaceConfigs, - ideSettings, - ideType, - overrideConfigYaml ?? rawYaml, + rawYaml, + overrideConfigYaml, + ide, + controlPlaneClient, ); if (!configYamlResult.config || configYamlResult.configLoadInterrupted) { @@ -310,6 +331,7 @@ export async function loadContinueConfigFromYaml( uniqueId, writeLog, workOsAccessToken, + platformConfigMetadata, ); const systemPromptDotFile = await getSystemPromptDotFile(ide); @@ -321,8 +343,16 @@ export async function loadContinueConfigFromYaml( } } + // Apply shared config + // TODO: override several of these values with user/org shared config + const sharedConfig = new GlobalContext().getSharedConfig(); + const withShared = modifyContinueConfigWithSharedConfig( + continueConfig, + sharedConfig, + ); + return { - config: continueConfig, + config: withShared, errors: configYamlResult.errors, configLoadInterrupted: false, }; diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index d6eb6d3e0..8fe34677f 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -3,21 +3,47 @@ import { ModelConfig } from "@continuedev/config-yaml"; import { IDE, IdeSettings, LLMOptions } from "../.."; import { BaseLLM } from "../../llm"; import { LLMClasses } from "../../llm/llms"; +import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader"; const AUTODETECT = "AUTODETECT"; +function getModelClass( + model: ModelConfig, +): (typeof LLMClasses)[number] | undefined { + return LLMClasses.find((llm) => llm.providerName === model.provider); +} + +function getContinueProxyModelName( + ownerSlug: string, + packageSlug: string, + model: ModelConfig, +): string { + return `${ownerSlug}/${packageSlug}/${model.provider}/${model.model}`; +} + async function modelConfigToBaseLLM( model: ModelConfig, uniqueId: string, ideSettings: IdeSettings, writeLog: (log: string) => Promise, + platformConfigMetadata: PlatformConfigMetadata | undefined, + systemMessage: string | undefined, ): Promise { - const cls = LLMClasses.find((llm) => llm.providerName === model.provider); + const cls = getModelClass(model); if (!cls) { return undefined; } + const usingContinueProxy = model.provider === "continue-proxy"; + const modelName = usingContinueProxy + ? getContinueProxyModelName( + platformConfigMetadata!.ownerSlug, + platformConfigMetadata!.packageSlug, + model, + ) + : model.model; + let options: LLMOptions = { ...model, completionOptions: { @@ -30,6 +56,8 @@ async function modelConfigToBaseLLM( writeLog, uniqueId, title: model.name, + model: modelName, + systemMessage, }; const llm = new cls(options); @@ -43,6 +71,8 @@ async function autodetectModels( uniqueId: string, ideSettings: IdeSettings, writeLog: (log: string) => Promise, + platformConfigMetadata: PlatformConfigMetadata | undefined, + systemMessage: string | undefined, ): Promise { try { const modelNames = await llm.listModels(); @@ -62,6 +92,8 @@ async function autodetectModels( uniqueId, ideSettings, writeLog, + platformConfigMetadata, + systemMessage, ); }), ); @@ -78,12 +110,16 @@ export async function llmsFromModelConfig( uniqueId: string, ideSettings: IdeSettings, writeLog: (log: string) => Promise, + platformConfigMetadata: PlatformConfigMetadata | undefined, + systemMessage: string | undefined, ): Promise { const baseLlm = await modelConfigToBaseLLM( model, uniqueId, ideSettings, writeLog, + platformConfigMetadata, + systemMessage, ); if (!baseLlm) { return []; @@ -97,6 +133,8 @@ export async function llmsFromModelConfig( uniqueId, ideSettings, writeLog, + platformConfigMetadata, + systemMessage, ); return models; } else { diff --git a/core/context/mcp/index.ts b/core/context/mcp/index.ts index 26be2f471..304c2a8c4 100644 --- a/core/context/mcp/index.ts +++ b/core/context/mcp/index.ts @@ -4,9 +4,9 @@ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js" import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js"; import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; +import { ConfigValidationError } from "@continuedev/config-yaml"; import { ContinueConfig, MCPOptions, SlashCommand, Tool } from "../.."; import { constructMcpSlashCommand } from "../../commands/slash/mcp"; -import { ConfigValidationError } from "../../config/validation"; import { encodeMCPToolUri } from "../../tools/callTool"; import MCPContextProvider from "../providers/MCPContextProvider"; diff --git a/core/context/providers/ContinueProxyContextProvider.ts b/core/context/providers/ContinueProxyContextProvider.ts index 2dcb91cc8..278a12678 100644 --- a/core/context/providers/ContinueProxyContextProvider.ts +++ b/core/context/providers/ContinueProxyContextProvider.ts @@ -1,4 +1,4 @@ -import { controlPlaneEnv } from "../../control-plane/env.js"; +import { getControlPlaneEnv } from "../../control-plane/env.js"; import { ContextItem, ContextProviderDescription, @@ -35,11 +35,9 @@ class ContinueProxyContextProvider extends BaseContextProvider { async loadSubmenuItems( args: LoadSubmenuItemsArgs, ): Promise { + const env = await getControlPlaneEnv(args.ide.getIdeSettings()); const response = await args.fetch( - new URL( - `/proxy/context/${this.options.id}/list`, - controlPlaneEnv.CONTROL_PLANE_URL, - ), + new URL(`/proxy/context/${this.options.id}/list`, env.CONTROL_PLANE_URL), { method: "GET", headers: { @@ -56,10 +54,11 @@ class ContinueProxyContextProvider extends BaseContextProvider { query: string, extras: ContextProviderExtras, ): Promise { + const env = await getControlPlaneEnv(extras.ide.getIdeSettings()); const response = await extras.fetch( new URL( `/proxy/context/${this.options.id}/retrieve`, - controlPlaneEnv.CONTROL_PLANE_URL, + env.CONTROL_PLANE_URL, ), { method: "POST", diff --git a/core/context/providers/DocsContextProvider.ts b/core/context/providers/DocsContextProvider.ts index 00e193354..cb8e926d5 100644 --- a/core/context/providers/DocsContextProvider.ts +++ b/core/context/providers/DocsContextProvider.ts @@ -20,10 +20,16 @@ class DocsContextProvider extends BaseContextProvider { displayTitle: "Docs", description: "Type to search docs", type: "submenu", + // Todo: consider a different renderInline so that when multiple docs are referenced in one message, + // Or the doc has an odd name unrelated to the content + // The name of the doc itself doesn't skew the embedding results + // renderInlineAs: "", }; constructor(options: any) { super(options); + const docsService = DocsService.getSingleton(); + docsService?.setGithubToken(this.options?.githubToken); } private async _rerankChunks( @@ -80,6 +86,7 @@ class DocsContextProvider extends BaseContextProvider { query: string, extras: ContextProviderExtras, ): Promise { + const nRetrieve = this.options?.nRetrieve ?? DocsContextProvider.nRetrieve; const useReranking = this.options?.useReranking ?? true; // Get docs service @@ -94,7 +101,7 @@ class DocsContextProvider extends BaseContextProvider { let chunks = await docsService.retrieveChunksFromQuery( extras.fullInput, // confusing: fullInput = the query, query = startUrl in this case query, - this.options?.nRetrieve ?? DocsContextProvider.nRetrieve, + nRetrieve, ); if (!chunks?.length) { return []; @@ -173,6 +180,10 @@ class DocsContextProvider extends BaseContextProvider { const canUsePreindexedDocs = await docsService.canUsePreindexedDocs(); if (canUsePreindexedDocs) { for (const { startUrl, title } of Object.values(preIndexedDocs)) { + // Skip if overridden in config + if (docs.find((d) => d.startUrl === startUrl)) { + continue; + } submenuItemsMap.set(startUrl, { title, id: startUrl, diff --git a/core/context/providers/RepoMapContextProvider.ts b/core/context/providers/RepoMapContextProvider.ts index 0805d341e..deabfe590 100644 --- a/core/context/providers/RepoMapContextProvider.ts +++ b/core/context/providers/RepoMapContextProvider.ts @@ -41,7 +41,7 @@ class RepoMapContextProvider extends BaseContextProvider { // Doesn't ALWAYS depend on indexing, so not setting dependsOnIndexing = true, just checking for it includeSignatures: extras.config.disableIndexing ? false - : (this.options?.includeSignatures ?? false), + : (this.options?.includeSignatures ?? true), }), }, ]; diff --git a/core/context/providers/_context-providers.test.ts b/core/context/providers/_context-providers.test.ts index 24cac2c44..22f1dffbc 100644 --- a/core/context/providers/_context-providers.test.ts +++ b/core/context/providers/_context-providers.test.ts @@ -31,7 +31,7 @@ async function getContextProviderExtras( ide, ideSettingsPromise, async (text) => {}, - new ControlPlaneClient(Promise.resolve(undefined)), + new ControlPlaneClient(Promise.resolve(undefined), ideSettingsPromise), ); const { config } = await configHandler.loadConfig(); if (!config) { diff --git a/core/continueServer/interface.ts b/core/continueServer/interface.ts index 3c67aa25e..c6e7ceda2 100644 --- a/core/continueServer/interface.ts +++ b/core/continueServer/interface.ts @@ -22,7 +22,7 @@ export interface IContinueServerClient { connected: boolean; url: URL | undefined; getUserToken(): string | undefined; - getConfig(): Promise<{ configJson: string; configJs: string }>; + getConfig(): Promise<{ configJson: string }>; getFromIndexCache( keys: string[], artifactId: T, diff --git a/core/continueServer/stubs/client.ts b/core/continueServer/stubs/client.ts index 49f02fb65..febed8bbd 100644 --- a/core/continueServer/stubs/client.ts +++ b/core/continueServer/stubs/client.ts @@ -30,7 +30,7 @@ export class ContinueServerClient implements IContinueServerClient { return this.url !== undefined && this.userToken !== undefined; } - public async getConfig(): Promise<{ configJson: string; configJs: string }> { + public async getConfig(): Promise<{ configJson: string }> { const userToken = await this.userToken; const response = await fetch(new URL("sync", this.url).href, { method: "GET", diff --git a/core/control-plane/auth/index.ts b/core/control-plane/auth/index.ts index ecb6221c7..8965f4fdb 100644 --- a/core/control-plane/auth/index.ts +++ b/core/control-plane/auth/index.ts @@ -1,14 +1,16 @@ import { v4 as uuidv4 } from "uuid"; +import { IdeSettings } from "../.."; +import { getControlPlaneEnv } from "../env"; -const CLIENT_ID = "client_01J0FW6XN8N2XJAECF7NE0Y65J"; -// const CLIENT_ID = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ"; // Staging - -export async function getAuthUrlForTokenPage(): Promise { +export async function getAuthUrlForTokenPage( + ideSettingsPromise: Promise, +): Promise { + const env = await getControlPlaneEnv(ideSettingsPromise); const url = new URL("https://api.workos.com/user_management/authorize"); const params = { response_type: "code", - client_id: CLIENT_ID, - redirect_uri: "https://app.continue.dev/tokens/callback", + client_id: env.WORKOS_CLIENT_ID, + redirect_uri: `${env.APP_URL}tokens/callback`, // redirect_uri: "http://localhost:3000/tokens/callback", state: uuidv4(), provider: "authkit", diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index b84e24570..6200bc8de 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -1,9 +1,16 @@ import { ConfigJson } from "@continuedev/config-types"; import fetch, { RequestInit, Response } from "node-fetch"; -import { ModelDescription } from "../index.js"; +import { IdeSettings, ModelDescription } from "../index.js"; -import { controlPlaneEnv } from "./env.js"; +import { + AssistantUnrolled, + ConfigResult, + FQSN, + FullSlug, + SecretResult, +} from "@continuedev/config-yaml"; +import { getControlPlaneEnv } from "./env.js"; export interface ControlPlaneSessionInfo { accessToken: string; @@ -25,7 +32,6 @@ export const TRIAL_PROXY_URL = "https://proxy-server-blue-l6vsfbzhba-uw.a.run.app"; export class ControlPlaneClient { - private static URL = controlPlaneEnv.CONTROL_PLANE_URL; private static ACCESS_TOKEN_VALID_FOR_MS = 1000 * 60 * 5; // 5 minutes private lastAccessTokenRefresh = 0; @@ -34,8 +40,22 @@ export class ControlPlaneClient { private readonly sessionInfoPromise: Promise< ControlPlaneSessionInfo | undefined >, + private readonly ideSettingsPromise: Promise, ) {} + async resolveFQSNs(fqsns: FQSN[]): Promise<(SecretResult | undefined)[]> { + const userId = await this.userId; + if (!userId) { + throw new Error("No user id"); + } + + const resp = await this.request("ide/sync-secrets", { + method: "POST", + body: JSON.stringify({ fqsns }), + }); + return (await resp.json()) as any; + } + get userId(): Promise { return this.sessionInfoPromise.then( (sessionInfo) => sessionInfo?.account.id, @@ -51,7 +71,9 @@ export class ControlPlaneClient { if (!accessToken) { throw new Error("No access token"); } - const url = new URL(path, ControlPlaneClient.URL).toString(); + + const env = await getControlPlaneEnv(this.ideSettingsPromise); + const url = new URL(path, env.CONTROL_PLANE_URL).toString(); const resp = await fetch(url, { ...init, headers: { @@ -85,6 +107,46 @@ export class ControlPlaneClient { } } + public async listAssistants(): Promise< + { + configResult: ConfigResult; + ownerSlug: string; + packageSlug: string; + iconUrl: string; + }[] + > { + const userId = await this.userId; + if (!userId) { + return []; + } + + try { + const resp = await this.request("ide/list-assistants", { + method: "GET", + }); + return (await resp.json()) as any; + } catch (e) { + return []; + } + } + + public async listAssistantFullSlugs(): Promise { + const userId = await this.userId; + if (!userId) { + return null; + } + + try { + const resp = await this.request("ide/list-assistant-full-slugs", { + method: "GET", + }); + const { fullSlugs } = (await resp.json()) as any; + return fullSlugs; + } catch (e) { + return null; + } + } + async getSettingsForWorkspace(workspaceId: string): Promise { const userId = await this.userId; if (!userId) { @@ -96,4 +158,21 @@ export class ControlPlaneClient { }); return ((await resp.json()) as any).settings; } + + async syncSecrets(secretNames: string[]): Promise> { + const userId = await this.userId; + if (!userId) { + throw new Error("No user id"); + } + + try { + const resp = await this.request("ide/sync-secrets", { + method: "POST", + body: JSON.stringify({ secretNames }), + }); + return (await resp.json()) as any; + } catch (e) { + return {}; + } + } } diff --git a/core/control-plane/env.ts b/core/control-plane/env.ts index 4556ce90f..8f5bb40a4 100644 --- a/core/control-plane/env.ts +++ b/core/control-plane/env.ts @@ -1,4 +1,6 @@ -interface ControlPlaneEnv { +import { IdeSettings } from ".."; + +export interface ControlPlaneEnv { DEFAULT_CONTROL_PLANE_PROXY_URL: string; CONTROL_PLANE_URL: string; AUTH_TYPE: string; @@ -21,7 +23,15 @@ const PRODUCTION_ENV: ControlPlaneEnv = { "https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/", AUTH_TYPE: WORKOS_ENV_ID_PRODUCTION, WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_PRODUCTION, - APP_URL: "https://app.continue.dev", + APP_URL: "https://app.continue.dev/", +}; + +const PRODUCTION_HUB_ENV: ControlPlaneEnv = { + DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api.continue.dev/", + CONTROL_PLANE_URL: "https://api.continue.dev/", + AUTH_TYPE: WORKOS_ENV_ID_PRODUCTION, + WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_PRODUCTION, + APP_URL: "https://hub.continue.dev/", }; const STAGING_ENV: ControlPlaneEnv = { @@ -31,7 +41,15 @@ const STAGING_ENV: ControlPlaneEnv = { "https://control-plane-api-service-537175798139.us-central1.run.app/", AUTH_TYPE: WORKOS_CLIENT_ID_STAGING, WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING, - APP_URL: "https://app-preview.continue.dev", + APP_URL: "https://app-preview.continue.dev/", +}; + +const TEST_ENV: ControlPlaneEnv = { + DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api-test.continue.dev/", + CONTROL_PLANE_URL: "https://api-test.continue.dev/", + AUTH_TYPE: WORKOS_ENV_ID_STAGING, + WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING, + APP_URL: "https://app-test.continue.dev/", }; const LOCAL_ENV: ControlPlaneEnv = { @@ -39,12 +57,42 @@ const LOCAL_ENV: ControlPlaneEnv = { CONTROL_PLANE_URL: "http://localhost:3001/", AUTH_TYPE: WORKOS_ENV_ID_STAGING, WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING, - APP_URL: "http://localhost:3000", + APP_URL: "http://localhost:3000/", }; -export const controlPlaneEnv = - process.env.CONTROL_PLANE_ENV === "local" +export async function getControlPlaneEnv( + ideSettingsPromise: Promise, +): Promise { + const ideSettings = await ideSettingsPromise; + return getControlPlaneEnvSync(ideSettings.continueTestEnvironment); +} + +export function getControlPlaneEnvSync( + ideTestEnvironment: IdeSettings["continueTestEnvironment"], +): ControlPlaneEnv { + const env = + ideTestEnvironment === "production" + ? "hub" + : ideTestEnvironment === "test" + ? "test" + : ideTestEnvironment === "local" + ? "local" + : process.env.CONTROL_PLANE_ENV; + + return env === "local" ? LOCAL_ENV - : process.env.CONTROL_PLANE_ENV === "staging" + : env === "staging" ? STAGING_ENV - : PRODUCTION_ENV; + : env === "test" + ? TEST_ENV + : env === "hub" + ? PRODUCTION_HUB_ENV + : PRODUCTION_ENV; +} + +export async function useHub( + ideSettingsPromise: Promise, +): Promise { + const ideSettings = await ideSettingsPromise; + return ideSettings.continueTestEnvironment !== "none"; +} diff --git a/core/core.ts b/core/core.ts index 7316f9aac..ff334c140 100644 --- a/core/core.ts +++ b/core/core.ts @@ -43,8 +43,16 @@ import { Telemetry } from "./util/posthog"; import { getSymbolsForManyFiles } from "./util/treeSitter"; import { TTS } from "./util/tts"; -import { type ContextItemId, type IDE, type IndexingProgressUpdate } from "."; +import { + ChatMessage, + DiffLine, + PromptLog, + type ContextItemId, + type IDE, + type IndexingProgressUpdate, +} from "."; +import { getControlPlaneEnv } from "./control-plane/env"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./protocol/messenger"; @@ -103,9 +111,13 @@ export class Core { const ideSettingsPromise = messenger.request("getIdeSettings", undefined); const sessionInfoPromise = messenger.request("getControlPlaneSessionInfo", { silent: true, + useOnboarding: false, }); - this.controlPlaneClient = new ControlPlaneClient(sessionInfoPromise); + this.controlPlaneClient = new ControlPlaneClient( + sessionInfoPromise, + ideSettingsPromise, + ); this.configHandler = new ConfigHandler( this.ide, @@ -124,7 +136,7 @@ export class Core { const serializedResult = await this.configHandler.getSerializedConfig(); this.messenger.send("configUpdate", { result: serializedResult, - profileId: this.configHandler.currentProfile.profileId, + profileId: this.configHandler.currentProfile.profileDescription.id, }); }); @@ -277,6 +289,7 @@ export class Core { on("config/ideSettingsUpdate", (msg) => { this.configHandler.updateIdeSettings(msg.data); }); + on("config/listProfiles", (msg) => { return this.configHandler.listProfiles(); }); @@ -285,6 +298,16 @@ export class Core { addContextProvider(msg.data); }); + on("config/updateSharedConfig", async (msg) => { + this.globalContext.updateSharedConfig(msg.data); + await this.configHandler.reloadConfig(); + }); + + on("controlPlane/openUrl", async (msg) => { + const env = await getControlPlaneEnv(this.ide.getIdeSettings()); + await this.messenger.request("openUrl", `${env.APP_URL}${msg.data.path}`); + }); + // Context providers on("context/addDocs", async (msg) => { void this.docsService.indexAndAdd(msg.data); @@ -378,7 +401,7 @@ export class Core { on("config/getSerializedProfileInfo", async (msg) => { return { result: await this.configHandler.getSerializedConfig(), - profileId: this.configHandler.currentProfile.profileId, + profileId: this.configHandler.currentProfile.profileDescription.id, }; }); @@ -395,7 +418,7 @@ export class Core { configHandler: ConfigHandler, abortedMessageIds: Set, msg: Message, - ) { + ): AsyncGenerator { const { config } = await configHandler.loadConfig(); if (!config) { throw new Error("Config not loaded"); @@ -431,7 +454,7 @@ export class Core { const chunk = next.value; - yield { content: chunk }; + yield chunk; next = await gen.next(); } @@ -448,7 +471,11 @@ export class Core { true, ); - return { done: true, content: next.value }; + if (!next.done) { + throw new Error("Will never happen"); + } + + return next.value; } on("llm/streamChat", (msg) => @@ -458,9 +485,8 @@ export class Core { async function* llmStreamComplete( configHandler: ConfigHandler, abortedMessageIds: Set, - msg: Message, - ) { + ): AsyncGenerator { const model = await configHandler.llmFromTitle(msg.data.title); const gen = model.streamComplete( msg.data.prompt, @@ -482,11 +508,13 @@ export class Core { }); break; } - yield { content: next.value }; + yield next.value; next = await gen.next(); } - - return { done: true, content: next.value }; + if (!next.done) { + throw new Error("This will never happen"); + } + return next.value; } on("llm/streamComplete", (msg) => @@ -548,7 +576,7 @@ export class Core { abortedMessageIds: Set, msg: Message, messenger: IMessenger, - ) { + ): AsyncGenerator { const { input, history, @@ -613,7 +641,7 @@ export class Core { break; } if (content) { - yield { content }; + yield content; } } } catch (e) { @@ -621,7 +649,6 @@ export class Core { } finally { clearInterval(checkActiveInterval); } - yield { done: true, content: "" }; } on("command/run", (msg) => runNodeJsSlashCommand( @@ -652,7 +679,7 @@ export class Core { configHandler: ConfigHandler, abortedMessageIds: Set, msg: Message, - ) { + ): AsyncGenerator { const data = msg.data; const llm = await configHandler.llmFromTitle(msg.data.modelTitle); for await (const diffLine of streamDiffLines( @@ -667,10 +694,8 @@ export class Core { abortedMessageIds.delete(msg.messageId); break; } - yield { content: diffLine }; + yield diffLine; } - - return { done: true }; } on("streamDiffLines", (msg) => @@ -844,6 +869,9 @@ export class Core { on("docs/initStatuses", async (msg) => { void this.docsService.initStatuses(); }); + on("docs/getDetails", async (msg) => { + return await this.docsService.getDetails(msg.data.startUrl); + }); // on("didChangeSelectedProfile", (msg) => { @@ -854,7 +882,7 @@ export class Core { this.configHandler.updateControlPlaneSessionInfo(msg.data.sessionInfo); }); on("auth/getAuthUrl", async (msg) => { - const url = await getAuthUrlForTokenPage(); + const url = await getAuthUrlForTokenPage(ideSettingsPromise); return { url }; }); diff --git a/core/index.d.ts b/core/index.d.ts index cd6510f19..f65c10622 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -223,16 +223,18 @@ export interface ContextSubmenuItemWithProvider extends ContextSubmenuItem { export interface SiteIndexingConfig { title: string; startUrl: string; - rootUrl?: string; maxDepth?: number; faviconUrl?: string; + useLocalCrawling?: boolean; + rootUrl?: string; // Currently only used by preindexed docs } -export interface SiteIndexingConfig { +export interface DocsIndexingDetails { startUrl: string; - rootUrl?: string; - title: string; - maxDepth?: number; + config: SiteIndexingConfig; + indexingStatus: IndexingStatus | undefined; + chunks: Chunk[]; + isPreIndexedDoc: boolean; } export interface IContextProvider { @@ -306,11 +308,17 @@ export interface CompletionOptions extends BaseCompletionOptions { export type ChatMessageRole = "user" | "assistant" | "system" | "tool"; -export interface MessagePart { - type: "text" | "imageUrl"; - text?: string; - imageUrl?: { url: string }; -} +export type TextMessagePart = { + type: "text"; + text: string; +}; + +export type ImageMessagePart = { + type: "imageUrl"; + imageUrl: { url: string }; +}; + +export type MessagePart = TextMessagePart | ImageMessagePart; export type MessageContent = string | MessagePart[]; @@ -425,6 +433,13 @@ interface ToolCallState { output?: ContextItem[]; } +interface Reasoning { + active: boolean; + text: string; + startAt: number; + endAt?: number; +} + export interface ChatHistoryItem { message: ChatMessage; contextItems: ContextItemWithId[]; @@ -435,6 +450,7 @@ export interface ChatHistoryItem { isGatheringContext?: boolean; checkpoint?: Checkpoint; isBeforeCheckpoint?: boolean; + reasoning?: Reasoning; } export interface LLMFullCompletionOptions extends BaseCompletionOptions { @@ -460,6 +476,7 @@ export interface LLMOptions { writeLog?: (str: string) => Promise; llmRequestHook?: (model: string, prompt: string) => any; apiKey?: string; + apiKeyLocation?: string; aiGatewaySlug?: string; apiBase?: string; cacheBehavior?: CacheBehavior; @@ -582,8 +599,8 @@ export interface IdeSettings { remoteConfigSyncPeriod: number; userToken: string; enableControlServerBeta: boolean; + continueTestEnvironment: "none" | "production" | "test" | "local"; pauseCodebaseIndexOnStart: boolean; - enableDebugLogs: boolean; } export interface FileStats { @@ -683,6 +700,11 @@ export interface IDE { getGitHubAuthToken(args: GetGhTokenArgs): Promise; + // Secret Storage + readSecrets(keys: string[]): Promise>; + + writeSecrets(secrets: { [key: string]: string }): Promise; + // LSP gotoDefinition(location: Location): Promise; @@ -820,7 +842,7 @@ export interface SlashCommandDescription { export interface CustomCommand { name: string; prompt: string; - description: string; + description?: string; } export interface Prediction { @@ -854,6 +876,13 @@ export interface Tool { uri?: string; } +interface ToolChoice { + type: "function"; + function: { + name: string; + }; +} + export interface BaseCompletionOptions { temperature?: number; topP?: number; @@ -871,6 +900,7 @@ export interface BaseCompletionOptions { stream?: boolean; prediction?: Prediction; tools?: Tool[]; + toolChoice?: ToolChoice; } export interface ModelCapability { @@ -882,6 +912,7 @@ export interface ModelDescription { provider: string; model: string; apiKey?: string; + apiKeyLocation?: string; apiBase?: string; contextLength?: number; maxStopWords?: number; @@ -925,7 +956,6 @@ export interface RerankerDescription { export interface TabAutocompleteOptions { disable: boolean; - useFileSuffix: boolean; maxPromptTokens: number; debounceDelay: number; maxSuffixPercentage: number; @@ -971,7 +1001,6 @@ export interface ContinueUIConfig { fontSize?: number; displayRawMarkdown?: boolean; showChatScrollbar?: boolean; - getChatTitles?: boolean; codeWrap?: boolean; } @@ -1198,6 +1227,8 @@ export interface BrowserSerializedContinueConfig { analytics?: AnalyticsConfig; docs?: SiteIndexingConfig[]; tools: Tool[]; + usePlatform: boolean; + tabAutocompleteOptions?: Partial; } // DOCS SUGGESTIONS AND PACKAGE INFO @@ -1235,9 +1266,9 @@ export type PackageDocsResult = { } & ( | { error: string; details?: never } | { details: PackageDetailsSuccess; error?: never } - ); +); export interface TerminalOptions { - reuseTerminal?: boolean, - terminalName?: string, + reuseTerminal?: boolean; + terminalName?: string; } diff --git a/core/indexing/CodebaseIndexer.test.ts b/core/indexing/CodebaseIndexer.test.ts index 211bc3732..517298597 100644 --- a/core/indexing/CodebaseIndexer.test.ts +++ b/core/indexing/CodebaseIndexer.test.ts @@ -14,12 +14,12 @@ import { } from "../test/testDir.js"; import { getIndexSqlitePath } from "../util/paths.js"; -import { pathToFileURL } from "node:url"; import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js"; import { getComputeDeleteAddRemove } from "./refreshIndex.js"; import { TestCodebaseIndex } from "./TestCodebaseIndex.js"; import { CodebaseIndex } from "./types.js"; import { walkDir } from "./walkDir.js"; +import { localPathToUri } from "../util/pathToUri.js"; jest.useFakeTimers(); @@ -159,7 +159,7 @@ describe("CodebaseIndexer", () => { test("should have created index folder with all necessary files", async () => { const exists = await testIde.fileExists( - pathToFileURL(getIndexSqlitePath()).toString(), + localPathToUri(getIndexSqlitePath()), ); expect(exists).toBe(true); }); diff --git a/core/indexing/docs/DocsCrawler.skip.ts b/core/indexing/docs/DocsCrawler.skip.ts deleted file mode 100644 index 93d1749c9..000000000 --- a/core/indexing/docs/DocsCrawler.skip.ts +++ /dev/null @@ -1,142 +0,0 @@ -import os from "os"; - -import { jest } from "@jest/globals"; - -import { ContinueConfig } from "../.."; -import { testConfigHandler } from "../../test/fixtures"; -import FileSystemIde from "../../util/filesystem"; - -import DocsCrawler, { ChromiumInstaller, type PageData } from "./DocsCrawler"; -import preIndexedDocs from "./preIndexedDocs"; - -// Temporary workaround until we have better caching of Chromium -// download between test runs -const TIMEOUT_MS = 1_000_000_000; - -// Overwrite the Chromium download path to `os.tmpdir()` -// so that we don't delete the Chromium install between tests -ChromiumInstaller.PCR_CONFIG = { downloadPath: os.tmpdir() }; - -// Skipped until we have a better way to cache Chromium installs -// between tests and in CI -describe.skip("DocsCrawler", () => { - const NUM_PAGES_TO_CRAWL = 5; - - let config: ContinueConfig; - let mockIde: FileSystemIde; - let chromiumInstaller; - let docsCrawler: DocsCrawler; - - beforeAll(async () => { - const result = await testConfigHandler.loadConfig(); - config = result.config!; - mockIde = new FileSystemIde(process.cwd()); - chromiumInstaller = new ChromiumInstaller(mockIde, config); - docsCrawler = new DocsCrawler(mockIde, config); - - // Make sure we have Chromium pulled down before beginning tests - await chromiumInstaller.install(); - }, TIMEOUT_MS); - - function crawlTest( - urls: string[], - numPagesToCrawl: number = NUM_PAGES_TO_CRAWL, - ) { - const numUrlsToTest = 5; - const randomUrls = urls - .sort(() => 0.5 - Math.random()) - .slice(0, numUrlsToTest); - - randomUrls.forEach((url) => { - it( - `Crawl test for ${url}`, - async () => { - const crawlResults: PageData[] = []; - - for await (const page of docsCrawler.crawl( - new URL(url), - NUM_PAGES_TO_CRAWL, - )) { - crawlResults.push(page); - } - - expect(crawlResults.length).toBeGreaterThanOrEqual(numPagesToCrawl); - }, - TIMEOUT_MS, - ); - }); - } - - describe("GitHub Crawler", () => { - const repoUrl = - "https://github.com/Patrick-Erichsen/test-github-repo-for-crawling"; - - let crawlResults: PageData[]; - - beforeAll(async () => { - crawlResults = []; - - for await (const page of docsCrawler.crawl(new URL(repoUrl))) { - crawlResults.push(page); - } - }, TIMEOUT_MS); - - test("finds expected markdown files", async () => { - expect(crawlResults.some((page) => page.path.endsWith("README.md"))).toBe( - true, - ); - - expect( - crawlResults.some((page) => page.path.endsWith("docs-depth-1.md")), - ).toBe(true); - }); - - test("html includes the correct content", async () => { - const doc = crawlResults.find((page) => - page.path.endsWith("docs-depth-1.md"), - ); - - expect(doc?.content.includes("Test body")).toBe(true); - expect(doc?.content.includes("Test H2 Header")).toBe(true); - }); - - test("ignores non-markdown files, e.g. `test.js` at the root", async () => { - expect(crawlResults.some((page) => page.path.endsWith("test.js"))).toBe( - false, - ); - }); - }); - - describe("Chromium Crawler", () => { - let shouldUseChromiumSpy: any; - - beforeAll(() => { - shouldUseChromiumSpy = jest - .spyOn(docsCrawler as any, "shouldUseChromium") - .mockReturnValue(true); - }); - - afterAll(() => { - shouldUseChromiumSpy.mockRestore(); - }); - - describe("Pre-indexed Docs", () => { - crawlTest(Object.keys(preIndexedDocs)); - }); - - describe("Running list of common sites", () => { - crawlTest([ - "https://docs.nestjs.com/", - "https://go.dev/doc/", - "https://clickhouse.com/docs", - "https://www.tensorflow.org/api_docs", - // "https://www.rust-lang.org/learn", TODO: This is failing - "https://docs.anthropic.com/en/docs", - ]); - }); - }); - - describe("Cheerio Crawler", () => { - crawlTest(["https://amplified.dev/"], 1); - }); -}); diff --git a/core/indexing/docs/DocsCrawler.ts b/core/indexing/docs/DocsCrawler.ts deleted file mode 100644 index 8854d8e87..000000000 --- a/core/indexing/docs/DocsCrawler.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { URL } from "node:url"; - -// @ts-ignore -// @prettier-ignore -import { ContinueConfig, IDE } from "../.."; - -import CheerioCrawler from "./crawlers/CheerioCrawler"; -import { ChromiumCrawler, ChromiumInstaller } from "./crawlers/ChromiumCrawler"; -import { DefaultCrawler } from "./crawlers/DefaultCrawler"; -import GitHubCrawler from "./crawlers/GitHubCrawler"; - -export type PageData = { - url: string; - path: string; - content: string; -}; - -class DocsCrawler { - private readonly MAX_REQUESTS_PER_CRAWL = 1000; - private readonly GITHUB_HOST = "github.com"; - private readonly chromiumInstaller: ChromiumInstaller; - - constructor( - private readonly ide: IDE, - private readonly config: ContinueConfig, - ) { - this.chromiumInstaller = new ChromiumInstaller(this.ide, this.config); - } - - private shouldUseChromium() { - return ( - this.config.experimental?.useChromiumForDocsCrawling && - this.chromiumInstaller.isInstalled() - ); - } - - async *crawl( - startUrl: URL, - maxRequestsPerCrawl: number = this.MAX_REQUESTS_PER_CRAWL, - ): AsyncGenerator { - if (startUrl.host === this.GITHUB_HOST) { - yield* new GitHubCrawler(startUrl).crawl(); - return; - } - - try { - const pageData = await new DefaultCrawler(startUrl).crawl(); - if (pageData.length > 0) { - yield* pageData; - return; - } - } catch (e) { - console.error("Default crawler failed, trying backup: ", e); - } - - if (this.shouldUseChromium()) { - yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl(); - } else { - let didCrawlSinglePage = false; - - for await (const pageData of new CheerioCrawler( - startUrl, - maxRequestsPerCrawl, - ).crawl()) { - yield pageData; - didCrawlSinglePage = true; - } - - // We assume that if we failed to crawl a single page, - // it was due to an error that using Chromium can resolve - const shouldProposeUseChromium = - !didCrawlSinglePage && - this.chromiumInstaller.shouldProposeUseChromiumOnCrawlFailure(); - - if (shouldProposeUseChromium) { - const didInstall = - await this.chromiumInstaller.proposeAndAttemptInstall( - startUrl.toString(), - ); - - if (didInstall) { - void this.ide.showToast( - "info", - `Successfully installed Chromium! Retrying crawl of: ${startUrl.toString()}`, - ); - - yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl(); - } - } - } - } -} - -export default DocsCrawler; -export { - CheerioCrawler, - ChromiumCrawler, - ChromiumInstaller, - GitHubCrawler, -}; diff --git a/core/indexing/docs/DocsService.skip.ts b/core/indexing/docs/DocsService.skip.ts index 8b4b6a8bf..0064f064c 100644 --- a/core/indexing/docs/DocsService.skip.ts +++ b/core/indexing/docs/DocsService.skip.ts @@ -4,7 +4,6 @@ import { ConfigHandler } from "../../config/ConfigHandler.js"; import { ControlPlaneClient } from "../../control-plane/client.js"; import { SiteIndexingConfig } from "../../index.js"; -import FreeTrial from "../../llm/llms/FreeTrial.js"; import FileSystemIde from "../../util/filesystem.js"; import { editConfigJson } from "../../util/paths.js"; @@ -37,17 +36,19 @@ describe.skip("DocsService Integration Tests", () => { beforeEach(async () => { ide = new FileSystemIde(process.cwd()); + const ideSettingsPromise = Promise.resolve({ + remoteConfigSyncPeriod: 60, + userToken: "", + enableControlServerBeta: false, + continueTestEnvironment: "none" as const, + pauseCodebaseIndexOnStart: false, + ideSettings: {} as any, + enableDebugLogs: false, + remoteConfigServerUrl: "", + }); configHandler = new ConfigHandler( ide, - Promise.resolve({ - remoteConfigSyncPeriod: 60, - userToken: "", - enableControlServerBeta: false, - pauseCodebaseIndexOnStart: false, - ideSettings: {} as any, - enableDebugLogs: false, - remoteConfigServerUrl: "", - }), + ideSettingsPromise, async () => {}, new ControlPlaneClient( Promise.resolve({ @@ -57,6 +58,7 @@ describe.skip("DocsService Integration Tests", () => { label: "", }, }), + ideSettingsPromise, ), ); @@ -105,28 +107,28 @@ describe.skip("DocsService Integration Tests", () => { expect(retrievedChunks.length).toBe(0); }); - test("Reindexes when changing embeddings provider", async () => { - const originalEmbeddingsProvider = - await docsService.getEmbeddingsProvider(); + // test("Reindexes when changing embeddings provider", async () => { + // const originalEmbeddingsProvider = + // await docsService.getEmbeddingsProvider(); - // Change embeddings provider - editConfigJson((config) => ({ - ...config, - embeddingsProvider: { - provider: FreeTrial.providerName, - }, - })); + // // Change embeddings provider + // editConfigJson((config) => ({ + // ...config, + // embeddingsProvider: { + // provider: FreeTrial.providerName, + // }, + // })); - await getReloadedConfig(); + // await getReloadedConfig(); - const newEmbeddingsProvider = await docsService.getEmbeddingsProvider(); + // const { provider, isPreindexed} = await docsService.getEmbeddingsProvider(); - // Verify reindexing - const [originalVector] = await originalEmbeddingsProvider.embed(["test"]); - const [newMockVector] = await newEmbeddingsProvider.embed(["test"]); + // // Verify reindexing + // const [originalVector] = await originalEmbeddingsProvider.embed(["test"]); + // const [newMockVector] = await provider.embed(["test"]); - expect(originalVector).not.toEqual(newMockVector); - }); + // expect(originalVector).not.toEqual(newMockVector); + // }); test("Handles pulling down and adding pre-indexed docs", async () => { const preIndexedDoc = Object.values(preIndexedDocs)[0]; diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 105d24b9e..f0d1e2f3c 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -5,6 +5,7 @@ import lancedb, { Connection } from "vectordb"; import { Chunk, ContinueConfig, + DocsIndexingDetails, IDE, IdeInfo, ILLM, @@ -25,9 +26,12 @@ import { } from "../../util/paths"; import { Telemetry } from "../../util/posthog"; -import { ConfigResult } from "../../config/load"; -import { Article, chunkArticle, pageToArticle } from "./article"; -import DocsCrawler from "./DocsCrawler"; +import { + ArticleWithChunks, + htmlPageToArticleWithChunks, + markdownPageToArticleWithChunks, +} from "./article"; +import DocsCrawler, { DocsCrawlerType, PageData } from "./crawlers/DocsCrawler"; import { runLanceMigrations, runSqliteMigrations } from "./migrations"; import { downloadFromS3, @@ -36,6 +40,7 @@ import { SiteIndexingResults, } from "./preIndexed"; import preIndexedDocs from "./preIndexedDocs"; +import { ConfigResult } from "@continuedev/config-yaml"; // Purposefully lowercase because lancedb converts export interface LanceDbDocsRow { @@ -73,8 +78,6 @@ export type AddParams = { - delete - reindex all - add/index one - - Currently a full reindex deletes all docs rather than storing PER embeddings provider - - The last successful embeddings provider is stored in global context and updated AFTER an indexing process is successful */ export default class DocsService { static lanceTableName = "docs"; @@ -92,8 +95,8 @@ export default class DocsService { private config!: ContinueConfig; private sqliteDb?: Database; - private docsCrawler!: DocsCrawler; private ideInfoPromise: Promise; + private githubToken?: string; constructor( configHandler: ConfigHandler, @@ -104,6 +107,10 @@ export default class DocsService { this.isInitialized = this.init(configHandler); } + setGithubToken(token: string) { + this.githubToken = token; + } + // Singleton pattern: only one service globally private static instance?: DocsService; static createSingleton( @@ -196,6 +203,7 @@ export default class DocsService { } } + // Used to check periodically during indexing if should cancel indexing shouldCancel(startUrl: string, startedWithEmbedder: string) { // Check if aborted const isAborted = this.statuses.get(startUrl)?.status === "aborted"; @@ -215,21 +223,6 @@ export default class DocsService { return false; } - // NOTE Pausing not supported for docs yet - // setPaused(startUrl: string, pause: boolean) { - // const status = this.statuses.get(startUrl); - // if (status) { - // this.handleStatusUpdate({ - // ...status, - // status: pause ? "paused" : "indexing", - // }); - // } - // } - - // isPaused(startUrl: string) { - // return this.statuses.get(startUrl)?.status === "paused"; - // } - /* * Currently, we generate and host embeddings for pre-indexed docs using transformers. * However, we don't ship transformers with the JetBrains extension. @@ -251,14 +244,29 @@ export default class DocsService { return isPreIndexedDocsProvider && !canUsePreindexedDocs; } - async getEmbeddingsProvider(isPreIndexedDoc: boolean = false): Promise { - const canUsePreindexedDocs = await this.canUsePreindexedDocs(); + // Determines if using preIndexed and returns proper embeddings provider + async getEmbeddingsProvider(startUrl: string) { + // Conditions for using a pre-indexed doc - if (canUsePreindexedDocs && isPreIndexedDoc) { - return DocsService.preIndexedDocsEmbeddingsProvider; + // Must be in pre indexed docs file + const preIndexedDoc = preIndexedDocs[startUrl]; + if (preIndexedDoc) { + // Most not be overriden by config + if (!this.config?.docs?.find((doc) => doc.startUrl === startUrl)) { + // Must be supported + const canUsePreindexedDocs = await this.canUsePreindexedDocs(); + if (canUsePreindexedDocs) { + return { + provider: DocsService.preIndexedDocsEmbeddingsProvider, + isPreindexed: true, + }; + } + } } - - return this.config.embeddingsProvider; + return { + provider: this.config.embeddingsProvider, + isPreindexed: false, + }; } private async handleConfigUpdate({ @@ -268,8 +276,6 @@ export default class DocsService { const oldConfig = this.config; this.config = newConfig; // IMPORTANT - need to set up top, other methods below use this without passing it in - this.docsCrawler = new DocsCrawler(this.ide, newConfig); - if (this.config.disableIndexing) { return; } @@ -322,7 +328,7 @@ export default class DocsService { } // Returns true if startUrl has been indexed with current embeddingsProvider - async hasMetadata(startUrl: string): Promise> { + async hasMetadata(startUrl: string): Promise { const db = await this.getOrCreateSqliteDb(); const title = await db.get( `SELECT title FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`, @@ -365,16 +371,13 @@ export default class DocsService { console.warn("Attempting to add/index docs when indexing is disabled"); return; } - const { startUrl } = siteIndexingConfig; + const { startUrl, useLocalCrawling, maxDepth } = siteIndexingConfig; - const canUsePreindexedDocs = await this.canUsePreindexedDocs(); - if (canUsePreindexedDocs) { - const preIndexedDoc = preIndexedDocs[startUrl]; - const isPreIndexedDoc = !!preIndexedDoc; - if (isPreIndexedDoc) { - console.warn("Can not override pre-indexed start urls"); - return; - } + const { isPreindexed, provider } = + await this.getEmbeddingsProvider(startUrl); + if (isPreindexed) { + console.warn("Attempted to indexAndAdd pre-indexed doc"); + return; } // Queue - indexAndAdd is invoked circularly by config edits. This prevents duplicate runs @@ -382,8 +385,7 @@ export default class DocsService { return; } - const embeddingsProvider = await this.getEmbeddingsProvider(); - const startedWithEmbedder = this.config.embeddingsProvider.embeddingId; + const startedWithEmbedder = provider.embeddingId; const indexExists = await this.hasMetadata(startUrl); // Build status update - most of it is fixed values @@ -393,7 +395,7 @@ export default class DocsService { > = { type: "docs", id: siteIndexingConfig.startUrl, - embeddingsProviderId: embeddingsProvider.embeddingId, + embeddingsProviderId: provider.embeddingId, isReindexing: reIndex && indexExists, title: siteIndexingConfig.title, debugInfo: `max depth: ${siteIndexingConfig.maxDepth}`, @@ -429,47 +431,81 @@ export default class DocsService { progress: 0, }); - const articles: Article[] = []; + // Crawl pages to get page data + const pages: PageData[] = []; let processedPages = 0; let estimatedProgress = 0; + let done = false; + let usedCrawler: DocsCrawlerType | undefined = undefined; - // Crawl pages and retrieve info as articles - for await (const page of this.docsCrawler.crawl(new URL(startUrl))) { - estimatedProgress += 1 / 2 ** (processedPages + 1); + const docsCrawler = new DocsCrawler( + this.ide, + this.config, + maxDepth, + undefined, + useLocalCrawling, + this.githubToken, + ); + const crawlerGen = docsCrawler.crawl(new URL(startUrl)); - // NOTE - during "indexing" phase, check if aborted before each status update - if (this.shouldCancel(startUrl, startedWithEmbedder)) { - return; + while (!done) { + const result = await crawlerGen.next(); + if (result.done) { + done = true; + usedCrawler = result.value; + } else { + const page = result.value; + estimatedProgress += 1 / 2 ** (processedPages + 1); + + // NOTE - during "indexing" phase, check if aborted before each status update + if (this.shouldCancel(startUrl, startedWithEmbedder)) { + return; + } + this.handleStatusUpdate({ + ...fixedStatus, + description: `Finding subpages (${page.path})`, + status: "indexing", + progress: + 0.15 * estimatedProgress + + Math.min(0.35, (0.35 * processedPages) / 500), + // For the first 50%, 15% is sum of series 1/(2^n) and the other 35% is based on number of files/ 500 max + }); + + pages.push(page); + + processedPages++; + + // Locks down GUI if no sleeping + // Wait proportional to how many docs are indexing + const toWait = 100 * this.docsIndexingQueue.size + 50; + await new Promise((resolve) => setTimeout(resolve, toWait)); } - this.handleStatusUpdate({ - ...fixedStatus, - description: `Finding subpages (${page.path})`, - status: "indexing", - progress: - 0.15 * estimatedProgress + - Math.min(0.35, (0.35 * processedPages) / 500), - // For the first 50%, 15% is sum of series 1/(2^n) and the other 35% is based on number of files/ 500 max - }); - - const article = pageToArticle(page); - if (!article) { - continue; - } - articles.push(article); - - processedPages++; - - // Locks down GUI if no sleeping - // Wait proportional to how many docs are indexing - const toWait = 100 * this.docsIndexingQueue.size + 50; - await new Promise((resolve) => setTimeout(resolve, toWait)); } void Telemetry.capture("docs_pages_crawled", { count: processedPages, }); + // Chunk pages based on which crawler was used + const articles: ArticleWithChunks[] = []; const chunks: Chunk[] = []; + const articleChunker = + usedCrawler === "github" + ? markdownPageToArticleWithChunks + : htmlPageToArticleWithChunks; + for (const page of pages) { + const articleWithChunks = await articleChunker( + page, + provider.maxEmbeddingChunkSize, + ); + if (articleWithChunks) { + articles.push(articleWithChunks); + } + const toWait = 20 * this.docsIndexingQueue.size + 10; + await new Promise((resolve) => setTimeout(resolve, toWait)); + } + + // const chunks: Chunk[] = []; const embeddings: number[][] = []; // Create embeddings of retrieved articles @@ -482,35 +518,26 @@ export default class DocsService { this.handleStatusUpdate({ ...fixedStatus, status: "indexing", - description: `Creating Embeddings: ${article.subpath}`, + description: `Creating Embeddings: ${article.article.subpath}`, progress: 0.5 + 0.3 * (i / articles.length), // 50% -> 80% }); try { - const chunkedArticle = chunkArticle( - article, - embeddingsProvider.maxEmbeddingChunkSize, + const subpathEmbeddings = await provider.embed( + article.chunks.map((c) => c.content), ); - - const chunkedArticleContents = chunkedArticle.map( - (chunk) => chunk.content, - ); - - chunks.push(...chunkedArticle); - - const subpathEmbeddings = await embeddingsProvider.embed( - chunkedArticleContents, - ); - + chunks.push(...article.chunks); embeddings.push(...subpathEmbeddings); + const toWait = 100 * this.docsIndexingQueue.size + 50; + await new Promise((resolve) => setTimeout(resolve, toWait)); } catch (e) { - console.warn("Error chunking article: ", e); + console.warn("Error embedding article chunks: ", e); } } if (embeddings.length === 0) { console.error( - `No embeddings were created for site: ${siteIndexingConfig.startUrl}\n Num chunks: ${chunks.length}`, + `No embeddings were created for site: ${startUrl}\n Num chunks: ${chunks.length}`, ); if (this.shouldCancel(startUrl, startedWithEmbedder)) { @@ -518,7 +545,7 @@ export default class DocsService { } this.handleStatusUpdate({ ...fixedStatus, - description: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`, + description: `No embeddings were created for site: ${startUrl}`, status: "failed", progress: 1, }); @@ -584,10 +611,19 @@ export default class DocsService { providers: ["docs"], }); } catch (e) { + let description = `Error getting docs from: ${siteIndexingConfig.startUrl}`; + if (e instanceof Error) { + if ( + e.message.includes("github.com") && + e.message.includes("rate limit") + ) { + description = "Github rate limit exceeded"; + } + } console.error("Error indexing docs", e); this.handleStatusUpdate({ ...fixedStatus, - description: `Error getting docs from: ${siteIndexingConfig.startUrl}`, + description, status: "failed", progress: 1, }); @@ -600,11 +636,12 @@ export default class DocsService { // And pre-indexed embeddings are supported // Fetch pre-indexed embeddings from S3, add to Lance, and then search those private async fetchAndAddPreIndexedDocEmbeddings(title: string) { - const embeddingsProvider = await this.getEmbeddingsProvider(true); - const data = await downloadFromS3( S3Buckets.continueIndexedDocs, - getS3Filename(embeddingsProvider.embeddingId, title), + getS3Filename( + DocsService.preIndexedDocsEmbeddingsProvider.embeddingId, + title, + ), ); const siteEmbeddings = JSON.parse(data) as SiteIndexingResults; @@ -645,36 +682,91 @@ export default class DocsService { return []; } - const preIndexedDoc = preIndexedDocs[startUrl]; - if (!!preIndexedDoc) { + const { isPreindexed, provider } = + await this.getEmbeddingsProvider(startUrl); + + if (isPreindexed) { void Telemetry.capture("docs_pre_indexed_doc_used", { - doc: preIndexedDoc["title"], + doc: preIndexedDocs[startUrl]!["title"], }); } - const embeddingsProvider = - await this.getEmbeddingsProvider(!!preIndexedDoc); + const [vector] = await provider.embed([query]); - const [vector] = await embeddingsProvider.embed([query]); - - return await this.retrieveChunks(startUrl, vector, nRetrieve); + return await this.retrieveChunks(startUrl, vector, nRetrieve, isPreindexed); } + private lanceDBRowToChunk(row: LanceDbDocsRow): Chunk { + return { + digest: row.path, + filepath: row.path, + startLine: row.startline, + endLine: row.endline, + index: 0, + content: row.content, + otherMetadata: { + title: row.title, + }, + }; + } + async getDetails(startUrl: string): Promise { + const db = await this.getOrCreateSqliteDb(); + + try { + const { isPreindexed, provider } = + await this.getEmbeddingsProvider(startUrl); + const preIndexedDoc = preIndexedDocs[startUrl]; + const isPreIndexedDoc = !!preIndexedDoc; + + const result = await db.get( + `SELECT startUrl, title, favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`, + startUrl, + provider.embeddingId, + ); + + if (!result) { + throw new Error(`${startUrl} not found in sqlite`); + } + const siteIndexingConfig: SiteIndexingConfig = { + startUrl, + faviconUrl: result.favicon, + title: result.title, + }; + + const table = await this.getOrCreateLanceTable({ + initializationVector: [], + startUrl, + }); + const rows = (await table + .filter(`starturl = '${startUrl}'`) + .limit(1000) + .execute()) as LanceDbDocsRow[]; + + return { + startUrl, + config: siteIndexingConfig, + indexingStatus: this.statuses.get(startUrl), + chunks: rows.map(this.lanceDBRowToChunk), + isPreIndexedDoc, + }; + } catch (e) { + console.warn("Error getting details", e); + throw e; + } + } // This is split into its own function so that it can be recursive // in the case of fetching preindexed docs from s3 async retrieveChunks( startUrl: string, vector: number[], nRetrieve: number, + isPreindexed: boolean, isRetry: boolean = false, ): Promise { - const preIndexedDoc = preIndexedDocs[startUrl]; - const isPreIndexedDoc = !!preIndexedDoc; - // Lance doesn't have an embeddingsprovider column, instead it includes it in the table name const table = await this.getOrCreateLanceTable({ initializationVector: vector, - isPreIndexedDoc, + startUrl, }); let docs: LanceDbDocsRow[] = []; @@ -689,31 +781,17 @@ export default class DocsService { } // No docs are found for preindexed? try fetching once - if (docs.length === 0 && isPreIndexedDoc) { + if (docs.length === 0 && isPreindexed) { if (isRetry) { return []; } - await this.fetchAndAddPreIndexedDocEmbeddings(preIndexedDoc.title); - return await this.retrieveChunks(startUrl, vector, nRetrieve, true); + await this.fetchAndAddPreIndexedDocEmbeddings( + preIndexedDocs[startUrl]!["title"], + ); + return await this.retrieveChunks(startUrl, vector, nRetrieve, true, true); } - if (isPreIndexedDoc) { - void Telemetry.capture("docs_pre_indexed_doc_used", { - doc: preIndexedDoc["title"], - }); - } - - return docs.map((doc) => ({ - digest: doc.path, - filepath: doc.path, - startLine: doc.startline, - endLine: doc.endline, - index: 0, - content: doc.content, - otherMetadata: { - title: doc.title, - }, - })); + return docs.map(this.lanceDBRowToChunk); } // SQLITE DB @@ -769,7 +847,7 @@ export default class DocsService { private async syncDocs( oldConfig: ContinueConfig | undefined, newConfig: ContinueConfig, - reindex: boolean, + forceReindex: boolean, ) { try { this.isSyncing = true; @@ -802,33 +880,38 @@ export default class DocsService { const oldConfigDoc = oldConfigDocs.find( (d) => d.startUrl === doc.startUrl, ); - // const currentStatus = this.statuses.get(doc.startUrl); + if ( - // currentStatus?.status === "complete" && oldConfigDoc && - (oldConfigDoc.maxDepth !== doc.maxDepth || - oldConfigDoc.title !== doc.title || - oldConfigDoc.faviconUrl !== doc.faviconUrl) + !this.siteIndexingConfigsAreEqual(oldConfigDoc, doc) ) { changedDocs.push(doc); } else { - // if get's here, not changed, no update needed, mark as complete - this.handleStatusUpdate({ - type: "docs", - id: doc.startUrl, - embeddingsProviderId: this.config.embeddingsProvider.embeddingId, - isReindexing: false, - title: doc.title, - debugInfo: "Config sync: not changed", - icon: doc.faviconUrl, - url: doc.startUrl, - progress: 1, - description: "Complete", - status: "complete", - }); + if (forceReindex) { + changedDocs.push(doc); + } else { + // if get's here, not changed, no update needed, mark as complete + this.handleStatusUpdate({ + type: "docs", + id: doc.startUrl, + embeddingsProviderId: + this.config.embeddingsProvider.embeddingId, + isReindexing: false, + title: doc.title, + debugInfo: "Config sync: not changed", + icon: doc.faviconUrl, + url: doc.startUrl, + progress: 1, + description: "Complete", + status: "complete", + }); + } } } else { - newDocs.push(doc); + const currentStatus = this.statuses.get(doc.startUrl); + if (currentStatus?.status !== "failed") { + newDocs.push(doc); + } } } @@ -892,10 +975,7 @@ export default class DocsService { return name.replace(/[^a-zA-Z0-9_.-]/g, "_"); } - private async getLanceTableName(isPreIndexedDoc: boolean) { - const embeddingsProvider = - await this.getEmbeddingsProvider(isPreIndexedDoc); - + private async getLanceTableName(embeddingsProvider: ILLM) { const tableName = this.sanitizeLanceTableName( `${DocsService.lanceTableName}${embeddingsProvider.embeddingId}`, ); @@ -905,15 +985,16 @@ export default class DocsService { private async getOrCreateLanceTable({ initializationVector, - isPreIndexedDoc, + startUrl, }: { initializationVector: number[]; - isPreIndexedDoc?: boolean; + startUrl: string; }) { const conn = await lancedb.connect(getLanceDbPath()); const tableNames = await conn.tableNames(); + const { provider } = await this.getEmbeddingsProvider(startUrl); const tableNameFromEmbeddingsProvider = - await this.getLanceTableName(!!isPreIndexedDoc); + await this.getLanceTableName(provider); if (!tableNames.includes(tableNameFromEmbeddingsProvider)) { if (initializationVector) { @@ -944,16 +1025,16 @@ export default class DocsService { embeddings, }: AddParams) { const sampleVector = embeddings[0]; - const isPreIndexedDoc = !!preIndexedDocs[siteIndexingConfig.startUrl]; + const { startUrl } = siteIndexingConfig; const table = await this.getOrCreateLanceTable({ - isPreIndexedDoc, + startUrl, initializationVector: sampleVector, }); const rows: LanceDbDocsRow[] = chunks.map((chunk, i) => ({ vector: embeddings[i], - starturl: siteIndexingConfig.startUrl, + starturl: startUrl, title: chunk.otherMetadata?.title || siteIndexingConfig.title, content: chunk.content, path: chunk.filepath, @@ -978,16 +1059,24 @@ export default class DocsService { ); } + private siteIndexingConfigsAreEqual( + config1: SiteIndexingConfig, + config2: SiteIndexingConfig, + ) { + return ( + config1.startUrl === config2.startUrl && + config1.faviconUrl === config2.faviconUrl && + config1.title === config2.title && + config1.maxDepth === config2.maxDepth && + config1.useLocalCrawling === config2.useLocalCrawling + ); + } + private addToConfig(siteIndexingConfig: SiteIndexingConfig) { // Handles the case where a user has manually added the doc to config.json // so it already exists in the file - const doesEquivalentDocExist = this.config.docs?.some( - (doc) => - doc.startUrl === siteIndexingConfig.startUrl && - doc.faviconUrl === siteIndexingConfig.faviconUrl && - siteIndexingConfig.title === doc.title, - // siteIndexingConfig.maxDepth === doc.maxDepth && - // doc.rootUrl === siteIndexingConfig.rootUrl, + const doesEquivalentDocExist = this.config.docs?.some((doc) => + this.siteIndexingConfigsAreEqual(doc, siteIndexingConfig), ); if (!doesEquivalentDocExist) { @@ -1045,7 +1134,7 @@ export default class DocsService { } } - async deleteIndexes(startUrl: string) { + private async deleteIndexes(startUrl: string) { await this.deleteEmbeddingsFromLance(startUrl); await this.deleteMetadataFromSqlite(startUrl); } diff --git a/core/indexing/docs/article.ts b/core/indexing/docs/article.ts index 8026280c9..428bae967 100644 --- a/core/indexing/docs/article.ts +++ b/core/indexing/docs/article.ts @@ -2,9 +2,9 @@ import { Readability } from "@mozilla/readability"; import { JSDOM } from "jsdom"; import { Chunk } from "../../"; -import { cleanFragment, cleanHeader } from "../chunk/markdown"; +import { cleanFragment, cleanHeader, markdownChunker } from "../chunk/markdown"; -import { type PageData } from "./DocsCrawler"; +import { type PageData } from "./crawlers/DocsCrawler"; export type ArticleComponent = { title: string; @@ -18,6 +18,11 @@ export type Article = { article_components: ArticleComponent[]; }; +export type ArticleWithChunks = { + article: Article; + chunks: Chunk[]; +}; + function breakdownArticleComponent( url: string, article: ArticleComponent, @@ -99,78 +104,100 @@ function breakdownArticleComponent( return chunks.filter((c) => c.content.trim().length > 20); } -export function chunkArticle( - articleResult: Article, - maxChunkSize: number, -): Chunk[] { - let chunks: Chunk[] = []; +function chunkArticle(article: Article, maxChunkSize: number): Chunk[] { + const chunks: Chunk[] = []; - for (const article of articleResult.article_components) { + for (const component of article.article_components) { const articleChunks = breakdownArticleComponent( - articleResult.url, - article, - articleResult.subpath, + article.url, + component, + article.subpath, maxChunkSize, ); - chunks = [...chunks, ...articleChunks]; + chunks.push(...articleChunks); } return chunks; } -function extractTitlesAndBodies(html: string): ArticleComponent[] { - const dom = new JSDOM(html); - const document = dom.window.document; - - const titles = Array.from(document.querySelectorAll("h2")); - const result = titles.map((titleElement) => { - const title = titleElement.textContent || ""; - let body = ""; - let nextSibling = titleElement.nextElementSibling; - - while (nextSibling && nextSibling.tagName !== "H2") { - body += nextSibling.textContent || ""; - nextSibling = nextSibling.nextElementSibling; - } - - return { title, body }; - }); - - return result; -} -export function stringToArticle( - url: string, - html: string, - subpath: string, -): Article | undefined { +export async function htmlPageToArticleWithChunks( + page: PageData, + maxChunkSize: number, +): Promise { try { + const html = page.content; + const subpath = page.path; + const url = page.url; + const dom = new JSDOM(html); const reader = new Readability(dom.window.document); - const article = reader.parse(); + const readability = reader.parse(); + + if (!readability) { + console.error("Docs indexing: Error getting readability for URL", url); - if (!article) { return undefined; } - const article_components = extractTitlesAndBodies(article.content); + const titles = Array.from(dom.window.document.querySelectorAll("h2")); + const article_components = titles.map((titleElement) => { + const title = titleElement.textContent || ""; + let body = ""; + let nextSibling = titleElement.nextElementSibling; - return { + while (nextSibling && nextSibling.tagName !== "H2") { + body += nextSibling.textContent || ""; + nextSibling = nextSibling.nextElementSibling; + } + + return { title, body }; + }); + + const article = { url, subpath, - title: article.title, + title: readability.title, article_components, }; + return { + article, + chunks: chunkArticle(article, maxChunkSize), + }; } catch (err) { console.error("Error converting URL to article components", err); - return undefined; } } -export function pageToArticle(page: PageData): Article | undefined { +export async function markdownPageToArticleWithChunks( + page: PageData, + maxChunkSize: number, +): Promise { try { - return stringToArticle(page.url, page.content, page.path); + let index = 0; + const chunks: Chunk[] = []; + const chunker = markdownChunker(page.content, maxChunkSize, 1); + for await (const chunk of chunker) { + const fullUrl = new URL(page.url); + fullUrl.hash = `#${cleanFragment(chunk.otherMetadata?.title)}`; + + chunks.push({ + ...chunk, + index, + filepath: fullUrl.toString(), + digest: fullUrl.toString(), + }); + index++; + } + return { + article: { + url: page.url, + subpath: page.path, + article_components: [], // TODO: markdown chunker just skips this for now since not used outside, only for html chunker + title: chunks[0]?.otherMetadata?.title || page.path, + }, + chunks, + }; } catch (err) { - console.error("Error converting URL to article components", err); - return undefined; + console.error(`Docs indexing: failed to chunk markdown from ${page.url}`); } } diff --git a/core/indexing/docs/crawlers/CheerioCrawler.ts b/core/indexing/docs/crawlers/CheerioCrawler.ts index cfdf68f12..dd5fb1918 100644 --- a/core/indexing/docs/crawlers/CheerioCrawler.ts +++ b/core/indexing/docs/crawlers/CheerioCrawler.ts @@ -2,7 +2,7 @@ import { URL } from "node:url"; import * as cheerio from "cheerio"; -import { PageData } from "../DocsCrawler"; +import { PageData } from "./DocsCrawler"; export default class CheerioCrawler { private readonly IGNORE_PATHS_ENDING_IN = [ @@ -21,23 +21,18 @@ export default class CheerioCrawler { constructor( private readonly startUrl: URL, private readonly maxRequestsPerCrawl: number, + private readonly maxDepth: number, ) {} async *crawl(): AsyncGenerator { - yield* this.crawlPage(this.startUrl); - } - - private async *crawlPage( - url: URL, - maxDepth: number = 3, - ): AsyncGenerator { + let currentPageCount = 0; console.log( `[${ (this.constructor as any).name - }] Starting crawl from: ${url} - Max Depth: ${maxDepth}`, + }] Starting crawl from: ${this.startUrl} - Max Depth: ${this.maxDepth}`, ); - const { baseUrl, basePath } = this.splitUrl(url); + const { baseUrl, basePath } = this.splitUrl(this.startUrl); let paths: { path: string; depth: number }[] = [ { path: basePath, depth: 0 }, @@ -63,11 +58,16 @@ export default class CheerioCrawler { path, depth, } of results) { - if (html !== "" && depth <= maxDepth) { - yield { url: url.toString(), path, content: html }; + if (html !== "" && depth <= this.maxDepth) { + yield { url: this.startUrl.toString(), path, content: html }; + currentPageCount++; + if (currentPageCount >= this.maxRequestsPerCrawl) { + console.log("Crawl completed - max requests reached"); + return; + } } - if (depth < maxDepth) { + if (depth < this.maxDepth) { for (let link of linksArray) { if (!paths.some((p) => p.path === link)) { paths.push({ path: link, depth: depth + 1 }); diff --git a/core/indexing/docs/crawlers/ChromiumCrawler.ts b/core/indexing/docs/crawlers/ChromiumCrawler.ts index 5ebeb095c..ef9b528ce 100644 --- a/core/indexing/docs/crawlers/ChromiumCrawler.ts +++ b/core/indexing/docs/crawlers/ChromiumCrawler.ts @@ -13,7 +13,7 @@ import { getChromiumPath, getContinueUtilsPath, } from "../../../util/paths"; -import { PageData } from "../DocsCrawler"; +import { PageData } from "./DocsCrawler"; export class ChromiumCrawler { private readonly LINK_GROUP_SIZE = 2; @@ -22,6 +22,7 @@ export class ChromiumCrawler { constructor( private readonly startUrl: URL, private readonly maxRequestsPerCrawl: number, + private readonly maxDepth: number, ) {} static setUseChromiumForDocsCrawling(useChromiumForDocsCrawling: boolean) { @@ -49,7 +50,7 @@ export class ChromiumCrawler { const page = await browser.newPage(); try { - yield* this.crawlSitePages(page, this.startUrl); + yield* this.crawlSitePages(page, this.startUrl, 0); } catch (e) { console.debug("Error getting links: ", e); console.debug( @@ -97,6 +98,7 @@ export class ChromiumCrawler { private async *crawlSitePages( page: Page, curUrl: URL, + depth: number, visitedLinks: Set = new Set(), ): AsyncGenerator { const urlStr = curUrl.toString(); @@ -124,9 +126,17 @@ export class ChromiumCrawler { for (const link of linkGroup) { enqueuedLinkCount++; - console.log({ enqueuedLinkCount, url: this.startUrl.toString() }); - if (enqueuedLinkCount <= this.maxRequestsPerCrawl) { - yield* this.crawlSitePages(page, new URL(link), visitedLinks); + // console.log({ enqueuedLinkCount, url: this.startUrl.toString() }); + if ( + enqueuedLinkCount <= this.maxRequestsPerCrawl && + depth <= this.maxDepth + ) { + yield* this.crawlSitePages( + page, + new URL(link), + depth + 1, + visitedLinks, + ); } } } diff --git a/core/indexing/docs/crawlers/DefaultCrawler.ts b/core/indexing/docs/crawlers/DefaultCrawler.ts index 7f0351080..0f0d9e593 100644 --- a/core/indexing/docs/crawlers/DefaultCrawler.ts +++ b/core/indexing/docs/crawlers/DefaultCrawler.ts @@ -2,10 +2,14 @@ import { URL } from "node:url"; import { getHeaders } from "../../../continueServer/stubs/headers"; import { TRIAL_PROXY_URL } from "../../../control-plane/client"; -import { PageData } from "../DocsCrawler"; +import { PageData } from "./DocsCrawler"; export class DefaultCrawler { - constructor(private readonly startUrl: URL) {} + constructor( + private readonly startUrl: URL, + private readonly maxRequestsPerCrawl: number, + private readonly maxDepth: number, + ) {} async crawl(): Promise { const resp = await fetch(new URL("crawl", TRIAL_PROXY_URL).toString(), { @@ -14,7 +18,11 @@ export class DefaultCrawler { "Content-Type": "application/json", ...(await getHeaders()), }, - body: JSON.stringify({ startUrl: this.startUrl.toString() }), + body: JSON.stringify({ + startUrl: this.startUrl.toString(), + maxDepth: this.maxDepth, + limit: this.maxRequestsPerCrawl, + }), }); if (!resp.ok) { const text = await resp.text(); diff --git a/core/indexing/docs/crawlers/DocsCrawler.test.ts b/core/indexing/docs/crawlers/DocsCrawler.test.ts new file mode 100644 index 000000000..d3a246cf9 --- /dev/null +++ b/core/indexing/docs/crawlers/DocsCrawler.test.ts @@ -0,0 +1,177 @@ +import os from "os"; + +import { ContinueConfig } from "../../.."; +import { testConfigHandler } from "../../../test/fixtures"; +import FileSystemIde from "../../../util/filesystem"; + +import DocsCrawler, { + ChromiumInstaller, + DocsCrawlerType, + type PageData, +} from "./DocsCrawler"; +import { commonDocsSites } from "./crawl-test-cases"; + +// Temporary workaround until we have better caching of Chromium +// download between test runs +const TIMEOUT_MS = 1_000_000_000; + +// Overwrite the Chromium download path to `os.tmpdir()` +// so that we don't delete the Chromium install between tests +ChromiumInstaller.PCR_CONFIG = { downloadPath: os.tmpdir() }; + +describe("DocsCrawler", () => { + let config: ContinueConfig; + let mockIde: FileSystemIde; + let chromiumInstaller: ChromiumInstaller; + let docsCrawler: DocsCrawler; + + beforeAll(async () => { + const result = await testConfigHandler.loadConfig(); + config = result.config!; + mockIde = new FileSystemIde(process.cwd()); + chromiumInstaller = new ChromiumInstaller(mockIde, config); + docsCrawler = new DocsCrawler(mockIde, config); + }, TIMEOUT_MS); + + async function runCrawl(url: string) { + const pages: PageData[] = []; + const generator = docsCrawler.crawl(new URL(url)); + let done = false; + let crawler: DocsCrawlerType = "default"; + while (!done) { + const result = await generator.next(); + if (result.done) { + done = true; + crawler = result.value; + } else { + pages.push(result.value); + } + } + return { + pages, + crawler, + }; + } + + describe("GitHub Crawler", () => { + const repoUrl = + "https://github.com/Patrick-Erichsen/test-github-repo-for-crawling"; + + let crawlResults: PageData[]; + let crawlerUsed: DocsCrawlerType; + + beforeAll(async () => { + docsCrawler = new DocsCrawler(mockIde, config, 5, 5, false); + const { pages, crawler } = await runCrawl(repoUrl); + crawlerUsed = crawler; + crawlResults = pages; + }, TIMEOUT_MS); + + test( + "finds expected markdown files", + async () => { + expect( + crawlResults.some((page) => page.path.endsWith("README.md")), + ).toBe(true); + + expect( + crawlResults.some((page) => page.path.endsWith("docs-depth-1.md")), + ).toBe(true); + }, + TIMEOUT_MS, + ); + + test( + "html includes the correct content", + async () => { + const doc = crawlResults.find((page) => + page.path.endsWith("docs-depth-1.md"), + ); + + expect(doc?.content.includes("Test body")).toBe(true); + expect(doc?.content.includes("Test H2 Header")).toBe(true); + }, + TIMEOUT_MS, + ); + + test( + "ignores non-markdown files, e.g. `test.js` at the root", + async () => { + expect(crawlResults.some((page) => page.path.endsWith("test.js"))).toBe( + false, + ); + }, + TIMEOUT_MS, + ); + }); + + // Skipped until we have a better way to cache Chromium installs + // between tests and in CI + // Run this periodically to make sure it's still working + describe.skip("Chromium Crawler", () => { + let shouldUseChromiumSpy: any; + + beforeAll(async () => { + docsCrawler = new DocsCrawler(mockIde, config, 5, 5, true); + await chromiumInstaller.install(); + shouldUseChromiumSpy = jest + .spyOn(docsCrawler as any, "shouldUseChromium") + .mockReturnValue(true); + }, TIMEOUT_MS); + + afterAll(() => { + shouldUseChromiumSpy.mockRestore(); + }, TIMEOUT_MS); + + commonDocsSites.forEach((url) => { + test( + `Chromium crawler common site: ${url}`, + async () => { + const { pages, crawler } = await runCrawl(url); + expect(pages.length).toBeGreaterThanOrEqual(1); + expect(crawler).toEqual("chromium"); + }, + TIMEOUT_MS, + ); + }); + }); + + describe("Default Crawler", () => { + beforeAll(() => { + docsCrawler = new DocsCrawler(mockIde, config, 2, 2, false); + }); + + test( + "works on static site", + async () => { + const { pages, crawler } = await runCrawl("https://amplified.dev/"); + expect(pages.length).toBeGreaterThanOrEqual(1); + expect(crawler).toEqual("default"); + }, + TIMEOUT_MS, + ); + + commonDocsSites.forEach((url) => { + test(`Default crawler common site: ${url}`, async () => { + const { pages, crawler } = await runCrawl(url); + expect(pages.length).toBeGreaterThanOrEqual(1); + expect(crawler).toEqual("default"); + }); + }); + }); + + describe("Cheerio Crawler", () => { + beforeAll(() => { + docsCrawler = new DocsCrawler(mockIde, config, 2, 2, true); + }); + test( + "works on static site", + async () => { + const { pages, crawler } = await runCrawl("https://amplified.dev/"); + expect(pages.length).toBeGreaterThanOrEqual(1); + expect(crawler).toEqual("cheerio"); + }, + TIMEOUT_MS, + ); + }); +}); diff --git a/core/indexing/docs/crawlers/DocsCrawler.ts b/core/indexing/docs/crawlers/DocsCrawler.ts new file mode 100644 index 000000000..bea95c3f4 --- /dev/null +++ b/core/indexing/docs/crawlers/DocsCrawler.ts @@ -0,0 +1,119 @@ +import { URL } from "node:url"; + +import { ContinueConfig, IDE } from "../../.."; + +import CheerioCrawler from "./CheerioCrawler"; +import { ChromiumCrawler, ChromiumInstaller } from "./ChromiumCrawler"; +import { DefaultCrawler } from "./DefaultCrawler"; +import GitHubCrawler from "./GitHubCrawler"; + +export type PageData = { + url: string; + path: string; + content: string; +}; + +export type DocsCrawlerType = "default" | "cheerio" | "chromium" | "github"; + +class DocsCrawler { + private readonly GITHUB_HOST = "github.com"; + private readonly chromiumInstaller: ChromiumInstaller; + + constructor( + private readonly ide: IDE, + private readonly config: ContinueConfig, + private readonly maxDepth: number = 4, + private readonly maxRequestsPerCrawl: number = 1000, + private readonly useLocalCrawling: boolean = false, + private readonly githubToken: string | undefined = undefined, + ) { + this.chromiumInstaller = new ChromiumInstaller(this.ide, this.config); + } + + private shouldUseChromium() { + return ( + this.config.experimental?.useChromiumForDocsCrawling && + this.chromiumInstaller.isInstalled() + ); + } + + /* + Returns the type of crawler used in the end + */ + async *crawl( + startUrl: URL, + ): AsyncGenerator { + if (startUrl.host === this.GITHUB_HOST) { + yield* new GitHubCrawler(startUrl, this.githubToken).crawl(); + return "github"; + } + + if (!this.useLocalCrawling) { + try { + const pageData = await new DefaultCrawler( + startUrl, + this.maxRequestsPerCrawl, + this.maxDepth, + ).crawl(); + if (pageData.length > 0) { + yield* pageData; + return "default"; + } + } catch (e) { + console.error("Default crawler failed, trying backup: ", e); + } + } + + if (this.shouldUseChromium()) { + yield* new ChromiumCrawler( + startUrl, + this.maxRequestsPerCrawl, + this.maxDepth, + ).crawl(); + return "chromium"; + } else { + let didCrawlSinglePage = false; + + for await (const pageData of new CheerioCrawler( + startUrl, + this.maxRequestsPerCrawl, + this.maxDepth, + ).crawl()) { + yield pageData; + didCrawlSinglePage = true; + } + + // We assume that if we failed to crawl a single page, + // it was due to an error that using Chromium can resolve + const shouldProposeUseChromium = + !didCrawlSinglePage && + this.chromiumInstaller.shouldProposeUseChromiumOnCrawlFailure(); + + if (shouldProposeUseChromium) { + const didInstall = + await this.chromiumInstaller.proposeAndAttemptInstall( + startUrl.toString(), + ); + + if (didInstall) { + void this.ide.showToast( + "info", + `Successfully installed Chromium! Retrying crawl of: ${startUrl.toString()}`, + ); + + yield* new ChromiumCrawler( + startUrl, + this.maxRequestsPerCrawl, + this.maxDepth, + ).crawl(); + return "chromium"; + } + } + + return "cheerio"; + } + } +} + +export default DocsCrawler; +export { CheerioCrawler, ChromiumCrawler, ChromiumInstaller, GitHubCrawler }; diff --git a/core/indexing/docs/crawlers/GitHubCrawler.ts b/core/indexing/docs/crawlers/GitHubCrawler.ts index ebad52fc3..a9867c435 100644 --- a/core/indexing/docs/crawlers/GitHubCrawler.ts +++ b/core/indexing/docs/crawlers/GitHubCrawler.ts @@ -2,13 +2,19 @@ import { URL } from "node:url"; import { Octokit } from "@octokit/rest"; -import { PageData } from "../DocsCrawler"; +import { PageData } from "./DocsCrawler"; class GitHubCrawler { private readonly markdownRegex = new RegExp(/\.(md|mdx)$/); - private octokit = new Octokit({ auth: undefined }); + private octokit: Octokit; + private FILES_TO_SKIP = [/TEMPLATE\.md$/, /template\.md$/]; - constructor(private readonly startUrl: URL) {} + constructor( + private readonly startUrl: URL, + private readonly githubToken: string | undefined, + ) { + this.octokit = new Octokit({ auth: this.githubToken }); + } async *crawl(): AsyncGenerator { console.debug( @@ -16,14 +22,20 @@ class GitHubCrawler { (this.constructor as any).name }] Crawling GitHub repo: ${this.startUrl.toString()}`, ); - const urlStr = this.startUrl.toString(); const [_, owner, repo] = this.startUrl.pathname.split("/"); const branch = await this.getGithubRepoDefaultBranch(owner, repo); + const paths = await this.getGitHubRepoPaths(owner, repo, branch); for await (const path of paths) { + if (this.FILES_TO_SKIP.some((skip) => skip.test(path))) { + continue; + } const content = await this.getGithubRepoFileContent(path, owner, repo); - yield { path, url: urlStr, content: content ?? "" }; + + const fullUrl = new URL(this.startUrl.toString()); + fullUrl.pathname += `/tree/${branch}/${path}`; + yield { path, url: fullUrl.toString(), content: content ?? "" }; } } diff --git a/core/indexing/docs/crawlers/crawl-test-cases.ts b/core/indexing/docs/crawlers/crawl-test-cases.ts new file mode 100644 index 000000000..3784c7daa --- /dev/null +++ b/core/indexing/docs/crawlers/crawl-test-cases.ts @@ -0,0 +1,64 @@ +export const commonDocsRepos: string[] = [ + // "https://github.com/freeCodeCamp/freeCodeCamp", + "https://github.com/996icu/996.ICU", + // "https://github.com/vuejs/vue", + // "https://github.com/tensorflow/tensorflow", + "https://github.com/sindresorhus/awesome", + "https://github.com/twbs/bootstrap", + // "https://github.com/facebook/react", + // "https://github.com/torvalds/linux", + // "https://github.com/nodejs/node", + // "https://github.com/microsoft/vscode", + // "https://github.com/ohmyzsh/ohmyzsh", + // "https://github.com/kamranahmedse/developer-roadmap", + // "https://github.com/electron/electron", + // "https://github.com/apache/spark", + // "https://github.com/tensorflow/models", + // "https://github.com/ansible/ansible", + // "https://github.com/airbnb/javascript", + // "https://github.com/torvalds/subsurface-for-dirk", + // "https://github.com/scikit-learn/scikit-learn", + // "https://github.com/denoland/deno", + // "https://github.com/donnemartin/system-design-primer", + // "https://github.com/reduxjs/redux", + // "https://github.com/nvie/gitflow", + // "https://github.com/pallets/flask", + // "https://github.com/keras-team/keras", + // "https://github.com/spring-projects/spring-boot", + // "https://github.com/JetBrains/kotlin", + // "https://github.com/saltstack/salt", + // "https://github.com/apache/kafka", + // "https://github.com/moby/moby", + // "https://github.com/ansible/ansible-lint", + // "https://github.com/angular/angular", + // "https://github.com/microsoft/Terminal", + // "https://github.com/EbookFoundation/free-programming-books", + // "https://github.com/hashicorp/terraform", + // "https://github.com/grafana/grafana", + // "https://github.com/flutter/flutter", + // "https://github.com/kubernetes/kubernetes", + "https://github.com/jquery/jquery", + // "https://github.com/laravel/laravel", + // "https://github.com/mrdoob/three.js", + // "https://github.com/prometheus/prometheus", + // "https://github.com/nltk/nltk", + // "https://github.com/facebook/react-native", + // "https://github.com/jekyll/jekyll", + // "https://github.com/wesbos/awesome-dev-podcasts", + // "https://github.com/expressjs/express", + // "https://github.com/elastic/elasticsearch", + // "https://github.com/RocketChat/Rocket.Chat", + // "https://github.com/open-source-labs/reactime", +]; + +export const commonDocsSites = [ + "https://docs.nestjs.com/", + "https://go.dev/doc/", + "https://clickhouse.com/docs", +]; + +export const failingDocsSites = [ + "https://www.tensorflow.org/api_docs", + "https://docs.anthropic.com/en/docs", + "https://www.rust-lang.org/learn", +]; diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 1f5ab4c4a..dfbd2da5d 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -106,9 +106,12 @@ function countTokens( const encoding = encodingForModel(modelName); if (Array.isArray(content)) { return content.reduce((acc, part) => { - return acc + part.type === "imageUrl" - ? countImageTokens(part) - : encoding.encode(part.text ?? "", "all", []).length; + return ( + acc + + (part.type === "text" + ? encoding.encode(part.text ?? "", "all", []).length + : countImageTokens(part)) + ); }, 0); } else { return encoding.encode(content ?? "", "all", []).length; @@ -335,7 +338,7 @@ function messageIsEmpty(message: ChatMessage): boolean { } if (Array.isArray(message.content)) { return message.content.every( - (item) => !item.imageUrl && item.text?.trim() === "", + (item) => item.type === "text" && item.text?.trim() === "", ); } return false; @@ -396,10 +399,10 @@ function compileChatMessages( if ( (systemMessage && systemMessage.trim() !== "") || - msgs?.[0].role === "system" + msgs?.[0]?.role === "system" ) { let content = ""; - if (msgs?.[0].role === "system") { + if (msgs?.[0]?.role === "system") { content = renderChatMessage(msgs?.[0]); } if (systemMessage && systemMessage.trim() !== "") { diff --git a/core/llm/index.ts b/core/llm/index.ts index 11b66ce8d..da1825407 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -117,6 +117,7 @@ export abstract class BaseLLM implements ILLM { writeLog?: (str: string) => Promise; llmRequestHook?: (model: string, prompt: string) => any; apiKey?: string; + apiKeyLocation?: string; apiBase?: string; cacheBehavior?: CacheBehavior; capabilities?: ModelCapability; @@ -194,6 +195,7 @@ export abstract class BaseLLM implements ILLM { this.writeLog = options.writeLog; this.llmRequestHook = options.llmRequestHook; this.apiKey = options.apiKey; + this.apiKeyLocation = options.apiKeyLocation; this.aiGatewaySlug = options.aiGatewaySlug; this.apiBase = options.apiBase; this.cacheBehavior = options.cacheBehavior; @@ -458,9 +460,11 @@ export abstract class BaseLLM implements ILLM { `${toolCall.function?.name}(${toolCall.function?.arguments})`, ) .join("\n"); - } else if ("content" in msg && Array.isArray(msg.content)) { - const content = renderChatMessage(msg); - msg.content = content; + } else if ("content" in msg) { + if (Array.isArray(msg.content)) { + msg.content = renderChatMessage(msg); + } + contentToShow = msg.content; } formatted += `<${msg.role}>\n${contentToShow}\n\n`; diff --git a/core/llm/llm.test.ts b/core/llm/llm.test.ts index cb2218d1d..4831cf800 100644 --- a/core/llm/llm.test.ts +++ b/core/llm/llm.test.ts @@ -1,13 +1,17 @@ import * as dotenv from "dotenv"; -import { CompletionOptions } from ".."; +import { AssistantChatMessage, CompletionOptions } from ".."; + import { BaseLLM } from "."; +import Anthropic from "./llms/Anthropic"; +import Gemini from "./llms/Gemini"; +import Mistral from "./llms/Mistral"; import OpenAI from "./llms/OpenAI"; dotenv.config(); const COMPLETION_OPTIONS: Partial = { - temperature: 0.5, + // temperature: 0.5, topP: 1, topK: 40, presencePenalty: 0, @@ -16,100 +20,197 @@ const COMPLETION_OPTIONS: Partial = { // maxTokens: 5, }; -function testLLM(llm: BaseLLM) { +function testLLM( + llm: BaseLLM, + { + skip, + testFim, + testToolCall, + timeout, + }: { + skip?: boolean; + testFim?: boolean; + testToolCall?: boolean; + timeout?: number; + }, +) { + if (skip) { + return; + } + beforeAll(() => { llm.completionOptions = { ...llm.completionOptions, ...COMPLETION_OPTIONS }; }); - describe(llm.providerName, () => { - test("Stream Chat works", async () => { - let total = ""; - for await (const chunk of llm.streamChat( - [{ role: "user", content: "Hi" }], - new AbortController().signal, - )) { - total += chunk.content; - } + describe(llm.providerName + "/" + llm.model, () => { + test( + "Stream Chat works", + async () => { + let total = ""; + for await (const chunk of llm.streamChat( + [{ role: "user", content: "Hi" }], + new AbortController().signal, + )) { + total += chunk.content; + } - expect(total.length).toBeGreaterThan(0); - return; - }); + expect(total.length).toBeGreaterThan(0); + return; + }, + timeout, + ); - test("Stream Complete works", async () => { - let total = ""; - for await (const chunk of llm.streamComplete( - "Hi", - new AbortController().signal, - )) { - total += chunk; - } + test( + "Stream Complete works", + async () => { + let total = ""; + for await (const chunk of llm.streamComplete( + "Hi", + new AbortController().signal, + )) { + total += chunk; + } - expect(total.length).toBeGreaterThan(0); - return; - }); + expect(total.length).toBeGreaterThan(0); + return; + }, + timeout, + ); - test("Complete works", async () => { - const completion = await llm.complete("Hi", new AbortController().signal); + test( + "Complete works", + async () => { + const completion = await llm.complete( + "Hi", + new AbortController().signal, + ); - expect(completion.length).toBeGreaterThan(0); - return; - }); + expect(completion.length).toBeGreaterThan(0); + return; + }, + timeout, + ); + + if (testFim) { + test( + "FIM works", + async () => { + let total = ""; + for await (const chunk of llm.streamFim( + "Hi", + "name is ChatGPT.", + new AbortController().signal, + )) { + total += chunk; + } + + expect(total.length).toBeGreaterThan(0); + return; + }, + timeout, + ); + } + + if (testToolCall) { + test( + "Tool Call works", + async () => { + let args = ""; + let isFirstChunk = true; + for await (const chunk of llm.streamChat( + [{ role: "user", content: "Hi, my name is Nate." }], + new AbortController().signal, + { + tools: [ + { + displayTitle: "Say Hello", + function: { + name: "say_hello", + description: "Say Hello", + parameters: { + type: "object", + properties: { + name: { + type: "string", + description: "The name of the person to greet", + }, + }, + }, + }, + type: "function", + wouldLikeTo: "Say hello", + readonly: true, + }, + ], + toolChoice: { + type: "function", + function: { + name: "say_hello", + }, + }, + }, + )) { + const typedChunk = chunk as AssistantChatMessage; + if (!typedChunk.toolCalls) { + continue; + } + const toolCall = typedChunk.toolCalls[0]; + args += toolCall.function?.arguments ?? ""; + + expect(chunk.role).toBe("assistant"); + expect(chunk.content).toBe(""); + expect(typedChunk.toolCalls).toHaveLength(1); + + if (isFirstChunk) { + isFirstChunk = false; + expect(toolCall.id).toBeDefined(); + expect(toolCall.function!.name).toBe("say_hello"); + } + } + + const parsedArgs = JSON.parse(args); + expect(parsedArgs.name).toBe("Nate"); + }, + timeout, + ); + } }); } -describe.skip("LLM", () => { - // testLLM( - // new FreeTrial({ - // model: "gpt-3.5-turbo", - // }), - // ); - // testLLM( - // new Anthropic({ - // model: "claude-2", - // apiKey: process.env.ANTHROPIC_API_KEY, - // }), - // ); +describe("LLM", () => { testLLM( - new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "gpt-3.5-turbo" }), + new Anthropic({ + model: "claude-3-5-sonnet-latest", + apiKey: process.env.ANTHROPIC_API_KEY, + }), + { + skip: false, + testToolCall: true, + }, + ); + testLLM(new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "gpt-4o" }), { + skip: false, + testToolCall: true, + }); + testLLM( + new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "o1-preview" }), + { skip: false, timeout: 20000 }, + ); + testLLM(new OpenAI({ apiKey: process.env.OPENAI_API_KEY, model: "o1" }), { + skip: false, + }); + testLLM( + new Gemini({ + model: "gemini-2.0-flash-exp", + apiKey: process.env.GEMINI_API_KEY, + }), + { skip: false }, + ); + testLLM( + new Mistral({ + apiKey: process.env.MISTRAL_API_KEY, + model: "codestral-latest", + }), + { testFim: true, skip: false }, ); - // TODO: Fix Replicate - // testLLM( - // new Replicate({ - // apiKey: process.env.REPLICATE_API_KEY, - // model: "codellama-7b", - // }) - // ); - // testLLM(new LMStudio({ model: "codellama-7b" })); - // testLLM(new Ollama({ model: "codellama-7b" })); - // testLLM( - // new Together({ - // apiKey: process.env.TOGETHER_API_KEY, - // model: "codellama-7b", - // }) - // ); - // testLLM(new LlamaCpp({ model: "deepseek-7b" })); - // testLLM(new Llamafile({ model: "mistral-7b" })); - // TODO: Test these - // testLLM(new TextGenWebUI({ model: "codellama-7b" })); - // testLLM(new HuggingFaceTGI({ model: "codellama-7b" })); - // testLLM(new HuggingFaceInferenceAPI({ model: "codellama-7b" })); - // testLLM( - // new Gemini({ - // model: "gemini-pro", - // // model: "chat-bison-001", - // apiKey: process.env.GOOGLE_PALM_API_KEY, - // }) - // ); - // testLLM( - // new Gemini({ model: "gemini-pro", apiKey: process.env.GOOGLE_PALM_API_KEY }) - // ); - // testLLM( - // new Mistral({ apiKey: process.env.MISTRAL_API_KEY, model: "mistral-small" }) - // ); - // testLLM( - // new Flowise({ apiKey: process.env.FLOWISE_API_KEY, model: "gpt-3.5-turbo" }) - // ); - // testLLM( - // new Nebius({ apiKey: process.env.NEBIUS_API_KEY, model: "llama3.1-8b" }) - // ); }); diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index 234c16860..df527d579 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -30,6 +30,12 @@ class Anthropic extends BaseLLM { description: tool.function.description, input_schema: tool.function.parameters, })), + tool_choice: options.toolChoice + ? { + type: "tool", + name: options.toolChoice.function.name, + } + : undefined, }; return finalOptions; diff --git a/core/llm/llms/Asksage.ts b/core/llm/llms/Asksage.ts index 544b947c2..59554efe5 100644 --- a/core/llm/llms/Asksage.ts +++ b/core/llm/llms/Asksage.ts @@ -1,4 +1,9 @@ -import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; +import { + ChatMessage, + CompletionOptions, + LLMOptions, + TextMessagePart, +} from "../../index.js"; import { BaseLLM } from "../index.js"; class Asksage extends BaseLLM { @@ -14,18 +19,19 @@ class Asksage extends BaseLLM { "gpt4-gov": "gpt4-gov", // Works "gpt-gov": "gpt-gov", // Works "gpt-4o": "gpt-4o", // Works - "gpt-4o-mini": "gpt-4o-mini", // Works - "gpt4": "gpt4", // Works + "gpt-4o-mini": "gpt-4o-mini", // Works + gpt4: "gpt4", // Works "gpt4-32k": "gpt4-32k", "gpt-o1": "gpt-o1", // Works "gpt-o1-mini": "gpt-o1-mini", // Works + "gpt-o3-mini": "gpt-o3-mini", // Stub "gpt-3.5-turbo": "gpt35-16k", // Works "aws-bedrock-claude-35-sonnet-gov": "aws-bedrock-claude-35-sonnet-gov", // Works "claude-3-5-sonnet-latest": "claude-35-sonnet", // Works "claude-3-opus-20240229": "claude-3-opus", // Works "claude-3-sonnet-20240229": "claude-3-sonnet", // Works "grok-beta": "xai-grok", - "groq-llama33": "groq-llama33", + "groq-llama33": "groq-llama33", "groq-70b": "groq-70b", "mistral-large-latest": "mistral-large", // Works "llama3-70b": "llma3", // Works @@ -50,7 +56,10 @@ class Asksage extends BaseLLM { message: typeof message.content === "string" ? message.content - : message.content.map((part) => part.text).join(""), + : message.content + .filter((part) => part.type === "text") + .map((part) => (part as TextMessagePart).text) + .join(""), }; } diff --git a/core/llm/llms/FreeTrial.ts b/core/llm/llms/FreeTrial.ts index 34b916346..c092a1ecb 100644 --- a/core/llm/llms/FreeTrial.ts +++ b/core/llm/llms/FreeTrial.ts @@ -113,10 +113,18 @@ class FreeTrial extends BaseLLM { } const parts = message.content.map((part) => { + if (part.type === "imageUrl") { + return { + type: "image_url", + image_url: { + url: part.imageUrl.url, + detail: "low", + }, + }; + } return { - type: part.type, + type: "text", text: part.text, - image_url: { ...part.imageUrl, detail: "low" }, }; }); return { diff --git a/core/llm/llms/Gemini.ts b/core/llm/llms/Gemini.ts index 02abd8bf9..4c0fb189b 100644 --- a/core/llm/llms/Gemini.ts +++ b/core/llm/llms/Gemini.ts @@ -1,12 +1,23 @@ +import { r } from "tar"; import { + AssistantChatMessage, ChatMessage, CompletionOptions, LLMOptions, MessagePart, + ToolCallDelta, } from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; import { streamResponse } from "../stream.js"; +import { + GeminiChatContentPart, + GeminiChatRequestBody, + GeminiChatResponse, + GeminiGenerationConfig, + GeminiToolFunctionDeclaration, +} from "./gemini-types.js"; +import { findLast } from "../../util/findLast.js"; class Gemini extends BaseLLM { static providerName = "gemini"; @@ -19,7 +30,7 @@ class Gemini extends BaseLLM { }; // Function to convert completion options to Gemini format - public convertArgs(options: CompletionOptions) { + public convertArgs(options: CompletionOptions): GeminiGenerationConfig { // should be public for use within VertexAI const finalOptions: any = {}; // Initialize an empty object @@ -42,7 +53,7 @@ class Gemini extends BaseLLM { .slice(0, this.maxStopWords ?? Gemini.defaultOptions.maxStopWords); } - return { generationConfig: finalOptions }; // Wrap options under 'generationConfig' + return finalOptions; } protected async *_streamComplete( @@ -59,7 +70,7 @@ class Gemini extends BaseLLM { } } - public removeSystemMessage(messages: ChatMessage[]) { + public removeSystemMessage(messages: ChatMessage[]): ChatMessage[] { // should be public for use within VertexAI const msgs = [...messages]; @@ -92,8 +103,8 @@ class Gemini extends BaseLLM { ? this.removeSystemMessage(messages) : messages; - if (options.model.includes("gemini")) { - for await (const message of this.streamChatGemini( + if (options.model.includes("bison")) { + for await (const message of this.streamChatBison( convertedMsgs, signal, options, @@ -101,7 +112,7 @@ class Gemini extends BaseLLM { yield message; } } else { - for await (const message of this.streamChatBison( + for await (const message of this.streamChatGemini( convertedMsgs, signal, options, @@ -111,7 +122,7 @@ class Gemini extends BaseLLM { } } - continuePartToGeminiPart(part: MessagePart) { + continuePartToGeminiPart(part: MessagePart): GeminiChatContentPart { return part.type === "text" ? { text: part.text, @@ -135,39 +146,165 @@ class Gemini extends BaseLLM { ); // This feels hacky to repeat code from above function but was the quickest // way to ensure system message re-formatting isn't done if user has specified v1 - const apiBase = - this.apiBase || - Gemini.defaultOptions?.apiBase || - "https://generativelanguage.googleapis.com/v1beta/"; // Determine if it's a v1 API call based on apiBase + const apiBase = this.apiBase || Gemini.defaultOptions.apiBase!; // Determine if it's a v1 API call based on apiBase const isV1API = apiBase.includes("/v1/"); - const contents = messages - .map((msg) => { - if (msg.role === "system" && !isV1API) { - return null; // Don't include system message in contents - } - if (msg.role === "tool") { - return null; - } - return { - role: msg.role === "assistant" ? "model" : "user", - parts: - typeof msg.content === "string" - ? [{ text: msg.content }] - : msg.content.map(this.continuePartToGeminiPart), - }; - }) - .filter((c) => c !== null); + // Convert chat messages to contents + const body: GeminiChatRequestBody = { + contents: messages + .filter((msg) => !(msg.role === "system" && isV1API)) + .map((msg) => { + if (msg.role === "tool") { + let fn_name = ""; + const lastToolCallMessage = findLast( + messages, + (msg) => "toolCalls" in msg && msg.toolCalls?.[0]?.function?.name, + ) as AssistantChatMessage; + if (lastToolCallMessage) { + fn_name = lastToolCallMessage.toolCalls![0]!.function!.name!; + } + if (!fn_name) { + console.warn( + "Sending tool call response for unidentified tool call", + ); + } + return { + role: "user", + parts: [ + { + functionResponse: { + name: fn_name || "unknown", + response: { + output: msg.content, // "output" key is opinionated - not all functions will output objects + }, + }, + }, + ], + }; + } + const assistantMsg = { + role: + msg.role === "assistant" ? ("model" as const) : ("user" as const), + parts: + typeof msg.content === "string" + ? [{ text: msg.content }] + : msg.content.map(this.continuePartToGeminiPart), + }; + if (msg.role === "assistant" && msg.toolCalls) { + msg.toolCalls.forEach((toolCall) => { + if (toolCall.function?.name && toolCall.function?.arguments) { + assistantMsg.parts.push({ + functionCall: { + name: toolCall.function.name, + args: JSON.parse(toolCall.function.arguments), + }, + }); + } + }); + } - const body = { - ...this.convertArgs(options), - contents, - // if this.systemMessage is defined, reformat it for Gemini API - ...(this.systemMessage && - !isV1API && { - systemInstruction: { parts: [{ text: this.systemMessage }] }, + return assistantMsg; }), }; + if (options) { + body.generationConfig = this.convertArgs(options); + } + + // https://ai.google.dev/gemini-api/docs/api-versions + if (!isV1API) { + if (this.systemMessage) { + body.systemInstruction = { parts: [{ text: this.systemMessage }] }; + } + // Convert and add tools if present + if (options.tools?.length) { + // Choosing to map all tools to the functionDeclarations of one tool + // Rather than map each tool to its own tool + functionDeclaration + // Same difference + const functions: GeminiToolFunctionDeclaration[] = []; + options.tools.forEach((tool) => { + if (tool.function.description && tool.function.name) { + const fn: GeminiToolFunctionDeclaration = { + description: tool.function.description, + name: tool.function.name, + }; + + if ( + tool.function.parameters && + "type" in tool.function.parameters + // && typeof tool.function.parameters.type === "string" + ) { + // const paramType = "TYPE_UNSPECIFIED" + // | "STRING" + // | "NUMBER" + // | "INTEGER" + // | "BOOLEAN" + // | "ARRAY" + // | "OBJECT" + + if (tool.function.parameters.type === "object") { + // Gemini can't take an empty object + // So if empty object param is present just don't add parameters + if ( + JSON.stringify(tool.function.parameters.properties) === "{}" + ) { + functions.push(fn); + return; + } + } + // Helper function to recursively clean JSON Schema objects + const cleanJsonSchema = (schema: any): any => { + if (!schema || typeof schema !== 'object') return schema; + + if (Array.isArray(schema)) { + return schema.map(cleanJsonSchema); + } + + const { + $schema, + additionalProperties, + default: defaultValue, + ...rest + } = schema; + + // Recursively clean nested properties + if (rest.properties) { + rest.properties = Object.entries(rest.properties).reduce( + (acc, [key, value]) => ({ + ...acc, + [key]: cleanJsonSchema(value), + }), + {} + ); + } + + // Clean items in arrays + if (rest.items) { + rest.items = cleanJsonSchema(rest.items); + } + + return rest; + }; + + // Clean the parameters and convert type to uppercase + const cleanedParams = cleanJsonSchema(tool.function.parameters); + fn.parameters = { + ...cleanedParams, + type: tool.function.parameters.type.toUpperCase(), + }; + } + functions.push(fn); + } + }); + if (functions.length) { + body.tools = [ + { + functionDeclarations: functions, + }, + ]; + } + } + } + const response = await this.fetch(apiURL, { method: "POST", body: JSON.stringify(body), @@ -192,24 +329,91 @@ class Gemini extends BaseLLM { let foundIncomplete = false; for (let i = 0; i < parts.length; i++) { const part = parts[i]; - let data; + let data: GeminiChatResponse; try { - data = JSON.parse(part); + data = JSON.parse(part) as GeminiChatResponse; } catch (e) { foundIncomplete = true; continue; // yo! } - if (data.error) { + + if ("error" in data) { throw new Error(data.error.message); } + // Check for existence of each level before accessing the final 'text' property - if (data?.candidates?.[0]?.content?.parts?.[0]?.text) { - // Incrementally stream the content to make it smoother - const content = data.candidates[0].content.parts[0].text; - yield { - role: "assistant", - content, - }; + const content = data?.candidates?.[0]?.content; + if (content) { + const supportedParts: MessagePart[] = []; + const toolCalls: ToolCallDelta[] = []; + + // Process all parts first to maintain order + const processedParts: Array<{ + type: 'content' | 'tool' | 'toolCall', + data: any + }> = []; + + for (const part of content.parts) { + if ("text" in part) { + supportedParts.push({ type: "text", text: part.text }); + } else if ("inlineData" in part) { + supportedParts.push({ + type: "imageUrl", + imageUrl: { + url: `data:image/jpeg;base64,${part.inlineData.data}`, + }, + }); + } else if ("functionCall" in part) { + // Queue function call + processedParts.push({ + type: 'toolCall', + data: { + type: "function", + id: "", // Not supported by gemini + function: { + name: part.functionCall.name, + arguments: + typeof part.functionCall.args === "string" + ? part.functionCall.args + : JSON.stringify(part.functionCall.args), + }, + } + }); + } else if ("functionResponse" in part) { + // Queue function response + processedParts.push({ + type: 'tool', + data: { + role: "tool", + content: part.functionResponse.response.output as string, + toolCallId: part.functionResponse.name, + } + }); + } else { + console.warn("Unsupported gemini part type received", part); + } + } + + // If we have supported content parts, yield them first + if (supportedParts.length) { + yield { + role: "assistant", + content: supportedParts, + }; + } + + // Then process tool calls and responses in order + for (const part of processedParts) { + if (part.type === 'toolCall') { + yield { + role: "assistant", + content: "", + toolCalls: [part.data], + }; + } else if (part.type === 'tool') { + yield part.data; + } + } } else { // Handle the case where the expected data structure is not found console.warn("Unexpected response format:", data); diff --git a/core/llm/llms/Groq.ts b/core/llm/llms/Groq.ts index cf26f993c..3585e73d8 100644 --- a/core/llm/llms/Groq.ts +++ b/core/llm/llms/Groq.ts @@ -10,19 +10,16 @@ class Groq extends OpenAI { maxStopWords: number | undefined = 4; private static modelConversion: { [key: string]: string } = { - "llama2-70b": "llama2-70b-4096", "mistral-8x7b": "mixtral-8x7b-32768", - gemma: "gemma-7b-it", gemma2: "gemma2-9b-it", "llama3-8b": "llama3-8b-8192", "llama3-70b": "llama3-70b-8192", "llama3.1-8b": "llama-3.1-8b-instant", - "llama3.1-70b": "llama-3.1-70b-versatile", - "llama3.1-405b": "llama-3.1-405b-reasoning", "llama3.2-1b": "llama-3.2-1b-preview", "llama3.2-3b": "llama-3.2-3b-preview", "llama3.2-11b": "llama-3.2-11b-vision-preview", "llama3.2-90b": "llama-3.2-90b-vision-preview", + "llama3.3-70b": "llama-3.3-70b-versatile", }; protected _convertModelName(model: string): string { return Groq.modelConversion[model] ?? model; diff --git a/core/llm/llms/Mock.ts b/core/llm/llms/Mock.ts index 236af9824..03e268074 100644 --- a/core/llm/llms/Mock.ts +++ b/core/llm/llms/Mock.ts @@ -1,7 +1,7 @@ import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; import { BaseLLM } from "../index.js"; -type MockMessage = ChatMessage | "REPEAT_LAST_MSG"; +type MockMessage = ChatMessage | "REPEAT_LAST_MSG" | "REPEAT_SYSTEM_MSG"; class MockLLM extends BaseLLM { public completion: string = "Test Completion"; @@ -42,6 +42,13 @@ class MockLLM extends BaseLLM { content: messages[messages.length - 1].content, }; break; + case "REPEAT_SYSTEM_MSG": + yield { + role: "assistant", + content: + messages.find((m) => m.role === "system")?.content || "", + }; + break; default: yield message; } diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index caa00e923..b9734acb9 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -1,4 +1,4 @@ -import { JSONSchema7Object, JSONSchema7Type } from "json-schema"; +import { JSONSchema7, JSONSchema7Object } from "json-schema"; import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; import { renderChatMessage } from "../../util/messageContent.js"; @@ -12,7 +12,7 @@ type OllamaChatMessage = { tool_calls?: { function: { name: string; - arguments: Record; + arguments: JSONSchema7Object; }; }[]; }; @@ -119,7 +119,7 @@ interface OllamaTool { function: { name: string; description?: string; - parameters?: JSONSchema7Object; + parameters?: JSONSchema7; }; } @@ -273,10 +273,8 @@ class Ollama extends BaseLLM { content: "", }; - if (typeof message.content === "string") { - ollamaMessage.content = message.content; - } else { - ollamaMessage.content = renderChatMessage(message); + ollamaMessage.content = renderChatMessage(message); + if (Array.isArray(message.content)) { const images: string[] = []; message.content.forEach((part) => { if (part.type === "imageUrl" && part.imageUrl) { diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 1cf1bc44e..e0acc961e 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -49,6 +49,7 @@ const CHAT_ONLY_MODELS = [ "gpt-4o-mini", "o1-preview", "o1-mini", + "o3-mini" ]; const formatMessageForO1 = (messages: ChatCompletionMessageParam[]) => { @@ -92,8 +93,8 @@ class OpenAI extends BaseLLM { return model; } - private isO1Model(model?: string): boolean { - return !!model && model.startsWith("o1"); + private isO3orO1Model(model?: string): boolean { + return !!model && (model.startsWith("o1") || model.startsWith("o3")); } protected supportsPrediction(model: string): boolean { @@ -113,6 +114,10 @@ class OpenAI extends BaseLLM { }; } + protected extraBodyProperties(): Record { + return {}; + } + protected getMaxStopWords(): number { const url = new URL(this.apiBase!); @@ -140,8 +145,8 @@ class OpenAI extends BaseLLM { finalOptions.stop = options.stop?.slice(0, this.getMaxStopWords()); - // OpenAI o1-preview and o1-mini: - if (this.isO1Model(options.model)) { + // OpenAI o1-preview and o1-mini or o3-mini: + if (this.isO3orO1Model(options.model)) { // a) use max_completion_tokens instead of max_tokens finalOptions.max_completion_tokens = options.maxTokens; finalOptions.max_tokens = undefined; @@ -150,6 +155,10 @@ class OpenAI extends BaseLLM { finalOptions.messages = formatMessageForO1(finalOptions.messages); } + if (options.model === "o1") { + finalOptions.stream = false; + } + if (options.prediction && this.supportsPrediction(options.model)) { if (finalOptions.presence_penalty) { // prediction doesn't support > 0 @@ -231,8 +240,8 @@ class OpenAI extends BaseLLM { ): ChatCompletionCreateParams { body.stop = body.stop?.slice(0, this.getMaxStopWords()); - // OpenAI o1-preview and o1-mini: - if (this.isO1Model(body.model)) { + // OpenAI o1-preview and o1-mini or o3-mini: + if (this.isO3orO1Model(body.model)) { // a) use max_completion_tokens instead of max_tokens body.max_completion_tokens = body.max_tokens; body.max_tokens = undefined; @@ -241,6 +250,11 @@ class OpenAI extends BaseLLM { body.messages = formatMessageForO1(body.messages); } + if (body.model === "o1") { + // o1 doesn't support streaming + body.stream = false; + } + if (body.prediction && this.supportsPrediction(body.model)) { if (body.presence_penalty) { // prediction doesn't support > 0 @@ -278,6 +292,7 @@ class OpenAI extends BaseLLM { body: JSON.stringify({ ...args, stream: true, + ...this.extraBodyProperties(), }), signal, }); @@ -319,7 +334,10 @@ class OpenAI extends BaseLLM { const response = await this.fetch(this._getEndpoint("chat/completions"), { method: "POST", headers: this._getHeaders(), - body: JSON.stringify(body), + body: JSON.stringify({ + ...body, + ...this.extraBodyProperties(), + }), signal, }); @@ -358,6 +376,7 @@ class OpenAI extends BaseLLM { presence_penalty: options.presencePenalty, stop: options.stop, stream: true, + ...this.extraBodyProperties(), }), headers: { "Content-Type": "application/json", @@ -404,6 +423,7 @@ class OpenAI extends BaseLLM { body: JSON.stringify({ input: chunks, model: this.model, + ...this.extraBodyProperties(), }), headers: { Authorization: `Bearer ${this.apiKey}`, diff --git a/core/llm/llms/VertexAI.ts b/core/llm/llms/VertexAI.ts index 43aa4d6ac..8d20c3212 100644 --- a/core/llm/llms/VertexAI.ts +++ b/core/llm/llms/VertexAI.ts @@ -124,7 +124,7 @@ class VertexAI extends BaseLLM { } for await (const value of streamSse(response)) { - if (value.type == "message_start") { + if (value.type === "message_start") { console.log(value); } if (value.delta?.text) { @@ -389,11 +389,11 @@ class VertexAI extends BaseLLM { const convertedMsgs = isV1API ? this.geminiInstance.removeSystemMessage(messages) : messages; - if (this.vertexProvider == "gemini") { + if (this.vertexProvider === "gemini") { yield* this.streamChatGemini(convertedMsgs, options); - } else if (this.vertexProvider == "mistral") { + } else if (this.vertexProvider === "mistral") { yield* this.StreamChatMistral(messages, options); - } else if (this.vertexProvider == "anthropic") { + } else if (this.vertexProvider === "anthropic") { yield* this.StreamChatAnthropic(messages, options); } else { if (options.model.includes("bison")) { diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts index bbc967519..17c8b1d4b 100644 --- a/core/llm/llms/WatsonX.ts +++ b/core/llm/llms/WatsonX.ts @@ -95,15 +95,16 @@ class WatsonX extends BaseLLM { } const parts = message.content.map((part) => { - const msg: any = { - type: part.type, + if (part.type === "imageUrl") { + return { + type: "image_url", + image_url: { ...part.imageUrl, detail: "low" }, + }; + } + return { + type: "text", text: part.text, }; - if (part.type === "imageUrl") { - msg.image_url = { ...part.imageUrl, detail: "low" }; - msg.type = "image_url"; - } - return msg; }); return { ...message, diff --git a/core/llm/llms/gemini-types.ts b/core/llm/llms/gemini-types.ts new file mode 100644 index 000000000..b9fb52c1d --- /dev/null +++ b/core/llm/llms/gemini-types.ts @@ -0,0 +1,268 @@ +import { JSONSchema7Object } from "json-schema"; + +// https://ai.google.dev/api/generate-content +export interface GeminiGenerationConfig { + stopSequences?: string[]; + responseMimeType?: string; + candidateCount?: number; + maxOutputTokens?: number; + temperature?: number; + topP?: number; + topK?: number; + presencePenalty?: number; + frequencyPenalty?: number; + responseLogprobs?: boolean; + logprobs?: number; + // responseSchema?: object; // https://ai.google.dev/api/caching#Schema +} + +export interface GeminiFunctionSchema { + type: + | "TYPE_UNSPECIFIED" + | "STRING" + | "NUMBER" + | "INTEGER" + | "BOOLEAN" + | "ARRAY" + | "OBJECT"; + format?: string; + description?: string; + nullable?: boolean; + enum?: string[]; + maxItems?: string; + minItems?: string; + properties?: Record; + required?: string[]; + items?: GeminiFunctionSchema; +} + +export type GeminiChatContentPart = + | { + text: string; + } + | { + inlineData: { + mimeType: string; + data: string; + }; + } + | { + functionCall: { + name: string; + args: JSONSchema7Object; + }; + } + | { + functionResponse: { + name: string; + response: JSONSchema7Object; + }; + } + | { + fileData: { + fileUri: string; + mimeType: string; // See possible values here: https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#filedata + }; + } + | { + executableCode: { + language: "PYTHON" | "LANGUAGE_UNSPECIFIED"; + code: string; + }; + } + | { + codeExecutionResult: { + outcome: + | "OUTCOME_UNSPECIFIED" + | "OUTCOME_OK" + | "OUTCOME_FAILED" + | "OUTCOME_DEADLINE_EXCEEDED"; + output: string; + }; + }; +export interface GeminiChatContent { + role?: "user" | "model"; + parts: GeminiChatContentPart[]; +} + +export interface GeminiToolFunctionDeclaration { + name: string; + description: string; + parameters?: GeminiFunctionSchema; +} +export interface GeminiTool { + functionDeclarations?: GeminiToolFunctionDeclaration[]; + googleSearchRetrieval?: { + dynamicRetrievalConfig: { + mode?: "MODE_DYNAMIC" | "MODE_UNSPECIFIED"; + dynamicThreshold?: number; + }; + }; + codeExecution?: {}; +} + +export interface GeminiToolConfig { + functionCallingConfig?: { + mode?: "NONE" | "ANY" | "AUTO"; + allowedFunctionNames?: string[]; + }; +} + +// https://ai.google.dev/api/generate-content#request-body +export interface GeminiChatRequestBody { + contents: GeminiChatContent[]; + tools?: GeminiTool[]; + toolConfig?: GeminiToolConfig; + systemInstruction?: GeminiChatContent; + generationConfig?: GeminiGenerationConfig; + // cachedContent?: string; +} + +export interface GeminiChatResponseSuccess { + candidates: Candidate[]; + promptFeedback: PromptFeedback; + usageMetadata: UsageMetadata; +} + +export interface GeminiChatResponseError { + error: { + message: string; + }; +} + +export type GeminiChatResponse = + | GeminiChatResponseError + | GeminiChatResponseSuccess; + +interface PromptFeedback { + blockReason?: BlockReason; + safetyRatings: SafetyRating[]; +} + +enum BlockReason { + BLOCK_REASON_UNSPECIFIED = "BLOCK_REASON_UNSPECIFIED", + SAFETY = "SAFETY", + OTHER = "OTHER", + BLOCKLIST = "BLOCKLIST", + PROHIBITED_CONTENT = "PROHIBITED_CONTENT", +} + +interface SafetyRating { + harmCategory: HarmCategory; + harmProbability: HarmProbability; + blocked: boolean; +} + +enum HarmCategory { + HARM_CATEGORY_UNSPECIFIED = "HARM_CATEGORY_UNSPECIFIED", + HARM_CATEGORY_DEROGATORY = "HARM_CATEGORY_DEROGATORY", + HARM_CATEGORY_TOXICITY = "HARM_CATEGORY_TOXICITY", + HARM_CATEGORY_VIOLENCE = "HARM_CATEGORY_VIOLENCE", + HARM_CATEGORY_SEXUAL = "HARM_CATEGORY_SEXUAL", + HARM_CATEGORY_MEDICAL = "HARM_CATEGORY_MEDICAL", + HARM_CATEGORY_DANGEROUS = "HARM_CATEGORY_DANGEROUS", + HARM_CATEGORY_HARASSMENT = "HARM_CATEGORY_HARASSMENT", + HARM_CATEGORY_HATE_SPEECH = "HARM_CATEGORY_HATE_SPEECH", + HARM_CATEGORY_SEXUALLY_EXPLICIT = "HARM_CATEGORY_SEXUALLY_EXPLICIT", + HARM_CATEGORY_DANGEROUS_CONTENT = "HARM_CATEGORY_DANGEROUS_CONTENT", + HARM_CATEGORY_CIVIC_INTEGRITY = "HARM_CATEGORY_CIVIC_INTEGRITY", +} + +enum HarmProbability { + HARM_PROBABILITY_UNSPECIFIED = "HARM_PROBABILITY_UNSPECIFIED", + NEGLIGIBLE = "NEGLIGIBLE", + LOW = "LOW", + MEDIUM = "MEDIUM", + HIGH = "HIGH", +} + +interface UsageMetadata { + promptTokenCount: number; + cachedContentTokenCount: number; + candidatesTokenCount: number; + totalTokenCount: number; +} + +interface Candidate { + content: GeminiChatContent; + finishReason: FinishReason; + safetyRatings: SafetyRating[]; + tokenCount: number; + groundingAttribution?: GroundingAttribution; + groundingMetadata?: GroundingMetadata; + avgLogprobs?: number; + logprobs?: LogprobsResult; + index: number; +} + +enum FinishReason { + FINISH_REASON_UNSPECIFIED = "FINISH_REASON_UNSPECIFIED", + STOP = "STOP", + MAX_TOKENS = "MAX_TOKENS", + SAFETY = "SAFETY", + RECITATION = "RECITATION", + LANGUAGE = "LANGUAGE", + OTHER = "OTHER", + BLOCKLIST = "BLOCKLIST", + PROHIBITED_CONTENT = "PROHIBITED_CONTENT", + SPII = "SPII", + MALFORMED_FUNCTION_CALL = "MALFORMED_FUNCTION_CALL", +} + +interface GroundingAttribution { + attributionSourceId: AttributionSourceId; + groundingSourceContent: string; +} + +interface AttributionSourceId { + groundingPassage?: GroundingPassageId; + semanticRetrieverChunk?: SemanticRetrieverChunk; +} + +interface GroundingPassageId { + passageId: string; + partIndex: number; +} + +interface SemanticRetrieverChunk { + source: string; + chunk: string; +} + +interface GroundingMetadata { + groundingSupport?: GroundingSupport[]; + webSearchQueries?: string[]; + searchEntryPoint?: SearchEntryPoint; + retrievalMetadata?: RetrievalMetadata; +} + +interface SearchEntryPoint { + renderedContent?: string; + sdkBlob?: string; +} + +interface RetrievalMetadata { + googleSearchDynamicRetrievalScore?: number; +} + +interface GroundingSupport { + groundingChunkIndices: number[]; + confidenceScores: number[]; + segment: Segment; +} + +interface Segment { + partIndex: number; + startIndex: number; + endIndex: number; + text: string; +} + +interface LogprobsResult { + topCandidates: TopCandidates[]; + chosenCandidates: Candidate[]; +} + +interface TopCandidates { + candidates: Candidate[]; +} diff --git a/core/llm/llms/stubs/ContinueProxy.ts b/core/llm/llms/stubs/ContinueProxy.ts index c037ebd61..848b3fff7 100644 --- a/core/llm/llms/stubs/ContinueProxy.ts +++ b/core/llm/llms/stubs/ContinueProxy.ts @@ -10,11 +10,31 @@ class ContinueProxy extends OpenAI { this.apiBase = new URL("openai/v1/", value.controlPlaneProxyUrl).toString(); } + // The apiKey and apiBase are set to the values for the proxy, + // but we need to keep track of the actual values that the proxy will use + // to call whatever LLM API is chosen + private actualApiBase?: string; + + constructor(options: LLMOptions) { + super(options); + this.actualApiBase = options.apiBase; + this.apiKeyLocation = options.apiKeyLocation; + } + static providerName = "continue-proxy"; static defaultOptions: Partial = { useLegacyCompletionsEndpoint: false, }; + protected extraBodyProperties(): Record { + return { + continueProperties: { + apiKeyLocation: this.apiKeyLocation, + apiBase: this.actualApiBase, + }, + }; + } + protected _getHeaders() { const headers: any = super._getHeaders(); headers["x-continue-unique-id"] = Telemetry.uniqueId; diff --git a/core/llm/openaiTypeConverters.ts b/core/llm/openaiTypeConverters.ts index 057219beb..4ed8be1c4 100644 --- a/core/llm/openaiTypeConverters.ts +++ b/core/llm/openaiTypeConverters.ts @@ -1,13 +1,21 @@ import { FimCreateParamsStreaming } from "@continuedev/openai-adapters/dist/apis/base"; import { + Chat, ChatCompletion, + ChatCompletionAssistantMessageParam, ChatCompletionChunk, ChatCompletionCreateParams, ChatCompletionMessageParam, + ChatCompletionUserMessageParam, CompletionCreateParams, } from "openai/resources/index"; -import { ChatMessage, CompletionOptions } from ".."; +import { + ChatMessage, + CompletionOptions, + MessageContent, + TextMessagePart, +} from ".."; export function toChatMessage( message: ChatMessage, @@ -26,43 +34,55 @@ export function toChatMessage( }; } - let msg: ChatCompletionMessageParam = { - role: message.role, - content: - typeof message.content === "string" - ? message.content || " " // LM Studio (and other providers) don't accept empty content - : !message.content.some((item) => item.type !== "text") - ? // If no multi-media is in the message, just send as text + if (message.role === "assistant") { + const msg: ChatCompletionAssistantMessageParam = { + role: "assistant", + content: + typeof message.content === "string" + ? message.content || " " // LM Studio (and other providers) don't accept empty content + : message.content + .filter((part) => part.type === "text") + .map((part) => part as TextMessagePart), // can remove with newer typescript version + }; + + if (message.toolCalls) { + msg.tool_calls = message.toolCalls.map((toolCall) => ({ + id: toolCall.id!, + type: toolCall.type!, + function: { + name: toolCall.function?.name!, + arguments: toolCall.function?.arguments!, + }, + })); + } + return msg; + } else { + return { + role: "user", + content: + typeof message.content === "string" + ? message.content || " " // LM Studio (and other providers) don't accept empty content + : // If no multi-media is in the message, just send as text // for compatibility with OpenAI-"compatible" servers // that don't support multi-media format - message.content.map((item) => item.text).join("") || " " - : message.content.map((part) => { - const msg: any = { - type: part.type, - text: part.text, - }; - if (part.type === "imageUrl") { - msg.image_url = { ...part.imageUrl, detail: "auto" }; - msg.type = "image_url"; - } - return msg; - }), - }; - if ( - msg.role === "assistant" && - message.role === "assistant" && - message.toolCalls - ) { - msg.tool_calls = message.toolCalls.map((toolCall) => ({ - id: toolCall.id!, - type: toolCall.type!, - function: { - name: toolCall.function?.name!, - arguments: toolCall.function?.arguments!, - }, - })); + message.content.some((item) => item.type !== "text") + ? message.content + .map((item) => (item as TextMessagePart).text) + .join("") || " " + : message.content.map((part) => { + if (part.type === "imageUrl") { + return { + type: "image_url" as const, + image_url: { + url: part.imageUrl.url, + detail: "auto" as const, + }, + }; + } + return part; + }), + }; } - return msg; } export function toChatBody( @@ -80,6 +100,7 @@ export function toChatBody( stream: options.stream ?? true, stop: options.stop, prediction: options.prediction, + tool_choice: options.toolChoice, }; if (options.tools?.length) { diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 889c98c91..dd8f72fb0 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -17,6 +17,10 @@ export const PROVIDER_TOOL_SUPPORT: Record< return true; } }, + gemini: (model) => { + // All gemini models support function calling + return model.toLowerCase().includes("gemini"); + }, // https://ollama.com/search?c=tools ollama: (model) => { if ( diff --git a/core/package-lock.json b/core/package-lock.json index 18a318596..7edab380e 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -13,7 +13,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.0", + "@continuedev/config-yaml": "^1.0.23", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", @@ -3030,18 +3030,19 @@ } }, "node_modules/@continuedev/config-types": { - "version": "1.0.13", - "resolved": "https://registry.npmjs.org/@continuedev/config-types/-/config-types-1.0.13.tgz", - "integrity": "sha512-5Qmy2x58uhW1GYknypFT/7iwxEJSbt8gMgfQReV7d6xjbJ09ISOTki3hIfCilKrTCo0gIY6pzKEfCoQkUTEi6Q==", + "version": "1.0.14", + "resolved": "https://registry.npmjs.org/@continuedev/config-types/-/config-types-1.0.14.tgz", + "integrity": "sha512-PVHyHPyRXd2QsaNgnCpiKYU3uHFTlyuQSkqE8OwrBmQqO6/TXUVIr/2EGtyIZGrml4Y+rGMSH40WU4/0t4SGpQ==", "dependencies": { "zod": "^3.23.8" } }, "node_modules/@continuedev/config-yaml": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.0.tgz", - "integrity": "sha512-NwagzzpnPLbMC3delzFSjWiFv5fp8ReFjdMQF0ko0Xg+U0Myja90k/J7JWGegF/SZMABxc/OJchElJFr58TwGA==", + "version": "1.0.23", + "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.23.tgz", + "integrity": "sha512-F2Hwc85iCwAHJuwJALOsmZIBeHdF+87mS0YT7dlC6QiE+zAhZKUHcLQ/nTt9bJuhyVyufpb9LApkp40UdGsaWw==", "dependencies": { + "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", "zod": "^3.23.8" } diff --git a/core/package.json b/core/package.json index e865e0ddb..111fbe902 100644 --- a/core/package.json +++ b/core/package.json @@ -46,7 +46,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.621.0", "@aws-sdk/credential-providers": "^3.620.1", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.0", + "@continuedev/config-yaml": "^1.0.23", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.2", "@continuedev/openai-adapters": "^1.0.10", diff --git a/core/promptFiles/v2/getPromptFiles.ts b/core/promptFiles/v2/getPromptFiles.ts index 2998b5f8f..d991d140a 100644 --- a/core/promptFiles/v2/getPromptFiles.ts +++ b/core/promptFiles/v2/getPromptFiles.ts @@ -16,11 +16,11 @@ export async function getPromptFilesFromDir( return []; } - const paths = await walkDir(dir, ide, { ignoreFiles: [] }); - const promptFilePaths = paths.filter((p) => p.endsWith(".prompt")); - const results = promptFilePaths.map(async (path) => { - const content = await ide.readFile(path); // make a try catch - return { path, content }; + const uris = await walkDir(dir, ide, { ignoreFiles: [] }); + const promptFilePaths = uris.filter((p) => p.endsWith(".prompt")); + const results = promptFilePaths.map(async (uri) => { + const content = await ide.readFile(uri); // make a try catch + return { path: uri, content }; }); return Promise.all(results); } catch (e) { diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 9495dc3b2..ce24dfcbb 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -1,6 +1,4 @@ -import { AutocompleteInput } from "../autocomplete/util/types"; -import { ProfileDescription } from "../config/ConfigHandler"; - +import { ConfigResult } from "@continuedev/config-yaml"; import type { BrowserSerializedContinueConfig, ChatMessage, @@ -9,11 +7,13 @@ import type { ContextProviderWithParams, ContextSubmenuItem, DiffLine, + DocsIndexingDetails, FileSymbolMap, IdeSettings, LLMFullCompletionOptions, ModelDescription, ModelRoles, + PromptLog, RangeInFile, SerializedContinueConfig, Session, @@ -21,28 +21,9 @@ import type { SiteIndexingConfig, ToolCall, } from "../"; -import { ConfigResult } from "../config/load"; - -export type ProtocolGeneratorYield = { - done?: boolean; - content: T; -}; -export type ProtocolGeneratorType = AsyncGenerator< - ProtocolGeneratorYield ->; - -export type AsyncGeneratorYieldType = - T extends AsyncGenerator - ? Y extends ProtocolGeneratorYield - ? PR - : never - : never; -// export type AsyncGeneratorReturnType = -// T extends AsyncGenerator -// ? R extends ProtocolGeneratorYield -// ? PR -// : never -// : never; +import { AutocompleteInput } from "../autocomplete/util/types"; +import { ProfileDescription } from "../config/ConfigHandler"; +import { SharedConfigSchema } from "../config/sharedConfig"; export type OnboardingModes = | "Local" @@ -91,6 +72,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { "config/reload": [undefined, ConfigResult]; "config/listProfiles": [undefined, ProfileDescription[]]; "config/openProfile": [{ profileId: string | undefined }, void]; + "config/updateSharedConfig": [SharedConfigSchema, void]; "context/getContextItems": [ { name: string; @@ -120,7 +102,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { historyIndex: number; selectedCode: RangeInFile[]; }, - ProtocolGeneratorType, + AsyncGenerator, ]; "llm/complete": [ { @@ -137,7 +119,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { completionOptions: LLMFullCompletionOptions; title: string; }, - ProtocolGeneratorType, + AsyncGenerator, ]; "llm/streamChat": [ { @@ -145,7 +127,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { completionOptions: LLMFullCompletionOptions; title: string; }, - ProtocolGeneratorType, + AsyncGenerator, ]; streamDiffLines: [ { @@ -156,7 +138,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { language: string | undefined; modelTitle: string | undefined; }, - ProtocolGeneratorType, + AsyncGenerator, ]; "chatDescriber/describe": [ { @@ -201,7 +183,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { "indexing/setPaused": [{ type: string; id: string; paused: boolean }, void]; "docs/getSuggestedDocs": [undefined, void]; "docs/initStatuses": [undefined, void]; - + "docs/getDetails": [{ startUrl: string }, DocsIndexingDetails]; addAutocompleteModel: [{ model: ModelDescription }, void]; "profiles/switch": [{ id: string }, undefined]; @@ -212,4 +194,5 @@ export type ToCoreFromIdeOrWebviewProtocol = { { contextItems: ContextItem[] }, ]; "clipboardCache/add": [{ content: string }, void]; + "controlPlane/openUrl": [{ path: string }, void]; }; diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index 8c0d2557c..5b2a7ab1f 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -13,8 +13,8 @@ import type { Problem, Range, RangeInFile, + TerminalOptions, Thread, - TerminalOptions } from "../"; export interface GetGhTokenArgs { @@ -29,7 +29,7 @@ export type ToIdeFromWebviewOrCoreProtocol = { showVirtualFile: [{ name: string; content: string }, void]; openFile: [{ path: string }, void]; openUrl: [string, void]; - runCommand: [{ command: string, options?: TerminalOptions }, void]; + runCommand: [{ command: string; options?: TerminalOptions }, void]; getSearchResults: [{ query: string }, string]; subprocess: [{ command: string; cwd?: string }, [string, string]]; saveFile: [{ filepath: string }, void]; @@ -72,6 +72,8 @@ export type ToIdeFromWebviewOrCoreProtocol = { isTelemetryEnabled: [undefined, boolean]; getUniqueId: [undefined, string]; getTags: [string, IndexTag[]]; + readSecrets: [{ keys: string[] }, Record]; + writeSecrets: [{ secrets: Record }, void]; // end methods from IDE type getIdeSettings: [undefined, IdeSettings]; @@ -92,7 +94,7 @@ export type ToIdeFromWebviewOrCoreProtocol = { getGitHubAuthToken: [GetGhTokenArgs, string | undefined]; getControlPlaneSessionInfo: [ - { silent: boolean }, + { silent: boolean; useOnboarding: boolean }, ControlPlaneSessionInfo | undefined, ]; logoutOfControlPlane: [undefined, void]; diff --git a/core/protocol/messenger/messageIde.ts b/core/protocol/messenger/messageIde.ts index aaa567f39..4bb78e0ed 100644 --- a/core/protocol/messenger/messageIde.ts +++ b/core/protocol/messenger/messageIde.ts @@ -29,6 +29,14 @@ export class MessageIde implements IDE { ) => void, ) {} + async readSecrets(keys: string[]): Promise> { + return this.request("readSecrets", { keys }); + } + + async writeSecrets(secrets: { [key: string]: string }): Promise { + return this.request("writeSecrets", { secrets }); + } + fileExists(fileUri: string): Promise { return this.request("fileExists", { filepath: fileUri }); } @@ -152,7 +160,7 @@ export class MessageIde implements IDE { await this.request("openUrl", url); } - async runCommand(command: string, options?: TerminalOptions): Promise { + async runCommand(command: string, options?: TerminalOptions): Promise { await this.request("runCommand", { command, options }); } diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index c4b999521..0ce81bfe8 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -23,6 +23,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "config/deleteModel", "config/listProfiles", "config/openProfile", + "config/updateSharedConfig", "context/getContextItems", "context/getSymbolsForFiles", "context/loadSubmenuItems", @@ -52,12 +53,14 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = "indexing/setPaused", "docs/getSuggestedDocs", "docs/initStatuses", + "docs/getDetails", // "completeOnboarding", "addAutocompleteModel", "profiles/switch", "didChangeSelectedProfile", "tools/call", + "controlPlane/openUrl", ]; // Message types to pass through from core to webview @@ -66,6 +69,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] = [ "configUpdate", + "configError", "getDefaultModelTitle", "indexProgress", // Codebase "indexing/statusUpdate", // Docs, etc. diff --git a/core/protocol/util.ts b/core/protocol/util.ts index c9fe3af1b..ab2225c84 100644 --- a/core/protocol/util.ts +++ b/core/protocol/util.ts @@ -1,17 +1,53 @@ import { FromWebviewProtocol } from "."; -interface ErrorWebviewMessengerResult { - done: boolean; +export interface ErrorWebviewMessage { status: "error"; error: string; + done: true; } -interface SuccessWebviewMessengerResult { - done: boolean; +export interface SuccessWebviewSingleMessage { + done: true; status: "success"; - content: FromWebviewProtocol[T][1]; + content: T; } -export type WebviewMessengerResult = - | ErrorWebviewMessengerResult - | SuccessWebviewMessengerResult; +export type WebviewSingleMessage = + | ErrorWebviewMessage + | SuccessWebviewSingleMessage; + +export type WebviewSingleProtocolMessage = + WebviewSingleMessage; + +// Generators +export type GeneratorYieldType = + T extends AsyncGenerator ? Yield : never; +export type GeneratorReturnType = + T extends AsyncGenerator ? Return : never; + +type SuccessWebviewGeneratorMessage = + | { + status: "success"; + done: false; + content: T; + } + | { + status: "success"; + done: true; + content: R; + }; + +export type WebviewGeneratorMessage = + | SuccessWebviewGeneratorMessage + | ErrorWebviewMessage; + +export type WebviewProtocolGeneratorMessage< + T extends keyof FromWebviewProtocol, +> = WebviewGeneratorMessage< + GeneratorYieldType, + GeneratorReturnType +>; + +export type WebviewMessage = + | WebviewSingleMessage + | WebviewGeneratorMessage; diff --git a/core/protocol/webview.ts b/core/protocol/webview.ts index 5e22faae6..822d9b532 100644 --- a/core/protocol/webview.ts +++ b/core/protocol/webview.ts @@ -1,11 +1,8 @@ -import { ConfigResult } from "../config/load.js"; -import { ConfigValidationError } from "../config/validation.js"; - +import { ConfigResult, ConfigValidationError } from "@continuedev/config-yaml"; import type { BrowserSerializedContinueConfig, ContextItemWithId, ContextProviderName, - ContextSubmenuItem, IndexingProgressUpdate, IndexingStatus, PackageDocsResult, diff --git a/core/test/fixtures.ts b/core/test/fixtures.ts index 78ee60150..4f8601303 100644 --- a/core/test/fixtures.ts +++ b/core/test/fixtures.ts @@ -11,6 +11,7 @@ export const ideSettingsPromise = testIde.getIdeSettings(); export const testControlPlaneClient = new ControlPlaneClient( Promise.resolve(undefined), + ideSettingsPromise, ); export const testConfigHandler = new ConfigHandler( diff --git a/core/tools/definitions/searchWeb.ts b/core/tools/definitions/searchWeb.ts index eb8e58c99..c5868f3e0 100644 --- a/core/tools/definitions/searchWeb.ts +++ b/core/tools/definitions/searchWeb.ts @@ -15,7 +15,7 @@ export const searchWebTool: Tool = { type: "object", required: ["query"], properties: { - repo_url: { + query: { type: "string", description: "The natural language search query", }, diff --git a/core/util/GlobalContext.ts b/core/util/GlobalContext.ts index 336dc8293..90b403d41 100644 --- a/core/util/GlobalContext.ts +++ b/core/util/GlobalContext.ts @@ -1,5 +1,11 @@ import fs from "node:fs"; +import { + salvageSharedConfig, + sharedConfigSchema, + SharedConfigSchema, +} from "../config/sharedConfig"; + import { getGlobalContextFilePath } from "./paths"; export type GlobalContextType = { @@ -16,6 +22,7 @@ export type GlobalContextType = { hasAlreadyCreatedAPromptFile: boolean; showConfigUpdateToast: boolean; isSupportedLanceDbCpuTarget: boolean; + sharedConfig: SharedConfigSchema; }; /** @@ -26,9 +33,10 @@ export class GlobalContext { key: T, value: GlobalContextType[T], ) { - if (!fs.existsSync(getGlobalContextFilePath())) { + const filepath = getGlobalContextFilePath(); + if (!fs.existsSync(filepath)) { fs.writeFileSync( - getGlobalContextFilePath(), + filepath, JSON.stringify( { [key]: value, @@ -38,7 +46,7 @@ export class GlobalContext { ), ); } else { - const data = fs.readFileSync(getGlobalContextFilePath(), "utf-8"); + const data = fs.readFileSync(filepath, "utf-8"); let parsed; try { @@ -49,21 +57,19 @@ export class GlobalContext { } parsed[key] = value; - fs.writeFileSync( - getGlobalContextFilePath(), - JSON.stringify(parsed, null, 2), - ); + fs.writeFileSync(filepath, JSON.stringify(parsed, null, 2)); } } get( key: T, ): GlobalContextType[T] | undefined { - if (!fs.existsSync(getGlobalContextFilePath())) { + const filepath = getGlobalContextFilePath(); + if (!fs.existsSync(filepath)) { return undefined; } - const data = fs.readFileSync(getGlobalContextFilePath(), "utf-8"); + const data = fs.readFileSync(filepath, "utf-8"); try { const parsed = JSON.parse(data); return parsed[key]; @@ -72,4 +78,31 @@ export class GlobalContext { return undefined; } } + + getSharedConfig(): SharedConfigSchema { + const sharedConfig = this.get("sharedConfig") ?? {}; + const result = sharedConfigSchema.safeParse(sharedConfig); + if (result.success) { + return result.data; + } else { + // in case of damaged shared config, repair it + // Attempt to salvage any values that are security concerns + console.error("Failed to load shared config, salvaging...", result.error); + const salvagedConfig = salvageSharedConfig(sharedConfig); + this.update("sharedConfig", salvagedConfig); + return salvagedConfig; + } + } + + updateSharedConfig( + newValues: Partial, + ): SharedConfigSchema { + const currentSharedConfig = this.getSharedConfig(); + const updatedSharedConfig = { + ...currentSharedConfig, + ...newValues, + }; + this.update("sharedConfig", updatedSharedConfig); + return updatedSharedConfig; + } } diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index b4297f7bc..3c6963071 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -21,6 +21,13 @@ import { GetGhTokenArgs } from "../protocol/ide.js"; class FileSystemIde implements IDE { constructor(private readonly workspaceDir: string) {} + + async readSecrets(keys: string[]): Promise> { + return {}; + } + + async writeSecrets(secrets: { [key: string]: string }): Promise {} + showToast( type: ToastType, message: string, @@ -46,8 +53,8 @@ class FileSystemIde implements IDE { remoteConfigSyncPeriod: 60, userToken: "", enableControlServerBeta: false, + continueTestEnvironment: "none", pauseCodebaseIndexOnStart: false, - enableDebugLogs: false, }; } async getGitHubAuthToken(args: GetGhTokenArgs): Promise { diff --git a/core/util/findLast.ts b/core/util/findLast.ts index fb39829e7..9e99fd473 100644 --- a/core/util/findLast.ts +++ b/core/util/findLast.ts @@ -12,3 +12,14 @@ export function findLastIndex( } return lastIndex; } + +export function findLast( + arr: T[], + criterion: (item: T) => any, +): T | undefined { + for (let i = arr.length - 1; i >= 0; i--) { + if (criterion(arr[i])) { + return arr[i]; + } + } +} diff --git a/core/util/messageContent.ts b/core/util/messageContent.ts index b1c91ca17..89462a1bf 100644 --- a/core/util/messageContent.ts +++ b/core/util/messageContent.ts @@ -3,6 +3,7 @@ import { ContextItem, MessageContent, MessagePart, + TextMessagePart, } from "../index"; export function stripImages(messageContent: MessageContent): string { @@ -12,7 +13,7 @@ export function stripImages(messageContent: MessageContent): string { return messageContent .filter((part) => part.type === "text") - .map((part) => part.text) + .map((part) => (part as TextMessagePart).text) .join("\n"); } diff --git a/core/util/parameters.ts b/core/util/parameters.ts index a7a11b503..648253712 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -2,7 +2,6 @@ import { TabAutocompleteOptions } from "../index.js"; export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { disable: false, - useFileSuffix: true, maxPromptTokens: 1024, prefixPercentage: 0.3, maxSuffixPercentage: 0.2, diff --git a/core/util/pathToUri.ts b/core/util/pathToUri.ts index 804b4fa99..67a249d74 100644 --- a/core/util/pathToUri.ts +++ b/core/util/pathToUri.ts @@ -4,7 +4,7 @@ import * as URI from "uri-js"; // CAN ONLY BE USED IN CORE -// Converts a local path to a file:// URI +// Converts a local path to a file:/// URI export function localPathToUri(path: string) { const url = pathToFileURL(path); return URI.normalize(url.toString()); diff --git a/core/util/paths.ts b/core/util/paths.ts index 8dd0cf84f..1198dec49 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -74,6 +74,10 @@ export function getGlobalContextFilePath(): string { return path.join(getIndexFolderPath(), "globalContext.json"); } +export function getSharedConfigFilePath(): string { + return path.join(getContinueGlobalPath(), "sharedConfig.json"); +} + export function getSessionFilePath(sessionId: string): string { return path.join(getSessionsFolderPath(), `${sessionId}.json`); } @@ -301,11 +305,6 @@ export function getPathToRemoteConfig(remoteConfigServerUrl: string): string { return dir; } -export function internalBetaPathExists(): boolean { - const sPath = path.join(getContinueGlobalPath(), ".internal_beta"); - return fs.existsSync(sPath); -} - export function getConfigJsonPathForRemote( remoteConfigServerUrl: string, ): string { diff --git a/docs/docs/actions/how-to-customize.md b/docs/docs/actions/how-to-customize.md index 81d33967b..0541bf464 100644 --- a/docs/docs/actions/how-to-customize.md +++ b/docs/docs/actions/how-to-customize.md @@ -50,6 +50,7 @@ export function modifyConfig(config: Config): Config { return config; } ``` + @@ -57,4 +58,4 @@ export function modifyConfig(config: Config): Config { Currently the other action triggers are not open for configuration, but we plan to allow this via .prompt files in the future. - + diff --git a/docs/docs/chat/model-setup.mdx b/docs/docs/chat/model-setup.mdx index eb7dc5430..e7e6ca94a 100644 --- a/docs/docs/chat/model-setup.mdx +++ b/docs/docs/chat/model-setup.mdx @@ -129,7 +129,8 @@ If your local machine can run an 8B parameter model, then we recommend running L { "title": "Llama 3.1 8B", "provider": "ollama", - "model": "llama3.1:8b" + "model": "llama3.1:8b", + "apiBase": "http://localhost:11434" } ] ``` @@ -158,7 +159,8 @@ If your local machine can run a 16B parameter model, then we recommend running D { "title": "DeepSeek Coder 2 16B", "provider": "ollama", - "model": "deepseek-coder-v2:16b" + "model": "deepseek-coder-v2:16b", + "apiBase": "http://localhost:11434" } ] ``` diff --git a/docs/docs/customize/context-providers.md b/docs/docs/customize/context-providers.md index 23d8c2253..d49b38c93 100644 --- a/docs/docs/customize/context-providers.md +++ b/docs/docs/customize/context-providers.md @@ -261,9 +261,9 @@ Uses the top _n_ levels (defaulting to 3) of the call stack for that thread. ### `@Repository Map` -Reference the outline of your codebase. +Reference the outline of your codebase. By default, signatures are included along with file in the repo map. -`includeSignatures` params can be used to include signatures for all files in the repo. Use with caution as will increase context size significantly. `includeSignatures` will not work if indexing is disabled. +`includeSignatures` params can be set to false to exclude signatures. This could be necessary for large codebases and/or to reduce context size significantly. Signatures will not be included if indexing is disabled. ```json title="config.json" { @@ -271,7 +271,7 @@ Reference the outline of your codebase. { "name": "repo-map", "params": { - "includeSignatures": false + "includeSignatures": false // default true } } ] diff --git a/docs/docs/customize/deep-dives/autocomplete.md b/docs/docs/customize/deep-dives/autocomplete.md index 221a6d49f..8d90f2145 100644 --- a/docs/docs/customize/deep-dives/autocomplete.md +++ b/docs/docs/customize/deep-dives/autocomplete.md @@ -58,16 +58,15 @@ This is just another object like the ones in the `"models"` array of `config.jso This object allows you to customize the behavior of tab-autocomplete. The available options are shown below, and you can find their default values [here](https://github.com/continuedev/continue/blob/fbeb2e4fe15d4b434a30a136f74b672485c852d9/core/util/parameters.ts). -- `disable`: Disable autocomplete (can also be done from IDE settings) +- `disable`: Disable autocomplete (can also be done from IDE settings) (default: `false`) - `template`: An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables. (String) -- `useFileSuffix`: Determines whether to use the file suffix in the prompt. (Boolean) -- `maxPromptTokens`: The maximum number of prompt tokens to use. A smaller number will yield faster completions, but less context. (Number) -- `prefixPercentage`: The percentage of the input that should be dedicated to the prefix. (Number) -- `maxSuffixPercentage`: The maximum percentage of the prompt that can be dedicated to the suffix. (Number) -- `debounceDelay`: The delay in milliseconds before triggering autocomplete after a keystroke. (Number) -- `multilineCompletions`: Whether to enable multiline completions ("always", "never", or "auto"). Defaults to "auto". -- `useCache`: Whether to cache and reuse completions when the prompt is the same as a previous one. May be useful to disable for testing purposes. -- `disableInFiles`: A list of glob patterns for files in which you want to disable tab autocomplete. +- `maxPromptTokens`: The maximum number of prompt tokens to use. A smaller number will yield faster completions, but less context. (Number) (default: `1024`) +- `prefixPercentage`: The percentage of the input that should be dedicated to the prefix. (Number) (default: `0.3`) +- `maxSuffixPercentage`: The maximum percentage of the prompt that can be dedicated to the suffix. (Number) (default: `0.2`) +- `debounceDelay`: The delay in milliseconds before triggering autocomplete after a keystroke. (Number) (default: `350`) +- `multilineCompletions`: Whether to enable multiline completions ("always", "never", or "auto"). Defaults to "auto". (default: `auto`) +- `useCache`: Whether to cache and reuse completions when the prompt is the same as a previous one. May be useful to disable for testing purposes. (default: `true`) +- `disableInFiles`: A list of glob patterns for files in which you want to disable tab autocomplete. (default: `[]`) ### Full example diff --git a/docs/docs/customize/deep-dives/configuration.md b/docs/docs/customize/deep-dives/configuration.md index e2e2b91d1..05fac6842 100644 --- a/docs/docs/customize/deep-dives/configuration.md +++ b/docs/docs/customize/deep-dives/configuration.md @@ -10,7 +10,7 @@ Continue can be deeply customized. User-level configuration is stored and can be - `~/.continue/config.json` (MacOS / Linux) - `%USERPROFILE%\.continue\config.json` (Windows) -To open `config.json`, you can click the "gear" icon in the bottom right corner of the Continue Chat sidebar. When editing this file, you can see the available options suggested as you type, or check the reference below. +To open `config.json`, you can click the "gear" icon in the header of the Continue Chat sidebar to open the settings page, and then click `Open [your config location]` to open the file. When editing this file, you can see the available options suggested as you type, or check the reference below. When you save `config.json`, Continue will automatically refresh to take into account your changes. `config.json` is automatically created the first time you use Continue. `config.json` is automatically generated if it doesn't exist. diff --git a/docs/docs/customize/deep-dives/docs.md b/docs/docs/customize/deep-dives/docs.md index 58612106d..f06de9fe4 100644 --- a/docs/docs/customize/deep-dives/docs.md +++ b/docs/docs/customize/deep-dives/docs.md @@ -1,18 +1,28 @@ --- description: Learn how to access and search your project's documentation directly within Continue -keywords: [documentation, indexing, context provider, embeddings, docs] +keywords: + [ + documentation, + indexing, + context provider, + embeddings, + docs, + embedder, + embeddings provider, + documentation, + ] toc_max_heading_level: 5 --- # @Docs -The [`@Docs` context provider](customize/context-providers.md#docs) allows you to interact with your documentation directly within Continue. This feature enables you to index any static site or GitHub markdown pages, making it easier to access and utilize your documentation while coding. +The [`@Docs` context provider](customize/context-providers.md#docs) allows you to efficiently reference locally-indexed documentation directly within Continue. ## Enabling the `@Docs` context provider -To enable the `@Docs` context provider, you need to add it to the list of context providers in your `config.json` file. +To enable the `@Docs` context provider, add it to the list of context providers in your `config.json` file. -```json +```json title="config.json" { "contextProviders": [ { @@ -24,54 +34,73 @@ To enable the `@Docs` context provider, you need to add it to the list of contex ## How It Works -The `@Docs` context provider works by crawling specified documentation sites, generating embeddings, and storing them locally for you. This process allows for quick and efficient access to your documentation content. +The `@Docs` context provider works by -1. We crawl the specified documentation site -2. Generate embeddings for the content -3. Store the embeddings locally on your machine -4. Provide access to the indexed content through the `@Docs` context provider +1. Crawling specified documentation sites +2. Generating embeddings for the chunked content +3. Storing the embeddings locally on your machine +4. Embedding chat input to include similar documentation chunks as context ## Pre-indexed Documentation Sites -We offer a selection of pre-indexed documentation sites for popular frameworks and libraries. You can view the list of [available pre-indexed sites and request additions here](https://github.com/continuedev/continue/blob/main/core/indexing/docs/preIndexedDocs.ts). +In VS Code, Continue offers a selection of pre-indexed documentation sites for popular frameworks and libraries. You can view the list of [available pre-indexed sites and request additions here](https://github.com/continuedev/continue/blob/main/core/indexing/docs/preIndexedDocs.ts). + +Pre-indexed docs are only available in VS Code because the VS Code extension ships with the Transformers.js embedder built in, while Jetbrains currently does not. You can override a pre-indexed doc to index it with your own embeddings provider by adding it to your config (unique by `startUrl`). Otherwise, it will always use Transformers.js for queries. ## Indexing Your Own Documentation ### Through the `@Docs` Context Provider -To add a single documentation site, we recommend using the `@Docs` context provider. +To add a single documentation site, we recommend using the **Add Documentation** Form within the GUI. This can be accessed -1. Type `@Docs` in the chat panel, hit enter -2. Type "add" and select the "Add Docs" option -3. Enter the required information into the dialog +- from the `@Docs` context provider - type `@Docs` in the chat, hit `Enter`, and search for `Add Docs` +- from the `More` page (three dots icon) in the `@docs indexes` section + the `@Docs` context provider. -Indexing will begin upon submission. +In the **Add Documentation** Form, enter a `Title` and `Start URL` for the site. -### Through `config.json` +- `Title`: The name of the documentation site, used for identification in the UI +- `Start URL`: The URL where the indexing process should begin. -To add multiple documentation sites, we recommend adding them in bulk to your `config.json` file. Indexing will kick off upon file save. +Indexing will begin upon submission. Progress can be viewed in the form or later in the `@docs indexes` section of the `More` page. -The [configuration schema for docs](https://github.com/continuedev/continue/blob/v0.9.212-vscode/extensions/vscode/config_schema.json#L1943-L1973) is as follows: +Documentation sources may be suggested based on package files in your repo. This currently works for Python `requirements.txt` files and Node.js (Javascript/Typescript) `package.json` files. -```json -"docs": [ +- Packages with a valid documentation URL (with a `+` icon) can be clicked to immediately kick off indexing +- Packages with partial information (with a pen icon) can be clicked to fill the form with the available information +- Note that you can hover over the information icon to see where the package suggestion was found. + +![Add documentation form](/img/docs-form.png) + +### Through global configuration + +For bulk documentation site adds or edits, we recommend editing your global configuration file directly. Documentation sites are stored in an array within `docs` in your global configuration, as follows: + +```json title="config.json" +{ + "docs": [ { - "title": "Continue", - "startUrl": "https://docs.continue.dev/intro", - "rootUrl": "https://docs.continue.dev", - "faviconUrl": "https://docs.continue.dev/favicon.ico", - } -] + "title": "Nest.js", + "startUrl": "https://docs.nestjs.com/", + "faviconUrl": "https://docs.nestjs.com/favicon.ico" + } + ] +} ``` -- `title`: The name of the documentation site, used for identification in the UI. -- `startUrl`: The URL where the indexing process should begin. -- `rootUrl`: The base URL of the documentation site, used to determine which pages to index. -- `faviconUrl`: The URL of the site's favicon, used for visual identification in the UI. +See [the config reference](../../reference) for all documentation site configuration options. + +Indexing will re-sync upon saving the configuration file. ## Configuration -As with [@Codebase context provider configuration](https://docs.continue.dev/customize/deep-dives/codebase#configuration), you can adjust the behavior of the docs context provider with the `nRetrieve`, `nFinal`, and `useReranking` +### Using Your Embeddings Provider + +If you have set up an [embeddings provider](../model-types/embeddings.md), @docs will use your embeddings provider. Switching embeddings providers will trigger a re-index of all documentation sites in your configuration. + +### Reranking + +As with [@Codebase context provider configuration](./codebase#configuration), you can adjust the reranking behavior of the `@Docs` context provider with the `nRetrieve`, `nFinal`, and `useReranking`. ```json title="config.json" { @@ -79,29 +108,163 @@ As with [@Codebase context provider configuration](https://docs.continue.dev/cus { "name": "docs", "params": { - "nRetrieve": 25, - "nFinal": 5, - "useReranking": true + "nRetrieve": 25, // The number of docs to retreive from the embeddings query + "nFinal": 5, // The number of docs chunks to return IF reranking + "useReranking": true // use reranking if a reranker is configured (defaults to true) } } ] } ``` -## Crawling dynamically generated sites with `useChromiumForDocsCrawling` +### Github -By default, we use a lighter weight tool to crawl documentation sites that cannot render sites that are dynamically generated using JavaScript. - -If you want to crawl a site that is dynamically generated, or you get an error while attempting to crawl a site, you can enable the experimental `useChromiumForDocsCrawling` feature in your `config.json`. This will download and install Chromium to `~/.continue/.utils`. +The Github API rate limits public requests to 60 per hour. If you want to reliably index Github repos, you can add a github token to your config file: ```json title="config.json" -"experimental": { - "useChromiumForDocsCrawling": true +{ + "contextProviders": [ + { + "name": "docs", + "params": { + "githubToken": "github_..." + } + } + ] } ``` -## FAQ +### Local Crawling -### How often is the indexed content updated? +By default, Continue crawls documentation sites using a specialized crawling service that provides the best experience for most users and documentation sites. -Currently we do not automatically re-index your docs. If you would like to force a re-index, you can use the following command: `Continue: Docs Force Re-Index`. +If your documentation is private, you can skip the default crawler and use a local crawler instead by setting `useLocalCrawling` to `true`. + +```json title="config.json" +{ + "docs": [ + { + "title": "My Private Docs", + "startUrl": "http://10.2.1.2/docs", + "faviconUrl": "http://10.2.1.2/docs/assets/favicon.ico", + "useLocalCrawling": true + } + ] +} +``` + +The default local crawler is a lightweight tool that cannot render sites that are dynamically generated using JavaScript. If your sites need to be rendered, you can enable the experimental `Use Chromium for Docs Crawling` feature from your [User Settings Page](../settings.md) This will download and install Chromium to `~/.continue/.utils`, and use it as the local crawler. + +Further notes: + +- If the site is only locally accessible, the default crawler will fail anyways and fall back to the local crawler. `useLocalCrawling` is especially useful if the URL itself is confidential. +- For Github Repos this has no effect because only the Github Crawler will be used, and if the repo is private it can only be accessed with a priveleged Github token anyways. + +## Managing your docs indexes + +You can view indexing statuses and manage your documentation sites from the `@docs indexes` section of the `More` page (three dots) + +- Continue does not automatically re-index your docs. Use `Click to re-index` to trigger a reindex for a specific source +- While a site is indexing, click `Cancel indexing` to cancel the process +- Failed indexing attempts will show an error status bar and icon +- Delete a documentation site from your configuration using the trash icon + +![More Page @docs indexes section](/img/docs-indexes.png) + +You can also view the overall status of currently indexing docs from a hideable progress bar at the bottom of the chat page +![Documentation indexing peek](/img/docs-indexing-peek.png) + +You can also use the following IDE command to force a re-index of all docs: `Continue: Docs Force Re-Index`. + +## Examples + +### VS Code minimal setup + +The following configuration example works out of the box for VS Code. This uses the built-in embeddings provider with no reranking. Pre-indexed docs will be accessible. + +```json title="config.json" + "contextProviders": [ + { + "name": "docs", + } + ], + "docs": [ + { + "title": "Nest.js", + "startUrl": "https://docs.nestjs.com/", + }, + ], +``` + +### Jetbrains minimal setup + +Here is the equivalent minimal example for Jetbrains, which requires setting up an [embeddings provider](../model-types/embeddings.md). Pre-indexed docs will _not_ be accessible. + +```json title="config.json" + "contextProviders": [ + { + "name": "docs", + } + ], + "docs": [ + { + "title": "Nest.js", + "startUrl": "https://docs.nestjs.com/", + }, + ], + "embeddingsProvider": { + "provider": "lmstudio", + "model": "nomic-ai/nomic-embed-text-v1.5-GGUF" + }, +``` + +### Full-power setup (VS Code or Jetbrains) + +The following configuration example includes: + +- Examples of both public and private documentation sources +- A custom embeddings provider +- A reranker model available, with reranking parameters customized +- A Github token to enable Github crawling + +```json title="config.json" +{ + "contextProviders": [ + { + "name": "docs", + "params": { + "githubToken": "github_...", + "nRetrieve": 25, + "nFinal": 5, + "useReranking": true + } + } + ], + "docs": [ + { + "title": "Nest.js", + "startUrl": "https://docs.nestjs.com/" + }, + { + "title": "My Private Docs", + "startUrl": "http://10.2.1.2/docs", + "faviconUrl": "http://10.2.1.2/docs/assets/favicon.ico", + "maxDepth": 4, + "useLocalCrawling": true + } + ], + "reranker": { + "name": "voyage", + "params": { + "model": "rerank-2", + "apiKey": "" + } + }, + "embeddingsProvider": { + "provider": "lmstudio", + "model": "nomic-ai/nomic-embed-text-v1.5-GGUF" + } +} +``` + +This could also involve enabling Chromium as a backup for local documentation the [User Settings Page](../settings.md). diff --git a/docs/docs/customize/model-providers/more/asksage.md b/docs/docs/customize/model-providers/more/asksage.md index e21133cb8..204d29421 100644 --- a/docs/docs/customize/model-providers/more/asksage.md +++ b/docs/docs/customize/model-providers/more/asksage.md @@ -60,6 +60,7 @@ The current Models available provided by Ask Sage are: | 8 | GPT-4-32K | Yes | ✅ | | 9 | GPT-o1 | Yes | ✅ | | 10 | GPT-o1-mini | Yes | ✅ | +| 10 | GPT-o3-mini | Yes | ✅ | | 11 | GPT-3.5-turbo | Yes | ✅ | | 12 | Calude 3.5 Sonnet Gov | Yes | ✅ | | 13 | Calude 3 Opus | Yes | ✅ | diff --git a/docs/docs/customize/model-providers/more/vllm.md b/docs/docs/customize/model-providers/more/vllm.md index d54baeb88..fe6932cc5 100644 --- a/docs/docs/customize/model-providers/more/vllm.md +++ b/docs/docs/customize/model-providers/more/vllm.md @@ -15,7 +15,7 @@ We recommend configuring **Llama3.1 8B** as your chat model. { "title": "Llama3.1 8B Instruct", "provider": "vllm", - "model": "meta-llama/Meta-Llama-3.1-8B-Instruct" + "model": "meta-llama/Meta-Llama-3.1-8B-Instruct", "apiBase": "http:///v1" } ] diff --git a/docs/docs/customize/model-providers/top-level/bedrock.md b/docs/docs/customize/model-providers/top-level/bedrock.md index 67d919a2f..c2fab040a 100644 --- a/docs/docs/customize/model-providers/top-level/bedrock.md +++ b/docs/docs/customize/model-providers/top-level/bedrock.md @@ -41,9 +41,9 @@ We recommend configuring **Claude 3.5 Sonnet** as your chat model. ## Autocomplete model -Bedrock currently does not offer any autocomplete models. +Bedrock currently does not offer any autocomplete models. However, [Codestral from Mistral](https://mistral.ai/news/codestral-2501/) and [Point from Poolisde](https://aws.amazon.com/bedrock/poolside/) will be supported in the near future. -[Click here](../../model-types/autocomplete.md) to see a list of autocomplete model providers. +In the meantime, you can view a list of autocomplete model providers [here](../../model-types/autocomplete.md). ## Embeddings model diff --git a/docs/docs/customize/model-providers/top-level/xAI.md b/docs/docs/customize/model-providers/top-level/xAI.md index fbdfa83ad..550cc0641 100644 --- a/docs/docs/customize/model-providers/top-level/xAI.md +++ b/docs/docs/customize/model-providers/top-level/xAI.md @@ -11,15 +11,15 @@ You can get an API key from the [xAI console](https://console.x.ai/) ## Chat model -We recommend configuring **grok-beta** as your chat model. +We recommend configuring **grok-2-latest** as your chat model. For information on other available models, visit [xAI Documentation](https://docs.x.ai/docs/models). ```json title="config.json" { "models": [ { - "title": "Grok Beta", + "title": "Grok 2", "provider": "xAI", - "model": "grok-beta", + "model": "grok-2-latest", "apiKey": "[API_KEY]" } ] diff --git a/docs/docs/customize/overview.md b/docs/docs/customize/overview.md index 83e479132..80c18846a 100644 --- a/docs/docs/customize/overview.md +++ b/docs/docs/customize/overview.md @@ -6,22 +6,22 @@ keywords: [customize, configure, config] Continue can be deeply customized. For example you might: -- **Change your Model Provider**. Continue allows you to choose your favorite or even add multiple model providers. This allows you to use different models for different tasks, or to try another model if you're not happy with the results from your current model. Continue supports all of the popular model providers, including OpenAI, Anthropic, Microsoft/Azure, Mistral, and more. You can even self host your own model provider if you'd like. Learn more about [model providers](/customize/model-providers). -- **Select different model providers for each Compose feature**. Different Continue features can use different model providers. We call these _model types_. For example, you can use a different model provider for chat than you do for autocomplete. Learn more about [model types](/customize/model-types) . -- **Add a Context Provider**. Context providers allow you to add information to your prompts, giving your LLM additional context to work with. Context providers allow you to reference snippets from your codebase, or lookup relevant documentation, or use a search engine to find information and much more. Learn more about [context providers](/customize/context-providers). -- **Create a Slash Command**. Slash commands allow you to easily add custom functionality to Continue. You can use a slash command that allows you to generate a shell command from natural language, or perhaps generate a commit message, or create your own custom command to do whatever you want. Learn more about [slash commands](/customize/slash-commands). -- **Call external tools and functions**. Unchain your LLM with the power of _Tools_. You can call any external tool or function from your prompts. Currently only available with Anthropic. Learn more about [Tools](/customize/tools). +- **Change your Model Provider**. Continue allows you to choose your favorite or even add multiple model providers. This allows you to use different models for different tasks, or to try another model if you're not happy with the results from your current model. Continue supports all of the popular model providers, including OpenAI, Anthropic, Microsoft/Azure, Mistral, and more. You can even self host your own model provider if you'd like. Learn more about [model providers](/customize/model-providers). +- **Select different model providers for each Compose feature**. Different Continue features can use different model providers. We call these _model types_. For example, you can use a different model provider for chat than you do for autocomplete. Learn more about [model types](/customize/model-types) . +- **Add a Context Provider**. Context providers allow you to add information to your prompts, giving your LLM additional context to work with. Context providers allow you to reference snippets from your codebase, or lookup relevant documentation, or use a search engine to find information and much more. Learn more about [context providers](/customize/context-providers). +- **Create a Slash Command**. Slash commands allow you to easily add custom functionality to Continue. You can use a slash command that allows you to generate a shell command from natural language, or perhaps generate a commit message, or create your own custom command to do whatever you want. Learn more about [slash commands](/customize/slash-commands). +- **Call external tools and functions**. Unchain your LLM with the power of _Tools_. You can call any external tool or function from your prompts. Currently only available with Anthropic. Learn more about [Tools](/customize/tools). Whatever you choose, you'll probably start by editing `config.json`. ## Editing config.json -Most custom configuration is done by editing `config.json`. This file is a JSON file that allows you to customize Continue to your liking. It is found at: +Most custom configuration is done by editing `config.json`. This file is a JSON file that allows you to customize Continue to your liking. It is found at: - MacOS and Linux: `~/.continue/config.json` - Windows: `%USERPROFILE%\.continue\config.json` -You can easily access `config.json` from the Continue Chat sidebar. Open the sidebar by pressing cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) and click the "gear" icon in the bottom right corner. +You can easily access `config.json` from the Continue Chat sidebar. Open the sidebar by pressing cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains) and click the "gear" icon in header to open the Settings page. Then click the button labeled `Open [your config profile]`. ![configure-continue](/img/configure-continue.png) @@ -29,7 +29,7 @@ When editing this file, you can see the available options suggested as you type, :::info -`config.json` is created the first time you use Continue. If you'd like to reset your configuration to the default, you can delete this file and Continue will automatically recreate it with the default settings. +`config.json` is created the first time you use Continue. If you'd like to reset your configuration to the default, you can delete this file and Continue will automatically recreate it with the default settings. ::: diff --git a/docs/docs/customize/settings.md b/docs/docs/customize/settings.md new file mode 100644 index 000000000..0d917df6e --- /dev/null +++ b/docs/docs/customize/settings.md @@ -0,0 +1,34 @@ +--- +title: User Settings Page +description: Reference for Adjusting User-Specific Settings +keywords: [config, settings, configuration, customize, customization, sidebar] +--- + +# The User Settings Page + +The **User Settings page** can be accessed by clicking the gear icon in the header of the Continue sidebar. + +![slash-commands](/img/header-buttons.png) + +Which takes you to this page: + +![User Settings Page](/img/settings-page.png) + +Click the `Open Config File` button to open your configuration file. See the [Configuration Reference](../reference.md) for more information. + +Below that, the following settings which are not part of a configuration file are available: + +- `Wrap Codeblocks`: If on, enables text wrapping in code blocks. Off by default. +- `Display Raw Markdown`: If on, shows raw markdown in responses. Off by default. +- `Allow Anonymous Telemetry`: If on, allows Continue to send anonymous telemetry. **On** by default. +- `Disable Indexing`: Prevents indexing of the codebase, useful primarily for debugging purposes. Off by default. +- `Disable Session Titles`: Prevents generating summary titles for each chat session when turned on. Off by default +- `Response Text to Speech`: If on, reads LLM responses aloud with TTS. Off by default. +- `Show Chat Scrollbar`: If on, enables a scrollbar in the chat window. Off by default. +- `Use autocomplete cache`: If on, caches completions. +- `Use Chromium for Docs Crawling`: Use Chromium to crawl docs locally. Useful if the default Cheerio crawler fails on sites that require JavaScript rendering. Downloads and installs Chromium to ~/.continue/.utils. Off by default +- `Codeblock Actions Position`: Sets the position for the actions that show when hovering over codeblocks. Defaults to `top` +- `Multiline Autocompletions`: Controls multiline completions for autocomplete. Can be set to `always`, `never`, or `auto`. Defaults to `auto` +- `Font Size`: Specifies base font size for UI elements +- `Workspace prompts path`: Where to find Prompt Files in a workspace - replaces the default .continue/prompts +- `Disable autocomplete in files`: List of comma-separated glob pattern to disable autocomplete in matching files. E.g., "\_/.md, \*/.txt" diff --git a/docs/docs/customize/tutorials/running-continue-without-internet.md b/docs/docs/customize/tutorials/running-continue-without-internet.md index c945f8c43..277272767 100644 --- a/docs/docs/customize/tutorials/running-continue-without-internet.md +++ b/docs/docs/customize/tutorials/running-continue-without-internet.md @@ -7,6 +7,6 @@ keywords: [no internet, air-gapped, local model] Continue can be run even on an air-gapped computer if you use a local model. Only a few adjustments are required for this to work. 1. Download the latest .vsix file from the [Open VSX Registry](https://open-vsx.org/extension/Continue/continue) and [install it to VS Code](https://code.visualstudio.com/docs/editor/extension-marketplace#_install-from-a-vsix). -2. Open `~/.continue/config.json` and set `"allowAnonymousTelemetry": false`. This will stop Continue from attempting requests to PostHog for [anonymous telemetry](../../telemetry.md). +2. Open the [User Settings Page](../settings.md) and turn off "Allow Anonymous Telemetry". This will stop Continue from attempting requests to PostHog for [anonymous telemetry](../../telemetry.md). 3. Also in `config.json`, set the default model to a local model. You can available options [here](../model-providers/). 4. Restart VS Code to ensure that the changes to `config.json` take effect. diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 814f6e4af..b492f47e9 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -83,16 +83,12 @@ Specifies options for tab autocompletion behavior. **Properties:** - `disable`: If `true`, disables tab autocomplete (default: `false`). -- `useFileSuffix`: If `true`, includes file suffix in the prompt. -- `maxPromptTokens`: Maximum number of tokens for the prompt. -- `debounceDelay`: Delay (in ms) before triggering autocomplete. -- `maxSuffixPercentage`: Maximum percentage of prompt for suffix. -- `prefixPercentage`: Percentage of input for prefix. +- `maxPromptTokens`: Maximum number of tokens for the prompt (default: `1024`). +- `debounceDelay`: Delay (in ms) before triggering autocomplete (default: `350`). +- `maxSuffixPercentage`: Maximum percentage of prompt for suffix (default: `0.2`). +- `prefixPercentage`: Percentage of input for prefix (default: `0.3`). - `template`: Template string for autocomplete, using Mustache templating. You can use the `{{{ prefix }}}`, `{{{ suffix }}}`, `{{{ filename }}}`, `{{{ reponame }}}`, and `{{{ language }}}` variables. -- `multilineCompletions`: Controls multiline completions (`"always"`, `"never"`, or `"auto"`). -- `useCache`: If `true`, caches completions. -- `onlyMyCode`: If `true`, only includes code within the repository. -- `disableInFiles`: Array of glob patterns for files where autocomplete is disabled. +- `onlyMyCode`: If `true`, only includes code within the repository (default: `true`). Example @@ -234,9 +230,10 @@ List of documentation sites to index. - `title` (**required**): Title of the documentation site, displayed in dropdowns, etc. - `startUrl` (**required**): Start page for crawling - usually root or intro page for docs -- `rootUrl`: Crawler will only index docs within this domain - pages that contain this URL -- `maxDepth`: Maximum depth for crawling. Default `3` + +- `maxDepth`: Maximum link depth for crawling. Default `4` - `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`). +- `useLocalCrawling`: Skip the default crawler and only crawl using a local crawler. Example @@ -245,7 +242,6 @@ Example { "title": "Continue", "startUrl": "https://docs.continue.dev/intro", - "rootUrl": "https://docs.continue.dev", "faviconUrl": "https://docs.continue.dev/favicon.ico", } ] @@ -341,40 +337,6 @@ Example } ``` -### `disableSessionTitles` - -Prevents generating summary titles for each chat session when set to `true`. - -### `ui` - -Customizable UI settings to control interface appearance and behavior. - -**Properties:** - -- `codeBlockToolbarPosition`: Sets the toolbar position within code blocks, either `top` (default) or `bottom`. -- `fontSize`: Specifies font size for UI elements. -- `displayRawMarkdown`: If `true`, shows raw markdown in responses. -- `showChatScrollbar`: If `true`, enables a scrollbar in the chat window. -- `codeWrap`: If `true`, enables text wrapping in code blocks. - -Example: - -```json title="config.json" -{ - "ui": { - "codeBlockToolbarPosition": "bottom", - "fontSize": 14, - "displayRawMarkdown": false, - "showChatScrollbar": false, - "codeWrap": false - } -} -``` - -### `allowAnonymousTelemetry` - -When `true`, anonymous usage data is collected using Posthog, to improve features. Default is `true`. - ### `userToken` An optional token that identifies the user, primarily for authenticated services. @@ -383,10 +345,6 @@ An optional token that identifies the user, primarily for authenticated services Defines a system message that appears before every response from the language model, providing guidance or context. -### `disableIndexing` - -Prevents indexing of the codebase, useful primarily for debugging purposes. - ### `experimental` Several experimental config parameters are available, as described below: @@ -398,8 +356,6 @@ Several experimental config parameters are available, as described below: - `inlineEdit`: Model title for inline edits. - `applyCodeBlock`: Model title for applying code blocks. - `repoMapFileSelection`: Model title for repo map selections. -- `readResponseTTS`: If `true`, reads LLM responses aloud with TTS. Default is `true`. -- `promptPath`: Change the path to custom prompt files from the default ".prompts" - `quickActions`: Array of custom quick actions - `title` (**required**): Display title for the quick action. - `prompt` (**required**): Prompt for quick action. @@ -409,7 +365,6 @@ Several experimental config parameters are available, as described below: - `docstring`: Prompt for adding docstrings. - `fix`: Prompt for fixing code. - `optimize`: Prompt for optimizing code. -- `useChromiumForDocsCrawling`: Use Chromium to crawl docs locally. Useful if the default Cheerio crawler fails on sites that require JavaScript rendering. Downloads and installs Chromium to `~/.continue/.utils`.. - `modelContextProtocolServers`: See [Model Context Protocol](/customize/context-providers#model-context-protocol) Example @@ -420,7 +375,6 @@ Example "modelRoles": { "inlineEdit": "Edit Model" }, - "promptPath": "custom/.prompts", "quickActions": [ { "title": "Tags", @@ -431,8 +385,6 @@ Example "contextMenuPrompts": { "fixGrammar": "Fix grammar in the above but allow for typos." }, - "readResponseTTS": false, - "useChromiumForDocsCrawling": true, "modelContextProtocolServers": [ { "transport": { @@ -445,3 +397,28 @@ Example } } ``` + +### Fully deprecated settings + +Some deprecated `config.json` settings are no longer stored in config and have been moved to be editable through the [User Settings Page](./customize/settings.md). If found in `config.json`, they will be migrated to the [User Settings Page](./customize/settings.md) and removed from `config.json`. + +- `allowAnonymousTelemetry`: This value will be migrated to the safest merged value (`false` if either are `false`). +- `promptPath`: This value will override during migration. +- `disableIndexing`: This value will be migrated to the safest merged value (`true` if either are `true`). +- `disableSessionTitles`/`ui.getChatTitles`: This value will be migrated to the safest merged value (`true` if either are `true`). `getChatTitles` takes precedence if set to false +- `tabAutocompleteOptions` + - `useCache`: This value will override during migration. + - `disableInFiles`: This value will be migrated to the safest merged value (arrays of file matches merged/deduplicated) + - `multilineCompletions`: This value will override during migration. +- `experimental` + - `useChromiumForDocsCrawling`: This value will override during migration. + - `readResponseTTS`: This value will override during migration. +- `ui` - all will override during migration + + - `codeBlockToolbarPosition` + - `fontSize` + - `codeWrap` + - `displayRawMarkdown` + - `showChatScrollbar` + + See [User Settings Page](./customize/settings.md) for more information about each option. diff --git a/docs/docs/telemetry.md b/docs/docs/telemetry.md index 8e7152d01..3d59ebf74 100644 --- a/docs/docs/telemetry.md +++ b/docs/docs/telemetry.md @@ -26,26 +26,6 @@ The following usage information is collected and reported: ## How to Opt Out -You can disable anonymous telemetry by modifying the `config.json` file located in the `~/.continue` directory. This file typically includes the following entry: +You can disable anonymous telemetry by visiting the [User Settings Page](./customize/settings.md) and toggling "Allow Anonymous Telemetry" off. -```json title="config.json" -{ - "allowAnonymousTelemetry": true -} -``` - -To opt out, change the value of `allowAnonymousTelemetry` to `false`. Alternatively, you can disable telemetry through your VS Code settings by unchecking the "Continue: Telemetry Enabled" box. - -### Steps to Disable Telemetry via Configuration File - -1. Open the `~/.continue/config.json` file in your text editor. -2. Locate the `"allowAnonymousTelemetry"` setting. -3. Change the value from `true` to `false`. -4. Save the file. - -### Steps to Disable Telemetry via VS Code Settings - -1. Open VS Code. -2. Navigate to `File` > `Preferences` > `Settings` (or use the keyboard shortcut ctrl + , on Windows/Linux or cmd + , on macOS). -3. In the search bar, type "Continue: Telemetry Enabled". -4. Uncheck the "Continue: Telemetry Enabled" checkbox. +Alternatively in VS Code, you can disable telemetry through your VS Code settings by unchecking the "Continue: Telemetry Enabled" box (this will override the Settings Page settings). diff --git a/docs/docs/yaml-migration.md b/docs/docs/yaml-migration.md index 1e43ac738..04f1b4e15 100644 --- a/docs/docs/yaml-migration.md +++ b/docs/docs/yaml-migration.md @@ -14,7 +14,7 @@ See also - [JSON Continue Config Reference](/reference) - [YAML Continue Config Reference](/yaml-reference) -### 1. Create YAML file +## Create YAML file Create a `config.yaml` file in your Continue Global Directory (`~/.continue` on Mac, `%USERPROFILE%\.continue`) alongside your current `config.json` file. If a `config.yaml` file is present, it will be loaded instead of `config.json`. @@ -25,14 +25,14 @@ name: my-configuration version: 0.0.1 ``` -### 2. Map Models +### Models Add all model configurations in `config.json`, including models in `models`, `tabAutocompleteModel`, `embeddingsProvider`, and `reranker`, to the `models` section of your new YAML config file. A new `roles` YAML field specifies which roles a model can be used for, with possible values `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`. -- `models` in config should have `roles: chat` -- `tabAutocompleteModel`(s) in config should have `roles: autocomplete` -- `embeddingsProvider` in config should have `roles: embed` -- `reranker` in config should have `roles: rerank` +- `models` in config should have `roles: [chat]` +- `tabAutocompleteModel`(s) in config should have `roles: [autocomplete]` +- `embeddingsProvider` in config should have `roles: [embed]` +- `reranker` in config should have `roles: [rerank]` - `experimental.modelRoles` is replaced by simply adding roles to the model - `inlineEdit` -> e.g. `roles: [chat, edit]` - `applyCodeBlock` -> e.g. `roles: [chat, apply]` @@ -103,46 +103,56 @@ models: - name: GPT-4 provider: openai model: gpt-4 + apiKey: defaultCompletionOptions: temperature: 0.5 - maxTokens: 2000' - roles: [chat, edit] - apiKey: + maxTokens: 2000 + roles: + - chat + - edit + - name: My Voyage Reranker provider: voyage - roles: rerank apiKey: + roles: + - rerank + - name: My Starcoder provider: ollama model: starcoder2:3b - roles: autocomplete + roles: + - autocomplete + - name: My Ada Embedder provider: openai - roles: embed apiKey: + roles: + - embed + - name: Ollama Autodetect provider: ollama model: AUTODETECT + - name: My Open AI Compatible Model - Apply provider: openai - apiBase: http://3.3.3.3/v1 model: my-openai-compatible-model + apiBase: http://3.3.3.3/v1 requestOptions: headers: X-Auth-Token: - roles: [chat, apply] + roles: + - chat + - apply ``` Note that the `repoMapFileSelection` experimental model role has been deprecated. -### 3. Map Context Providers +### Context Providers -The JSON `contextProviders` and `docs` fields are replaced by the YAML `context` array. +The JSON `contextProviders` field is replaced by the YAML `context` array. -- JSON `name` maps to `uses` -- JSON `params` map to `with` -- Use multiple `docs` entries rather than the array of docs in the JSON format - +- JSON `name` maps to `provider` +- JSON `params` map to `params` **Before** @@ -150,10 +160,7 @@ The JSON `contextProviders` and `docs` fields are replaced by the YAML `context` { "contextProviders": [ { - "name": "docs", - "params": { - "startUrl": "https://docs.continue.dev/intro" - } + "name": "docs" }, { "name": "codebase", @@ -166,7 +173,86 @@ The JSON `contextProviders` and `docs` fields are replaced by the YAML `context` "name": "diff", "params": {} } - ], + ] +} +``` + +**After** + +```yaml title="config.yaml" +context: + - provider: docs + + - provider: codebase + params: + nRetrieve: 30 + nFinal: 3 + + - params: diff +``` + +### System Message + +The `systemMessage` property has been replaced with a `rules` property that takes an array of strings. + +**Before** + +```json title="config.json" +{ + "systemMessage": "Always give concise responses" +} +``` + +**After** + +```yaml title="config.yaml" +rules: + - Always give concise responses +``` + +### Prompts + +Rather than with `customCommands`, you can now use the `prompts` field to define custom prompts. + +**Before** + +```json title="config.json" +{ + "customCommands": [ + { + "name": "check", + "description": "Check for mistakes in my code", + "prompt": "{{{ input }}}\n\nPlease read the highlighted code and check for any mistakes. You should look for the following, and be extremely vigilant:\n- Syntax errors\n- Logic errors\n- Security vulnerabilities\n- Performance issues\n- Anything else that looks wrong\n\nOnce you find an error, please explain it as clearly as possible, but without using extra words. For example, instead of saying 'I think there is a syntax error on line 5', you should say 'Syntax error on line 5'. Give your answer as one bullet point per mistake found." + } + ] +} +``` + +**After** + +```yaml title="config.yaml" +prompts: + - name: check + description: Check for mistakes in my code + prompt: | + Please read the highlighted code and check for any mistakes. You should look for the following, and be extremely vigilant: + - Syntax errors + - Logic errors + - Security vulnerabilities + - Performance issues + - Anything else that looks wrong + + Once you find an error, please explain it as clearly as possible, but without using extra words. For example, instead of saying 'I think there is a syntax error on line 5', you should say 'Syntax error on line 5'. Give your answer as one bullet point per mistake found. +``` + +### Documentation + +Documentation is largely the same, but the `title` property has been replaced with `name`. The `startUrl`, `rootUrl`, and `faviconUrl` properties remain. + +**Before** + +```json title="config.json" +{ "docs": [ { "startUrl": "https://docs.nestjs.com/", @@ -183,23 +269,15 @@ The JSON `contextProviders` and `docs` fields are replaced by the YAML `context` **After** ```yaml title="config.yaml" -context: - - uses: docs - with: - startUrl: https://docs.nestjs.com/ - title: nest.js - - uses: docs - with: - startUrl: https://mysite.com/docs/ - title: My Site - - uses: codebase - with: - nRetrieve: 30 - nFinal: 3 - - uses: diff +docs: + - name: nest.js + startUrl: https://docs.nestjs.com/ + + - name: My site + startUrl: https://mysite.com/docs/ ``` -## Map MCP Servers +### MCP Servers @@ -220,7 +298,10 @@ context: "transport": { "type": "stdio", "command": "uvx", - "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"] + "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"], + "env": { + "KEY": "" + } } } ] @@ -238,27 +319,35 @@ mcpServers: - mcp-server-sqlite - --db-path - /Users/NAME/test.db + env: + KEY: ``` --- ## Deprecated configuration options -The following top-level fields from `config.json` have been deprecated +Some deprecated `config.json` settings are no longer stored in config and have been moved to be editable through the [User Settings Page](./customize/settings.md) (Gear Icon). If found in `config.json`, they will be migrated to the [User Settings Page](./customize/settings.md) and removed from `config.json`. + +See the [JSON Config Reference](./reference#fully-deprecated-settings) for more information on fully deprecated options. + +The following top-level fields from `config.json` still work when using `config.json` but have been deprecated and don't have a YAML equivalent: - Slash commands (JSON `slashCommands`) - top-level `requestOptions` - top-level `completionOptions` - `tabAutocompleteOptions` + - `disable` + - `maxPromptTokens` + - `debounceDelay` + - `maxSuffixPercentage` + - `prefixPercentage` + - `template` + - `onlyMyCode` - `analytics` - `customCommands` -- `disableSessionTitles` - `experimental` -- `allowAnonymousTelemetry` (moved to user/IDE level) -- `ui` (moved to user/IDE level) - `userToken` -- `systemMessage` -- `disableIndexing` (moved to user/IDE level) ## New Configuration options diff --git a/docs/docs/yaml-reference.md b/docs/docs/yaml-reference.md index bcf8a7504..e504c95fd 100644 --- a/docs/docs/yaml-reference.md +++ b/docs/docs/yaml-reference.md @@ -6,7 +6,7 @@ keywords: [config, yaml, configuration, customize, customization] # Config YAML Reference - + Continue can be configured using a YAML file `config.yaml` which for local configuration can be placed in your global `.continue` folder (`~/.continue` on Mac, `%USERPROFILE%\.continue`) @@ -23,11 +23,11 @@ Config YAML does not work alongside `config.json` - it replaces it. View the **[ The top-level properties in the `config.yaml` configuration file are: - [`name`](#name) (**required**) - - [`version`](#version) (**required**) - [`models`](#models) - [`context`](#context) - [`rules`](#rules) +- [`prompts`](#prompts) - [`docs`](#docs) @@ -119,22 +119,22 @@ More information about usage/params for each context provider can be found [here **Properties:** -- `uses` (**required**): The identifier or name of the context provider (e.g., `code`, `docs`, `web`). -- `with`: Optional parameters to configure the context provider's behavior. +- `provider` (**required**): The identifier or name of the context provider (e.g., `code`, `docs`, `web`). +- `params`: Optional parameters to configure the context provider's behavior. **Example:** ```yaml title="config.yaml" context: - - uses: files - - uses: code - - uses: codebase - with: + - provider: files + - provider: code + - provider: codebase + params: nFinal: 10 - - uses: docs - - uses: diff - - uses: folder - - uses: terminal + - provider: docs + - provider: diff + - provider: folder + - provider: terminal ``` --- @@ -153,6 +153,23 @@ rules: --- +### `prompts` + +A list of custom prompts that can be invoked from the chat window. Each prompt has a name, description, and the actual prompt text. + +```yaml title="config.yaml" +prompts: + - name: check + description: Check for mistakes in my code + prompt: | + Please read the highlighted code and check for any mistakes. You should look for the following, and be extremely vigilant: + - Syntax errors + - Logic errors + - Security vulnerabilities +``` + +--- + ### `docs` List of documentation sites to index. @@ -161,8 +178,10 @@ List of documentation sites to index. - `name` (**required**): Name of the documentation site, displayed in dropdowns, etc. - `startUrl` (**required**): Start page for crawling - usually root or intro page for docs -- `rootUrl`: Crawler will only index docs within this domain - pages that contain this URL + - `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`). +- `maxDepth`: M +- `useLocalCrawling`: Force use of local crawling Example @@ -170,15 +189,12 @@ Example docs: - name: Continue startUrl: https://docs.continue.dev/intro - rootUrl: https://docs.continue.dev favicon: https://docs.continue.dev/favicon.ico ``` --- -### `tools` - - + ### `mcpServers` @@ -247,6 +263,7 @@ Putting it all together, here's a complete example of a `config.yaml` configurat ```yaml title="config.yaml" name: MyProject +version: 0.0.1 models: - name: GPT-4 @@ -261,6 +278,7 @@ models: requestOptions: headers: Authorization: Bearer YOUR_OPENAI_API_KEY + - name: Ollama Starcoder provider: ollama model: starcoder @@ -271,17 +289,25 @@ models: stop: - "\n" -context: - - uses: diff - - uses: docs - with: - startUrl: https://docs.example.com/introduction - rootUrl: https://docs.example.com - maxDepth: 3 +rules: + - Give concise responses + - Always assume TypeScript rather than JavaScript -tools: - - url: https://api.exampletool.com - apiKey: YOUR_TOOL_API_KEY +prompts: + - name: test + description: Unit test a function + prompt: | + Please write a complete suite of unit tests for this function. You should use the Jest testing framework. The tests should cover all possible edge cases and should be as thorough as possible. You should also include a description of each test case. + +context: + - provider: diff + - provider: file + - provider: codebase + - provider: code + - provider: docs + params: + startUrl: https://docs.example.com/introduction + maxDepth: 3 mcpServers: - name: DevServer diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md index 15cb94c4d..985a66809 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/autocomplete.md @@ -60,7 +60,6 @@ ollama run starcoder2:3b - `disable`: 禁用自动补全(也可以在 IDE 配置中完成) - `template`: 一个用来自动补全的可选的模板字符串。它使用 Mustache 模板语言渲染,并且传递 'prefix' 和 'suffix' 变量。(字符串) -- `useFileSuffix`: 决定是否使用文件后缀在提示词中。(布尔型) - `maxPromptTokens`: 提示词使用的 token 的最大数量。一个较小的数字生成较快的补全,但是较少的上下文。(数字) - `prefixPercentage`: 输入专注于前缀的百分比。(数字) - `maxSuffixPercentage`: The maximum percentage of the prompt that can be dedicated to the suffix. (Number) diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/docs.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/docs.md index 79862b38f..e14ac4afc 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/docs.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/deep-dives/docs.md @@ -58,7 +58,6 @@ toc_max_heading_level: 5 { "title": "Continue", "startUrl": "https://docs.continue.dev/intro", - "rootUrl": "https://docs.continue.dev", "faviconUrl": "https://docs.continue.dev/favicon.ico", } ] @@ -66,7 +65,7 @@ toc_max_heading_level: 5 - `title`: 文档网站的名称,用来在 UI 中进行识别。 - `startUrl`: 索引进程开始的 URL 。 -- `rootUrl`: 文档网站的基本 URL ,用来确定哪个页面索引。 + - `faviconUrl`: 网站 favicon 的 URL ,用来在 UI 中进行视觉识别。 ## 使用 `useChromiumForDocsCrawling` 爬取动态生成的网站 diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md index a224cf8a8..98addf212 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/reference.md @@ -83,16 +83,15 @@ Specifies options for tab autocompletion behavior. **Properties:** - `disable`: If `true`, disables tab autocomplete (default: `false`). -- `useFileSuffix`: If `true`, includes file suffix in the prompt. -- `maxPromptTokens`: Maximum number of tokens for the prompt. -- `debounceDelay`: Delay (in ms) before triggering autocomplete. -- `maxSuffixPercentage`: Maximum percentage of prompt for suffix. -- `prefixPercentage`: Percentage of input for prefix. +- `maxPromptTokens`: Maximum number of tokens for the prompt (default: `1024`). +- `debounceDelay`: Delay (in ms) before triggering autocomplete (default: `350`). +- `maxSuffixPercentage`: Maximum percentage of prompt for suffix (default: `0.2`). +- `prefixPercentage`: Percentage of input for prefix (default: `0.3`). - `template`: Template string for autocomplete, using Mustache templating. -- `multilineCompletions`: Controls multiline completions (`"always"`, `"never"`, or `"auto"`). -- `useCache`: If `true`, caches completions. -- `onlyMyCode`: If `true`, only includes code within the repository. -- `disableInFiles`: Array of glob patterns for files where autocomplete is disabled. +- `multilineCompletions`: Controls multiline completions (`"always"`, `"never"`, or `"auto"`) (default: `auto`). +- `useCache`: If `true`, caches completions (default: `true`). +- `onlyMyCode`: If `true`, only includes code within the repository (default: `true`). +- `disableInFiles`: Array of glob patterns for files where autocomplete is disabled (default: `[]`). Example @@ -233,8 +232,8 @@ List of documentation sites to index. - `title` (**required**): Title of the documentation site, displayed in dropdowns, etc. - `startUrl` (**required**): Start page for crawling - usually root or intro page for docs -- `rootUrl`: Crawler will only index docs within this domain - pages that contain this URL -- `maxDepth`: Maximum depth for crawling. Default `3` + +- `maxDepth`: Maximum link depth for crawling. Default `4` - `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`). Example @@ -244,7 +243,6 @@ Example { "title": "Continue", "startUrl": "https://docs.continue.dev/intro", - "rootUrl": "https://docs.continue.dev", "faviconUrl": "https://docs.continue.dev/favicon.ico", } ] diff --git a/docs/sidebars.js b/docs/sidebars.js index c5026b1ef..380377f8a 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -132,12 +132,13 @@ const sidebars = { }, ], }, - "customize/changelog", + "customize/settings", { type: "link", label: "Reference", href: "/reference", }, + "customize/changelog", // { // type: "link", // label: "YAML Reference", diff --git a/docs/static/img/docs-form.png b/docs/static/img/docs-form.png new file mode 100644 index 000000000..3607049d1 Binary files /dev/null and b/docs/static/img/docs-form.png differ diff --git a/docs/static/img/docs-indexes.png b/docs/static/img/docs-indexes.png new file mode 100644 index 000000000..efa3746e7 Binary files /dev/null and b/docs/static/img/docs-indexes.png differ diff --git a/docs/static/img/docs-indexing-peek.png b/docs/static/img/docs-indexing-peek.png new file mode 100644 index 000000000..51e2d217f Binary files /dev/null and b/docs/static/img/docs-indexing-peek.png differ diff --git a/docs/static/img/header-buttons.png b/docs/static/img/header-buttons.png new file mode 100644 index 000000000..f6a644d03 Binary files /dev/null and b/docs/static/img/header-buttons.png differ diff --git a/docs/static/img/settings-page.png b/docs/static/img/settings-page.png new file mode 100644 index 000000000..f4b58cfd5 Binary files /dev/null and b/docs/static/img/settings-page.png differ diff --git a/extensions/intellij/.run/IDE Logs.run.xml b/extensions/intellij/.run/IDE Logs.run.xml new file mode 100644 index 000000000..2743ca662 --- /dev/null +++ b/extensions/intellij/.run/IDE Logs.run.xml @@ -0,0 +1,17 @@ + + + + \ No newline at end of file diff --git a/extensions/intellij/.run/Run Continue.run.xml b/extensions/intellij/.run/Run Continue.run.xml index 2cc85210f..1366cd39e 100644 --- a/extensions/intellij/.run/Run Continue.run.xml +++ b/extensions/intellij/.run/Run Continue.run.xml @@ -2,6 +2,7 @@ + diff --git a/extensions/intellij/.run/Start Core Dev Server (CE).run.xml b/extensions/intellij/.run/Start Core Dev Server (CE).run.xml index 7469eb5e8..739ac3749 100644 --- a/extensions/intellij/.run/Start Core Dev Server (CE).run.xml +++ b/extensions/intellij/.run/Start Core Dev Server (CE).run.xml @@ -1,11 +1,11 @@ -