Merge pull request #12570 from continuedev/main

Merge staged work from continue-fork
This commit is contained in:
Nate Sesti 2026-06-07 21:21:56 -07:00 • committed by GitHub
commit eaa23c5a9d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
509 changed files with 19095 additions and 104104 deletions

View file

@ -15,7 +15,7 @@ Use double quotes (or backticks if needed) for strings
The code being tested is used in IDE extensions, and it:
- accesses code workspaces through the IDE ("workspace directories")
- persists extension-related data to the the local machine of the user ("global directory"), and
- uses configuration via a `ConfigHandler`, which is stored in either the global directory (default) or accessed via a remote "control plane" using the `ControlPlaneClient`
- uses configuration via a `ConfigHandler`, which is stored in the global directory
Jest testing setup includes
- @core/test/jest.global-setup.ts initializes a temporary global directory, which is where files that store persisted extension data live.
@ -25,7 +25,6 @@ Jest testing setup includes
@core/test/fixtures.ts provides fixtures that should be used in tests to emulate extension behavior
- import `testIde` for IDE/workspace operations
- import `testConfigHandler` for any ConfigHandler needs
- import `testControlPlaneClient` for control plane operations
- import `ideSettingsPromise` for any IdeSettings needs
- import `testLLM` for any ILLM/BaseLLM needs. Set the `completion` property to the desired completion, e.g. `testLLM.completion = "Desired completion";`

55
.github/workflows/docs-gh-pages.yml vendored Normal file
View file

@ -0,0 +1,55 @@
name: Deploy Docs to GitHub Pages
on:
push:
branches: [main]
paths:
- "docs/**"
- "docs-site/**"
workflow_dispatch:
permissions:
contents: read
pages: write
id-token: write
concurrency:
group: "pages"
cancel-in-progress: true
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
cache-dependency-path: docs-site/package-lock.json
- name: Install dependencies
working-directory: docs-site
run: npm ci
- name: Build
working-directory: docs-site
run: npm run build
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: docs-site/out
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
needs: build
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4

View file

@ -125,10 +125,22 @@ jobs:
needs:
- build
if: github.event_name != 'workflow_dispatch' || github.event.inputs.publish_build == 'true'
permissions:
contents: write
pull-requests: write
steps:
# 0. Setup git
- name: Checkout
uses: actions/checkout@v6
- name: Set up Git
run: |
git config --local user.email "action@github.com"
git config --local user.name "GitHub Action"
- name: Pull latest changes from release
run: git fetch origin ${{ github.ref }} && git checkout ${{ github.ref }}
# 1. Download the artifacts
- uses: actions/download-artifact@v8
with:
@ -151,3 +163,52 @@ jobs:
cd extensions/vscode
npx ovsx publish --pre-release -p ${{ secrets.VSX_REGISTRY_TOKEN }} --packagePath ../../vsix-artifacts/*.vsix
# 4. Create PR with version bump
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version-file: ".nvmrc"
- name: Create PR branch
run: |
BRANCH_NAME="chore/bump-vscode-version-$(date +%Y%m%d-%H%M%S)"
git checkout -b $BRANCH_NAME
echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_ENV
- name: Bump version in package.json
run: |
cd extensions/vscode
npm version patch --no-git-tag-version
VERSION=$(node -p "require('./package.json').version")
echo "NEW_VERSION=$VERSION" >> $GITHUB_ENV
- name: Create Pull Request
uses: peter-evans/create-pull-request@v8
with:
token: ${{ secrets.CI_GITHUB_TOKEN }}
commit-message: "chore: bump vscode extension version to ${{ env.NEW_VERSION }}"
title: "chore: bump vscode extension version to ${{ env.NEW_VERSION }}"
body: |
Automated PR to bump the VS Code extension version after successful pre-release publication.
- Bumped version in extensions/vscode/package.json to ${{ env.NEW_VERSION }}
branch: ${{ env.BRANCH_NAME }}
base: main
delete-branch: true
# 5. Update version in package.json
# - name: Update version in package.json
# run: |
# cd extensions/vscode
# npm version patch
# - name: Commit changes
# run: |
# git config --local user.email "action@github.com"
# git config --local user.name "GitHub Action"
# git commit -am "💚 Update package.json version [skip ci]"
# - name: Push changes
# uses: ad-m/github-push-action@master
# with:
# github_token: ${{ secrets.GITHUB_TOKEN }}
# branch: ${{ github.ref }}

1
.gitignore vendored
View file

@ -15,6 +15,7 @@ downloads/
eggs/
.eggs/
lib/
!docs-site/lib/
lib64/
parts/
sdist/

2
.idea/gradle.xml generated
View file

@ -5,7 +5,7 @@
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="externalProjectPath" value="$PROJECT_DIR$/extensions/intellij" />
<option name="gradleJvm" value="#JAVA_HOME" />
<option name="gradleHome" value="/usr/local/Cellar/gradle/8.13/libexec" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$/extensions/intellij" />

6
.vscode/launch.json vendored
View file

@ -142,9 +142,6 @@
"env": {
"NODE_ENV": "development",
"USE_VERCEL_AI_SDK_ANTHROPIC": "true"
// "CONTINUE_API_BASE": "http://localhost:3001/",
// "WORKOS_CLIENT_ID": "client_01J0FW6XCPMJMQ3CG51RB4HBZQ",
// "HUB_URL": "http://localhost:3000"
},
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
@ -172,9 +169,6 @@
"env": {
"NODE_ENV": "development",
"CONTINUE_USE_BEDROCK": "1"
// "CONTINUE_API_BASE": "http://localhost:3001/",
// "WORKOS_CLIENT_ID": "client_01J0FW6XCPMJMQ3CG51RB4HBZQ",
// "HUB_URL": "http://localhost:3000"
},
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",

105
BUILD_DEPENDENCIES.md Normal file
View file

@ -0,0 +1,105 @@
# Build Dependencies & Secrets
This document catalogs all build dependencies, secrets, and environment variables required by the continue-fork repository.
---
## VS Code Extension
| Secret | Purpose | Referenced In |
| -------------------- | ----------------------------------------------------------------------------------- | --------------------------- |
| `VSCE_TOKEN` | Personal access token for publishing to the VS Code Marketplace (set as `VSCE_PAT`) | `main.yaml`, `preview.yaml` |
| `VSX_REGISTRY_TOKEN` | Token for publishing to the Open VSX Registry | `main.yaml`, `preview.yaml` |
---
## JetBrains Extension
| Secret | Purpose | Referenced In |
| -------------------------------- | --------------------------------------------------------------------- | ------------------------ |
| `APPLE_CERT_DATA` | Base64-encoded Apple signing certificate (p12) for macOS code signing | `jetbrains-release.yaml` |
| `APPLE_CERT_PASSWORD` | Password for the Apple signing certificate | `jetbrains-release.yaml` |
| `APPLE_NOTARY_USER` | Apple notarization username (currently commented out) | `jetbrains-release.yaml` |
| `APPLE_NOTARY_PASSWORD` | Apple notarization password (currently commented out) | `jetbrains-release.yaml` |
| `JETBRAINS_PUBLISH_TOKEN` | Token for publishing to JetBrains Marketplace | `jetbrains-release.yaml` |
| `JETBRAINS_CERTIFICATE_CHAIN` | Certificate chain for signing the JetBrains plugin | `jetbrains-release.yaml` |
| `JETBRAINS_PRIVATE_KEY` | Private key for signing the JetBrains plugin | `jetbrains-release.yaml` |
| `JETBRAINS_PRIVATE_KEY_PASSWORD` | Password for the JetBrains signing private key | `jetbrains-release.yaml` |
---
## CLI
| Variable | Purpose | Referenced In |
| ------------------- | ----------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| `CONTINUE_API_BASE` | Base URL for the Continue API (defaults to `https://api.continue.dev/`) | `extensions/cli/.env.example` |
| `CONTINUE_API_KEY` | API key for Continue authentication | `extensions/cli/.env.example`, `packages/continue-sdk/typescript/.env.example`, multiple workflows |
---
## NPM Package Releases
| Secret | Purpose | Referenced In |
| ------------------------------- | ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `SEMANTIC_RELEASE_GITHUB_TOKEN` | GitHub token used by semantic-release for creating releases | `release-openai-adapters.yml`, `release-config-yaml.yml`, `release-fetch.yml`, `release-llm-info.yml`, `reusable-release.yml` |
| `SEMANTIC_RELEASE_NPM_TOKEN` | npm token used by semantic-release for publishing packages | `release-openai-adapters.yml`, `release-config-yaml.yml`, `release-fetch.yml`, `release-llm-info.yml`, `reusable-release.yml` |
| `SEMANTIC_RELEASE_TOKEN` | GitHub token for stable release workflow | `stable-release.yml` |
---
## AI Provider API Keys (Testing & Releases)
Used for integration tests in PR checks and package releases.
| Secret | Purpose | Referenced In |
| ------------------------------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| `OPENAI_API_KEY` | OpenAI API key | `pr-checks.yaml`, `reusable-release.yml`, `release-*.yml` |
| `ANTHROPIC_API_KEY` | Anthropic API key | `pr-checks.yaml`, `reusable-release.yml`, `release-*.yml`, `cli-pr-checks.yml`, `continue-agents.yml` |
| `GEMINI_API_KEY` | Google Gemini API key | `pr-checks.yaml`, `reusable-release.yml`, `release-*.yml` |
| `MISTRAL_API_KEY` | Mistral API key | `pr-checks.yaml`, `reusable-release.yml`, `release-*.yml` |
| `AZURE_OPENAI_API_KEY` | Azure OpenAI API key | `pr-checks.yaml`, `reusable-release.yml`, `release-*.yml` |
| `AZURE_FOUNDRY_CODESTRAL_API_KEY` | Azure AI Foundry Codestral API key | `pr-checks.yaml`, `reusable-release.yml`, `release-*.yml` |
| `AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY` | Azure AI Foundry Mistral Small API key | `pr-checks.yaml`, `reusable-release.yml`, `release-*.yml` |
| `AZURE_OPENAI_GPT41_API_KEY` | Azure OpenAI GPT-4.1 API key | `pr-checks.yaml`, `reusable-release.yml`, `release-*.yml` |
| `VOYAGE_API_KEY` | Voyage AI embeddings API key | `pr-checks.yaml`, `reusable-release.yml`, `release-*.yml` |
| `RELACE_API_KEY` | Relace API key | `pr-checks.yaml`, `reusable-release.yml`, `release-*.yml` |
| `INCEPTION_API_KEY` | Inception API key | `pr-checks.yaml`, `reusable-release.yml`, `release-*.yml` |
---
## CI/CD & GitHub
| Secret | Purpose | Referenced In |
| ------------------ | --------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `GITHUB_TOKEN` | Default GitHub Actions token (automatic) | Many workflows |
| `CI_GITHUB_TOKEN` | Elevated GitHub PAT for cross-repo operations and PR management | `jetbrains-release.yaml`, `preview.yaml`, `main.yaml`, `pr-checks.yaml`, `auto-assign-issue.yaml` |
| `CONTINUE_API_KEY` | Continue platform API key for agent workflows | `run-continue-agent.yml`, `tidy-up-codebase.yml`, `snyk-agent.yaml`, `auto-fix-failed-tests.yml`, `cli-pr-checks.yml` |
| `RUNLOOP_API_KEY` | Runloop API key for uploading sandbox blueprints | `stable-release.yml`, `upload-runloop-blueprint.yml` |
| `SNYK_TOKEN` | Snyk security scanning token | `snyk-agent.yaml` |
---
## Issue/PR Tooling
| Secret | Purpose | Referenced In |
| ------------------------------------ | ---------------------------------------------------- | -------------------- |
| `CHROMA_CLOUD_API_KEY` | Chroma vector DB API key for similar issue detection | `similar-issues.yml` |
| `CHROMA_TENANT` | Chroma tenant identifier | `similar-issues.yml` |
| `CHROMA_DATABASE` | Chroma database name | `similar-issues.yml` |
| `ISSUE_PR_METRICS_SLACK_WEBHOOK_URL` | Slack webhook for PR/issue metrics notifications | `metrics.yaml` |
---
## SSH Testing
| Secret | Purpose | Referenced In |
| ------------------------------ | ------------------------------------------- | ---------------- |
| `GH_ACTIONS_SSH_TEST_KEY_PEM` | SSH private key for remote connection tests | `pr-checks.yaml` |
| `GH_ACTIONS_SSH_TEST_DNS_NAME` | DNS name of the SSH test host | `pr-checks.yaml` |
---
All workflow files are located under `.github/workflows/`. Environment example files are at:
- `extensions/cli/.env.example`
- `packages/continue-sdk/typescript/.env.example`

View file

@ -1,85 +1,63 @@
<div align="center"></div>
<h1 align="center">Continue</h1>
<p align="center">Pioneering open-source coding agent</p>
<div align="center">
<a target="_blank" href="https://opensource.org/licenses/Apache-2.0" style="background:none">
<img src="https://img.shields.io/badge/License-Apache_2.0-blue.svg" style="height: 22px;" />
</a>
<a target="_blank" href="https://docs.continue.dev" style="background:none">
<img src="https://img.shields.io/badge/Continue-docs-%23BE1B55.svg?logo=data:image/svg%2bxml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNiAyNCIgZmlsbD0id2hpdGUiPgogIDxwYXRoIGQ9Ik0yMC41Mjg2IDMuMjY4MTFMMTkuMTUxMiA1LjY1Njk0TDIyLjYzMjggMTEuNjg0OUMyMi42NTgyIDExLjczMDYgMjIuNjczNSAxMS43ODY2IDIyLjY3MzUgMTEuODM3NEMyMi42NzM1IDExLjg4ODIgMjIuNjU4MiAxMS45NDQxIDIyLjYzMjggMTEuOTg5OUwxOS4xNTEyIDE4LjAyMjlMMjAuNTI4NiAyMC40MTE3TDI1LjQ3OTEgMTEuODM3NEwyMC41Mjg2IDMuMjYzMDNWMy4yNjgxMVpNMTguNjE3NiA1LjM0NjlMMTkuOTk1IDIuOTU4MDdIMTcuMjQwMkwxNS44NjI4IDUuMzQ2OUgxOC42MjI3SDE4LjYxNzZaTTE1Ljg1NzcgNS45NjY5N0wxOS4wNzUgMTEuNTMyNEgyMS44Mjk4TDE4LjYxNzYgNS45NjY5N0gxNS44NTc3Wk0xOC42MTc2IDE3LjcxNzlMMjEuODI5OCAxMi4xNDc0SDE5LjA3NUwxNS44NTc3IDE3LjcxNzlIMTguNjE3NlpNMTUuODU3NyAxOC4zMzhMMTcuMjM1MSAyMC43MTY3SDE5Ljk4OTlMMTguNjEyNSAxOC4zMzhIMTUuODUyNkgxNS44NTc3Wk02LjUyMDk4IDIxLjMwNjNDNi40NjUwNyAyMS4zMDYzIDYuNDE0MjQgMjEuMjkxIDYuMzY4NSAyMS4yNjU2QzYuMzIyNzYgMjEuMjQwMiA2LjI4MjA5IDIxLjE5OTUgNi4yNTY2OCAyMS4xNTM4TDIuNzcwMDIgMTUuMTIwN0gwLjAxNTI0ODJMNC45NjU3IDIzLjY5SDE0Ljg2MTVMMTMuNDg0MSAyMS4zMDYzSDYuNTI2MDZINi41MjA5OFpNMTQuMDE3OCAyMC45OTYyTDE1LjM5NTIgMjMuMzhMMTYuNzcyNiAyMC45OTExTDE1LjM5NTIgMTguNjAyM0wxNC4wMTc4IDIwLjk5MTFWMjAuOTk2MlpNMTQuODYxNSAxOC4yOTc0SDguNDM3MTJMNy4wNTk3MyAyMC42ODYySDEzLjQ4NDFMMTQuODYxNSAxOC4yOTc0Wk03Ljg5ODM2IDE3Ljk5MjRMNC42ODEwOCAxMi40MjE5TDMuMzAzNjkgMTQuODEwN0w2LjUyMDk4IDIwLjM4MTJMNy44OTgzNiAxNy45OTI0Wk0wLjAxMDE2NTQgMTQuNTAwN0gyLjc2NDk0TDQuMTQyMzIgMTIuMTExOEgxLjM5MjYzTDAuMDEwMTY1NCAxNC41MDA3Wk02LjI0MTQzIDIuNTQxM0M2LjI2Njg1IDIuNDk1NTYgNi4zMDc1MSAyLjQ1NDkgNi4zNTMyNSAyLjQyOTQ4QzYuMzk5IDIuNDA0MDcgNi40NTQ5IDIuMzg4ODIgNi41MDU3MyAyLjM4ODgySDEzLjQ3NEwxNC44NTE0IDBINC45NTA0NUwwIDguNTc0MzVIMi43NTQ3N0w2LjIzMTI3IDIuNTQ2MzhMNi4yNDE0MyAyLjU0MTNaTTQuMTQyMzIgMTEuNTc4MkwyLjc2NDk0IDkuMTg5MzRIMC4wMTAxNjU0TDEuMzg3NTUgMTEuNTc4Mkg0LjE0MjMyWk02LjUxMDgxIDMuMzEzODZMMy4yOTg2MSA4Ljg3OTNMNC42NzU5OSAxMS4yNjgxTDcuODg4MiA1LjcwMjY4TDYuNTEwODEgMy4zMTM4NlpNMTMuNDc5MSAzLjAwMzgySDcuMDQ0NDhMOC40MjE4NyA1LjM5MjY0SDE0Ljg1NjRMMTMuNDc5MSAzLjAwMzgyWk0xNS4zOTUyIDUuMDgyNkwxNi43Njc1IDIuNjk4ODZMMTUuMzk1MiAwLjMxMDAzOEwxNC4wMTc4IDIuNjkzNzhMMTUuMzk1MiA1LjA4MjZaIi8+Cjwvc3ZnPg==" style="height: 22px;" />
</a>
<a target="_blank" href="https://changelog.continue.dev" style="background:none">
<img src="https://img.shields.io/badge/changelog-%96EFF3" style="height: 22px;" />
</a>
<p></p>
**Source-controlled AI checks, enforceable in CI**
<a href="https://opensource.org/licenses/Apache-2.0"><img src="https://img.shields.io/badge/License-Apache_2.0-blue.svg" /></a>
<a href="https://docs.continue.dev"><img src="https://img.shields.io/badge/Docs-docs.continue.dev-blue" /></a>
<a href="https://github.com/continuedev/continue/releases"><img src="https://img.shields.io/badge/Changelog-GitHub_Releases-blue" /></a>
</div>
![Banner](media/github-readme.png)
<p align="center">
<img src="media/github-readme.png" alt="Banner" />
</p>
## Getting started
## What is Continue?
Paste this into your coding agent of choice:
> _Note: The `continuedev/continue` repository is no longer actively maintained and is read-only for all users._
```
Help me write checks for this codebase: https://continue.dev/walkthrough
```
Continue is a coding agent available as a [CLI](#cli), [VS Code extension](#vs-code), and [JetBrains plugin](#jetbrains).
## How it works
## Documentation
Continue runs agents on every pull request as GitHub status checks. Each agent is a markdown file in your repo at `.continue/checks/`. Green if the code looks good, red with a suggested diff if not. Here is an example that performs a security review:
To learn how to configure Continue, how it works, and how to customize it, check out the [Continue Docs](https://docs.continue.dev).
```yaml
---
name: Security Review
description: Review PR for basic security vulnerabilities
---
Review this PR and check that:
- No secrets or API keys are hardcoded
- All new API endpoints have input validation
- Error responses use the standard error format
```
## Final 2.0.0 Release
## Install CLI
We polished Continue and did a final 2.0.0 release of the VS Code extension, CLI, and JetBrains plugin.
AI checks are powered by the open-source Continue CLI (`cn`).
This included removing anonymous telemetry, pulling out authentication, squashing bugs, and more.
**macOS / Linux:**
### VS Code
```bash
curl -fsSL https://raw.githubusercontent.com/continuedev/continue/main/extensions/cli/scripts/install.sh | bash
```
[![VS Code Marketplace](https://img.shields.io/badge/VS_Code_Marketplace-007ACC?logo=visualstudiocode&logoColor=white)](https://marketplace.visualstudio.com/items?itemName=Continue.continue) [![OpenVSX Registry](https://img.shields.io/badge/OpenVSX_Registry-C160EF?logo=eclipseide&logoColor=white)](https://open-vsx.org/extension/Continue/continue) [![View source](https://img.shields.io/badge/View_source-181717?logo=github&logoColor=white)](extensions/vscode)
**Windows (PowerShell):**
### CLI
```powershell
irm https://raw.githubusercontent.com/continuedev/continue/main/extensions/cli/scripts/install.ps1 | iex
```
[![npm](https://img.shields.io/badge/npm-CB3837?logo=npm&logoColor=white)](https://www.npmjs.com/package/@continuedev/cli) [![View source](https://img.shields.io/badge/View_source-181717?logo=github&logoColor=white)](extensions/cli)
Or with npm (requires Node.js 20+):
### JetBrains
```bash
npm i -g @continuedev/cli
```
> _Note: We recommend using the Continue CLI instead of the JetBrains plugin._
Then run:
[![GitHub Releases](https://img.shields.io/badge/GitHub_Releases-181717?logo=github&logoColor=white)](https://github.com/continuedev/continue/releases) [![View source](https://img.shields.io/badge/View_source-181717?logo=github&logoColor=white)](extensions/intellij)
```bash
cn
```
## Contributors
Looking for the VS Code extension? [See here](extensions/vscode/README.md).
Thank you to the entire Continue community for helping us create a pioneering coding agent.
## Contributing
What we built together pushed the boundaries of what AI developer tooling could be.
Read the [contributing guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md), and
join the [GitHub Discussions](https://github.com/continuedev/continue/discussions).
We hope this codebase continues to serve as a foundation for others.
## Code friends
<a href="https://github.com/continuedev/continue/graphs/contributors">
<img src="https://contrib.rocks/image?repo=continuedev/continue&max=500" />
</a>
## License
[Apache 2.0 © 2023-2024 Continue Dev, Inc.](./LICENSE)
Apache 2.0 © 2023-2026 Continue Dev, Inc.

30
TESTING.md Normal file
View file

@ -0,0 +1,30 @@
# PR #2 Testing Checklist — Strip Hub/Mission Control Code
## Critical
- [x] **Extension cold start** — Launch VS Code with the extension. No errors in Output panel ("Continue" channel) or Dev Tools console. _(Found and fixed `message.includes` crash in `webviewProtocol.ts` + removed dead proxy-server error handling block.)_
- [x] **Fresh install onboarding** — Delete/rename `~/.continue/config.yaml`, restart. Onboarding card shows "Configure your models" (no Hub sign-in). _(Removed "Credits" tab, fixed Ollama link padding, title font sizes, and "Google Gemini API API key" duplicate.)_
- [x] **Existing config loads** — With existing `config.yaml`, models/context providers/MCP servers all load.
- [x] **API key resolution from `.env`** — Models using secrets from `~/.continue/.env` or workspace `.env` authenticate and respond.
- [x] **Config reload** — Edit `config.yaml` while running, changes picked up without restart.
## High Priority
- [x] **Profile/assistant switching** — Assistant dropdown shows only local profiles. Switching works. _(Fixed missing profiles list in GUI by adding `profiles` to configUpdate message. Also fixed initial Redux state label and adjusted dropdown styling.)_
- [x] **Compilation** — `tsc --noEmit` passes for core, GUI, and VS Code extension.
- [x] **Test suite** — Vitest tests pass: `LocalPlatformClient` (8), `LocalProfileLoader` (2), `doLoadConfig` (2) — all 12 pass.
- [x] **No telemetry network calls** — Dev Tools Network tab shows no requests to `posthog.com` or `sentry.io`.
- [x] **Agent mode tools** — Start an agent conversation, all tools load correctly.
## Medium Priority
- [x] **MCP servers connect** — Configured MCP servers connect and tools appear.
- [x] **Local blocks in YAML** — Local model block files in `.continue/models/` auto-merge into config correctly.
- [x] **Background mode view** — N/A, component removed from UI routing. No way to navigate to it.
- [x] **Keyboard shortcut `Cmd+Shift+'`** — Toggles between configs without errors.
- [x] **Config settings page** — Settings page renders cleanly, no Account dropdown or Organizations tab. _(Removed GitHub issue/community links.)_
## Low Priority
- [x] **"Main Config" naming** — Fresh installs show "Main Config" as default profile name.
- [x] **IntelliJ startup** — Profiles load correctly after rebuilding core binary. _(Core binary must be rebuilt for IntelliJ to pick up changes.)_

View file

@ -16,7 +16,6 @@ The build process is otherwise defined entirely in `build.js`.
### List of dynamically imported modules
- posthog-node
- @octokit/rest
- esbuild

65579
binary/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -50,7 +50,6 @@
"mac-ca": "^2.0.3",
"ncp": "^2.0.0",
"node-fetch": "^3.3.2",
"posthog-node": "^3.6.3",
"system-ca": "^1.0.2",
"tar": "^7.5.13",
"undici": "^7.24.0",

View file

@ -282,8 +282,6 @@ export class CompletionProvider {
gitRepo: await this.ide.getRepoName(helper.filepath),
uniqueId: await this.ide.getUniqueId(),
timestamp: new Date().toISOString(),
profileType:
this.configHandler.currentProfile?.profileDescription.profileType,
...helper.options,
};

View file

@ -1,6 +1,6 @@
import { DataLogger } from "../../data/log";
import { COUNT_COMPLETION_REJECTED_AFTER } from "../../util/parameters";
import { Telemetry } from "../../util/posthog";
import { getUriFileExtension } from "../../util/uri";
import { AutocompleteOutcome } from "./types";
@ -119,14 +119,6 @@ export class AutocompleteLoggingService {
time: restOfOutcome.time,
useRecentlyEdited: restOfOutcome.useRecentlyEdited,
numLines: restOfOutcome.numLines,
profileType: restOfOutcome.profileType,
};
outcome.enabledStaticContextualization
? void Telemetry.capture("autocomplete", {
...toLog,
enabledStaticContextualization: true,
})
: void Telemetry.capture("autocomplete", toLog);
}
}

View file

@ -43,5 +43,4 @@ export interface AutocompleteOutcome extends TabAutocompleteOptions {
uniqueId: string;
timestamp: string;
enabledStaticContextualization?: boolean;
profileType?: "local" | "platform" | "control-plane";
}

View file

@ -1,6 +1,5 @@
import { ConfigResult, ConfigValidationError } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../control-plane/client.js";
import {
BrowserSerializedContinueConfig,
ContinueConfig,
@ -13,26 +12,16 @@ import { GlobalContext } from "../util/GlobalContext.js";
import { getConfigYamlPath } from "../util/paths.js";
import EventEmitter from "node:events";
import {
AuthType,
ControlPlaneSessionInfo,
} from "../control-plane/AuthTypes.js";
import { getControlPlaneEnv } from "../control-plane/env.js";
import { PolicySingleton } from "../control-plane/PolicySingleton.js";
import { Logger } from "../util/Logger.js";
import { Telemetry } from "../util/posthog.js";
import {
getAllDotContinueDefinitionFiles,
LoadAssistantFilesOptions,
} from "./loadLocalAssistants.js";
import LocalProfileLoader from "./profile/LocalProfileLoader.js";
import PlatformProfileLoader from "./profile/PlatformProfileLoader.js";
import {
OrganizationDescription,
OrgWithProfiles,
ProfileDescription,
ProfileLifecycleManager,
SerializedOrgWithProfiles,
} from "./ProfileLifecycleManager.js";
export type { ProfileDescription };
@ -40,13 +29,15 @@ export type { ProfileDescription };
type ConfigUpdateFunction = (payload: ConfigResult<ContinueConfig>) => void;
export class ConfigHandler {
controlPlaneClient: ControlPlaneClient;
private readonly globalContext = new GlobalContext();
private globalLocalProfileManager: ProfileLifecycleManager;
private organizations: OrgWithProfiles[] = [];
private profiles: ProfileLifecycleManager[] = [];
get profileDescriptions(): ProfileDescription[] {
return this.profiles.map((p) => p.profileDescription);
}
currentProfile: ProfileLifecycleManager | null;
currentOrg: OrgWithProfiles | null;
totalConfigReloads: number = 0;
public isInitialized: Promise<void>;
@ -61,22 +52,15 @@ export class ConfigHandler {
constructor(
private readonly ide: IDE,
private llmLogger: ILLMLogger,
initialSessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
) {
this.controlPlaneClient = new ControlPlaneClient(
initialSessionInfoPromise,
this.ide,
);
// This profile manager will always be available
this.globalLocalProfileManager = new ProfileLifecycleManager(
new LocalProfileLoader(ide, this.controlPlaneClient, this.llmLogger),
new LocalProfileLoader(ide, this.llmLogger),
this.ide,
);
this.currentOrg = null;
this.currentProfile = null;
this.organizations = [];
this.profiles = [];
this.initter = new EventEmitter();
this.isInitialized = new Promise((resolve) => {
@ -96,66 +80,49 @@ export class ConfigHandler {
return this.workspaceDirs.join("&");
}
async getProfileKey(orgId: string) {
const workspaceId = await this.getWorkspaceId();
return `${workspaceId}:::${orgId}`;
}
private async cascadeInit(reason: string, isLogin?: boolean) {
private async cascadeInit(reason: string) {
const signal = this.cascadeAbortController.signal;
this.workspaceDirs = null; // forces workspace dirs reload
// Always update globalLocalProfileManager before recreating all the loaders
// during every cascadeInit so it holds the most recent controlPlaneClient.
this.globalLocalProfileManager = new ProfileLifecycleManager(
new LocalProfileLoader(this.ide, this.controlPlaneClient, this.llmLogger),
new LocalProfileLoader(this.ide, this.llmLogger),
this.ide,
);
try {
const { orgs, errors } = await this.getOrgs();
const { profiles, errors } = await this.loadProfiles();
// Figure out selected org
// Figure out selected profile
const workspaceId = await this.getWorkspaceId();
const selectedOrgs =
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
let currentSelection = selectedOrgs[workspaceId];
const selectedProfiles =
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
const currentSelection = selectedProfiles[workspaceId];
// reset personal org to first available non-personal org on login
if (isLogin && currentSelection === "personal") {
currentSelection = null;
}
const fallback = profiles.length > 0 ? profiles[0] : null;
const firstNonPersonal = orgs.find(
(org) => org.id !== this.PERSONAL_ORG_DESC.id,
);
const fallback: OrgWithProfiles | null =
firstNonPersonal ?? orgs[0] ?? null;
let selectedOrg: OrgWithProfiles | null;
let selectedProfile: ProfileLifecycleManager | null;
if (currentSelection) {
const match = orgs.find((org) => org.id === currentSelection);
if (match) {
selectedOrg = match;
} else {
selectedOrg = fallback;
}
const match = profiles.find(
(profile) => profile.profileDescription.id === currentSelection,
);
selectedProfile = match ?? fallback;
} else {
selectedOrg = fallback;
selectedProfile = fallback;
}
if (signal.aborted) {
return; // local only case, no`fetch to throw abort error
return;
}
this.globalContext.update("lastSelectedOrgIdForWorkspace", {
...selectedOrgs,
[workspaceId]: selectedOrg?.id,
});
if (selectedProfile) {
this.globalContext.update("lastSelectedProfileForWorkspace", {
...selectedProfiles,
[workspaceId]: selectedProfile.profileDescription.id,
});
}
this.organizations = orgs;
this.currentOrg = selectedOrg;
this.currentProfile = selectedOrg?.currentProfile;
this.profiles = profiles;
this.currentProfile = selectedProfile;
await this.reloadConfig(reason, errors);
} catch (e) {
@ -168,190 +135,33 @@ export class ConfigHandler {
}
}
private async getOrgs(): Promise<{
orgs: OrgWithProfiles[];
private async loadProfiles(): Promise<{
profiles: ProfileLifecycleManager[];
errors?: ConfigValidationError[];
}> {
const errors: ConfigValidationError[] = [];
const isSignedIn = await this.controlPlaneClient.isSignedIn();
if (isSignedIn) {
try {
// TODO use policy returned with org, not policy endpoint
const policyResponse = await this.controlPlaneClient.getPolicy();
PolicySingleton.getInstance().policy = policyResponse;
const orgDescriptions =
await this.controlPlaneClient.listOrganizations();
const orgsWithPolicy = orgDescriptions.map((d) => ({
...d,
policy: policyResponse?.policy,
}));
if (policyResponse?.policy?.allowOtherOrgs === false) {
if (orgsWithPolicy.length === 0) {
return { orgs: [] };
} else {
const firstOrg = await this.getNonPersonalHubOrg(orgsWithPolicy[0]);
return { orgs: [firstOrg] };
}
}
const orgs = await Promise.all([
this.getPersonalHubOrg(),
...orgsWithPolicy.map((org) => this.getNonPersonalHubOrg(org)),
]);
// TODO make try/catch more granular here, to catch specific org errors
return { orgs };
} catch (e) {
errors.push({
fatal: false,
message: `Error loading Continue Hub assistants${e instanceof Error ? ":\n" + e.message : ""}`,
});
}
} else {
PolicySingleton.getInstance().policy = null;
}
// Load local org if not signed in or hub orgs fail
try {
const orgs = [await this.getLocalOrg()];
return { orgs };
const profiles = await this.getLocalProfiles({
includeGlobal: true,
includeWorkspace: true,
});
return { profiles };
} catch (e) {
errors.push({
fatal: true,
message: `Error loading local assistants${e instanceof Error ? ":\n" + e.message : ""}`,
});
return {
orgs: [],
profiles: [],
errors,
};
}
}
getSerializedOrgs(): SerializedOrgWithProfiles[] {
return this.organizations.map((org) => ({
iconUrl: org.iconUrl,
id: org.id,
name: org.name,
slug: org.slug,
profiles: org.profiles.map((profile) => profile.profileDescription),
selectedProfileId: org.currentProfile?.profileDescription.id || null,
}));
}
private async getHubProfiles(orgScopeId: string | null) {
const assistants = await this.controlPlaneClient.listAssistants(orgScopeId);
return await Promise.all(
assistants.map(async (assistant) => {
const profileLoader = await PlatformProfileLoader.create({
configResult: {
...assistant.configResult,
config: assistant.configResult.config,
},
ownerSlug: assistant.ownerSlug,
packageSlug: assistant.packageSlug,
iconUrl: assistant.iconUrl,
versionSlug: assistant.configResult.config?.version ?? "latest",
controlPlaneClient: this.controlPlaneClient,
ide: this.ide,
llmLogger: this.llmLogger,
rawYaml: assistant.rawYaml,
orgScopeId: orgScopeId,
});
return new ProfileLifecycleManager(profileLoader, this.ide);
}),
);
}
private async getNonPersonalHubOrg(
org: OrganizationDescription,
): Promise<OrgWithProfiles> {
const localProfiles = await this.getLocalProfiles({
includeGlobal: false,
includeWorkspace: true,
});
const profiles = [...(await this.getHubProfiles(org.id)), ...localProfiles];
return this.rectifyProfilesForOrg(org, profiles);
}
private PERSONAL_ORG_DESC: OrganizationDescription = {
iconUrl: "",
id: "personal",
name: "Personal",
slug: undefined,
};
private async getPersonalHubOrg() {
const localProfiles = await this.getLocalProfiles({
includeGlobal: true,
includeWorkspace: true,
});
const hubProfiles = await this.getHubProfiles(null);
const profiles = [...hubProfiles, ...localProfiles];
return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, profiles);
}
private async getLocalOrg() {
const localProfiles = await this.getLocalProfiles({
includeGlobal: true,
includeWorkspace: true,
});
return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, localProfiles);
}
private async rectifyProfilesForOrg(
org: OrganizationDescription,
profiles: ProfileLifecycleManager[],
): Promise<OrgWithProfiles> {
const profileKey = await this.getProfileKey(org.id);
const selectedProfiles =
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
const currentSelection = selectedProfiles[profileKey];
const firstNonLocal = profiles.find(
(profile) => profile.profileDescription.profileType !== "local",
);
const fallback =
firstNonLocal ?? (profiles.length > 0 ? profiles[0] : null);
let currentProfile: ProfileLifecycleManager | null;
if (currentSelection) {
const match = profiles.find(
(profile) => profile.profileDescription.id === currentSelection,
);
if (match) {
currentProfile = match;
} else {
currentProfile = fallback;
}
} else {
currentProfile = fallback;
}
if (currentProfile) {
this.globalContext.update("lastSelectedProfileForWorkspace", {
...selectedProfiles,
[profileKey]: currentProfile.profileDescription.id,
});
}
return {
...org,
profiles,
currentProfile,
};
}
async getLocalProfiles(options: LoadAssistantFilesOptions) {
/**
* Users can define as many local agents as they want in a `.continue/agents` (or previous .continue/assistants) folder
*/
// Local customization disabled for on-premise deployments
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
if (env.AUTH_TYPE === AuthType.OnPrem) {
return [];
}
const localProfiles: ProfileLifecycleManager[] = [];
if (options.includeGlobal) {
@ -368,12 +178,7 @@ export class ConfigHandler {
])
).flat();
const profiles = allFiles.map((assistant) => {
return new LocalProfileLoader(
this.ide,
this.controlPlaneClient,
this.llmLogger,
assistant,
);
return new LocalProfileLoader(this.ide, this.llmLogger, assistant);
});
const localAssistantProfiles = profiles.map(
(profile) => new ProfileLifecycleManager(profile, this.ide),
@ -398,101 +203,27 @@ export class ConfigHandler {
await this.cascadeInit("IDE settings update");
}
// Session change: refresh session and cascade refresh from the top
async updateControlPlaneSessionInfo(
sessionInfo: ControlPlaneSessionInfo | undefined,
) {
const currentSession = await this.controlPlaneClient.sessionInfoPromise;
const newSession = sessionInfo;
let reload = false;
let isLogin = false;
if (newSession) {
if (currentSession) {
if (
newSession.AUTH_TYPE !== AuthType.OnPrem &&
currentSession.AUTH_TYPE !== AuthType.OnPrem
) {
if (newSession.account.id !== currentSession.account.id) {
// session id change (non-on-prem)
reload = true;
}
}
} else {
// log in
reload = true;
isLogin = true;
}
} else {
if (currentSession) {
// log out
reload = true;
}
}
if (reload) {
this.controlPlaneClient = new ControlPlaneClient(
Promise.resolve(sessionInfo),
this.ide,
);
this.abortCascade();
await this.cascadeInit("Control plane session info update", isLogin);
}
return reload;
}
// Org id: check id validity, save selection, switch and reload
async setSelectedOrgId(orgId: string, profileId?: string) {
if (orgId === this.currentOrg?.id) {
return;
}
const org = this.organizations.find((org) => org.id === orgId);
if (!org) {
throw new Error(`Org ${orgId} not found`);
}
const workspaceId = await this.getWorkspaceId();
const selectedOrgs =
this.globalContext.get("lastSelectedOrgIdForWorkspace") ?? {};
this.globalContext.update("lastSelectedOrgIdForWorkspace", {
...selectedOrgs,
[workspaceId]: org.id,
});
this.currentOrg = org;
if (profileId) {
await this.setSelectedProfileId(profileId);
} else {
this.currentProfile = org.currentProfile;
await this.reloadConfig("Selected org changed");
}
}
// Profile id: check id validity, save selection, switch and reload
async setSelectedProfileId(profileId: string) {
if (!this.currentOrg) {
throw new Error(`No org selected`);
}
if (
this.currentProfile &&
profileId === this.currentProfile.profileDescription.id
) {
return;
}
const profile = this.currentOrg.profiles.find(
const profile = this.profiles.find(
(profile) => profile.profileDescription.id === profileId,
);
if (!profile) {
throw new Error(`Profile ${profileId} not found in current org`);
throw new Error(`Profile ${profileId} not found`);
}
const profileKey = await this.getProfileKey(this.currentOrg.id);
const workspaceId = await this.getWorkspaceId();
const selectedProfiles =
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
this.globalContext.update("lastSelectedProfileForWorkspace", {
...selectedProfiles,
[profileKey]: profileId,
[workspaceId]: profileId,
});
this.currentProfile = profile;
@ -517,14 +248,12 @@ export class ConfigHandler {
return out;
}
for (const org of this.organizations) {
for (const profile of org.profiles) {
if (
profile.profileDescription.id !==
this.currentProfile.profileDescription.id
) {
profile.clearConfig();
}
for (const profile of this.profiles) {
if (
profile.profileDescription.id !==
this.currentProfile.profileDescription.id
) {
profile.clearConfig();
}
}
@ -542,25 +271,6 @@ export class ConfigHandler {
this.initter.emit("init");
// Track config loading telemetry
const endTime = performance.now();
const duration = endTime - startTime;
const isSignedIn = await this.controlPlaneClient.isSignedIn();
const profileDescription = this.currentProfile.profileDescription;
const telemetryData: Record<string, any> = {
duration,
reason,
totalConfigLoads: this.totalConfigReloads,
configLoadInterrupted,
profileType: profileDescription.profileType,
isPersonalOrg: this.currentOrg?.id === this.PERSONAL_ORG_DESC.id,
errorCount: errors.length,
isSignedIn,
};
void Telemetry.capture("config_reload", telemetryData);
if (errors.length) {
Logger.error("Errors loading config: ", errors);
}
@ -627,7 +337,7 @@ export class ConfigHandler {
if (!openProfileId) {
return;
}
const profile = this.currentOrg?.profiles.find(
const profile = this.profiles.find(
(p) => p.profileDescription.id === openProfileId,
);
if (!profile) {
@ -635,14 +345,9 @@ export class ConfigHandler {
return;
}
if (profile.profileDescription.profileType === "local") {
getConfigYamlPath();
const configFile = element?.sourceFile ?? profile.profileDescription.uri;
await this.ide.openFile(configFile);
} else {
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
await this.ide.openUrl(`${env.APP_URL}${openProfileId}`);
}
getConfigYamlPath();
const configFile = element?.sourceFile ?? profile.profileDescription.uri;
await this.ide.openFile(configFile);
}
// Ancient method of adding custom providers through vs code

View file

@ -10,10 +10,6 @@ import { defaultConfig } from "./default";
describe.skip("Test the ConfigHandler and E2E config loading", () => {
test("should show only local profile", () => {
const profiles = testConfigHandler.currentOrg?.profiles;
expect(profiles?.length).toBe(1);
expect(profiles?.[0].profileDescription.id).toBe("local");
const currentProfile = testConfigHandler.currentProfile;
expect(currentProfile?.profileDescription.id).toBe("local");
});

View file

@ -2,7 +2,6 @@ import {
ConfigResult,
ConfigValidationError,
FullSlug,
Policy,
} from "@continuedev/config-yaml";
import {
@ -18,7 +17,6 @@ import { IProfileLoader } from "./profile/IProfileLoader.js";
export interface ProfileDescription {
fullSlug: FullSlug;
profileType: "control-plane" | "local" | "platform";
title: string;
id: string;
iconUrl: string;
@ -27,24 +25,6 @@ export interface ProfileDescription {
rawYaml?: string;
}
export interface OrganizationDescription {
id: string;
iconUrl: string;
name: string;
slug: string | undefined; // TODO: This doesn't need to be undefined, just doing while transitioning the backend
policy?: Policy;
}
export type OrgWithProfiles = OrganizationDescription & {
profiles: ProfileLifecycleManager[];
currentProfile: ProfileLifecycleManager | null;
};
export type SerializedOrgWithProfiles = OrganizationDescription & {
profiles: ProfileDescription[];
selectedProfileId: string | null;
};
export class ProfileLifecycleManager {
private savedConfigResult: ConfigResult<ContinueConfig> | undefined;
private savedBrowserConfigResult?: ConfigResult<BrowserSerializedContinueConfig>;
@ -99,7 +79,6 @@ export class ProfileLifecycleManager {
try {
result = await this.profileLoader.doLoadConfig();
} catch (e) {
// Capture config loading system failures to Sentry
Logger.error(e, {
context: "profile_config_loading",
});

View file

@ -1,7 +1,7 @@
import { ConfigYaml } from "@continuedev/config-yaml";
export const defaultConfig: ConfigYaml = {
name: "Local Config",
name: "Main Config",
version: "1.0.0",
schema: "v1",
models: [],

View file

@ -36,7 +36,6 @@ import { getLegacyBuiltInSlashCommandFromDescription } from "../commands/slash/b
import { convertCustomCommandToSlashCommand } from "../commands/slash/customSlashCommand";
import { slashCommandFromPromptFile } from "../commands/slash/promptFileSlashCommand";
import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton";
import { useHub } from "../control-plane/env";
import { BaseLLM } from "../llm";
import { LLMClasses, llmFromDescription } from "../llm/llms";
import CustomLLMClass from "../llm/llms/CustomLLM";
@ -60,7 +59,6 @@ import { localPathToUri } from "../util/pathToUri";
import { loadJsonMcpConfigs } from "../context/mcp/json/loadJsonMcpConfigs";
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
import { PolicySingleton } from "../control-plane/PolicySingleton";
import { getBaseToolDefinitions, serializeTool } from "../tools";
import { resolveRelativePathInDir } from "../util/ideUtils";
import { getWorkspaceRcConfigs } from "./json/loadRcConfigs";
@ -240,7 +238,6 @@ async function intermediateToFinalConfig({
ideInfo,
uniqueId,
llmLogger,
workOsAccessToken,
loadPromptFiles = true,
}: {
config: Config;
@ -249,7 +246,6 @@ async function intermediateToFinalConfig({
ideInfo: IdeInfo;
uniqueId: string;
llmLogger: ILLMLogger;
workOsAccessToken: string | undefined;
loadPromptFiles?: boolean;
}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
const errors: ConfigValidationError[] = [];
@ -346,13 +342,6 @@ async function intermediateToFinalConfig({
"summarize",
]); // Default to chat role if not specified
// Free trial provider will be completely ignored
let warnAboutFreeTrial = false;
models = models.filter((model) => model.providerName !== "free-trial");
if (models.filter((m) => m.providerName === "free-trial").length) {
warnAboutFreeTrial = true;
}
// Tab autocomplete model
const tabAutocompleteModels: BaseLLM[] = [];
if (config.tabAutocompleteModel) {
@ -373,11 +362,7 @@ async function intermediateToFinalConfig({
config.completionOptions,
);
if (llm) {
if (llm.providerName === "free-trial") {
warnAboutFreeTrial = true;
} else {
tabAutocompleteModels.push(llm);
}
tabAutocompleteModels.push(llm);
}
} else {
tabAutocompleteModels.push(new CustomLLMClass(desc));
@ -418,10 +403,7 @@ async function intermediateToFinalConfig({
return embedConfig;
}
const { provider, ...options } = embedConfig;
if (provider === "transformers.js" || provider === "free-trial") {
if (provider === "free-trial") {
warnAboutFreeTrial = true;
}
if (provider === "transformers.js") {
return new TransformersJsEmbeddingsProvider();
} else {
const cls = LLMClasses.find((c) => c.providerName === provider);
@ -458,10 +440,6 @@ async function intermediateToFinalConfig({
return rerankingConfig;
}
const { name, params } = config.reranker as RerankerDescription;
if (name === "free-trial") {
warnAboutFreeTrial = true;
return null;
}
if (name === "llm") {
const llm = models.find((model) => model.title === params?.modelTitle);
if (!llm) {
@ -492,14 +470,6 @@ async function intermediateToFinalConfig({
}
const newReranker = getRerankingILLM(config.reranker);
if (warnAboutFreeTrial) {
errors.push({
fatal: false,
message:
"Model provider 'free-trial' is no longer supported, will be ignored",
});
}
const continueConfig: ContinueConfig = {
...config,
contextProviders,
@ -550,10 +520,7 @@ async function intermediateToFinalConfig({
// Trigger MCP server refreshes (Config is reloaded again once connected!)
const mcpManager = MCPManagerSingleton.getInstance();
const orgPolicy = PolicySingleton.getInstance().policy;
if (orgPolicy?.policy?.allowMcpServers === false) {
await mcpManager.shutdown();
} else {
{
const mcpOptions: InternalMcpOptions[] = (
config.experimental?.modelContextProtocolServers ?? []
).map((server, index) => ({
@ -677,7 +644,6 @@ async function finalToBrowserConfig(
tools: final.tools.map(serializeTool),
mcpServerStatuses: final.mcpServerStatuses,
tabAutocompleteOptions: final.tabAutocompleteOptions,
usePlatform: await useHub(ide.getIdeSettings()),
modelsByRole: Object.fromEntries(
Object.entries(final.modelsByRole).map(([k, v]) => [
k,
@ -828,7 +794,6 @@ async function loadContinueConfigFromJson(
ideInfo: IdeInfo,
uniqueId: string,
llmLogger: ILLMLogger,
workOsAccessToken: string | undefined,
overrideConfigJson: SerializedContinueConfig | undefined,
): Promise<ConfigResult<ContinueConfig>> {
const workspaceConfigs = await getWorkspaceRcConfigs(ide);
@ -924,7 +889,6 @@ async function loadContinueConfigFromJson(
ideInfo,
uniqueId,
llmLogger,
workOsAccessToken,
});
return {
config: finalConfig,

View file

@ -1,6 +1,5 @@
import { ConfigResult } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { ContinueConfig, IDE, ILLMLogger } from "../../index.js";
import { ProfileDescription } from "../ProfileLifecycleManager.js";
@ -17,7 +16,6 @@ export default class LocalProfileLoader implements IProfileLoader {
constructor(
private ide: IDE,
private controlPlaneClient: ControlPlaneClient,
private llmLogger: ILLMLogger,
private overrideAssistantFile?:
| { path: string; content: string }
@ -25,7 +23,6 @@ export default class LocalProfileLoader implements IProfileLoader {
) {
this.description = {
id: overrideAssistantFile?.path ?? LocalProfileLoader.ID,
profileType: "local",
fullSlug: {
ownerSlug: "",
packageSlug: "",
@ -34,7 +31,7 @@ export default class LocalProfileLoader implements IProfileLoader {
iconUrl: "",
title: overrideAssistantFile?.path
? getUriPathBasename(overrideAssistantFile.path)
: "Local Config",
: "Main Config",
errors: undefined,
uri:
overrideAssistantFile?.path ??
@ -46,11 +43,9 @@ export default class LocalProfileLoader implements IProfileLoader {
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
const result = await doLoadConfig({
ide: this.ide,
controlPlaneClient: this.controlPlaneClient,
llmLogger: this.llmLogger,
profileId: this.description.id,
overrideConfigYamlByPath: this.overrideAssistantFile?.path,
orgScopeId: null,
packageIdentifier: {
uriType: "file",
fileUri: this.overrideAssistantFile?.path ?? getPrimaryConfigFilePath(),

View file

@ -1,6 +1,5 @@
import { describe, expect, it, vi } from "vitest";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { LLMLogger } from "../../llm/logger.js";
import { testIde } from "../../test/fixtures.js";
import LocalProfileLoader from "./LocalProfileLoader.js";
@ -17,10 +16,6 @@ vi.mock("./doLoadConfig.js", () => ({
}));
describe("LocalProfileLoader", () => {
const controlPlaneClient = new ControlPlaneClient(
Promise.resolve(undefined),
testIde,
);
const llmLogger = new LLMLogger();
it("should pass pre-read content in packageIdentifier for override files", async () => {
@ -29,12 +24,7 @@ describe("LocalProfileLoader", () => {
content: "name: Test\nversion: 1.0.0\nschema: v1\n",
};
const loader = new LocalProfileLoader(
testIde,
controlPlaneClient,
llmLogger,
overrideFile,
);
const loader = new LocalProfileLoader(testIde, llmLogger, overrideFile);
await loader.doLoadConfig();
@ -50,11 +40,7 @@ describe("LocalProfileLoader", () => {
});
it("should not include content in packageIdentifier when no override file", async () => {
const loader = new LocalProfileLoader(
testIde,
controlPlaneClient,
llmLogger,
);
const loader = new LocalProfileLoader(testIde, llmLogger);
await loader.doLoadConfig();
@ -76,13 +62,9 @@ describe("LocalProfileLoader", () => {
configName: "My Custom Config",
});
const loader = new LocalProfileLoader(
testIde,
controlPlaneClient,
llmLogger,
);
const loader = new LocalProfileLoader(testIde, llmLogger);
expect(loader.description.title).toBe("Local Config");
expect(loader.description.title).toBe("Main Config");
await loader.doLoadConfig();
@ -96,14 +78,10 @@ describe("LocalProfileLoader", () => {
configLoadInterrupted: false,
});
const loader = new LocalProfileLoader(
testIde,
controlPlaneClient,
llmLogger,
);
const loader = new LocalProfileLoader(testIde, llmLogger);
await loader.doLoadConfig();
expect(loader.description.title).toBe("Local Config");
expect(loader.description.title).toBe("Main Config");
});
});

View file

@ -1,158 +0,0 @@
import { AssistantUnrolled, ConfigResult } from "@continuedev/config-yaml";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { getControlPlaneEnv } from "../../control-plane/env.js";
import { ContinueConfig, IDE, ILLMLogger } from "../../index.js";
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
private configResult: ConfigResult<AssistantUnrolled>;
private readonly ownerSlug: string;
private readonly packageSlug: string;
private readonly iconUrl: string;
private readonly versionSlug: string;
private readonly controlPlaneClient: ControlPlaneClient;
private readonly ide: IDE;
private llmLogger: ILLMLogger;
readonly description: ProfileDescription;
private readonly orgScopeId: string | null;
private constructor({
configResult,
ownerSlug,
packageSlug,
iconUrl,
versionSlug,
controlPlaneClient,
ide,
llmLogger,
description,
orgScopeId,
}: {
configResult: ConfigResult<AssistantUnrolled>;
ownerSlug: string;
packageSlug: string;
iconUrl: string;
versionSlug: string;
controlPlaneClient: ControlPlaneClient;
ide: IDE;
llmLogger: ILLMLogger;
description: ProfileDescription;
orgScopeId: string | null;
}) {
this.configResult = configResult;
this.ownerSlug = ownerSlug;
this.packageSlug = packageSlug;
this.iconUrl = iconUrl;
this.versionSlug = versionSlug;
this.controlPlaneClient = controlPlaneClient;
this.ide = ide;
this.llmLogger = llmLogger;
this.description = description;
this.orgScopeId = orgScopeId;
}
static async create({
configResult,
ownerSlug,
packageSlug,
iconUrl,
versionSlug,
controlPlaneClient,
ide,
llmLogger,
rawYaml,
orgScopeId,
}: {
configResult: ConfigResult<AssistantUnrolled>;
ownerSlug: string;
packageSlug: string;
iconUrl: string;
versionSlug: string;
controlPlaneClient: ControlPlaneClient;
ide: IDE;
llmLogger: ILLMLogger;
rawYaml: string;
orgScopeId: string | null;
}): Promise<PlatformProfileLoader> {
const controlPlaneEnv = await getControlPlaneEnv(ide.getIdeSettings());
const description: ProfileDescription = {
id: `${ownerSlug}/${packageSlug}`,
profileType: "platform",
fullSlug: {
ownerSlug,
packageSlug,
versionSlug,
},
title: configResult.config?.name ?? `${ownerSlug}/${packageSlug}`,
errors: configResult.errors,
iconUrl: iconUrl,
uri: `${controlPlaneEnv.APP_URL}${ownerSlug}/${packageSlug}`,
rawYaml,
};
return new PlatformProfileLoader({
configResult,
ownerSlug,
packageSlug,
iconUrl,
versionSlug,
controlPlaneClient,
ide,
llmLogger,
description,
orgScopeId,
});
}
async doLoadConfig(): Promise<ConfigResult<ContinueConfig>> {
if (this.configResult.errors?.find((e) => e.fatal)) {
return {
config: undefined,
errors: this.configResult.errors,
configLoadInterrupted: false,
};
}
const results = await doLoadConfig({
ide: this.ide,
controlPlaneClient: this.controlPlaneClient,
llmLogger: this.llmLogger,
overrideConfigYaml: this.configResult.config,
profileId: this.description.id,
orgScopeId: this.orgScopeId,
packageIdentifier: {
uriType: "slug",
fullSlug: {
ownerSlug: this.ownerSlug,
packageSlug: this.packageSlug,
versionSlug: this.versionSlug,
},
},
});
return {
config: results.config,
errors: [...(this.configResult.errors ?? []), ...(results.errors ?? [])],
configLoadInterrupted: results.configLoadInterrupted,
};
}
setIsActive(isActive: boolean): void {}
}

View file

@ -4,7 +4,6 @@ import {
AssistantUnrolled,
ConfigResult,
ConfigValidationError,
ModelRole,
PackageIdentifier,
} from "@continuedev/config-yaml";
@ -20,14 +19,7 @@ import {
import { stringifyMcpPrompt } from "../../commands/slash/mcpSlashCommand";
import { convertRuleBlockToSlashCommand } from "../../commands/slash/ruleBlockSlashCommand";
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
import ContinueProxyContextProvider from "../../context/providers/ContinueProxyContextProvider";
import MCPContextProvider from "../../context/providers/MCPContextProvider";
import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { getControlPlaneEnv } from "../../control-plane/env.js";
import { PolicySingleton } from "../../control-plane/PolicySingleton";
import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js";
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy";
import { initSlashCommand } from "../../promptFiles/initPrompt";
import { getConfigDependentToolDefinitions } from "../../tools";
import { encodeMCPToolUri } from "../../tools/callTool";
@ -35,8 +27,7 @@ import { getMCPToolName } from "../../tools/mcpToolName";
import { GlobalContext } from "../../util/GlobalContext";
import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths";
import { localPathOrUriToPath } from "../../util/pathToUri";
import { Telemetry } from "../../util/posthog";
import { SentryLogger } from "../../util/sentry/SentryLogger";
import { IdeInfoService } from "../../util/IdeInfoService";
import { TTS } from "../../util/tts";
import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles";
import { loadContinueConfigFromJson } from "../load";
@ -72,32 +63,26 @@ async function loadRules(ide: IDE) {
export default async function doLoadConfig(options: {
ide: IDE;
controlPlaneClient: ControlPlaneClient;
llmLogger: ILLMLogger;
overrideConfigJson?: SerializedContinueConfig;
overrideConfigYaml?: AssistantUnrolled;
profileId: string;
overrideConfigYamlByPath?: string;
orgScopeId: string | null;
packageIdentifier: PackageIdentifier;
}): Promise<ConfigResult<ContinueConfig>> {
const {
ide,
controlPlaneClient,
llmLogger,
overrideConfigJson,
overrideConfigYaml,
profileId,
overrideConfigYamlByPath,
orgScopeId,
packageIdentifier,
} = options;
const ideInfo = await ide.getIdeInfo();
const uniqueId = await ide.getUniqueId();
const ideSettings = await ide.getIdeSettings();
const workOsAccessToken = await controlPlaneClient.getAccessToken();
const isSignedIn = await controlPlaneClient.isSignedIn();
// Migrations for old config files
// Removes
@ -131,10 +116,7 @@ export default async function doLoadConfig(options: {
uniqueId,
llmLogger,
overrideConfigYaml,
controlPlaneClient,
orgScopeId,
packageIdentifier,
workOsAccessToken,
});
newConfig = result.config;
errors = result.errors;
@ -147,7 +129,6 @@ export default async function doLoadConfig(options: {
ideInfo,
uniqueId,
llmLogger,
workOsAccessToken,
overrideConfigJson,
);
newConfig = result.config;
@ -190,14 +171,6 @@ export default async function doLoadConfig(options: {
newConfig.slashCommands.push(initSlashCommand);
const proxyContextProvider = newConfig.contextProviders?.find(
(cp) => cp.description.title === "continue-proxy",
);
if (proxyContextProvider) {
(proxyContextProvider as ContinueProxyContextProvider).workOsAccessToken =
workOsAccessToken;
}
// Show deprecation warnings for providers
const globalContext = new GlobalContext();
newConfig.contextProviders.forEach((provider) => {
@ -320,7 +293,6 @@ export default async function doLoadConfig(options: {
rules: newConfig.rules,
enableExperimentalTools:
newConfig.experimental?.enableExperimentalTools ?? false,
isSignedIn,
isRemote: await ide.isWorkspaceRemote(),
modelName: newConfig.selectedModelByRole.chat?.model,
ide,
@ -377,82 +349,12 @@ export default async function doLoadConfig(options: {
}
}
// Org policies
const policy = PolicySingleton.getInstance().policy?.policy;
if (policy?.allowAnonymousTelemetry === false) {
newConfig.allowAnonymousTelemetry = false;
}
if (policy?.allowCodebaseIndexing === false) {
newConfig.disableIndexing = true;
}
// Setup telemetry only after (and if) we know it is enabled
await Telemetry.setup(
newConfig.allowAnonymousTelemetry ?? true,
await ide.getUniqueId(),
ideInfo,
);
// Setup Sentry logger with same telemetry settings
// TODO: Remove Continue team member check once Sentry is ready for all users
let userEmail: string | undefined;
try {
// Access the session info to get user email for Continue team member check
const sessionInfo = await (controlPlaneClient as any).sessionInfoPromise;
userEmail = sessionInfo?.account?.id;
} catch (error) {
// Ignore errors getting session info, will default to no Sentry
}
await SentryLogger.setup(
newConfig.allowAnonymousTelemetry ?? false,
await ide.getUniqueId(),
ideInfo,
userEmail,
);
// Setup IdeInfoService
IdeInfoService.setup(uniqueId, ideInfo);
// TODO: pass config to pre-load non-system TTS models
await TTS.setup();
// Set up control plane proxy if configured
const controlPlane = (newConfig as any).controlPlane;
const useOnPremProxy =
controlPlane?.useContinueForTeamsProxy === false && controlPlane?.proxyUrl;
const env = await getControlPlaneEnv(Promise.resolve(ideSettings));
let controlPlaneProxyUrl: string = useOnPremProxy
? controlPlane?.proxyUrl
: env.DEFAULT_CONTROL_PLANE_PROXY_URL;
if (!controlPlaneProxyUrl.endsWith("/")) {
controlPlaneProxyUrl += "/";
}
const controlPlaneProxyInfo = {
profileId,
controlPlaneProxyUrl,
workOsAccessToken,
};
if (newConfig.analytics) {
// FIXME before re-enabling TeamAnalytics.setup() populate workspaceId in
// controlPlaneProxyInfo to prevent /proxy/analytics/undefined/capture calls
// where undefined is :workspaceId
// await TeamAnalytics.setup(
// newConfig.analytics,
// uniqueId,
// ideInfo.extensionVersion,
// controlPlaneClient,
// controlPlaneProxyInfo,
// );
} else {
await TeamAnalytics.shutdown();
}
newConfig = await injectControlPlaneProxyInfo(
newConfig,
controlPlaneProxyInfo,
);
return {
config: newConfig,
errors,
@ -460,32 +362,3 @@ export default async function doLoadConfig(options: {
configName,
};
}
// Pass ControlPlaneProxyInfo to objects that need it
async function injectControlPlaneProxyInfo(
config: ContinueConfig,
info: ControlPlaneProxyInfo,
): Promise<ContinueConfig> {
Object.keys(config.modelsByRole).forEach((key) => {
config.modelsByRole[key as ModelRole].forEach((model) => {
if (model.providerName === "continue-proxy") {
(model as ContinueProxy).controlPlaneProxyInfo = info;
}
});
});
Object.keys(config.selectedModelByRole).forEach((key) => {
const model = config.selectedModelByRole[key as ModelRole];
if (model?.providerName === "continue-proxy") {
(model as ContinueProxy).controlPlaneProxyInfo = info;
}
});
config.modelsByRole.chat.forEach((model) => {
if (model.providerName === "continue-proxy") {
(model as ContinueProxy).controlPlaneProxyInfo = info;
}
});
return config;
}

View file

@ -61,12 +61,6 @@ vi.mock("../../tools/callTool", () => ({
vi.mock("../../tools/mcpToolName", () => ({
getMCPToolName: vi.fn(),
}));
vi.mock("../../util/posthog", () => ({
Telemetry: { setup: vi.fn() },
}));
vi.mock("../../util/sentry/SentryLogger", () => ({
SentryLogger: { setup: vi.fn() },
}));
vi.mock("../../util/tts", () => ({
TTS: { setup: vi.fn() },
}));
@ -78,20 +72,6 @@ vi.mock("../../util/GlobalContext", () => ({
update() {}
},
}));
vi.mock("../../control-plane/env", () => ({
getControlPlaneEnv: vi.fn().mockResolvedValue({
DEFAULT_CONTROL_PLANE_PROXY_URL: "https://proxy.example.com/",
}),
getControlPlaneEnvSync: vi.fn().mockReturnValue({
CONTROL_PLANE_URL: "https://api.example.com/",
}),
}));
vi.mock("../../control-plane/PolicySingleton", () => ({
PolicySingleton: { getInstance: () => ({ policy: null }) },
}));
vi.mock("../../control-plane/TeamAnalytics", () => ({
TeamAnalytics: { setup: vi.fn(), shutdown: vi.fn() },
}));
vi.mock("../../promptFiles/initPrompt", () => ({
initSlashCommand: { name: "init", description: "init" },
}));
@ -125,12 +105,6 @@ const mockIde = {
isWorkspaceRemote: vi.fn().mockResolvedValue(true),
} as any;
const mockControlPlaneClient = {
getAccessToken: vi.fn().mockResolvedValue("token"),
isSignedIn: vi.fn().mockResolvedValue(false),
sessionInfoPromise: Promise.resolve(undefined),
} as any;
const mockLlmLogger = {} as any;
describe("doLoadConfig pre-read content bypass", () => {
@ -147,11 +121,11 @@ describe("doLoadConfig pre-read content bypass", () => {
await doLoadConfig({
ide: mockIde,
controlPlaneClient: mockControlPlaneClient,
llmLogger: mockLlmLogger,
profileId: "test-profile",
overrideConfigYamlByPath: packageIdentifier.fileUri,
orgScopeId: null,
packageIdentifier,
});
@ -171,11 +145,11 @@ describe("doLoadConfig pre-read content bypass", () => {
await doLoadConfig({
ide: mockIde,
controlPlaneClient: mockControlPlaneClient,
llmLogger: mockLlmLogger,
profileId: "test-profile",
overrideConfigYamlByPath: packageIdentifier.fileUri,
orgScopeId: null,
packageIdentifier,
});

View file

@ -818,7 +818,6 @@ declare global {
| "currentFile"
| "greptile"
| "outline"
| "continue-proxy"
| "highlights"
| "file"
| "issue"

View file

@ -1,40 +0,0 @@
import { decodeSecretLocation, SecretType } from "@continuedev/config-yaml";
import { BrowserSerializedContinueConfig, ModelDescription } from "..";
/**
* Helper function to determine if the config uses an API key that relies on Continue credits (free trial or models add-on)
* @param config The serialized config object
* @returns true if the config is using any free trial models
*/
export function usesCreditsBasedApiKey(
config: BrowserSerializedContinueConfig | null,
): boolean {
if (!config) {
return false;
}
// Check if the currently selected chat model uses free-trial provider
const modelsByRole = config.modelsByRole;
const allModels = [...Object.values(modelsByRole)].flat();
// Check if any of the chat models use free-trial provider
try {
const hasFreeTrial = allModels?.some(modelUsesCreditsBasedApiKey);
return hasFreeTrial;
} catch (e) {
console.error("Error checking for free trial API key:", e);
}
return false;
}
const modelUsesCreditsBasedApiKey = (model: ModelDescription) => {
if (!model.apiKeyLocation) {
return false;
}
const secretType = decodeSecretLocation(model.apiKeyLocation).secretType;
return secretType === SecretType.FreeTrial;
};

View file

@ -1,360 +0,0 @@
import { beforeEach, describe, expect, test, vi } from "vitest";
import { BrowserSerializedContinueConfig } from "..";
// Create the mock before importing anything else
const mockDecodeSecretLocation = vi.fn();
// Mock the module
vi.mock("@continuedev/config-yaml", () => ({
SecretType: {
User: "user",
Organization: "organization",
FreeTrial: "free_trial",
},
decodeSecretLocation: mockDecodeSecretLocation,
}));
describe("usesFreeTrialApiKey", () => {
let usesFreeTrialApiKey: typeof import("./usesFreeTrialApiKey").usesCreditsBasedApiKey;
let SecretType: typeof import("@continuedev/config-yaml").SecretType;
beforeEach(async () => {
mockDecodeSecretLocation.mockReset();
usesFreeTrialApiKey = (await import("./usesFreeTrialApiKey"))
.usesCreditsBasedApiKey;
SecretType = (await import("@continuedev/config-yaml")).SecretType;
});
test("usesFreeTrialApiKey should return false when config is null", () => {
const result = usesFreeTrialApiKey(null);
expect(result).toBe(false);
});
test("usesFreeTrialApiKey should return false when config is undefined", () => {
const result = usesFreeTrialApiKey(undefined as any);
expect(result).toBe(false);
});
test("usesFreeTrialApiKey should return false when no models have apiKeyLocation", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
underlyingProviderName: "test",
},
{
title: "Model 2",
provider: "test",
model: "test-model-2",
underlyingProviderName: "test",
},
],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
subagent: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
subagent: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
});
test("usesFreeTrialApiKey should return false when models have apiKeyLocation but none are free trial", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "user:testuser/api-key",
underlyingProviderName: "test",
},
],
edit: [
{
title: "Model 2",
provider: "test",
model: "test-model-2",
apiKeyLocation: "organization:testorg/api-key",
underlyingProviderName: "test",
},
],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
subagent: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
subagent: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation
.mockReturnValueOnce({
secretType: SecretType.User,
userSlug: "testuser",
secretName: "api-key",
})
.mockReturnValueOnce({
secretType: SecretType.Organization,
orgSlug: "testorg",
secretName: "api-key",
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
});
test("usesFreeTrialApiKey should return true when at least one model uses free trial API key", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "user:testuser/api-key",
underlyingProviderName: "test",
},
{
title: "Free Trial Model",
provider: "test",
model: "free-trial-model",
apiKeyLocation: "free_trial:owner/package/api-key",
underlyingProviderName: "test",
},
],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
subagent: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
subagent: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation
.mockReturnValueOnce({
secretType: SecretType.User,
userSlug: "testuser",
secretName: "api-key",
})
.mockReturnValueOnce({
secretType: SecretType.FreeTrial,
blockSlug: { ownerSlug: "owner", packageSlug: "package" },
secretName: "api-key",
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(true);
expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
});
test("usesFreeTrialApiKey should return true when free trial model is in a different role", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "user:testuser/api-key",
underlyingProviderName: "test",
},
],
edit: [
{
title: "Free Trial Edit Model",
provider: "test",
model: "free-trial-edit-model",
apiKeyLocation: "free_trial:owner/package/api-key",
underlyingProviderName: "test",
},
],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
subagent: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
subagent: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation
.mockReturnValueOnce({
secretType: SecretType.User,
userSlug: "testuser",
secretName: "api-key",
})
.mockReturnValueOnce({
secretType: SecretType.FreeTrial,
blockSlug: { ownerSlug: "owner", packageSlug: "package" },
secretName: "api-key",
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(true);
});
test("usesFreeTrialApiKey should return false and log error when decodeSecretLocation throws", () => {
const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "invalid-secret-location",
underlyingProviderName: "test",
},
],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
subagent: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
subagent: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation.mockImplementation(() => {
throw new Error("Invalid secret location format");
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
expect(consoleSpy).toHaveBeenCalledWith(
"Error checking for free trial API key:",
expect.any(Error),
);
consoleSpy.mockRestore();
});
test("usesFreeTrialApiKey should handle empty modelsByRole object", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
subagent: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
subagent: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
expect(mockDecodeSecretLocation).not.toHaveBeenCalled();
});
});

View file

@ -1,7 +1,6 @@
import { ConfigValidationError } from "@continuedev/config-yaml";
import { ModelDescription, SerializedContinueConfig } from "../";
import { Telemetry } from "../util/posthog";
/**
* Validates a SerializedContinueConfig object to ensure all properties are correctly formed.
@ -158,14 +157,6 @@ export function validateConfig(config: SerializedContinueConfig) {
});
if (errors.length > 0) {
void Telemetry.capture(
"configValidationError",
{
errors,
},
true,
);
return errors;
}

View file

@ -6,16 +6,11 @@ import {
} from "@continuedev/config-yaml";
import * as dotenv from "dotenv";
import { IDE } from "../..";
import { ControlPlaneClient } from "../../control-plane/client";
import { getContinueDotEnv } from "../../util/paths";
import { joinPathsToUri } from "../../util/uri";
export class LocalPlatformClient implements PlatformClient {
constructor(
private orgScopeId: string | null,
private readonly client: ControlPlaneClient,
private readonly ide: IDE,
) {}
constructor(private readonly ide: IDE) {}
/**
* searches for the first valid secret file in order of ~/.continue/.env, <workspace>/.continue/.env, <workspace>/.env
@ -97,41 +92,28 @@ export class LocalPlatformClient implements PlatformClient {
return [];
}
let results: (SecretResult | undefined)[] = [];
try {
results = await this.client.resolveFQSNs(fqsns, this.orgScopeId);
} catch (e) {
console.error("Error getting secrets from control plane", e);
}
const results: (SecretResult | undefined)[] = [];
// For any secret that isn't found, look in .env files, then process.env
for (let i = 0; i < results.length; i++) {
if (!results[i]?.found) {
let secretResult = await this.findSecretInEnvFiles(fqsns[i]);
for (let i = 0; i < fqsns.length; i++) {
let secretResult = await this.findSecretInEnvFiles(fqsns[i]);
// If not found in .env files, try process.env
if (!secretResult?.found) {
const secretValueFromProcessEnv = process.env[fqsns[i].secretName];
if (secretValueFromProcessEnv !== undefined) {
secretResult = {
found: true,
fqsn: fqsns[i],
value: secretValueFromProcessEnv,
secretLocation: {
secretName: fqsns[i].secretName,
// Cast to SecretType.ProcessEnv is necessary because the specific type
// ProcessEnvSecretLocation expects secretType to be exactly SecretType.ProcessEnv,
// not the general enum SecretType.
secretType: SecretType.ProcessEnv as SecretType.ProcessEnv,
},
};
}
}
if (secretResult?.found) {
results[i] = secretResult;
// If not found in .env files, try process.env
if (!secretResult?.found) {
const secretValueFromProcessEnv = process.env[fqsns[i].secretName];
if (secretValueFromProcessEnv !== undefined) {
secretResult = {
found: true,
fqsn: fqsns[i],
value: secretValueFromProcessEnv,
secretLocation: {
secretName: fqsns[i].secretName,
secretType: SecretType.ProcessEnv as SecretType.ProcessEnv,
},
};
}
}
results[i] = secretResult;
}
return results;

View file

@ -9,7 +9,6 @@ import {
vi,
} from "vitest";
import { IDE } from "../..";
import { ControlPlaneClient } from "../../control-plane/client";
import { LocalPlatformClient } from "./LocalPlatformClient";
vi.mock("../../util/paths", { spy: true });
@ -34,23 +33,11 @@ describe("LocalPlatformClient", () => {
secretName: "TEST_WORKSPACE_SECRET_KEY",
};
const testResolvedFQSN: SecretResult = {
found: true,
fqsn: testFQSN,
secretLocation: {
secretName: testFQSN.secretName,
secretType: SecretType.Organization,
orgSlug: "test-org-slug",
},
};
let testControlPlaneClient: ControlPlaneClient;
let testIde: IDE;
beforeEach(
/**dynamic import before each test for test isolation */
async () => {
const testFixtures = await import("../../test/fixtures");
testControlPlaneClient = testFixtures.testControlPlaneClient;
testIde = testFixtures.testIde;
},
);
@ -79,28 +66,11 @@ describe("LocalPlatformClient", () => {
});
test("should not be able to resolve FQSNs if they do not exist", async () => {
const localPlatformClient = new LocalPlatformClient(
null,
testControlPlaneClient,
testIde,
);
const localPlatformClient = new LocalPlatformClient(testIde);
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
expect(resolvedFQSNs.length).toBeGreaterThan(0);
expect(resolvedFQSNs[0]?.found).toBe(false);
});
test("should be able to resolve FQSNs if they exist", async () => {
testControlPlaneClient.resolveFQSNs = vi.fn(async () => [testResolvedFQSN]);
const localPlatformClient = new LocalPlatformClient(
null,
testControlPlaneClient,
testIde,
);
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
expect(testControlPlaneClient.resolveFQSNs).toHaveBeenCalled();
expect(resolvedFQSNs).toEqual([testResolvedFQSN]);
expect(resolvedFQSNs[0]?.found).toBe(true);
expect(resolvedFQSNs[0]?.found).toBeUndefined();
});
describe("searches for secrets in local .env files", () => {
@ -112,11 +82,7 @@ describe("LocalPlatformClient", () => {
});
test("should be able to get secrets from ~/.continue/.env files", async () => {
const localPlatformClient = new LocalPlatformClient(
null,
testControlPlaneClient,
testIde,
);
const localPlatformClient = new LocalPlatformClient(testIde);
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
expect(getContinueDotEnv).toHaveBeenCalled();
expect(resolvedFQSNs.length).toBe(1);
@ -155,11 +121,7 @@ describe("LocalPlatformClient", () => {
return originalIdeReadFile(fileUri);
});
const localPlatformClient = new LocalPlatformClient(
null,
testControlPlaneClient,
testIde,
);
const localPlatformClient = new LocalPlatformClient(testIde);
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([
testFQSN,
testFQSN2,
@ -209,11 +171,7 @@ describe("LocalPlatformClient", () => {
return originalIdeReadFile(fileUri);
});
const localPlatformClient = new LocalPlatformClient(
null,
testControlPlaneClient,
testIde,
);
const localPlatformClient = new LocalPlatformClient(testIde);
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
expect(resolvedFQSNs.length).toBe(1);
@ -234,20 +192,6 @@ describe("LocalPlatformClient", () => {
const ogProcessEnv = { ...process.env };
beforeEach(async () => {
// Ensure secrets are not found in ControlPlane initially for these tests
const mockResolveFQSNsNotFound = async (
fqsns: FQSN[],
): Promise<(SecretResult | undefined)[]> =>
fqsns.map((fqsn) => ({
found: false,
fqsn,
secretLocation: {
secretName: fqsn.secretName,
secretType: SecretType.NotFound as SecretType.NotFound,
},
}));
testControlPlaneClient.resolveFQSNs = vi.fn(mockResolveFQSNsNotFound);
// Ensure secrets are not found in local .env files
const utilPaths = await import("../../util/paths");
utilPaths.getContinueDotEnv = vi.fn(() => ({}));
@ -270,11 +214,7 @@ describe("LocalPlatformClient", () => {
const processEnvSecretValue = "secret-from-process-env";
process.env[testFQSN.secretName] = processEnvSecretValue;
const localPlatformClient = new LocalPlatformClient(
null,
testControlPlaneClient,
testIde,
);
const localPlatformClient = new LocalPlatformClient(testIde);
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
expect(resolvedFQSNs.length).toBe(1);
@ -297,58 +237,11 @@ describe("LocalPlatformClient", () => {
// Ensure it's not in process.env
expect(process.env[testFQSN.secretName]).toBeUndefined();
const localPlatformClient = new LocalPlatformClient(
null,
testControlPlaneClient,
testIde,
);
const localPlatformClient = new LocalPlatformClient(testIde);
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
expect(resolvedFQSNs.length).toBe(1);
expect(resolvedFQSNs[0]?.found).toBe(false);
expect(resolvedFQSNs[0]?.secretLocation?.secretType).toBe(
SecretType.NotFound,
);
});
test("should prioritize ControlPlane over process.env", async () => {
const controlPlaneValue = "secret-from-control-plane";
const mockResolveFQSNsControlPlaneFound = async (): Promise<
(SecretResult | undefined)[]
> => [
{
found: true,
fqsn: testFQSN,
value: controlPlaneValue,
secretLocation: {
secretType: SecretType.Organization as SecretType.Organization,
orgSlug: (testResolvedFQSN.secretLocation as any).orgSlug,
secretName: testFQSN.secretName,
},
},
];
testControlPlaneClient.resolveFQSNs = vi.fn(
mockResolveFQSNsControlPlaneFound,
);
process.env[testFQSN.secretName] =
"secret-from-process-env-should-be-ignored";
const localPlatformClient = new LocalPlatformClient(
null,
testControlPlaneClient,
testIde,
);
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
expect(resolvedFQSNs.length).toBe(1);
const result = resolvedFQSNs[0];
expect(result?.found).toBe(true);
expect((result as SecretResult & { value: unknown })?.value).toBe(
controlPlaneValue,
);
expect(result?.secretLocation?.secretType).toBe(SecretType.Organization);
expect(resolvedFQSNs[0]).toBeUndefined();
});
test("should prioritize local ~/.continue/.env file over process.env", async () => {
@ -361,11 +254,7 @@ describe("LocalPlatformClient", () => {
process.env[testFQSN.secretName] =
"secret-from-process-env-should-be-ignored";
const localPlatformClient = new LocalPlatformClient(
null,
testControlPlaneClient,
testIde,
);
const localPlatformClient = new LocalPlatformClient(testIde);
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
expect(resolvedFQSNs.length).toBe(1);
@ -393,11 +282,7 @@ describe("LocalPlatformClient", () => {
process.env[testFQSN.secretName] =
"secret-from-process-env-should-be-ignored";
const localPlatformClient = new LocalPlatformClient(
null,
testControlPlaneClient,
testIde,
);
const localPlatformClient = new LocalPlatformClient(testIde);
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
expect(resolvedFQSNs.length).toBe(1);

View file

@ -4,7 +4,7 @@ import { AssistantUnrolled } from "@continuedev/config-yaml";
export const defaultConfigYaml: AssistantUnrolled = {
models: [],
context: [],
name: "Local Config",
name: "Main Config",
version: "1.0.0",
schema: "v1",
};
@ -12,7 +12,7 @@ export const defaultConfigYaml: AssistantUnrolled = {
export const defaultConfigYamlJetBrains: AssistantUnrolled = {
models: [],
context: [],
name: "Local Config",
name: "Main Config",
version: "1.0.0",
schema: "v1",
};

View file

@ -6,7 +6,6 @@ import {
unrollAssistantFromContent,
} from "@continuedev/config-yaml";
import { IDE } from "../..";
import { ControlPlaneClient } from "../../control-plane/client";
import { LocalPlatformClient } from "./LocalPlatformClient";
// This is a certain approach to unrolling local YAML where it
@ -16,8 +15,6 @@ export async function unrollLocalYamlBlocks(
packageIdentifiers: PackageIdentifier[],
ide: IDE,
registryClient: RegistryClient,
orgScopeId: string | null,
controlPlaneClient: ControlPlaneClient,
): Promise<ConfigResult<AssistantUnrolled>> {
try {
const unrollResult = await unrollAssistantFromContent(
@ -29,13 +26,7 @@ export async function unrollLocalYamlBlocks(
registryClient,
{
currentUserSlug: "",
onPremProxyUrl: null,
orgScopeId,
platformClient: new LocalPlatformClient(
orgScopeId,
controlPlaneClient,
ide,
),
platformClient: new LocalPlatformClient(ide),
renderSecrets: true,
injectBlocks: packageIdentifiers,
},

View file

@ -23,7 +23,6 @@ import {
InternalMcpOptions,
} from "../..";
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
import { ControlPlaneClient } from "../../control-plane/client";
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
import { getAllPromptFiles } from "../../promptFiles/getPromptFiles";
import { GlobalContext } from "../../util/GlobalContext";
@ -32,8 +31,6 @@ import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand";
import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand";
import { loadJsonMcpConfigs } from "../../context/mcp/json/loadJsonMcpConfigs";
import { getControlPlaneEnvSync } from "../../control-plane/env";
import { PolicySingleton } from "../../control-plane/PolicySingleton";
import { getBaseToolDefinitions } from "../../tools";
import { getCleanUriPath } from "../../util/uri";
import { loadConfigContextProviders } from "../loadContextProviders";
@ -48,20 +45,11 @@ import {
async function loadConfigYaml(options: {
overrideConfigYaml: AssistantUnrolled | undefined;
controlPlaneClient: ControlPlaneClient;
orgScopeId: string | null;
ideSettings: IdeSettings;
ide: IDE;
packageIdentifier: PackageIdentifier;
}): Promise<ConfigResult<AssistantUnrolled>> {
const {
overrideConfigYaml,
controlPlaneClient,
orgScopeId,
ideSettings,
ide,
packageIdentifier,
} = options;
const { overrideConfigYaml, ideSettings, ide, packageIdentifier } = options;
// Add local .continue blocks
// Use "content" field to pass pre-read content directly, avoiding
@ -82,10 +70,6 @@ async function loadConfigYaml(options: {
await Promise.all(localBlockPromises)
).flat();
// logger.info(
// `Loading config.yaml from ${JSON.stringify(packageIdentifier)} with root path ${rootPath}`,
// );
// Registry client is only used if local blocks are present, but logic same for hub/local assistants
const getRegistryClient = async () => {
const rootPath =
@ -93,9 +77,6 @@ async function loadConfigYaml(options: {
? dirname(getCleanUriPath(packageIdentifier.fileUri))
: undefined;
return new RegistryClient({
accessToken: await controlPlaneClient.getAccessToken(),
apiBase: getControlPlaneEnvSync(ideSettings.continueTestEnvironment)
.CONTROL_PLANE_URL,
rootPath,
});
};
@ -111,8 +92,6 @@ async function loadConfigYaml(options: {
localPackageIdentifiers,
ide,
await getRegistryClient(),
orgScopeId,
controlPlaneClient,
);
if (unrolledLocal.errors) {
errors.push(...unrolledLocal.errors);
@ -129,13 +108,7 @@ async function loadConfigYaml(options: {
{
renderSecrets: true,
currentUserSlug: "",
onPremProxyUrl: null,
orgScopeId,
platformClient: new LocalPlatformClient(
orgScopeId,
controlPlaneClient,
ide,
),
platformClient: new LocalPlatformClient(ide),
injectBlocks: localPackageIdentifiers,
},
);
@ -186,7 +159,6 @@ export async function configYamlToContinueConfig(options: {
ideInfo: IdeInfo;
uniqueId: string;
llmLogger: ILLMLogger;
workOsAccessToken: string | undefined;
}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
let { unrolledAssistant, ide, ideInfo, uniqueId, llmLogger } = options;
@ -305,14 +277,10 @@ export async function configYamlToContinueConfig(options: {
});
// Models
let warnAboutFreeTrial = false;
const defaultModelRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"];
for (const model of config.models ?? []) {
model.roles = model.roles ?? defaultModelRoles; // Default to all 4 chat-esque roles if not specified
if (model.provider === "free-trial") {
warnAboutFreeTrial = true;
}
try {
const llms = await llmsFromModelConfig({
model,
@ -386,14 +354,6 @@ export async function configYamlToContinueConfig(options: {
);
}
if (warnAboutFreeTrial) {
localErrors.push({
fatal: false,
message:
"Model provider 'free-trial' is no longer supported, will be ignored.",
});
}
const { providers, errors: contextErrors } = loadConfigContextProviders(
config.context,
!!config.docs?.length,
@ -406,23 +366,18 @@ export async function configYamlToContinueConfig(options: {
// Trigger MCP server refreshes (Config is reloaded again once connected!)
const mcpManager = MCPManagerSingleton.getInstance();
const orgPolicy = PolicySingleton.getInstance().policy;
if (orgPolicy?.policy?.allowMcpServers === false) {
await mcpManager.shutdown();
} else {
const mcpOptions: InternalMcpOptions[] = (config.mcpServers ?? []).map(
(server) =>
convertYamlMcpConfigToInternalMcpOptions(server, config.requestOptions),
);
const { errors: jsonMcpErrors, mcpServers } = await loadJsonMcpConfigs(
ide,
true,
config.requestOptions,
);
localErrors.push(...jsonMcpErrors);
mcpOptions.push(...mcpServers);
mcpManager.setConnections(mcpOptions, false, { ide });
}
const mcpOptions: InternalMcpOptions[] = (config.mcpServers ?? []).map(
(server) =>
convertYamlMcpConfigToInternalMcpOptions(server, config.requestOptions),
);
const { errors: jsonMcpErrors, mcpServers } = await loadJsonMcpConfigs(
ide,
true,
config.requestOptions,
);
localErrors.push(...jsonMcpErrors);
mcpOptions.push(...mcpServers);
mcpManager.setConnections(mcpOptions, false, { ide });
return { config: continueConfig, errors: localErrors };
}
@ -433,10 +388,7 @@ export async function loadContinueConfigFromYaml(options: {
ideInfo: IdeInfo;
uniqueId: string;
llmLogger: ILLMLogger;
workOsAccessToken: string | undefined;
overrideConfigYaml: AssistantUnrolled | undefined;
controlPlaneClient: ControlPlaneClient;
orgScopeId: string | null;
packageIdentifier: PackageIdentifier;
}): Promise<ConfigResult<ContinueConfig>> {
const {
@ -445,17 +397,12 @@ export async function loadContinueConfigFromYaml(options: {
ideInfo,
uniqueId,
llmLogger,
workOsAccessToken,
overrideConfigYaml,
controlPlaneClient,
orgScopeId,
packageIdentifier,
} = options;
const configYamlResult = await loadConfigYaml({
overrideConfigYaml,
controlPlaneClient,
orgScopeId,
ideSettings,
ide,
packageIdentifier,
@ -477,7 +424,6 @@ export async function loadContinueConfigFromYaml(options: {
ideInfo,
uniqueId,
llmLogger,
workOsAccessToken,
});
// Apply shared config

View file

@ -47,14 +47,6 @@ function getModelClass(
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,
uniqueId,

View file

@ -1,82 +0,0 @@
import { getControlPlaneEnv } from "../../control-plane/env.js";
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../../index.js";
import { BaseContextProvider } from "../index.js";
class ContinueProxyContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "continue-proxy",
displayTitle: "Continue Proxy",
description: "Retrieve a context item from a Continue for Teams add-on",
type: "submenu",
};
workOsAccessToken: string | undefined = undefined;
override get description(): ContextProviderDescription {
return {
title:
this.options.title || ContinueProxyContextProvider.description.title,
displayTitle:
this.options.displayTitle ||
this.options.name ||
ContinueProxyContextProvider.description.displayTitle,
description:
this.options.description ||
ContinueProxyContextProvider.description.description,
type: this.options.type || ContinueProxyContextProvider.description.type,
};
}
async loadSubmenuItems(
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
const env = await getControlPlaneEnv(args.ide.getIdeSettings());
const response = await args.fetch(
new URL(`/proxy/context/${this.options.id}/list`, env.CONTROL_PLANE_URL),
{
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.workOsAccessToken}`,
},
},
);
const data = await response.json();
return data.items;
}
async getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const env = await getControlPlaneEnv(extras.ide.getIdeSettings());
const response = await extras.fetch(
new URL(
`/proxy/context/${this.options.id}/retrieve`,
env.CONTROL_PLANE_URL,
),
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.workOsAccessToken}`,
},
body: JSON.stringify({
query: query || "",
fullInput: extras.fullInput,
}),
},
);
const items: any = await response.json();
return items;
}
}
export default ContinueProxyContextProvider;

View file

@ -8,8 +8,6 @@ import {
LoadSubmenuItemsArgs,
RuleWithSource,
} from "../..";
import { getControlPlaneEnv } from "../../control-plane/env";
class RulesContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "rules",
@ -33,10 +31,7 @@ class RulesContextProvider extends BaseContextProvider {
return rule.description ?? rule.name ?? "";
}
private getUriFromRule(
rule: RuleWithSource,
appUrl: string,
): ContextItemUri | undefined {
private getUriFromRule(rule: RuleWithSource): ContextItemUri | undefined {
if (rule.sourceFile) {
return {
type: "file",
@ -44,14 +39,6 @@ class RulesContextProvider extends BaseContextProvider {
};
}
if (rule.slug) {
let url = `${appUrl}${rule.slug}`;
return {
type: "url",
value: url,
};
}
return undefined;
}
@ -66,13 +53,12 @@ class RulesContextProvider extends BaseContextProvider {
return [];
}
const env = await getControlPlaneEnv(extras.ide.getIdeSettings());
return [
{
name: this.getNameFromRule(rule),
content: rule.rule,
description: this.getDescriptionFromRule(rule),
uri: this.getUriFromRule(rule, env.APP_URL),
uri: this.getUriFromRule(rule),
},
];
}

View file

@ -6,7 +6,7 @@ import {
FetchFunction,
} from "../..";
import { getHeaders } from "../../continueServer/stubs/headers";
import { TRIAL_PROXY_URL } from "../../control-plane/client";
const TRIAL_PROXY_URL = "https://proxy-server-blue-l6vsfbzhba-uw.a.run.app";
export const fetchSearchResults = async (
query: string,

View file

@ -29,11 +29,7 @@ async function getContextProviderExtras(
setUpTestDir();
const ide = new FileSystemIde(TEST_DIR);
const llmLogger = new LLMLogger();
const configHandler = new ConfigHandler(
ide,
llmLogger,
Promise.resolve(undefined),
);
const configHandler = new ConfigHandler(ide, llmLogger);
await configHandler.isInitialized;
const { config } = await configHandler.loadConfig();
if (!config) {

View file

@ -4,7 +4,7 @@ import { ContextProviderName } from "../../";
import ClipboardContextProvider from "./ClipboardContextProvider";
import CodebaseContextProvider from "./CodebaseContextProvider";
import CodeContextProvider from "./CodeContextProvider";
import ContinueProxyContextProvider from "./ContinueProxyContextProvider";
import CurrentFileContextProvider from "./CurrentFileContextProvider";
import DatabaseContextProvider from "./DatabaseContextProvider";
import DebugLocalsProvider from "./DebugLocalsProvider";
@ -63,7 +63,6 @@ export const Providers: (typeof BaseContextProvider)[] = [
CodeContextProvider,
CurrentFileContextProvider,
URLContextProvider,
ContinueProxyContextProvider,
RepoMapContextProvider,
DiscordContextProvider,
GreptileContextProvider,

View file

@ -1,5 +1,5 @@
import { Chunk } from "../../../";
import { Telemetry } from "../../../util/posthog";
import { findUriInDirs } from "../../../util/uri";
import { requestFilesFromRepoMap } from "../repoMapRequest";
import { deduplicateChunks } from "../util";
@ -24,7 +24,6 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
try {
ftsChunks = await this.retrieveFts(args, ftsNFinal);
} catch (error) {
await Telemetry.captureError("no_reranker_fts_retrieval", error);
// console.error("Error retrieving FTS chunks:", error);
}
@ -34,7 +33,6 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
? await this.retrieveEmbeddings(input, embeddingsNFinal)
: [];
} catch (error) {
await Telemetry.captureError("no_reranker_embeddings_retrieval", error);
console.error("Error retrieving embeddings:", error);
}
@ -43,10 +41,6 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
recentlyEditedFilesChunks =
await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal);
} catch (error) {
await Telemetry.captureError(
"no_reranker_recently_edited_retrieval",
error,
);
console.error("Error retrieving recently edited files:", error);
}
@ -60,7 +54,6 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
filterDirectory,
);
} catch (error) {
await Telemetry.captureError("no_reranker_repo_map_retrieval", error);
console.error("Error retrieving repo map chunks:", error);
}

View file

@ -1,6 +1,6 @@
import { Chunk } from "../../..";
import { RETRIEVAL_PARAMS } from "../../../util/parameters";
import { Telemetry } from "../../../util/posthog";
import { findUriInDirs } from "../../../util/uri";
import { requestFilesFromRepoMap } from "../repoMapRequest";
import { deduplicateChunks } from "../util";
@ -21,7 +21,6 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
try {
ftsChunks = await this.retrieveFts(args, nRetrieve);
} catch (error) {
await Telemetry.captureError("reranker_fts_retrieval", error);
// console.error("Error retrieving FTS chunks:", error);
}
@ -31,7 +30,6 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
? await this.retrieveEmbeddings(input, nRetrieve)
: [];
} catch (error) {
await Telemetry.captureError("reranker_embeddings_retrieval", error);
console.error("Error retrieving embeddings chunks:", error);
}
@ -40,7 +38,6 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
recentlyEditedFilesChunks =
await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve);
} catch (error) {
await Telemetry.captureError("reranker_recently_edited_retrieval", error);
console.error("Error retrieving recently edited files chunks:", error);
}
@ -54,7 +51,6 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
filterDirectory,
);
} catch (error) {
await Telemetry.captureError("reranker_repo_map_retrieval", error);
console.error("Error retrieving repo map chunks:", error);
}

View file

@ -1,13 +1,13 @@
import { constants, getTimestamp } from "../../deploy/constants.js";
import { Telemetry } from "../../util/posthog.js";
import { IdeInfoService } from "../../util/IdeInfoService.js";
export async function getHeaders() {
return {
key: constants.c,
timestamp: getTimestamp(),
v: "1",
extensionVersion: Telemetry.ideInfo?.extensionVersion ?? "0.0.0",
os: Telemetry.os ?? "Unknown",
uniqueId: Telemetry.uniqueId ?? "None",
extensionVersion: IdeInfoService.ideInfo?.extensionVersion ?? "0.0.0",
os: IdeInfoService.os ?? "Unknown",
uniqueId: IdeInfoService.uniqueId ?? "None",
};
}

View file

@ -1,51 +0,0 @@
export interface HubSessionInfo {
AUTH_TYPE: AuthType.WorkOsProd | AuthType.WorkOsStaging;
accessToken: string;
account: {
label: string;
id: string;
};
}
export interface OnPremSessionInfo {
AUTH_TYPE: AuthType.OnPrem;
}
export type ControlPlaneSessionInfo = HubSessionInfo | OnPremSessionInfo;
export function isOnPremSession(
sessionInfo: ControlPlaneSessionInfo | undefined,
): sessionInfo is OnPremSessionInfo {
return sessionInfo !== undefined && sessionInfo.AUTH_TYPE === AuthType.OnPrem;
}
export enum AuthType {
WorkOsProd = "continue",
WorkOsStaging = "continue-staging",
OnPrem = "on-prem",
}
export interface HubEnv {
DEFAULT_CONTROL_PLANE_PROXY_URL: string;
CONTROL_PLANE_URL: string;
AUTH_TYPE: AuthType.WorkOsProd | AuthType.WorkOsStaging;
WORKOS_CLIENT_ID: string;
APP_URL: string;
}
export interface OnPremEnv {
AUTH_TYPE: AuthType.OnPrem;
DEFAULT_CONTROL_PLANE_PROXY_URL: string;
CONTROL_PLANE_URL: string;
APP_URL: string;
}
export type ControlPlaneEnv = HubEnv | OnPremEnv;
export function isHubEnv(env: ControlPlaneEnv): env is HubEnv {
return (
"AUTH_TYPE" in env &&
env.AUTH_TYPE !== "on-prem" &&
"WORKOS_CLIENT_ID" in env
);
}

View file

@ -1,15 +0,0 @@
import { PolicyResponse } from "./client.js";
export class PolicySingleton {
private static instance: PolicySingleton;
public policy: PolicyResponse | null = null;
private constructor() {}
public static getInstance(): PolicySingleton {
if (!PolicySingleton.instance) {
PolicySingleton.instance = new PolicySingleton();
}
return PolicySingleton.instance;
}
}

View file

@ -1,77 +0,0 @@
import os from "node:os";
import ContinueProxyAnalyticsProvider from "./analytics/ContinueProxyAnalyticsProvider.js";
import {
ControlPlaneProxyInfo,
IAnalyticsProvider,
} from "./analytics/IAnalyticsProvider.js";
import LogStashAnalyticsProvider from "./analytics/LogStashAnalyticsProvider.js";
import PostHogAnalyticsProvider from "./analytics/PostHogAnalyticsProvider.js";
import { ControlPlaneClient } from "./client.js";
import { AnalyticsConfig } from "../index.js";
function createAnalyticsProvider(
config: AnalyticsConfig,
): IAnalyticsProvider | undefined {
// @ts-ignore
switch (config.provider) {
case "posthog":
return new PostHogAnalyticsProvider();
case "logstash":
return new LogStashAnalyticsProvider();
case "continue-proxy":
return new ContinueProxyAnalyticsProvider();
default:
return undefined;
}
}
export class TeamAnalytics {
static provider: IAnalyticsProvider | undefined = undefined;
static uniqueId = "NOT_UNIQUE";
static os: string | undefined = undefined;
static extensionVersion: string | undefined = undefined;
static async capture(event: string, properties: { [key: string]: any }) {
void TeamAnalytics.provider?.capture(event, {
...properties,
os: TeamAnalytics.os,
extensionVersion: TeamAnalytics.extensionVersion,
});
}
static async setup(
config: AnalyticsConfig,
uniqueId: string,
extensionVersion: string,
controlPlaneClient: ControlPlaneClient,
controlPlaneProxyInfo: ControlPlaneProxyInfo,
) {
TeamAnalytics.uniqueId = uniqueId;
TeamAnalytics.os = os.platform();
TeamAnalytics.extensionVersion = extensionVersion;
TeamAnalytics.provider = createAnalyticsProvider(config);
await TeamAnalytics.provider?.setup(
config,
uniqueId,
controlPlaneProxyInfo,
);
if (config.provider === "continue-proxy") {
(
TeamAnalytics.provider as ContinueProxyAnalyticsProvider
).controlPlaneClient = controlPlaneClient;
}
}
static async shutdown() {
if (TeamAnalytics.provider) {
await TeamAnalytics.provider.shutdown();
TeamAnalytics.provider = undefined;
TeamAnalytics.os = undefined;
TeamAnalytics.extensionVersion = undefined;
TeamAnalytics.uniqueId = "NOT_UNIQUE";
}
}
}

View file

@ -1,54 +0,0 @@
import { Analytics } from "@continuedev/config-types";
import fetch from "node-fetch";
import { ControlPlaneClient } from "../client.js";
import {
ControlPlaneProxyInfo,
IAnalyticsProvider,
} from "./IAnalyticsProvider.js";
export default class ContinueProxyAnalyticsProvider
implements IAnalyticsProvider
{
uniqueId?: string;
controlPlaneProxyInfo?: ControlPlaneProxyInfo;
controlPlaneClient?: ControlPlaneClient;
async capture(
event: string,
properties: { [key: string]: any },
): Promise<void> {
if (!this.controlPlaneProxyInfo?.workspaceId) {
return;
}
const url = new URL(
`proxy/analytics/${this.controlPlaneProxyInfo.workspaceId}/capture`,
this.controlPlaneProxyInfo?.controlPlaneProxyUrl,
).toString();
void fetch(url, {
method: "POST",
body: JSON.stringify({
event,
properties,
uniqueId: this.uniqueId,
}),
headers: {
Authorization: `Bearer ${await this.controlPlaneClient?.getAccessToken()}`,
},
});
}
async setup(
config: Analytics,
uniqueId: string,
controlPlaneProxyInfo?: ControlPlaneProxyInfo,
): Promise<void> {
this.uniqueId = uniqueId;
this.controlPlaneProxyInfo = controlPlaneProxyInfo;
}
async shutdown(): Promise<void> {}
}

View file

@ -1,21 +0,0 @@
import { AnalyticsConfig } from "../..";
export interface AnalyticsMetadata {
extensionVersion: string;
}
export interface ControlPlaneProxyInfo {
workspaceId?: string;
controlPlaneProxyUrl: string;
workOsAccessToken?: string;
}
export interface IAnalyticsProvider {
capture(event: string, properties: { [key: string]: any }): Promise<void>;
setup(
config: AnalyticsConfig,
uniqueId: string,
controlPlaneProxyInfo?: ControlPlaneProxyInfo,
): Promise<void>;
shutdown(): Promise<void>;
}

View file

@ -1,52 +0,0 @@
import net from "node:net";
import { Analytics } from "@continuedev/config-types";
import {
ControlPlaneProxyInfo,
IAnalyticsProvider,
} from "./IAnalyticsProvider.js";
export default class LogStashAnalyticsProvider implements IAnalyticsProvider {
private host?: string;
private port?: number;
private uniqueId?: string;
async capture(
event: string,
properties: { [key: string]: any },
): Promise<void> {
if (this.host === undefined || this.port === undefined) {
console.warn("LogStashAnalyticsProvider not set up yet.");
}
const payload = {
event,
properties,
uniqueId: this.uniqueId,
};
const client = new net.Socket();
client.connect(this.port!, this.host!, () => {
client.write(JSON.stringify(payload));
client.end();
});
}
async setup(
config: Analytics,
uniqueId: string,
controlPlaneProxyInfo?: ControlPlaneProxyInfo,
): Promise<void> {
if (!config.url) {
console.warn("LogStashAnalyticsProvider is missing a URL");
return;
}
const url = new URL(config.url);
this.host = url.hostname;
this.port = parseInt(url.port);
this.uniqueId = uniqueId;
}
async shutdown(): Promise<void> {}
}

View file

@ -1,45 +0,0 @@
import { Analytics } from "@continuedev/config-types";
import {
ControlPlaneProxyInfo,
IAnalyticsProvider,
} from "./IAnalyticsProvider.js";
export default class PostHogAnalyticsProvider implements IAnalyticsProvider {
client?: any;
uniqueId?: string;
async capture(
event: string,
properties: { [key: string]: any },
): Promise<void> {
this.client?.capture({
distinctId: this.uniqueId,
event,
properties,
});
}
async setup(
config: Analytics,
uniqueId: string,
controlPlaneProxyInfo?: ControlPlaneProxyInfo,
): Promise<void> {
if (!config || !config.clientKey || !config.url) {
this.client = undefined;
} else {
try {
this.uniqueId = uniqueId;
const { PostHog } = await import("posthog-node");
this.client = new PostHog(config.clientKey, {
host: config.url,
});
} catch (e) {
console.error(`Failed to setup telemetry: ${e}`);
}
}
}
async shutdown(): Promise<void> {}
}

View file

@ -1,29 +0,0 @@
import { v4 as uuidv4 } from "uuid";
import { IdeSettings } from "../..";
import { isHubEnv } from "../AuthTypes";
import { getControlPlaneEnv } from "../env";
export async function getAuthUrlForTokenPage(
ideSettingsPromise: Promise<IdeSettings>,
useOnboarding: boolean,
): Promise<string> {
const env = await getControlPlaneEnv(ideSettingsPromise);
if (!isHubEnv(env)) {
throw new Error("Sign in disabled");
}
const url = new URL("https://api.workos.com/user_management/authorize");
const params = {
response_type: "code",
client_id: env.WORKOS_CLIENT_ID,
redirect_uri: `${env.APP_URL}tokens/${useOnboarding ? "onboarding-" : ""}callback`,
// redirect_uri: "http://localhost:3000/tokens/callback",
state: uuidv4(),
provider: "authkit",
};
Object.keys(params).forEach((key) =>
url.searchParams.append(key, params[key as keyof typeof params]),
);
return url.toString();
}

View file

@ -1,666 +0,0 @@
import { ConfigJson } from "@continuedev/config-types";
import {
AssistantUnrolled,
ConfigResult,
FQSN,
FullSlug,
Policy,
SecretResult,
SecretType,
} from "@continuedev/config-yaml";
import fetch, { RequestInit, Response } from "node-fetch";
import { OrganizationDescription } from "../config/ProfileLifecycleManager.js";
import {
BaseSessionMetadata,
IDE,
ModelDescription,
Session,
} from "../index.js";
import { Logger } from "../util/Logger.js";
import {
ControlPlaneSessionInfo,
HubSessionInfo,
isOnPremSession,
} from "./AuthTypes.js";
import { getControlPlaneEnv } from "./env.js";
export interface PolicyResponse {
orgSlug?: string;
policy?: Policy;
}
export interface ControlPlaneWorkspace {
id: string;
name: string;
settings: ConfigJson;
}
export interface ControlPlaneModelDescription extends ModelDescription {}
export interface CreditStatus {
optedInToFreeTrial: boolean;
hasCredits: boolean;
creditBalance: number;
hasPurchasedCredits: boolean;
}
export const TRIAL_PROXY_URL =
"https://proxy-server-blue-l6vsfbzhba-uw.a.run.app";
export interface RemoteSessionMetadata extends BaseSessionMetadata {
isRemote: true;
remoteId: string;
}
export interface AgentSessionMetadata {
createdBy: string;
github_repo: string;
organizationId?: string;
idempotencyKey?: string;
source?: string;
continueApiKeyId?: string;
s3Url?: string;
prompt?: string | null;
createdBySlug?: string;
}
export interface AgentSessionView {
id: string;
devboxId: string | null;
name: string | null;
icon: string | null;
status: string;
agentStatus: string | null;
unread: boolean;
state: string;
metadata: AgentSessionMetadata;
repoUrl: string;
branch: string | null;
pullRequestUrl: string | null;
pullRequestStatus: string | null;
tunnelUrl: string | null;
createdAt: string;
updatedAt: string;
create_time_ms: string;
end_time_ms: string;
}
export class ControlPlaneClient {
constructor(
readonly sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
private readonly ide: IDE,
) {}
async resolveFQSNs(
fqsns: FQSN[],
orgScopeId: string | null,
): Promise<(SecretResult | undefined)[]> {
if (!(await this.isSignedIn())) {
return fqsns.map((fqsn) => ({
found: false,
fqsn,
secretLocation: {
secretName: fqsn.secretName,
secretType: SecretType.NotFound,
},
}));
}
const resp = await this.requestAndHandleError("ide/sync-secrets", {
method: "POST",
body: JSON.stringify({ fqsns, orgScopeId }),
});
return (await resp.json()) as any;
}
async isSignedIn(): Promise<boolean> {
const sessionInfo = await this.sessionInfoPromise;
return !!sessionInfo;
}
async getAccessToken(): Promise<string | undefined> {
const sessionInfo = await this.sessionInfoPromise;
return isOnPremSession(sessionInfo) ? undefined : sessionInfo?.accessToken;
}
private async request(path: string, init: RequestInit): Promise<Response> {
const sessionInfo = await this.sessionInfoPromise;
const onPremSession = isOnPremSession(sessionInfo);
const accessToken = await this.getAccessToken();
// Bearer token not necessary for on-prem auth type
if (!accessToken && !onPremSession) {
throw new Error("No access token");
}
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
const url = new URL(path, env.CONTROL_PLANE_URL).toString();
const ideInfo = await this.ide.getIdeInfo();
const resp = await fetch(url, {
...init,
headers: {
...init.headers,
Authorization: `Bearer ${accessToken}`,
...{
"x-extension-version": ideInfo.extensionVersion,
"x-is-prerelease": String(ideInfo.isPrerelease),
},
},
});
return resp;
}
private async requestAndHandleError(
path: string,
init: RequestInit,
): Promise<Response> {
const resp = await this.request(path, init);
if (!resp.ok) {
throw new Error(
`Control plane request failed: ${resp.status} ${await resp.text()}`,
);
}
return resp;
}
public async listAssistants(organizationId: string | null): Promise<
{
configResult: ConfigResult<AssistantUnrolled>;
ownerSlug: string;
packageSlug: string;
iconUrl: string;
rawYaml: string;
}[]
> {
if (!(await this.isSignedIn())) {
return [];
}
try {
const url = organizationId
? `ide/list-assistants?organizationId=${organizationId}`
: "ide/list-assistants";
const resp = await this.requestAndHandleError(url, {
method: "GET",
});
return (await resp.json()) as any;
} catch (e) {
// Capture control plane API failures to Sentry
Logger.error(e, {
context: "control_plane_list_assistants",
organizationId,
});
return [];
}
}
public async listOrganizations(): Promise<Array<OrganizationDescription>> {
if (!(await this.isSignedIn())) {
return [];
}
// We try again here because when users sign up with an email domain that is
// captured by an org, we need to wait for the user account creation webhook to
// take effect. Otherwise the organization(s) won't show up.
// This error manifests as a 404 (user not found)
let retries = 0;
const maxRetries = 10;
const maxWaitTime = 20000; // 20 seconds in milliseconds
while (retries < maxRetries) {
const resp = await this.request("ide/list-organizations", {
method: "GET",
});
if (resp.status === 404) {
retries++;
if (retries >= maxRetries) {
console.warn(
`Failed to list organizations after ${maxRetries} retries: user not found`,
);
return [];
}
const waitTime = Math.min(
Math.pow(2, retries) * 100,
maxWaitTime / maxRetries,
);
await new Promise((resolve) => setTimeout(resolve, waitTime));
continue;
} else if (!resp.ok) {
console.warn(
`Failed to list organizations (${resp.status}): ${await resp.text()}`,
);
return [];
}
const { organizations } = (await resp.json()) as any;
return organizations;
}
// This should never be reached due to the while condition, but adding for safety
console.warn(
`Failed to list organizations after ${maxRetries} retries: maximum attempts exceeded`,
);
return [];
}
public async listAssistantFullSlugs(
organizationId: string | null,
): Promise<FullSlug[] | null> {
if (!(await this.isSignedIn())) {
return null;
}
const url = organizationId
? `ide/list-assistant-full-slugs?organizationId=${organizationId}`
: "ide/list-assistant-full-slugs";
try {
const resp = await this.requestAndHandleError(url, {
method: "GET",
});
const { fullSlugs } = (await resp.json()) as any;
return fullSlugs;
} catch (e) {
// Capture control plane API failures to Sentry
Logger.error(e, {
context: "control_plane_list_assistant_slugs",
organizationId,
});
return null;
}
}
public async getPolicy(): Promise<PolicyResponse | null> {
if (!(await this.isSignedIn())) {
return null;
}
try {
const resp = await this.request(`ide/policy`, {
method: "GET",
});
return (await resp.json()) as PolicyResponse;
} catch (e) {
return null;
}
}
public async getCreditStatus(): Promise<CreditStatus | null> {
if (!(await this.isSignedIn())) {
return null;
}
try {
const resp = await this.requestAndHandleError("ide/credits", {
method: "GET",
});
return (await resp.json()) as CreditStatus;
} catch (e) {
// Capture control plane API failures to Sentry
Logger.error(e, {
context: "control_plane_credit_status",
});
return null;
}
}
/**
* JetBrains does not support deep links, so we only check for `vsCodeUriScheme`
* @param vsCodeUriScheme
* @returns
*/
public async getModelsAddOnCheckoutUrl(
vsCodeUriScheme?: string,
): Promise<{ url: string } | null> {
if (!(await this.isSignedIn())) {
return null;
}
try {
const params = new URLSearchParams({
// LocalProfileLoader ID
profile_id: "local",
});
if (vsCodeUriScheme) {
params.set("vscode_uri_scheme", vsCodeUriScheme);
}
const resp = await this.requestAndHandleError(
`ide/get-models-add-on-checkout-url?${params.toString()}`,
{
method: "GET",
},
);
return (await resp.json()) as { url: string };
} catch (e) {
// Capture control plane API failures to Sentry
Logger.error(e, {
context: "control_plane_models_checkout_url",
vsCodeUriScheme,
});
return null;
}
}
/**
* Check if remote sessions should be enabled based on feature flags
*/
public async shouldEnableRemoteSessions(): Promise<boolean> {
// Check if user is signed in
if (!(await this.isSignedIn())) {
return false;
}
try {
const sessionInfo = await this.sessionInfoPromise;
if (isOnPremSession(sessionInfo) || !sessionInfo) {
return false;
}
return true;
} catch (e) {
Logger.error(e, {
context: "control_plane_check_remote_sessions_enabled",
});
return false;
}
}
/**
* Get current user's session info
*/
public async getSessionInfo(): Promise<ControlPlaneSessionInfo | undefined> {
return await this.sessionInfoPromise;
}
/**
* Fetch remote agents/sessions from the control plane
*/
public async listRemoteSessions(): Promise<RemoteSessionMetadata[]> {
if (!(await this.isSignedIn())) {
return [];
}
try {
const resp = await this.requestAndHandleError("agents/devboxes", {
method: "GET",
});
const agents = (await resp.json()) as any[];
return agents.map(
(agent: any): RemoteSessionMetadata => ({
sessionId: `remote-${agent.id}`,
title: agent.name || "Remote Agent",
dateCreated: new Date(agent.create_time_ms).toISOString(),
workspaceDirectory: "",
isRemote: true,
remoteId: agent.id,
}),
);
} catch (e) {
// Log error but don't throw - remote sessions are optional
Logger.error(e, {
context: "control_plane_list_remote_sessions",
});
return [];
}
}
public async loadRemoteSession(remoteId: string): Promise<Session> {
if (!(await this.isSignedIn())) {
throw new Error("Not signed in to load remote session");
}
try {
// First get the tunnel URL for the remote agent
const tunnelResp = await this.requestAndHandleError(
`agents/devboxes/${remoteId}/tunnel`,
{
method: "POST",
},
);
const tunnelData = (await tunnelResp.json()) as { url?: string };
const tunnelUrl = tunnelData.url;
if (!tunnelUrl) {
throw new Error(`Failed to get tunnel URL for agent ${remoteId}`);
}
// Now fetch the session state from the remote agent's /state endpoint
const stateResponse = await fetch(`${tunnelUrl}/state`);
if (!stateResponse.ok) {
throw new Error(
`Failed to fetch state from remote agent: ${stateResponse.statusText}`,
);
}
const remoteState = (await stateResponse.json()) as { session?: Session };
// The remote state contains a session property with the full session data
if (!remoteState.session) {
throw new Error(
"Remote agent returned invalid state - no session found",
);
}
return remoteState.session;
} catch (e) {
Logger.error(e, {
context: "control_plane_load_remote_session",
remoteId,
});
throw new Error(
`Failed to load remote session: ${e instanceof Error ? e.message : "Unknown error"}`,
);
}
}
/**
* Create a new background agent
*/
public async createBackgroundAgent(
prompt: string,
repoUrl: string,
name: string,
branch?: string,
organizationId?: string,
contextItems?: any[],
selectedCode?: any[],
agent?: string,
): Promise<{ id: string }> {
if (!(await this.isSignedIn())) {
throw new Error("Not signed in to Continue");
}
const requestBody: any = {
prompt,
repoUrl,
name,
branchName: branch,
};
if (organizationId) {
requestBody.organizationId = organizationId;
}
// Include context items if provided
if (contextItems && contextItems.length > 0) {
requestBody.contextItems = contextItems.map((item) => ({
content: item.content,
description: item.description,
name: item.name,
uri: item.uri,
}));
}
// Include selected code if provided
if (selectedCode && selectedCode.length > 0) {
requestBody.selectedCode = selectedCode.map((code) => ({
filepath: code.filepath,
range: code.range,
contents: code.contents,
}));
}
// Include agent configuration if provided
if (agent) {
requestBody.agent = agent;
}
const resp = await this.requestAndHandleError("agents", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(requestBody),
});
return (await resp.json()) as { id: string };
}
/**
* List all background agents for the current user or organization
* @param organizationId - Optional organization ID to filter agents by organization scope
* @param limit - Optional limit for number of agents to return (default: 5)
*/
public async listBackgroundAgents(
organizationId?: string,
limit?: number,
): Promise<{
agents: Array<{
id: string;
name: string | null;
status: string;
repoUrl: string;
createdAt: string;
metadata?: {
github_repo?: string;
};
}>;
totalCount: number;
}> {
if (!(await this.isSignedIn())) {
return { agents: [], totalCount: 0 };
}
try {
// Build URL with query parameters
const params = new URLSearchParams();
if (organizationId) {
params.set("organizationId", organizationId);
}
if (limit !== undefined) {
params.set("limit", limit.toString());
}
const url = `agents${params.toString() ? `?${params.toString()}` : ""}`;
const resp = await this.requestAndHandleError(url, {
method: "GET",
});
const result = (await resp.json()) as {
agents: AgentSessionView[];
totalCount: number;
};
return {
agents: result.agents.map((agent) => ({
id: agent.id,
name: agent.name,
status: agent.status,
repoUrl: agent.repoUrl,
createdAt: agent.createdAt,
metadata: {
github_repo: agent.metadata.github_repo,
},
})),
totalCount: result.totalCount,
};
} catch (e) {
Logger.error(e, {
context: "control_plane_list_background_agents",
});
return { agents: [], totalCount: 0 };
}
}
/**
* Get the full agent session information
* @param agentSessionId - The ID of the agent session
* @returns The agent session view including metadata and status
*/
public async getAgentSession(
agentSessionId: string,
): Promise<AgentSessionView | null> {
if (!(await this.isSignedIn())) {
return null;
}
try {
const resp = await this.requestAndHandleError(
`agents/${agentSessionId}`,
{
method: "GET",
},
);
return (await resp.json()) as AgentSessionView;
} catch (e) {
Logger.error(e, {
context: "control_plane_get_agent_session",
agentSessionId,
});
return null;
}
}
/**
* Get the state of a specific background agent
* @param agentSessionId - The ID of the agent session
* @returns The agent's session state including history, workspace, and branch
*/
public async getAgentState(agentSessionId: string): Promise<{
session: Session;
isProcessing: boolean;
messageQueueLength: number;
pendingPermission: any;
} | null> {
if (!(await this.isSignedIn())) {
return null;
}
try {
const resp = await this.requestAndHandleError(
`agents/${agentSessionId}/state`,
{
method: "GET",
},
);
const result = (await resp.json()) as {
session: Session;
isProcessing: boolean;
messageQueueLength: number;
pendingPermission: any;
};
return result;
} catch (e) {
Logger.error(e, {
context: "control_plane_get_agent_state",
agentSessionId,
});
return null;
}
}
}

View file

@ -1,105 +0,0 @@
import * as fs from "node:fs";
import { IdeSettings } from "..";
import {
getLocalEnvironmentDotFilePath,
getStagingEnvironmentDotFilePath,
} from "../util/paths";
import { AuthType, ControlPlaneEnv } from "./AuthTypes";
import { getLicenseKeyData } from "./mdm/mdm";
export const EXTENSION_NAME = "continue";
const WORKOS_CLIENT_ID_PRODUCTION = "client_01J0FW6XN8N2XJAECF7NE0Y65J";
const WORKOS_CLIENT_ID_STAGING = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ";
const PRODUCTION_HUB_ENV: ControlPlaneEnv = {
DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api.continue.dev/",
CONTROL_PLANE_URL: "https://api.continue.dev/",
AUTH_TYPE: AuthType.WorkOsProd,
WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_PRODUCTION,
APP_URL: "https://continue.dev/",
};
const STAGING_ENV: ControlPlaneEnv = {
DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api.continue-stage.tools/",
CONTROL_PLANE_URL: "https://api.continue-stage.tools/",
AUTH_TYPE: AuthType.WorkOsStaging,
WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING,
APP_URL: "https://hub.continue-stage.tools/",
};
const TEST_ENV: ControlPlaneEnv = {
DEFAULT_CONTROL_PLANE_PROXY_URL: "https://api-test.continue.dev/",
CONTROL_PLANE_URL: "https://api-test.continue.dev/",
AUTH_TYPE: AuthType.WorkOsStaging,
WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING,
APP_URL: "https://app-test.continue.dev/",
};
const LOCAL_ENV: ControlPlaneEnv = {
DEFAULT_CONTROL_PLANE_PROXY_URL: "http://localhost:3001/",
CONTROL_PLANE_URL: "http://localhost:3001/",
AUTH_TYPE: AuthType.WorkOsStaging,
WORKOS_CLIENT_ID: WORKOS_CLIENT_ID_STAGING,
APP_URL: "http://localhost:3000/",
};
export async function enableHubContinueDev() {
return true;
}
export async function getControlPlaneEnv(
ideSettingsPromise: Promise<IdeSettings>,
): Promise<ControlPlaneEnv> {
const ideSettings = await ideSettingsPromise;
return getControlPlaneEnvSync(ideSettings.continueTestEnvironment);
}
export function getControlPlaneEnvSync(
ideTestEnvironment: IdeSettings["continueTestEnvironment"],
): ControlPlaneEnv {
// MDM override
const licenseKeyData = getLicenseKeyData();
if (licenseKeyData?.unsignedData?.apiUrl) {
const { apiUrl } = licenseKeyData.unsignedData;
return {
AUTH_TYPE: AuthType.OnPrem,
DEFAULT_CONTROL_PLANE_PROXY_URL: apiUrl,
CONTROL_PLANE_URL: apiUrl,
APP_URL: "https://continue.dev/",
};
}
// Note .local overrides .staging
if (fs.existsSync(getLocalEnvironmentDotFilePath())) {
return LOCAL_ENV;
}
if (fs.existsSync(getStagingEnvironmentDotFilePath())) {
return STAGING_ENV;
}
const env =
ideTestEnvironment === "production"
? "hub"
: ideTestEnvironment === "staging"
? "staging"
: ideTestEnvironment === "local"
? "local"
: process.env.CONTROL_PLANE_ENV;
return env === "local"
? LOCAL_ENV
: env === "staging"
? STAGING_ENV
: env === "test"
? TEST_ENV
: PRODUCTION_HUB_ENV;
}
export async function useHub(
ideSettingsPromise: Promise<IdeSettings>,
): Promise<boolean> {
const ideSettings = await ideSettingsPromise;
return ideSettings.continueTestEnvironment !== "none";
}

View file

@ -1,370 +0,0 @@
import * as crypto from "crypto";
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import * as plist from "plist";
export interface MdmKeys {
licenseKey: string;
}
const CONTINUE_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz1pFVzsW2UScSnaPAwFp
93QU4+txtyJj8AOC3Kx7YkX1d48DGU2Fy1he7SXPHgcuhXYIqfWGn/Vy/4yJxXD7
HlU8RM7LlWHRk7ecAvF4WtxZDjPE0OSG5T69w5f7tMCtQPQseInCKqleJuCjxrvA
zyTWTwKA1S6e+KxXS/kbqsumriljFujNr6Gmh8ygDnpF055Xo0vTenkMipVw/oYn
U0EHx5ic+Fmcob3EyOj25lu/CVYtU1Rn8jPbrBOMiIq5sePh2QXOwGRsuTiZk2mP
LXSsjLbeWHifRrQ18wj/PC990E33QaFGNFp0NcBXMPbq5eKYKEzKZ0GsxtLoGxar
FQIDAQAB
-----END PUBLIC KEY-----`;
interface LicenseKeyUnsignedData {
apiUrl: string;
}
export interface LicenseKey {
signature: string;
data: string;
unsignedData: LicenseKeyUnsignedData;
}
export interface LicenseKeyData {
customerId: string;
createdAt: string;
expiresAt: string;
}
export function validateLicenseKey(licenseKey: string): {
isValid: boolean;
licenseKeyData?: LicenseKey;
} {
try {
// Decode the base64 license key
const decodedString = Buffer.from(licenseKey, "base64").toString("utf8");
const { data, signature, unsignedData } = JSON.parse(decodedString);
// Verify the signature
const verify = crypto.createVerify("SHA256");
verify.update(data);
verify.end();
const isValid = verify.verify(CONTINUE_PUBLIC_KEY, signature, "base64");
if (!isValid) return { isValid: false };
// Check license expiration
const licenseData: LicenseKeyData = JSON.parse(data);
const expirationDate = new Date(licenseData.expiresAt);
const now = new Date();
const isNotExpired = expirationDate > now;
if (!isNotExpired) return { isValid: false };
// Return both validation result and license key data
const licenseKeyData: LicenseKey = {
signature,
data,
unsignedData,
};
return { isValid: true, licenseKeyData };
} catch (error) {
console.error("License validation error:", error);
return { isValid: false };
}
}
const MACOS_MDM_PATHS = [
// Organization-specific MDM plist
"/Library/Managed Preferences/dev.continue.app.plist",
// User-specific MDM plist
path.join(os.homedir(), "Library/Managed Preferences/dev.continue.app.plist"),
];
function readMdmKeysMacOS(): MdmKeys | undefined {
try {
// MDM configuration is typically stored in /Library/Managed Preferences/ on macOS
// The filename is often the bundle identifier of the application
// Try to find a valid MDM configuration file
for (const mdmPath of MACOS_MDM_PATHS) {
if (fs.existsSync(mdmPath)) {
// Read the file content
const fileContent = fs.readFileSync(mdmPath, "utf8");
try {
// Parse the plist file using the plist package
const config = plist.parse(fileContent) as
| { licenseKey: string | undefined }
| undefined;
if (config && config?.licenseKey) {
// Extract the license key from the configuration
return { licenseKey: config?.licenseKey };
} else {
console.error("Invalid MDM configuration format");
}
} catch (parseError) {
console.error(`Error parsing MDM configuration: ${parseError}`);
}
}
}
return undefined;
} catch (error) {
console.error("Error reading macOS MDM keys:", error);
return undefined;
}
}
function readMdmKeysWindows(): MdmKeys | undefined {
try {
// For Windows, we need to read from the registry
// Using regedit or another synchronous registry access module
const { execSync } = require("child_process");
// Path to the registry where MDM configuration is stored
const regPath = "HKLM\\Software\\Continue\\MDM";
const userRegPath = "HKCU\\Software\\Continue\\MDM";
// Try to read from HKEY_LOCAL_MACHINE first
try {
// Use REG QUERY command to read registry values
const licenseKeyCmd = `reg query "${regPath}" /v licenseKey`;
const licenseKeyOutput = execSync(licenseKeyCmd, {
encoding: "utf8",
stdio: ["pipe", "pipe", "pipe"],
});
// Extract values from command output
const licenseKey = extractRegValue(licenseKeyOutput);
if (licenseKey) {
return { licenseKey };
}
} catch (error) {
// Registry key might not exist, fallback to HKEY_CURRENT_USER
}
// Try HKEY_CURRENT_USER if not found in HKEY_LOCAL_MACHINE
try {
const licenseKeyCmd = `reg query "${userRegPath}" /v licenseKey`;
const licenseKeyOutput = execSync(licenseKeyCmd, {
encoding: "utf8",
stdio: ["pipe", "pipe", "pipe"],
});
// Extract values from command output
const licenseKey = extractRegValue(licenseKeyOutput);
if (licenseKey) {
return { licenseKey };
}
} catch (error) {
// Registry key might not exist in HKCU either
}
return undefined;
} catch (error) {
console.error("Error reading Windows MDM keys:", error);
return undefined;
}
}
// Helper function to extract registry values from reg query output
function extractRegValue(output: string): string | undefined {
const match = output.match(/REG_SZ\s+(.+)$/m);
return match ? match[1].trim() : undefined;
}
// Common locations for MDM configurations in Linux systems
const LINUX_MDM_PATHS = [
// System-wide configuration
"/etc/continue/mdm.json",
"/var/lib/continue/mdm.json",
// User-specific configuration
path.join(os.homedir(), ".config/continue/mdm.json"),
];
function readMdmKeysLinux(): MdmKeys | undefined {
try {
// Try to find a valid MDM configuration file
for (const mdmPath of LINUX_MDM_PATHS) {
if (fs.existsSync(mdmPath)) {
// Read the file content
const fileContent = fs.readFileSync(mdmPath, "utf8");
try {
// Parse the JSON configuration file
const config = JSON.parse(fileContent);
// Check if required key is present
if (config.licenseKey) {
return {
licenseKey: config.licenseKey,
};
}
} catch (parseError) {
console.error(`Error parsing Linux MDM configuration: ${parseError}`);
}
}
}
return undefined;
} catch (error) {
console.error("Error reading Linux MDM keys:", error);
return undefined;
}
}
function readMdmKeys(): MdmKeys | undefined {
const platform = os.platform();
switch (platform) {
case "darwin":
return readMdmKeysMacOS();
case "win32":
return readMdmKeysWindows();
case "linux":
return readMdmKeysLinux();
default:
console.error(`MDM keys not supported on platform: ${platform}`);
return undefined;
}
}
/**
* Read and validate MDM keys from the operating system's configuration files or registry.
*/
export function getLicenseKeyData(): LicenseKey | undefined {
try {
const mdmKeys = readMdmKeys();
if (mdmKeys) {
const { isValid, licenseKeyData } = validateLicenseKey(
mdmKeys.licenseKey,
);
if (!isValid) {
console.error("Invalid license key found: ", mdmKeys.licenseKey);
return undefined;
}
return licenseKeyData;
}
return undefined;
} catch (e) {
console.warn("Error reading MDM keys: ", e);
return undefined;
}
}
function writeMdmKeysMacOS(licenseKey: string): boolean {
try {
// Write to user-specific MDM plist
const userMdmPath = path.join(
os.homedir(),
"Library/Managed Preferences/dev.continue.app.plist",
);
const config = {
licenseKey,
};
// Ensure directory exists
fs.mkdirSync(path.dirname(userMdmPath), { recursive: true });
// Write the plist file
const plistContent = plist.build(config);
fs.writeFileSync(userMdmPath, plistContent, "utf8");
return true;
} catch (error) {
console.error("Error writing macOS MDM keys:", error);
return false;
}
}
function writeMdmKeysWindows(licenseKey: string): boolean {
try {
const { execSync } = require("child_process");
// Use HKEY_CURRENT_USER to avoid needing admin privileges
const userRegPath = "HKCU\\Software\\Continue\\MDM";
// Create the registry key if it doesn't exist
try {
execSync(`reg add "${userRegPath}" /f`);
} catch (error) {
// Key might already exist
}
// Set the license key and API URL
execSync(
`reg add "${userRegPath}" /v licenseKey /t REG_SZ /d "${licenseKey}" /f`,
);
return true;
} catch (error) {
console.error("Error writing Windows MDM keys:", error);
return false;
}
}
function writeMdmKeysLinux(licenseKey: string): boolean {
try {
// Write to user-specific configuration
const userMdmPath = path.join(os.homedir(), ".config/continue/mdm.json");
const config = {
licenseKey,
};
// Ensure directory exists
fs.mkdirSync(path.dirname(userMdmPath), { recursive: true });
// Write the JSON configuration file
fs.writeFileSync(userMdmPath, JSON.stringify(config, null, 2), "utf8");
return true;
} catch (error) {
console.error("Error writing Linux MDM keys:", error);
return false;
}
}
/**
* Store the license key in the appropriate OS-specific location.
* For now, we'll use a default API URL since it's not provided in the command.
*/
export function setMdmLicenseKey(licenseKey: string): boolean {
try {
// Validate the license key first
const { isValid } = validateLicenseKey(licenseKey);
if (!isValid) {
return false;
}
const platform = os.platform();
switch (platform) {
case "darwin":
return writeMdmKeysMacOS(licenseKey);
case "win32":
return writeMdmKeysWindows(licenseKey);
case "linux":
return writeMdmKeysLinux(licenseKey);
default:
console.error(
`Setting MDM keys not supported on platform: ${platform}`,
);
return false;
}
} catch (error) {
console.error("Error setting MDM license key:", error);
return false;
}
}

View file

@ -1,211 +0,0 @@
import * as crypto from "crypto";
import { expect, test } from "vitest";
import { LicenseKeyData, validateLicenseKey } from "./mdm";
// We'll create a real key pair once for all tests
const testKeyPair = crypto.generateKeyPairSync("rsa", {
modulusLength: 2048,
publicKeyEncoding: {
type: "spki",
format: "pem",
},
privateKeyEncoding: {
type: "pkcs8",
format: "pem",
},
});
// Custom function to create test licenses with the new structure including unsignedData
function createTestLicense(
licenseData: LicenseKeyData,
apiUrl: string = "https://api.continue.dev",
useValidSignature: boolean = true,
): string {
// Convert license data to a string
const licenseDataStr = JSON.stringify(licenseData);
// Create a signature with our generated private key
const sign = crypto.createSign("SHA256");
sign.update(licenseDataStr);
sign.end();
let signature: string;
if (useValidSignature) {
signature = sign.sign(testKeyPair.privateKey, "base64");
} else {
// For invalid tests, create an intentionally wrong signature by signing different data
const wrongSign = crypto.createSign("SHA256");
wrongSign.update(licenseDataStr + "tampered");
wrongSign.end();
signature = wrongSign.sign(testKeyPair.privateKey, "base64");
}
// Combine data, signature, and unsigned data into a license key
const licenseKeyObj = {
data: licenseDataStr,
signature: signature,
unsignedData: {
apiUrl: apiUrl,
},
};
return Buffer.from(JSON.stringify(licenseKeyObj)).toString("base64");
}
// We need to test the actual implementation - which we can't mock with ESM
// Instead, we'll have tests that bypass validation or are expected to fail
// depending on what we're testing
test("validateLicenseKey returns false for malformed license key", () => {
// Test with a completely invalid license key
const invalidLicenseKey = "not-a-valid-license-key";
// Test - no mocks, real validation
const result = validateLicenseKey(invalidLicenseKey);
// Assert
expect(result.isValid).toBe(false);
expect(result.licenseKeyData).toBeUndefined();
});
test("validateLicenseKey returns false for invalid JSON in license key", () => {
// Create a malformed but base64-encoded string
const malformedLicenseKey = Buffer.from("this is not valid JSON").toString(
"base64",
);
// Test - no mocks, real validation
const result = validateLicenseKey(malformedLicenseKey);
// Assert
expect(result.isValid).toBe(false);
expect(result.licenseKeyData).toBeUndefined();
});
test("validateLicenseKey returns false for expired license", () => {
// Without mocking, we expect this to fail signature verification
// We're testing the date logic by itself
const licenseData: LicenseKeyData = {
customerId: "customer123",
createdAt: new Date(Date.now() - 2000 * 60 * 60 * 24).toISOString(), // Created 2 days ago
expiresAt: new Date(Date.now() - 1000 * 60 * 60 * 24).toISOString(), // Expired 1 day ago
};
// Create a license key with apiUrl in unsignedData - will fail verification but test logic still works
const expiredLicenseKey = createTestLicense(
licenseData,
"https://api.continue.dev",
);
// Test - expect false, either due to signature or expiration - both are valid test cases
const result = validateLicenseKey(expiredLicenseKey);
// Assert
expect(result.isValid).toBe(false);
expect(result.licenseKeyData).toBeUndefined();
});
test("validateLicenseKey returns false for invalid signature", () => {
// Create license data with valid dates
const licenseData: LicenseKeyData = {
customerId: "customer123",
createdAt: new Date().toISOString(),
expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(), // Valid for 1 day
};
// Create a license with an invalid signature but valid unsignedData structure
const invalidSignatureKey = createTestLicense(
licenseData,
"https://api.continue.dev",
false,
);
// Test - no mocks, real validation
const result = validateLicenseKey(invalidSignatureKey);
// Assert
expect(result.isValid).toBe(false);
expect(result.licenseKeyData).toBeUndefined();
});
test("validateLicenseKey handles JSON parsing errors gracefully", () => {
// Create a base64 string that decodes to valid JSON but lacks required fields
const invalidStructureKey = Buffer.from(
JSON.stringify({
notTheRightField: "wrong structure",
}),
).toString("base64");
// Test - no mocks, real validation
const result = validateLicenseKey(invalidStructureKey);
// Assert
expect(result.isValid).toBe(false);
expect(result.licenseKeyData).toBeUndefined();
});
test("validateLicenseKey handles missing unsignedData gracefully", () => {
// Create a license key structure without unsignedData field
const licenseData: LicenseKeyData = {
customerId: "customer123",
createdAt: new Date().toISOString(),
expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(),
};
const licenseDataStr = JSON.stringify(licenseData);
const sign = crypto.createSign("SHA256");
sign.update(licenseDataStr);
sign.end();
const signature = sign.sign(testKeyPair.privateKey, "base64");
// Create license key without unsignedData
const licenseKeyObj = {
data: licenseDataStr,
signature: signature,
// Missing unsignedData field
};
const licenseKey = Buffer.from(JSON.stringify(licenseKeyObj)).toString(
"base64",
);
// Test - no mocks, real validation
const result = validateLicenseKey(licenseKey);
// Assert - should fail due to signature verification with wrong public key
expect(result.isValid).toBe(false);
expect(result.licenseKeyData).toBeUndefined();
});
test("validateLicenseKey handles invalid unsignedData structure", () => {
// Create license data with valid dates
const licenseData: LicenseKeyData = {
customerId: "customer123",
createdAt: new Date().toISOString(),
expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(),
};
const licenseDataStr = JSON.stringify(licenseData);
const sign = crypto.createSign("SHA256");
sign.update(licenseDataStr);
sign.end();
const signature = sign.sign(testKeyPair.privateKey, "base64");
// Create license key with invalid unsignedData structure
const licenseKeyObj = {
data: licenseDataStr,
signature: signature,
unsignedData: "not an object", // Should be an object with apiUrl
};
const licenseKey = Buffer.from(JSON.stringify(licenseKeyObj)).toString(
"base64",
);
// Test - no mocks, real validation
const result = validateLicenseKey(licenseKey);
// Assert - should fail due to signature verification with wrong public key
expect(result.isValid).toBe(false);
expect(result.licenseKeyData).toBeUndefined();
});

View file

@ -1,144 +0,0 @@
import { z } from "zod";
const modelDescriptionSchema = z.object({
title: z.string(),
provider: z.enum([
"openai",
"anthropic",
"cohere",
"ollama",
"huggingface-tgi",
"huggingface-inference-api",
"replicate",
"gemini",
"mistral",
"bedrock",
"sagemaker",
"cloudflare",
"azure",
"ovhcloud",
"nebius",
"siliconflow",
"tensorix",
"scaleway",
"watsonx",
]),
model: z.string(),
apiKey: z.string().optional(),
apiBase: z.string().optional(),
contextLength: z.number().optional(),
maxStopWords: z.number().optional(),
template: z
.enum([
"llama2",
"alpaca",
"zephyr",
"phi2",
"phind",
"anthropic",
"chatml",
"none",
"openchat",
"deepseek",
"xwin-coder",
"neural-chat",
"codellama-70b",
"llava",
"gemma",
"llama3",
"codestral",
])
.optional(),
completionOptions: z
.object({
temperature: z.number().optional(),
topP: z.number().optional(),
topK: z.number().optional(),
minP: z.number().optional(),
presencePenalty: z.number().optional(),
frequencyPenalty: z.number().optional(),
mirostat: z.number().optional(),
stop: z.array(z.string()).optional(),
maxTokens: z.number().optional(),
numThreads: z.number().optional(),
useMmap: z.boolean().optional(),
keepAlive: z.number().optional(),
numGpu: z.number().optional(),
raw: z.boolean().optional(),
stream: z.boolean().optional(),
})
.optional(),
systemMessage: z.string().optional(),
requestOptions: z
.object({
timeout: z.number().optional(),
verifySsl: z.boolean().optional(),
caBundlePath: z.union([z.string(), z.array(z.string())]).optional(),
proxy: z.string().optional(),
headers: z.record(z.string()).optional(),
extraBodyProperties: z.record(z.any()).optional(),
noProxy: z.array(z.string()).optional(),
})
.optional(),
promptTemplates: z.record(z.string()).optional(),
});
const embeddingsProviderSchema = z.object({
provider: z.enum([
"transformers.js",
"ollama",
"openai",
"cohere",
"gemini",
"ovhcloud",
"nebius",
"siliconflow",
"tensorix",
"scaleway",
"watsonx",
]),
apiBase: z.string().optional(),
apiKey: z.string().optional(),
model: z.string().optional(),
deployment: z.string().optional(),
apiType: z.string().optional(),
apiVersion: z.string().optional(),
requestOptions: z
.object({
timeout: z.number().optional(),
verifySsl: z.boolean().optional(),
caBundlePath: z.union([z.string(), z.array(z.string())]).optional(),
proxy: z.string().optional(),
headers: z.record(z.string()).optional(),
extraBodyProperties: z.record(z.any()).optional(),
noProxy: z.array(z.string()).optional(),
})
.optional(),
});
const rerankerSchema = z.object({
name: z.enum(["cohere", "voyage", "llm", "watsonx"]),
params: z.record(z.any()).optional(),
});
const analyticsSchema = z.object({
url: z.string().optional(),
clientKey: z.string().optional(),
});
export type ControlPlaneAnalytics = z.infer<typeof analyticsSchema>;
const devDataSchema = z.object({
url: z.string().optional(),
});
export const controlPlaneSettingsSchema = z.object({
models: z.array(modelDescriptionSchema),
tabAutocompleteModel: modelDescriptionSchema,
embeddingsModel: embeddingsProviderSchema,
reranker: rerankerSchema,
analytics: analyticsSchema,
devData: devDataSchema,
});
export type ControlPlaneSettings = z.infer<typeof controlPlaneSettingsSchema>;

View file

@ -9,8 +9,6 @@ import {
} from "./autocomplete/util/openedFilesLruCache";
import { ConfigHandler } from "./config/ConfigHandler";
import { addModel, deleteModel } from "./config/util";
import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
import { getControlPlaneEnv } from "./control-plane/env";
import { DevDataSqliteDb } from "./data/devdataSqlite";
import { DataLogger } from "./data/log";
import { CodebaseIndexer } from "./indexing/CodebaseIndexer";
@ -27,7 +25,7 @@ import { compactConversation } from "./util/conversationCompaction";
import { GlobalContext } from "./util/GlobalContext";
import historyManager from "./util/history";
import { editConfigFile, migrateV1DevDataFiles } from "./util/paths";
import { Telemetry } from "./util/posthog";
import {
isProcessBackgrounded,
killTerminalProcess,
@ -70,7 +68,6 @@ import {
} from "./config/workspace/workspaceBlocks";
import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton";
import { performAuth, removeMCPAuth } from "./context/mcp/MCPOauth";
import { setMdmLicenseKey } from "./control-plane/mdm/mdm";
import { myersDiff } from "./diff/myers";
import { ApplyAbortManager } from "./edit/applyAbortManager";
import { streamDiffLines } from "./edit/streamDiffLines";
@ -138,19 +135,7 @@ export class Core {
const ideInfoPromise = messenger.request("getIdeInfo", undefined);
const ideSettingsPromise = messenger.request("getIdeSettings", undefined);
const initialSessionInfoPromise = messenger.request(
"getControlPlaneSessionInfo",
{
silent: true,
useOnboarding: false,
},
);
this.configHandler = new ConfigHandler(
this.ide,
this.llmLogger,
initialSessionInfoPromise,
);
this.configHandler = new ConfigHandler(this.ide, this.llmLogger);
this.docsService = DocsService.createSingleton(
this.configHandler,
@ -189,8 +174,7 @@ export class Core {
result: serializedResult,
profileId:
this.configHandler.currentProfile?.profileDescription.id || null,
organizations: this.configHandler.getSerializedOrgs(),
selectedOrgId: this.configHandler.currentOrg?.id ?? null,
profiles: this.configHandler.profileDescriptions,
});
if (await this.codeBaseIndexer.wasAnyOneIndexAdded()) {
@ -294,11 +278,6 @@ export class Core {
// Note, VsCode's in-process messenger doesn't do anything with this
// It will only show for jetbrains
this.messenger.onError((message, err) => {
void Telemetry.capture("core_messenger_error", {
message: err.message,
stack: err.stack,
});
// just to prevent duplicate error messages in jetbrains (same logic in webview protocol)
if (
["llm/streamChat", "chatDescriber/describe"].includes(
@ -324,26 +303,9 @@ export class Core {
// History
on("history/list", async (msg) => {
const localSessions = historyManager.list(msg.data);
// Check if remote sessions should be enabled based on feature flags
const shouldFetchRemote =
await this.configHandler.controlPlaneClient.shouldEnableRemoteSessions();
// Get remote sessions from control plane if feature is enabled
const remoteSessions = shouldFetchRemote
? await this.configHandler.controlPlaneClient.listRemoteSessions()
: [];
// Combine and sort by date (most recent first)
const allSessions = [...localSessions, ...remoteSessions].sort(
(a, b) =>
new Date(b.dateCreated).getTime() - new Date(a.dateCreated).getTime(),
);
// Apply limit if specified
const sessions = historyManager.list(msg.data);
const limit = msg.data?.limit ?? 100;
return allSessions.slice(0, limit);
return sessions.slice(0, limit);
});
on("history/delete", (msg) => {
@ -354,12 +316,6 @@ export class Core {
return historyManager.load(msg.data.id);
});
on("history/loadRemote", async (msg) => {
return this.configHandler.controlPlaneClient.loadRemoteSession(
msg.data.remoteId,
);
});
on("history/save", (msg) => {
historyManager.save(msg.data);
});
@ -482,11 +438,9 @@ export class Core {
const codebaseRulesCache = CodebaseRulesCache.getInstance();
await codebaseRulesCache.refresh(this.ide);
const { selectOrgId, selectProfileId, reason } = msg.data ?? {};
const { selectProfileId, reason } = msg.data ?? {};
await this.configHandler.refreshAll(reason);
if (selectOrgId) {
await this.configHandler.setSelectedOrgId(selectOrgId, selectProfileId);
} else if (selectProfileId) {
if (selectProfileId) {
await this.configHandler.setSelectedProfileId(selectProfileId);
}
});
@ -511,28 +465,6 @@ export class Core {
return newSelectedModels;
});
on("controlPlane/openUrl", async (msg) => {
const env = await getControlPlaneEnv(this.ide.getIdeSettings());
const urlPath = msg.data.path.startsWith("/")
? msg.data.path.slice(1)
: msg.data.path;
let url;
if (msg.data.orgSlug) {
url = `${env.APP_URL}organizations/${msg.data.orgSlug}/${urlPath}`;
} else {
url = `${env.APP_URL}${urlPath}`;
}
await this.messenger.request("openUrl", url);
});
on("controlPlane/getEnvironment", async (msg) => {
return await getControlPlaneEnv(this.ide.getIdeSettings());
});
on("controlPlane/getCreditStatus", async (msg) => {
return this.configHandler.controlPlaneClient.getCreditStatus();
});
on("mcp/reloadServer", async (msg) => {
await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
});
@ -624,8 +556,7 @@ export class Core {
result: await this.configHandler.getSerializedConfig(),
profileId:
this.configHandler.currentProfile?.profileDescription.id ?? null,
organizations: this.configHandler.getSerializedOrgs(),
selectedOrgId: this.configHandler.currentOrg?.id ?? null,
profiles: this.configHandler.profileDescriptions,
};
});
@ -1109,30 +1040,8 @@ export class Core {
}
});
on("didChangeSelectedOrg", async (msg) => {
if (msg.data.id) {
await this.configHandler.setSelectedOrgId(
msg.data.id,
msg.data.profileId || undefined,
);
}
});
on("didChangeControlPlaneSessionInfo", async (msg) => {
this.messenger.send("sessionUpdate", {
sessionInfo: msg.data.sessionInfo,
});
await this.configHandler.updateControlPlaneSessionInfo(
msg.data.sessionInfo,
);
});
on("auth/getAuthUrl", async (msg) => {
const url = await getAuthUrlForTokenPage(
ideSettingsPromise,
msg.data.useOnboarding,
);
return { url };
on("auth/getAuthUrl", async (_msg) => {
return { url: "" };
});
on("tools/call", async ({ data: { toolCall } }) =>
@ -1224,11 +1133,6 @@ export class Core {
await killTerminalProcess(toolCallId);
});
on("mdm/setLicenseKey", ({ data: { licenseKey } }) => {
const isValid = setMdmLicenseKey(licenseKey);
return isValid;
});
on("models/fetch", async (msg) => {
try {
return await fetchModels(
@ -1497,10 +1401,6 @@ export class Core {
}
try {
void Telemetry.capture("context_provider_get_context_items", {
name: provider.description.title,
});
const items = await provider.getContextItems(query, {
config,
llm,
@ -1516,14 +1416,6 @@ export class Core {
isInAgentMode: msg.data.isInAgentMode,
});
void Telemetry.capture(
"useContextProvider",
{
name: provider.description.title,
},
true,
);
return items.map((item) => {
const id: ContextItemId = {
providerTitle: provider.description.title,

View file

@ -189,13 +189,8 @@ export class DataLogger {
"Content-Type": "application/json",
};
// If an API key is provided, use it, otherwise use the Continue access token
if (dataConfig.apiKey) {
headers["Authorization"] = `Bearer ${dataConfig.apiKey}`;
} else {
const accessToken =
await this.core?.configHandler.controlPlaneClient.getAccessToken();
headers["Authorization"] = `Bearer ${accessToken}`;
}
const profileId =

View file

@ -87,9 +87,6 @@ describe("DataLogger", () => {
id: "test-profile-id",
},
},
controlPlaneClient: {
getAccessToken: vi.fn().mockResolvedValue("test-access-token"),
},
},
} as unknown as Core;

View file

@ -23,7 +23,7 @@ import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRule
import { gptEditPrompt } from "../llm/templates/edit";
import { defaultApplyPrompt } from "../llm/templates/edit/gpt";
import { findLast } from "../util/findLast";
import { Telemetry } from "../util/posthog";
import { recursiveStream } from "./recursiveStream";
function constructEditPrompt(
@ -83,15 +83,6 @@ export async function* streamDiffLines(
): AsyncGenerator<DiffLine> {
const { type, prefix, highlighted, suffix, input, language } = options;
void Telemetry.capture(
"inlineEdit",
{
model: llm.model,
provider: llm.providerName,
},
true,
);
// Strip common indentation for the LLM, then add back after generation
let oldLines =
highlighted.length > 0

8
core/index.d.ts vendored
View file

@ -667,7 +667,6 @@ export interface LLMOptions {
apiKeyLocation?: string;
envSecretLocations?: Record<string, string>;
apiBase?: string;
orgScopeId?: string | null;
onPremProxyUrl?: string | null;
@ -1029,7 +1028,6 @@ export type ContextProviderName =
| "currentFile"
| "greptile"
| "outline"
| "continue-proxy"
| "highlights"
| "file"
| "issue"
@ -1188,7 +1186,6 @@ interface ToolChoice {
export interface ConfigDependentToolParams {
rules: RuleWithSource[];
enableExperimentalTools: boolean;
isSignedIn: boolean;
isRemote: boolean;
modelName: string | undefined;
ide: IDE;
@ -1236,7 +1233,6 @@ export interface ModelDescription {
apiBase?: string;
apiKeyLocation?: string;
envSecretLocations?: Record<string, string>;
orgScopeId?: string | null;
onPremProxyUrl?: string | null;
@ -1371,9 +1367,6 @@ export interface MCPPrompt {
arguments?: MCPPromptArgs;
}
// Leaving here to ideate on
// export type ContinueConfigSource = "local-yaml" | "local-json" | "hub-assistant" | "hub"
// https://modelcontextprotocol.io/docs/concepts/resources#direct-resources
export interface MCPResource {
name: string;
@ -1864,7 +1857,6 @@ export interface BrowserSerializedContinueConfig {
tools: Omit<Tool, "preprocessArgs", "evaluateToolCallPolicy">[];
mcpServerStatuses: MCPServerStatus[];
rules: RuleWithSource[];
usePlatform: boolean;
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
modelsByRole: Record<ModelRole, ModelDescription[]>;
selectedModelByRole: Record<ModelRole, ModelDescription | null>;

View file

@ -127,7 +127,6 @@ export class CodebaseIndexer {
try {
await fs.unlink(sqliteFilepath);
} catch (error) {
// Capture indexer system failures to Sentry
Logger.error(error, {
filepath: sqliteFilepath,
});
@ -137,7 +136,6 @@ export class CodebaseIndexer {
try {
await fs.rm(lanceDbFolder, { recursive: true, force: true });
} catch (error) {
// Capture indexer system failures to Sentry
Logger.error(error, {
folderPath: lanceDbFolder,
});

View file

@ -25,7 +25,6 @@ import {
getDocsSqlitePath,
getLanceDbPath,
} from "../../util/paths";
import { Telemetry } from "../../util/posthog";
import {
ArticleWithChunks,
@ -588,10 +587,6 @@ export default class DocsService {
}
}
void Telemetry.capture("docs_pages_crawled", {
count: processedPages,
});
// Chunk pages based on which crawler was used
const articles: ArticleWithChunks[] = [];
const chunks: Chunk[] = [];
@ -1006,7 +1001,6 @@ export default class DocsService {
}
} else {
addedDocs.push(doc);
void Telemetry.capture("add_docs_config", { url: doc.startUrl });
}
}

View file

@ -1,7 +1,7 @@
import { URL } from "node:url";
import { getHeaders } from "../../../continueServer/stubs/headers";
import { TRIAL_PROXY_URL } from "../../../control-plane/client";
const TRIAL_PROXY_URL = "https://proxy-server-blue-l6vsfbzhba-uw.a.run.app";
import { PageData } from "./DocsCrawler";
export class DefaultCrawler {

View file

@ -56,7 +56,6 @@ const PROVIDER_HANDLES_TEMPLATING: string[] = [
"bedrock",
"cohere",
"sagemaker",
"continue-proxy",
"mistral",
"mimo",
"sambanova",
@ -122,7 +121,6 @@ const PROVIDER_SUPPORTS_IMAGES: string[] = [
"anthropic",
"bedrock",
"sagemaker",
"continue-proxy",
"openrouter",
"clawrouter",
"venice",

View file

@ -37,7 +37,6 @@ import { Logger } from "../util/Logger.js";
import mergeJson from "../util/merge.js";
import { renderChatMessage } from "../util/messageContent.js";
import { isOllamaInstalled } from "../util/ollamaHelper.js";
import { TokensBatchingService } from "../util/TokensBatchingService.js";
import { withExponentialBackoff } from "../util/withExponentialBackoff.js";
import {
@ -100,10 +99,6 @@ export abstract class BaseLLM implements ILLM {
return (this.constructor as typeof BaseLLM).providerName;
}
/**
* This exists because for the continue-proxy, sometimes we want to get the value of the underlying provider that is used on the server
* For example, the underlying provider should always be sent with dev data
*/
get underlyingProviderName(): string {
return this.providerName;
}
@ -169,8 +164,6 @@ export abstract class BaseLLM implements ILLM {
apiKeyLocation?: string;
envSecretLocations?: Record<string, string>;
apiBase?: string;
orgScopeId?: string | null;
onPremProxyUrl?: string | null;
cacheBehavior?: CacheBehavior;
@ -223,11 +216,7 @@ export abstract class BaseLLM implements ILLM {
this.model = options.model;
// Use @continuedev/llm-info package to autodetect certain parameters
const modelSearchString =
this.providerName === "continue-proxy"
? this.model?.split("/").pop() || this.model
: this.model;
const llmInfo = findLlmInfo(modelSearchString, this.underlyingProviderName);
const llmInfo = findLlmInfo(this.model, this.underlyingProviderName);
const templateType =
options.template ?? autodetectTemplateType(options.model);
@ -273,7 +262,6 @@ export abstract class BaseLLM implements ILLM {
// continueProperties
this.apiKeyLocation = options.apiKeyLocation;
this.envSecretLocations = options.envSecretLocations;
this.orgScopeId = options.orgScopeId;
this.apiBase = options.apiBase;
this.onPremProxyUrl = options.onPremProxyUrl;
@ -362,13 +350,6 @@ export abstract class BaseLLM implements ILLM {
let generatedTokens = this.countTokens(completion);
let thinkingTokens = thinking ? this.countTokens(thinking) : 0;
TokensBatchingService.getInstance().addTokens(
model,
this.providerName,
promptTokens,
generatedTokens,
);
void DevDataSqliteDb.logTokensGenerated(
model,
this.providerName,
@ -487,7 +468,6 @@ export abstract class BaseLLM implements ILLM {
return resp;
} catch (e: any) {
// Capture all fetch errors to Sentry for monitoring
Logger.error(e, {
context: "llm_fetch",
url: String(input),
@ -682,7 +662,6 @@ export abstract class BaseLLM implements ILLM {
undefined,
);
} catch (e) {
// Capture FIM (Fill-in-the-Middle) completion failures to Sentry
Logger.error(e as Error, {
context: "llm_stream_fim",
model: completionOptions.model,
@ -813,7 +792,6 @@ export abstract class BaseLLM implements ILLM {
undefined,
);
} catch (e) {
// Capture streaming completion failures to Sentry
Logger.error(e as Error, {
context: "llm_stream_complete",
model: completionOptions.model,
@ -922,7 +900,6 @@ export abstract class BaseLLM implements ILLM {
undefined,
);
} catch (e) {
// Capture completion failures to Sentry
Logger.error(e as Error, {
context: "llm_complete",
model: completionOptions.model,
@ -1308,7 +1285,6 @@ export abstract class BaseLLM implements ILLM {
usage,
);
} catch (e) {
// Capture chat streaming failures to Sentry
Logger.error(e as Error, {
context: "llm_stream_chat",
model: completionOptions.model,

View file

@ -59,7 +59,6 @@ import SambaNova from "./SambaNova";
import Scaleway from "./Scaleway";
import SiliconFlow from "./SiliconFlow";
import Tensorix from "./Tensorix";
import ContinueProxy from "./stubs/ContinueProxy";
import TARS from "./TARS";
import TestLLM from "./Test";
import TextGenWebUI from "./TextGenWebUI";
@ -104,7 +103,6 @@ export const LLMClasses = [
Groq,
Fireworks,
NCompass,
ContinueProxy,
Cloudflare,
Deepseek,
Docker,
@ -186,16 +184,6 @@ export async function llmFromDescription(
uniqueId,
};
if (desc.provider === "continue-proxy") {
options.apiKey = ideSettings.userToken;
if (ideSettings.remoteConfigServerUrl) {
options.apiBase = new URL(
"/proxy/v1",
ideSettings.remoteConfigServerUrl,
).toString();
}
}
return new cls(options);
}

View file

@ -1,156 +0,0 @@
import {
ContinueProperties,
decodeSecretLocation,
parseProxyModelName,
SecretType,
} from "@continuedev/config-yaml";
import { ControlPlaneProxyInfo } from "../../../control-plane/analytics/IAnalyticsProvider.js";
import { Telemetry } from "../../../util/posthog.js";
import OpenAI from "../OpenAI.js";
import type { Chunk, LLMOptions } from "../../../index.js";
import { LLMConfigurationStatuses } from "../../constants.js";
import { LlmApiRequestType } from "../../openaiTypeConverters.js";
class ContinueProxy extends OpenAI {
set controlPlaneProxyInfo(value: ControlPlaneProxyInfo) {
this.apiKey = value.workOsAccessToken;
if (!this.onPremProxyUrl) {
this.apiBase = new URL(
"model-proxy/v1/",
value.controlPlaneProxyUrl,
).toString();
}
}
protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = [];
// The apiKey and apiBase are set to the values for the proxy,
// but we need to keep track of the actual values that the proxy will use
// to call whatever LLM API is chosen
private actualApiBase?: string;
// Contains extra properties that we pass along to the proxy. Originally from `env` property on LLMOptions
private configEnv?: Record<string, any>;
constructor(options: LLMOptions) {
super(options);
this.configEnv = options.env;
// This it set to `undefined` to handle the case where we are proxying requests to Azure. We pass the correct env vars
// needed to do this in `extraBodyProperties` below, but if we don't set `apiType` to `undefined`, we end up proxying to
// `/openai/deployments/` which is invalid since that URL construction happens on the proxy.
this.apiType = undefined;
this.actualApiBase = options.apiBase;
this.apiKeyLocation = options.apiKeyLocation;
this.envSecretLocations = options.envSecretLocations;
this.orgScopeId = options.orgScopeId;
this.onPremProxyUrl = options.onPremProxyUrl;
if (this.onPremProxyUrl) {
this.apiBase = new URL("model-proxy/v1/", this.onPremProxyUrl).toString();
}
}
static providerName = "continue-proxy";
static defaultOptions: Partial<LLMOptions> = {
useLegacyCompletionsEndpoint: false,
};
get underlyingProviderName(): string {
const { provider } = parseProxyModelName(this.model);
return provider;
}
protected extraBodyProperties(): Record<string, any> {
const continueProperties: ContinueProperties = {
apiKeyLocation: this.apiKeyLocation,
envSecretLocations: this.envSecretLocations,
apiBase: this.actualApiBase,
orgScopeId: this.orgScopeId ?? null,
env: this.configEnv,
};
return {
continueProperties,
};
}
getConfigurationStatus() {
if (!this.apiKeyLocation && !this.envSecretLocations) {
return LLMConfigurationStatuses.VALID;
}
if (this.apiKeyLocation) {
const secretLocation = decodeSecretLocation(this.apiKeyLocation);
if (secretLocation.secretType === SecretType.NotFound) {
return LLMConfigurationStatuses.MISSING_API_KEY;
}
}
if (this.envSecretLocations) {
for (const secretLocation of Object.values(this.envSecretLocations)) {
const decoded = decodeSecretLocation(secretLocation);
if (decoded.secretType === SecretType.NotFound) {
return LLMConfigurationStatuses.MISSING_ENV_SECRET;
}
}
}
return LLMConfigurationStatuses.VALID;
}
protected _getHeaders() {
const headers: any = super._getHeaders();
headers["x-continue-unique-id"] = Telemetry.uniqueId;
headers["user-agent"] = this._getUserAgent();
return headers;
}
private _getUserAgent(): string {
const ideInfo = Telemetry.ideInfo;
const extensionVersion = ideInfo?.extensionVersion ?? "unknown";
const ideName = ideInfo?.name ?? "unknown";
const ideType = ideInfo?.ideType ?? "unknown";
return `Continue/${extensionVersion} (${ideName}; ${ideType})`;
}
supportsCompletions(): boolean {
// This was a hotfix and contains duplicate logic from class-specific completion support methods
if (this.underlyingProviderName === "vllm") {
return true;
}
// other providers that don't support completions include groq, mistral, nvidia, deepseek, etc.
// For now disabling all except vllm
return false;
}
supportsFim(): boolean {
const { provider } = parseProxyModelName(this.model);
if (provider === "vllm") {
return false;
}
return true;
}
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
const url = new URL("rerank", this.apiBase);
const resp = await this.fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
"user-agent": this._getUserAgent(),
},
body: JSON.stringify({
query,
documents: chunks.map((chunk) => chunk.content),
model: this.model,
...this.extraBodyProperties(),
}),
});
const data: any = await resp.json();
const results = data.data.sort((a: any, b: any) => a.index - b.index);
return results.map((result: any) => result.relevance_score);
}
}
export default ContinueProxy;

View file

@ -1,758 +0,0 @@
import { afterEach, describe, expect, test, vi } from "vitest";
import { ILLM } from "../../../index.js";
import ContinueProxy from "./ContinueProxy.js";
vi.mock("@continuedev/config-yaml", async (importOriginal) => {
const mod = (await importOriginal()) as any;
return {
...mod,
parseProxyModelName: vi.fn(() => ({
provider: "test-provider",
model: "test-model",
ownerSlug: "test-owner",
packageSlug: "test-package",
})),
};
});
interface LlmTestCase {
llm: ILLM;
methodToTest: keyof ILLM;
params: any[];
expectedRequest: {
url: string;
method: string;
headers?: Record<string, string>;
body?: Record<string, any>;
};
mockResponse?: any;
mockStream?: any[];
}
function createMockStream(mockStream: any[]) {
const encoder = new TextEncoder();
return new ReadableStream({
start(controller) {
for (const chunk of mockStream) {
controller.enqueue(
encoder.encode(
`data: ${
typeof chunk === "string" ? chunk : JSON.stringify(chunk)
}\n\n`,
),
);
}
controller.close();
},
});
}
function setupMockFetch(mockResponse?: any, mockStream?: any[]) {
const mockFetch = vi.fn();
if (mockStream) {
const stream = createMockStream(mockStream);
mockFetch.mockResolvedValue(
new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
},
}),
);
} else {
mockFetch.mockResolvedValue(
new Response(JSON.stringify(mockResponse), {
headers: { "Content-Type": "application/json" },
}),
);
}
return mockFetch;
}
function setupReadableStreamPolyfill() {
// This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved
// @ts-ignore
const originalFrom = ReadableStream.from;
// @ts-ignore
ReadableStream.from = (body) => {
if (body?.source) {
return body;
}
return originalFrom(body);
};
}
async function executeLlmMethod(
llm: ILLM,
methodToTest: keyof ILLM,
params: any[],
) {
if (typeof (llm as any)[methodToTest] !== "function") {
throw new Error(
`Method ${String(methodToTest)} does not exist on the LLM instance.`,
);
}
const result = await (llm as any)[methodToTest](...params);
if (result?.next) {
for await (const _ of result) {
}
}
}
function assertFetchCall(mockFetch: any, expectedRequest: any) {
expect(mockFetch).toHaveBeenCalledTimes(1);
const [url, options] = mockFetch.mock.calls[0];
expect(url.toString()).toBe(expectedRequest.url);
expect(options.method).toBe(expectedRequest.method);
if (expectedRequest.headers) {
expect(options.headers).toEqual(
expect.objectContaining(expectedRequest.headers),
);
}
if (expectedRequest.body) {
const actualBody = JSON.parse(options.body as string);
expect(actualBody).toEqual(expectedRequest.body);
}
}
async function runLlmTest(testCase: LlmTestCase) {
const {
llm,
methodToTest,
params,
expectedRequest,
mockResponse,
mockStream,
} = testCase;
const mockFetch = setupMockFetch(mockResponse, mockStream);
setupReadableStreamPolyfill();
(llm as any).fetch = mockFetch;
await executeLlmMethod(llm, methodToTest, params);
assertFetchCall(mockFetch, expectedRequest);
}
describe("ContinueProxy", () => {
afterEach(() => {
vi.clearAllMocks();
});
test("rerank should send a valid request", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "rerank",
params: [
"test query",
[{ content: "document1" }, { content: "document2" }],
],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/rerank",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
},
body: {
query: "test query",
documents: ["document1", "document2"],
model: "test-model",
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
orgScopeId: null,
},
},
},
mockResponse: {
data: [
{ index: 0, relevance_score: 0.9 },
{ index: 1, relevance_score: 0.1 },
],
},
});
});
test("streamChat should send a valid request", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "streamChat",
params: [[{ role: "user", content: "hello" }]],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
"x-continue-unique-id": "NOT_UNIQUE",
},
body: {
model: "test-model",
messages: [{ role: "user", content: "hello" }],
max_tokens: 4096,
stream: true,
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
orgScopeId: null,
},
},
},
mockStream: [
'{"choices": [{"delta": {"content": "response"}}]}',
"[DONE]",
],
});
});
test("chat should send a valid request", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "chat",
params: [[{ role: "user", content: "hello" }]],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
"x-continue-unique-id": "NOT_UNIQUE",
},
body: {
model: "test-model",
messages: [{ role: "user", content: "hello" }],
max_tokens: 4096,
stream: true,
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
orgScopeId: null,
},
},
},
mockStream: [
'{"choices": [{"delta": {"content": "Hello! How can I help you today?"}}]}',
"[DONE]",
],
});
});
test("streamComplete should send a valid request", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "streamComplete",
params: ["Complete this: Hello"],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
"x-continue-unique-id": "NOT_UNIQUE",
},
body: {
model: "test-model",
messages: [{ role: "user", content: "Complete this: Hello" }],
max_tokens: 4096,
stream: true,
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
orgScopeId: null,
},
},
},
mockStream: [
'{"choices": [{"delta": {"content": " world!"}}]}',
"[DONE]",
],
});
});
test("complete should send a valid request", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "complete",
params: ["Complete this: Hello"],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
"x-continue-unique-id": "NOT_UNIQUE",
},
body: {
model: "test-model",
messages: [{ role: "user", content: "Complete this: Hello" }],
max_tokens: 4096,
stream: true,
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
orgScopeId: null,
},
},
},
mockStream: [
'{"choices": [{"delta": {"content": " world!"}}]}',
"[DONE]",
],
});
});
test("streamFim should send a valid request", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "streamFim",
params: ["function test() {\n ", "\n}"],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/fim/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"x-api-key": "test-api-key",
Authorization: "Bearer test-api-key",
},
body: {
model: "test-model",
prompt: "function test() {\n ",
suffix: "\n}",
max_tokens: 4096,
stream: true,
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
orgScopeId: null,
},
},
},
mockStream: [
'{"choices": [{"delta": {"content": "console.log("Hello");"}}]}',
"[DONE]",
],
});
});
test("embed should send a valid request", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "embed",
params: [["text to embed", "another text"]],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/embeddings",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
input: ["text to embed", "another text"],
model: "test-model",
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
orgScopeId: null,
},
},
},
mockResponse: {
data: [{ embedding: [0.1, 0.2, 0.3] }, { embedding: [0.4, 0.5, 0.6] }],
},
});
});
test("listModels should send a valid request", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "listModels",
params: [],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/models",
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
},
mockResponse: {
data: [{ id: "gpt-4" }, { id: "gpt-3.5-turbo" }],
},
});
});
describe("Different provider configurations", () => {
test("should handle on-prem proxy URL", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
onPremProxyUrl: "https://my-proxy.company.com/",
});
await runLlmTest({
llm: proxy,
methodToTest: "rerank",
params: [
"test query",
[{ content: "document1" }, { content: "document2" }],
],
expectedRequest: {
url: "https://my-proxy.company.com/model-proxy/v1/rerank",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
},
body: {
query: "test query",
documents: ["document1", "document2"],
model: "test-model",
continueProperties: {
apiBase: undefined,
apiKeyLocation: undefined,
env: undefined,
envSecretLocations: undefined,
orgScopeId: null,
},
},
},
mockResponse: {
data: [
{ index: 0, relevance_score: 0.9 },
{ index: 1, relevance_score: 0.1 },
],
},
});
});
test("should handle environment variables", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
env: {
CUSTOM_VAR: "custom-value",
ANOTHER_VAR: "another-value",
},
});
await runLlmTest({
llm: proxy,
methodToTest: "streamChat",
params: [[{ role: "user", content: "hello" }]],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
"x-continue-unique-id": "NOT_UNIQUE",
},
body: {
model: "test-model",
messages: [{ role: "user", content: "hello" }],
max_tokens: 4096,
stream: true,
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
env: {
CUSTOM_VAR: "custom-value",
ANOTHER_VAR: "another-value",
},
orgScopeId: null,
},
},
},
mockStream: [
'{"choices": [{"delta": {"content": "response"}}]}',
"[DONE]",
],
});
});
test("should handle API key location", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
apiKeyLocation: "env:OPENAI_API_KEY",
});
await runLlmTest({
llm: proxy,
methodToTest: "embed",
params: [["test text"]],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/embeddings",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
input: ["test text"],
model: "test-model",
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
apiKeyLocation: "env:OPENAI_API_KEY",
env: undefined,
envSecretLocations: undefined,
orgScopeId: null,
},
},
},
mockResponse: {
data: [{ embedding: [0.1, 0.2, 0.3] }],
},
});
});
test("should handle env secret locations", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
envSecretLocations: {
AZURE_API_KEY: "env:AZURE_API_KEY",
AZURE_ENDPOINT: "env:AZURE_ENDPOINT",
},
});
await runLlmTest({
llm: proxy,
methodToTest: "streamFim",
params: ["const x = ", ";"],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/fim/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"x-api-key": "test-api-key",
Authorization: "Bearer test-api-key",
},
body: {
model: "test-model",
prompt: "const x = ",
suffix: ";",
max_tokens: 4096,
stream: true,
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
envSecretLocations: {
AZURE_API_KEY: "env:AZURE_API_KEY",
AZURE_ENDPOINT: "env:AZURE_ENDPOINT",
},
orgScopeId: null,
},
},
},
mockStream: ['{"choices": [{"delta": {"content": "42"}}]}', "[DONE]"],
});
});
test("should handle organization scope ID", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
orgScopeId: "org_12345",
});
await runLlmTest({
llm: proxy,
methodToTest: "listModels",
params: [],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/models",
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
},
mockResponse: {
data: [{ id: "gpt-4" }],
},
});
});
});
describe("Edge cases", () => {
test("should handle empty chunks array for rerank", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "rerank",
params: ["test query", []],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/rerank",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
},
body: {
query: "test query",
documents: [],
model: "test-model",
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
apiKeyLocation: undefined,
env: undefined,
envSecretLocations: undefined,
orgScopeId: null,
},
},
},
mockResponse: {
data: [],
},
});
});
test("should handle complex chat messages", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
const complexMessages = [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Hello!" },
{ role: "assistant", content: "Hi there! How can I help you today?" },
{ role: "user", content: "What's the weather like?" },
];
await runLlmTest({
llm: proxy,
methodToTest: "streamChat",
params: [complexMessages],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/chat/completions",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
"x-continue-unique-id": "NOT_UNIQUE",
},
body: {
model: "test-model",
messages: complexMessages,
max_tokens: 4096,
stream: true,
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
orgScopeId: null,
},
},
},
mockStream: [
'{"choices": [{"delta": {"content": "I don\'t have access to current weather data."}}]}',
"[DONE]",
],
});
});
test("should handle single embedding chunk", async () => {
const proxy = new ContinueProxy({
apiKey: "test-api-key",
model: "test-model",
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
});
await runLlmTest({
llm: proxy,
methodToTest: "embed",
params: [["single text"]],
expectedRequest: {
url: "https://proxy.continue.dev/model-proxy/v1/embeddings",
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer test-api-key",
"api-key": "test-api-key",
},
body: {
input: ["single text"],
model: "test-model",
continueProperties: {
apiBase: "https://proxy.continue.dev/model-proxy/v1/",
apiKeyLocation: undefined,
env: undefined,
envSecretLocations: undefined,
orgScopeId: null,
},
},
},
mockResponse: {
data: [{ embedding: [0.1, 0.2, 0.3] }],
},
});
});
});
});

View file

@ -4,35 +4,10 @@ import Deepseek from "../Deepseek.js";
import FunctionNetwork from "../FunctionNetwork.js";
import Mistral from "../Mistral.js";
import OpenAI from "../OpenAI.js";
import ContinueProxy from "../stubs/ContinueProxy.js";
import Vllm from "../Vllm.js";
// Mock the parseProxyModelName function
const mockParseProxyModelName = jest.fn();
jest.mock("@continuedev/config-yaml", () => ({
parseProxyModelName: mockParseProxyModelName,
decodeSecretLocation: jest.fn(),
SecretType: { NotFound: "not-found" },
}));
// Test cases: [LLM class, model, expected supportsFim result, description]
const testCases: [any, string, boolean, string][] = [
[ContinueProxy, "owner/package/vllm/some-model", false, "vllm provider"],
[ContinueProxy, "owner/package/openai/gpt-4", true, "openai provider"],
[
ContinueProxy,
"owner/package/anthropic/claude-3",
true,
"anthropic provider",
],
[ContinueProxy, "owner/package/cohere/command-r", true, "cohere provider"],
[
ContinueProxy,
"owner/package/unknown-provider/some-model",
true,
"unknown provider",
],
[ContinueProxy, "owner/package/groq/llama-model", true, "groq provider"],
[Vllm, "any-model", false, "Vllm"],
[Anthropic, "claude-3-5-sonnet-latest", false, "Anthropic"],
[FunctionNetwork, "any-model", false, "FunctionNetwork"],

View file

@ -1,12 +1,10 @@
import { fetchwithRequestOptions } from "@continuedev/fetch";
import { ChatMessage, IDE, PromptLog } from "..";
import { ConfigHandler } from "../config/ConfigHandler";
import { usesCreditsBasedApiKey } from "../config/usesFreeTrialApiKey";
import { FromCoreProtocol, ToCoreProtocol } from "../protocol";
import { IMessenger, Message } from "../protocol/messenger";
import { Telemetry } from "../util/posthog";
import { TTS } from "../util/tts";
import { isOutOfStarterCredits } from "./utils/starterCredits";
export async function* llmStreamChat(
configHandler: ConfigHandler,
@ -136,17 +134,6 @@ export async function* llmStreamChat(
void TTS.read(next.value?.completion);
}
void Telemetry.capture(
"chat",
{
model: model.model,
provider: model.providerName,
},
true,
);
void checkForOutOfStarterCredits(configHandler, messenger);
if (!next.done) {
throw new Error("Will never happen");
}
@ -158,24 +145,3 @@ export async function* llmStreamChat(
throw error;
}
}
async function checkForOutOfStarterCredits(
configHandler: ConfigHandler,
messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
) {
try {
const { config } = await configHandler.getSerializedConfig();
const creditStatus =
await configHandler.controlPlaneClient.getCreditStatus();
if (
config &&
creditStatus &&
isOutOfStarterCredits(usesCreditsBasedApiKey(config), creditStatus)
) {
void messenger.request("freeTrialExceeded", undefined);
}
} catch (error) {
console.error("Error checking free trial status:", error);
}
}

View file

@ -2,72 +2,6 @@
import { PROVIDER_TOOL_SUPPORT, isRecommendedAgentModel } from "./toolSupport";
describe("PROVIDER_TOOL_SUPPORT", () => {
describe("continue-proxy", () => {
const supportsFn = PROVIDER_TOOL_SUPPORT["continue-proxy"];
it("should return true for Claude 3.5 models", () => {
expect(
supportsFn("ownerSlug/packageSlug/anthropic/claude-3-5-sonnet"),
).toBe(true);
expect(
supportsFn("ownerSlug/packageSlug/anthropic/claude-3.5-sonnet"),
).toBe(true);
});
it("should return true for Claude 3.7 models", () => {
expect(
supportsFn("ownerSlug/packageSlug/anthropic/claude-3-7-haiku"),
).toBe(true);
expect(
supportsFn("ownerSlug/packageSlug/anthropic/claude-3.7-sonnet"),
).toBe(true);
});
it("should return true for GPT-4 models", () => {
expect(supportsFn("ownerSlug/packageSlug/openai/gpt-4-turbo")).toBe(true);
expect(
supportsFn("ownerSlug/packageSlug/openai/gpt-4-1106-preview"),
).toBe(true);
});
it("should return true for Gemma models", () => {
expect(supportsFn("ownerSlug/packageSlug/openai/gemma")).toBe(true);
expect(supportsFn("ownerSlug/packageSlug/openai/gemma3")).toBe(true);
expect(supportsFn("ownerSlug/packageSlug/openai/gemma4")).toBe(true);
});
it("should return true for O3 models", () => {
expect(supportsFn("ownerSlug/packageSlug/openai/o3-preview")).toBe(true);
});
it("should return true for Gemini models", () => {
expect(supportsFn("ownerSlug/packageSlug/gemini/gemini-pro")).toBe(true);
expect(supportsFn("ownerSlug/packageSlug/gemini/gemini-2.5-pro")).toBe(
true,
);
});
it("should return false for unsupported models", () => {
expect(supportsFn("ownerSlug/packageSlug/openai/gpt-3.5-turbo")).toBe(
false,
);
expect(supportsFn("ownerSlug/packageSlug/anthropic/claude-2")).toBe(
false,
);
expect(supportsFn("ownerSlug/packageSlug/together/llama-3")).toBe(false);
});
it("should handle case insensitivity", () => {
expect(
supportsFn("ownerSlug/packageSlug/anthropic/CLAUDE-3-5-sonnet"),
).toBe(true);
expect(supportsFn("ownerSlug/packageSlug/openai/GPT-4-turbo")).toBe(true);
expect(supportsFn("ownerSlug/packageSlug/openai/Gemma3")).toBe(true);
expect(supportsFn("ownerSlug/packageSlug/openai/Gemma4")).toBe(true);
expect(supportsFn("ownerSlug/packageSlug/gemini/GEMINI-pro")).toBe(true);
});
});
describe("anthropic", () => {
const supportsFn = PROVIDER_TOOL_SUPPORT["anthropic"];
@ -448,7 +382,6 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
describe("edge cases", () => {
it("should handle empty model names", () => {
expect(PROVIDER_TOOL_SUPPORT["continue-proxy"]("")).toBe(false);
expect(PROVIDER_TOOL_SUPPORT["anthropic"]("")).toBe(false);
expect(PROVIDER_TOOL_SUPPORT["openai"]("")).toBe(false);
expect(PROVIDER_TOOL_SUPPORT["gemini"]("")).toBe(false);

View file

@ -1,28 +1,7 @@
import { parseProxyModelName } from "@continuedev/config-yaml";
import { ModelDescription } from "..";
export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
{
"continue-proxy": (model) => {
try {
const { provider, model: _model } = parseProxyModelName(model);
if (provider && _model && provider !== "continue-proxy") {
const fn = PROVIDER_TOOL_SUPPORT[provider];
if (fn) {
return fn(_model);
}
}
} catch (e) {}
const lower = model.toLowerCase();
return (
lower.startsWith("claude") ||
!!lower.match(/^gpt-[4-9]/) ||
!!lower.match(/^o[1-9]/) ||
lower.startsWith("gemini") ||
lower.startsWith("gemma")
);
},
anthropic: (model) => {
if (model.includes("claude-2") || model.includes("claude-instant")) {
return false;

View file

@ -1,12 +0,0 @@
import { CreditStatus } from "../../control-plane/client";
export function isOutOfStarterCredits(
usingModelsAddOnApiKey: boolean,
creditStatus: CreditStatus,
): boolean {
return (
usingModelsAddOnApiKey &&
!creditStatus.hasCredits &&
!creditStatus.hasPurchasedCredits
);
}

View file

@ -1,9 +1,7 @@
import { COUNT_COMPLETION_REJECTED_AFTER } from "../util/parameters";
import { fetchwithRequestOptions } from "@continuedev/fetch";
import { getControlPlaneEnvSync } from "../control-plane/env";
import { DataLogger } from "../data/log";
import { Telemetry } from "../util/posthog";
import { NextEditOutcome } from "./types";
export class NextEditLoggingService {
@ -217,39 +215,5 @@ export class NextEditLoggingService {
});
// const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome;
if (outcome.requestId && outcome.accepted !== undefined) {
void this.logAcceptReject(outcome.requestId, outcome.accepted);
}
void Telemetry.capture("nextEditOutcome", outcome, true);
}
private async logAcceptReject(
requestId: string,
accepted: boolean,
): Promise<void> {
try {
if (!Telemetry.client) {
return;
}
const controlPlaneEnv = getControlPlaneEnvSync("production");
const resp = await fetchwithRequestOptions(
new URL("model-proxy/v1/feedback", controlPlaneEnv.CONTROL_PLANE_URL),
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
requestId,
accepted,
}),
},
);
const text = await resp.text();
console.debug("Feedback: ", text);
} catch (error: any) {
console.debug(`Error capturing feedback: ${error.message}`);
}
}
}

View file

@ -156,13 +156,6 @@ export class NextEditProvider {
if (llm instanceof OpenAI && llm.providerName !== "openrouter") {
llm.useLegacyCompletionsEndpoint = true;
}
// TODO: Resolve import error with TRIAL_FIM_MODEL
// else if (
// llm.providerName === "free-trial" &&
// llm.model !== TRIAL_FIM_MODEL
// ) {
// llm.model = TRIAL_FIM_MODEL;
// }
return llm;
}
@ -510,9 +503,6 @@ export class NextEditProvider {
let outcome: NextEditOutcome | undefined;
// Handle based on diff type.
const profileType =
this.configHandler.currentProfile?.profileDescription.profileType;
if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) {
outcome = await this.modelProvider.handlePartialFileDiff({
helper,
@ -523,7 +513,6 @@ export class NextEditProvider {
nextCompletion,
promptMetadata: this.promptMetadata!,
ide: this.ide,
profileType,
});
} else {
outcome = await this.modelProvider.handleFullFileDiff({
@ -535,7 +524,6 @@ export class NextEditProvider {
nextCompletion,
promptMetadata: this.promptMetadata!,
ide: this.ide,
profileType,
});
}

View file

@ -56,7 +56,6 @@ export abstract class BaseNextEditModelProvider {
nextCompletion: string;
promptMetadata: PromptMetadata;
ide: IDE;
profileType?: "local" | "platform" | "control-plane";
}): Promise<NextEditOutcome> {
const {
helper,
@ -67,7 +66,6 @@ export abstract class BaseNextEditModelProvider {
nextCompletion,
promptMetadata,
ide,
profileType,
} = params;
const oldEditRangeSlice = helper.fileContents
.split("\n")
@ -95,7 +93,6 @@ export abstract class BaseNextEditModelProvider {
originalEditableRange: oldEditRangeSlice,
diffLines: [],
ide,
profileType,
});
return outcome;
@ -110,7 +107,6 @@ export abstract class BaseNextEditModelProvider {
nextCompletion: string;
promptMetadata: PromptMetadata;
ide: IDE;
profileType?: "local" | "platform" | "control-plane";
}): Promise<NextEditOutcome | undefined> {
const {
helper,
@ -121,7 +117,6 @@ export abstract class BaseNextEditModelProvider {
nextCompletion,
promptMetadata,
ide,
profileType,
} = params;
const fileSlice = helper.fileLines
.slice(editableRegionStartLine, editableRegionEndLine + 1)
@ -145,7 +140,6 @@ export abstract class BaseNextEditModelProvider {
prefetchQueue,
promptMetadata,
ide,
profileType,
});
if (cursorLocalDiffGroup) {
@ -158,7 +152,6 @@ export abstract class BaseNextEditModelProvider {
isCurrentCursorGroup: true,
promptMetadata,
ide,
profileType,
});
}
@ -177,7 +170,6 @@ export abstract class BaseNextEditModelProvider {
prefetchQueue: PrefetchQueue;
promptMetadata: PromptMetadata;
ide: IDE;
profileType?: "local" | "platform" | "control-plane";
}): Promise<DiffGroup | undefined> {
const {
diffGroups,
@ -188,7 +180,6 @@ export abstract class BaseNextEditModelProvider {
prefetchQueue,
promptMetadata,
ide,
profileType,
} = params;
let cursorGroup: DiffGroup | undefined;
@ -204,7 +195,6 @@ export abstract class BaseNextEditModelProvider {
prefetchQueue,
promptMetadata,
ide,
profileType,
});
}
}
@ -220,7 +210,6 @@ export abstract class BaseNextEditModelProvider {
prefetchQueue: PrefetchQueue;
promptMetadata: PromptMetadata;
ide: IDE;
profileType?: "local" | "platform" | "control-plane";
}): Promise<void> {
const {
group,
@ -230,7 +219,6 @@ export abstract class BaseNextEditModelProvider {
prefetchQueue,
promptMetadata,
ide,
profileType,
} = params;
// Extract lines that are not old.
const groupContent = group.lines
@ -274,7 +262,6 @@ export abstract class BaseNextEditModelProvider {
completionId: uuidv4(), // Generate a new ID for this prefetched item.
diffLines: group.lines,
ide,
profileType,
});
prefetchQueue.enqueueProcessed({
@ -292,7 +279,6 @@ export abstract class BaseNextEditModelProvider {
isCurrentCursorGroup: boolean;
promptMetadata: PromptMetadata;
ide: IDE;
profileType?: "local" | "platform" | "control-plane";
}): Promise<NextEditOutcome> {
const {
diffGroup,
@ -303,7 +289,6 @@ export abstract class BaseNextEditModelProvider {
isCurrentCursorGroup,
promptMetadata,
ide,
profileType,
} = params;
const groupContent = diffGroup.lines
.filter((l) => l.type !== "old")
@ -342,7 +327,6 @@ export abstract class BaseNextEditModelProvider {
completionId,
diffLines: diffGroup.lines,
ide,
profileType,
});
return outcomeNext;
@ -364,7 +348,6 @@ export abstract class BaseNextEditModelProvider {
completionId?: string;
diffLines: DiffLine[];
ide: IDE;
profileType?: "local" | "platform" | "control-plane";
}): Promise<NextEditOutcome> {
return {
elapsed: Date.now() - outcomeCtx.startTime,
@ -391,7 +374,6 @@ export abstract class BaseNextEditModelProvider {
editableRegionStartLine: outcomeCtx.editableRegionStartLine,
editableRegionEndLine: outcomeCtx.editableRegionEndLine,
diffLines: outcomeCtx.diffLines,
profileType: outcomeCtx.profileType,
...outcomeCtx.helper.options,
};
}

View file

@ -68,7 +68,6 @@ export interface NextEditOutcome extends TabAutocompleteOptions {
editableRegionStartLine: number;
editableRegionEndLine: number;
diffLines: DiffLine[];
profileType?: "local" | "platform" | "control-plane";
}
export interface PromptMetadata {

11726
core/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -8,10 +8,9 @@
"test:coverage": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --coverage && open ./coverage/lcov-report/index.html",
"tsc:check": "tsc -p ./ --noEmit",
"build": "tsc -p ./tsconfig.npm.json",
"build:npm": "npm run build && npm run sentry:sourcemaps",
"build:npm": "npm run build",
"lint": "eslint . --ext ts",
"lint:fix": "eslint . --ext ts --fix",
"sentry:sourcemaps": "sentry-cli sourcemaps inject --org continue-xd --project continue ./dist && sentry-cli sourcemaps upload --org continue-xd --project continue ./dist"
"lint:fix": "eslint . --ext ts --fix"
},
"type": "module",
"author": "Continue Dev, Inc",
@ -68,11 +67,6 @@
"@modelcontextprotocol/sdk": "^1.25.2",
"@mozilla/readability": "^0.6.0",
"@octokit/rest": "^20.1.1",
"@sentry/cli": "^2.50.2",
"@sentry/core": "^9.43.0",
"@sentry/esbuild-plugin": "^4.0.2",
"@sentry/node": "^9.43.0",
"@sentry/vite-plugin": "^5.0.0",
"@xenova/transformers": "2.14.0",
"adf-to-md": "^1.1.0",
"async-mutex": "^0.5.0",
@ -109,7 +103,6 @@
"partial-json": "^0.1.7",
"pg": "^8.11.3",
"plist": "^3.1.0",
"posthog-node": "^3.6.3",
"puppeteer": "^24.15.0",
"puppeteer-chromium-resolver": "^23.0.0",
"quick-lru": "^7.0.0",

View file

@ -10,6 +10,7 @@ import {
AutocompleteInput,
RecentlyEditedRange,
} from "../autocomplete/util/types";
import { ProfileDescription } from "../config/ProfileLifecycleManager";
import { SharedConfigSchema } from "../config/sharedConfig";
import { GlobalContextModelSelections } from "../util/GlobalContext";
@ -44,12 +45,6 @@ import {
import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types";
import { GetLspDefinitionsFunction } from "../autocomplete/types";
import { ConfigHandler } from "../config/ConfigHandler";
import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager";
import {
ControlPlaneEnv,
ControlPlaneSessionInfo,
} from "../control-plane/AuthTypes";
import { CreditStatus, RemoteSessionMetadata } from "../control-plane/client";
import { ProcessedItem } from "../nextEdit/NextEditPrefetchQueue";
import { NextEditOutcome } from "../nextEdit/types";
import { ContinueErrorReason } from "../util/errors";
@ -57,7 +52,6 @@ import { ContinueErrorReason } from "../util/errors";
export enum OnboardingModes {
API_KEY = "API Key",
LOCAL = "Local",
MODELS_ADD_ON = "Models Add-On",
}
export interface ListHistoryOptions {
@ -73,13 +67,9 @@ export type ToCoreFromIdeOrWebviewProtocol = {
cancelApply: [undefined, void];
// History
"history/list": [
ListHistoryOptions,
(BaseSessionMetadata | RemoteSessionMetadata)[],
];
"history/list": [ListHistoryOptions, BaseSessionMetadata[]];
"history/delete": [{ id: string }, void];
"history/load": [{ id: string }, Session];
"history/loadRemote": [{ remoteId: string }, Session];
"history/save": [Session, void];
"history/share": [{ id: string; outputDir?: string }, void];
"history/clear": [undefined, void];
@ -106,8 +96,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
{
result: ConfigResult<BrowserSerializedContinueConfig>;
profileId: string | null;
organizations: SerializedOrgWithProfiles[];
selectedOrgId: string | null;
profiles: ProfileDescription[];
},
];
"config/deleteModel": [{ title: string }, void];
@ -116,7 +105,6 @@ export type ToCoreFromIdeOrWebviewProtocol = {
| undefined
| {
reason?: string;
selectOrgId?: string;
selectProfileId?: string;
}
),
@ -339,14 +327,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
},
];
"clipboardCache/add": [{ content: string }, void];
"controlPlane/openUrl": [{ path: string; orgSlug?: string }, void];
"controlPlane/getEnvironment": [undefined, ControlPlaneEnv];
"controlPlane/getCreditStatus": [undefined, CreditStatus | null];
isItemTooBig: [{ item: ContextItemWithId }, boolean];
didChangeControlPlaneSessionInfo: [
{ sessionInfo: ControlPlaneSessionInfo | undefined },
void,
];
"process/markAsBackgrounded": [{ toolCallId: string }, void];
"process/isBackgrounded": [{ toolCallId: string }, boolean];
"process/killTerminalProcess": [{ toolCallId: string }, void];

View file

@ -3,6 +3,5 @@ import { ToWebviewFromIdeOrCoreProtocol } from "./webview.js";
export type ToCoreFromWebviewProtocol = ToCoreFromIdeOrWebviewProtocol & {
didChangeSelectedProfile: [{ id: string }, void];
didChangeSelectedOrg: [{ id: string; profileId?: string }, void];
};
export type ToWebviewFromCoreProtocol = ToWebviewFromIdeOrCoreProtocol;

View file

@ -14,8 +14,6 @@ import type {
TerminalOptions,
Thread,
} from "../";
import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes";
export interface GetGhTokenArgs {
force?: boolean;
}
@ -88,11 +86,6 @@ export type ToIdeFromWebviewOrCoreProtocol = {
getReferences: [{ location: Location }, RangeInFile[]];
getDocumentSymbols: [{ textDocumentIdentifier: string }, DocumentSymbol[]];
getControlPlaneSessionInfo: [
{ silent: boolean; useOnboarding: boolean },
ControlPlaneSessionInfo | undefined,
];
logoutOfControlPlane: [undefined, void];
reportError: [any, void];
closeSidebar: [undefined, void];
};

View file

@ -6,10 +6,8 @@ import {
AddToChatPayload,
ApplyState,
ApplyToFilePayload,
ContextItemWithId,
HighlightedCodePayload,
MessageContent,
RangeInFile,
RangeInFileWithContents,
SetCodeToEditPayload,
ShowFilePayload,
@ -52,38 +50,6 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
"edit/addCurrentSelection": [undefined, void];
"edit/clearDecorations": [undefined, void];
"session/share": [{ sessionId: string }, void];
createBackgroundAgent: [
{
content: MessageContent;
contextItems: ContextItemWithId[];
selectedCode: RangeInFile[];
organizationId?: string;
agent?: string;
},
void,
];
listBackgroundAgents: [
{ organizationId?: string; limit?: number },
{
agents: Array<{
id: string;
name: string | null;
status: string;
repoUrl: string;
createdAt: string;
metadata?: {
github_repo?: string;
};
}>;
totalCount: number;
},
];
openAgentLocally: [
{
agentSessionId: string;
},
void,
];
};
export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
@ -100,7 +66,6 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
focusContinueSessionId: [{ sessionId: string | undefined }, void];
newSession: [undefined, void];
loadAgentSession: [{ session: any }, void];
setTheme: [{ theme: any }, void];
setColors: [{ [key: string]: string }, void];
"jetbrains/editorInsetRefresh": [undefined, void];

View file

@ -90,13 +90,11 @@ export class InProcessMessenger<
try {
return listener(msg);
} catch (error) {
// Capture message handling errors to Sentry
Logger.error(error, {
messageType: String(messageType),
messageId: msg.messageId,
});
// Re-throw the original error
throw error;
}
}
@ -141,13 +139,11 @@ export class InProcessMessenger<
});
return response;
} catch (error) {
// Capture message handling errors to Sentry
Logger.error(error, {
messageType: String(messageType),
messageId,
});
// Re-throw the original error
throw error;
}
}
@ -178,13 +174,11 @@ export class InProcessMessenger<
});
return Promise.resolve(response);
} catch (error) {
// Capture message handling errors to Sentry
Logger.error(error, {
messageType: String(messageType),
messageId,
});
// Re-throw the original error
throw error;
}
}

View file

@ -109,11 +109,6 @@ export class ReverseMessageIde {
return this.ide.showLines(data.filepath, data.startLine, data.endLine);
});
this.on("getControlPlaneSessionInfo", async (msg) => {
// Not supported in testing
return undefined;
});
this.on("writeFile", (data) => {
return this.ide.writeFile(data.path, data.contents);
});

View file

@ -13,7 +13,6 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"history/list",
"history/delete",
"history/load",
"history/loadRemote",
"history/save",
"history/clear",
"devdata/log",
@ -80,13 +79,9 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"onboarding/complete",
"addAutocompleteModel",
"didChangeSelectedProfile",
"didChangeSelectedOrg",
"tools/call",
"tools/evaluatePolicy",
"tools/preprocessArgs",
"controlPlane/getEnvironment",
"controlPlane/getCreditStatus",
"controlPlane/openUrl",
"isItemTooBig",
"process/markAsBackgrounded",
"process/isBackgrounded",
@ -111,5 +106,4 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
"sessionUpdate",
"didCloseFiles",
"toolCallPartialOutput",
"freeTrialExceeded",
];

View file

@ -1,6 +1,4 @@
import { ConfigResult } from "@continuedev/config-yaml";
import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager.js";
import { ControlPlaneSessionInfo } from "../control-plane/AuthTypes.js";
import type {
BrowserSerializedContinueConfig,
ContextItemWithId,
@ -8,14 +6,14 @@ import type {
IndexingProgressUpdate,
IndexingStatus,
} from "../index.js";
import type { ProfileDescription } from "../config/ProfileLifecycleManager.js";
export type ToWebviewFromIdeOrCoreProtocol = {
configUpdate: [
{
result: ConfigResult<BrowserSerializedContinueConfig>;
profileId: string | null;
organizations: SerializedOrgWithProfiles[];
selectedOrgId: string | null;
profiles: ProfileDescription[];
},
void,
];
@ -41,7 +39,6 @@ export type ToWebviewFromIdeOrCoreProtocol = {
getWebviewHistoryLength: [undefined, number];
getCurrentSessionId: [undefined, string];
"jetbrains/setColors": [Record<string, string | null | undefined>, void];
sessionUpdate: [{ sessionInfo: ControlPlaneSessionInfo | undefined }, void];
sessionUpdate: [{ sessionInfo: any | undefined }, void];
toolCallPartialOutput: [{ toolCallId: string; contextItems: any[] }, void];
freeTrialExceeded: [undefined, void];
};

View file

@ -1,5 +1,4 @@
import { ConfigHandler } from "../config/ConfigHandler";
import { ControlPlaneClient } from "../control-plane/client";
import Mock from "../llm/llms/Mock";
import { LLMLogger } from "../llm/logger";
import FileSystemIde from "../util/filesystem";
@ -10,16 +9,7 @@ export const testIde = new FileSystemIde(TEST_DIR);
export const ideSettingsPromise = testIde.getIdeSettings();
export const testControlPlaneClient = new ControlPlaneClient(
Promise.resolve(undefined),
testIde,
);
export const testConfigHandler = new ConfigHandler(
testIde,
new LLMLogger(),
Promise.resolve(undefined),
);
export const testConfigHandler = new ConfigHandler(testIde, new LLMLogger());
export const testLLM = new Mock({
model: "mock-model",

View file

@ -6,6 +6,9 @@ import path from "path";
export default async function () {
process.env.CONTINUE_GLOBAL_DIR = path.join(__dirname, ".continue-test");
if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR)) {
fs.rmdirSync(process.env.CONTINUE_GLOBAL_DIR, { recursive: true });
fs.rmSync(process.env.CONTINUE_GLOBAL_DIR, {
recursive: true,
force: true,
});
}
}

View file

@ -6,6 +6,9 @@ import path from "path";
export default async function () {
process.env.CONTINUE_GLOBAL_DIR = path.join(__dirname, ".continue-test");
if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR)) {
fs.rmdirSync(process.env.CONTINUE_GLOBAL_DIR, { recursive: true });
fs.rmSync(process.env.CONTINUE_GLOBAL_DIR, {
recursive: true,
force: true,
});
}
}

View file

@ -7,7 +7,6 @@ describe("Tool Definitions", () => {
const mockParams: ConfigDependentToolParams = {
rules: [],
enableExperimentalTools: false,
isSignedIn: false,
isRemote: false,
modelName: "a model",
ide: {} as any,

View file

@ -18,16 +18,13 @@ export const getBaseToolDefinitions = () => [
export const getConfigDependentToolDefinitions = async (
params: ConfigDependentToolParams,
): Promise<Tool[]> => {
const { modelName, isSignedIn, enableExperimentalTools, isRemote } = params;
const { modelName, enableExperimentalTools, isRemote } = params;
const tools: Tool[] = [];
tools.push(await toolDefinitions.requestRuleTool(params));
tools.push(await toolDefinitions.readSkillTool(params));
if (isSignedIn) {
// Web search is only available for signed-in users
tools.push(toolDefinitions.searchWebTool);
}
tools.push(toolDefinitions.searchWebTool);
if (enableExperimentalTools) {
tools.push(

View file

@ -2,35 +2,18 @@ import { expect, test } from "vitest";
import { BuiltInToolNames } from "./builtIn";
import { getConfigDependentToolDefinitions } from "./index";
test("searchWeb tool is only available when user is signed in", async () => {
// Test with signed-in user
const signedInTools = await getConfigDependentToolDefinitions({
test("searchWeb tool is always available", async () => {
const tools = await getConfigDependentToolDefinitions({
rules: [],
enableExperimentalTools: false,
isSignedIn: true,
isRemote: false,
modelName: "",
ide: {} as any,
});
const searchWebToolSignedIn = signedInTools.find(
const searchWebTool = tools.find(
(tool) => tool.function.name === BuiltInToolNames.SearchWeb,
);
expect(searchWebToolSignedIn).toBeDefined();
expect(searchWebToolSignedIn?.displayTitle).toBe("Search Web");
// Test with non-signed-in user
const notSignedInTools = await getConfigDependentToolDefinitions({
rules: [],
enableExperimentalTools: false,
isSignedIn: false,
isRemote: false,
modelName: "",
ide: {} as any,
});
const searchWebToolNotSignedIn = notSignedInTools.find(
(tool) => tool.function.name === BuiltInToolNames.SearchWeb,
);
expect(searchWebToolNotSignedIn).toBeUndefined();
expect(searchWebTool).toBeDefined();
expect(searchWebTool?.displayTitle).toBe("Search Web");
});

View file

@ -0,0 +1,12 @@
import { IdeInfo } from "../index.js";
export class IdeInfoService {
static uniqueId = "NOT_UNIQUE";
static os: string | undefined = undefined;
static ideInfo: IdeInfo | undefined = undefined;
static setup(uniqueId: string, ideInfo: IdeInfo): void {
IdeInfoService.uniqueId = uniqueId;
IdeInfoService.ideInfo = ideInfo;
}
}

View file

@ -1,5 +1,4 @@
import winston from "winston";
import { captureException } from "./sentry/SentryLogger";
class LoggerClass {
private static instance: LoggerClass;
@ -43,10 +42,6 @@ class LoggerClass {
return LoggerClass.instance;
}
private shouldSendToSentry(): boolean {
return process.env.NODE_ENV !== "test" && process.env.NODE_ENV !== "e2e";
}
public log(message: string, meta?: any): void {
this.winston.info(message, meta);
}
@ -78,10 +73,6 @@ class LoggerClass {
}
this.winston.error(errorMessage, context);
if (this.shouldSendToSentry() && error instanceof Error) {
captureException(error, context);
}
}
}

View file

@ -1,106 +0,0 @@
import { Telemetry } from "./posthog.js";
interface TokenBatch {
model: string;
provider: string;
count: number;
totalPromptTokens: number;
totalGeneratedTokens: number;
lastEventTime: number;
}
export class TokensBatchingService {
private static instance: TokensBatchingService;
private batches = new Map<string, TokenBatch>();
private flushTimer: NodeJS.Timeout | null = null;
private readonly BATCH_SIZE_LIMIT = 25;
private readonly FLUSH_INTERVAL_MS = 10 * 60 * 1000; // 10 minutes
static getInstance(): TokensBatchingService {
if (!TokensBatchingService.instance) {
TokensBatchingService.instance = new TokensBatchingService();
}
return TokensBatchingService.instance;
}
private constructor() {
this.startFlushTimer();
}
addTokens(
model: string,
provider: string,
promptTokens: number,
generatedTokens: number,
): void {
const key = `${provider}:${model}`;
if (!this.batches.has(key)) {
this.batches.set(key, {
model,
provider,
count: 0,
totalPromptTokens: 0,
totalGeneratedTokens: 0,
lastEventTime: Date.now(),
});
}
const batch = this.batches.get(key)!;
batch.count++;
batch.totalPromptTokens += promptTokens;
batch.totalGeneratedTokens += generatedTokens;
batch.lastEventTime = Date.now();
// Flush if batch is full
if (batch.count >= this.BATCH_SIZE_LIMIT) {
this.flushBatch(key, batch);
}
}
private flushBatch(key: string, batch: TokenBatch): void {
if (batch.count === 0) return;
void Telemetry.capture(
"tokens_generated_batch",
{
model: batch.model,
provider: batch.provider,
eventCount: batch.count,
totalPromptTokens: batch.totalPromptTokens,
totalGeneratedTokens: batch.totalGeneratedTokens,
avgPromptTokens: Math.round(batch.totalPromptTokens / batch.count),
avgGeneratedTokens: Math.round(
batch.totalGeneratedTokens / batch.count,
),
},
true,
);
this.batches.delete(key);
}
private startFlushTimer(): void {
this.flushTimer = setInterval(() => {
this.flushAllBatches();
}, this.FLUSH_INTERVAL_MS);
// Allow the process to exit if this timer is the only thing keeping it alive
// This prevents test hangs and allows graceful shutdown
this.flushTimer.unref();
}
private flushAllBatches(): void {
for (const [key, batch] of this.batches.entries()) {
this.flushBatch(key, batch);
}
}
shutdown(): void {
if (this.flushTimer) {
clearInterval(this.flushTimer);
this.flushTimer = null;
}
this.flushAllBatches();
}
}

View file

@ -1,3 +1,5 @@
export const EXTENSION_NAME = "continue";
export const NEW_SESSION_TITLE = "New Session";
export const GITHUB_LINK =

View file

@ -1,155 +0,0 @@
import os from "node:os";
import { TeamAnalytics } from "../control-plane/TeamAnalytics.js";
import { IdeInfo } from "../index.js";
import type { PostHog as PostHogType } from "posthog-node";
import { extractMinimalStackTraceInfo } from "./extractMinimalStackTraceInfo.js";
import { TokensBatchingService } from "./TokensBatchingService.js";
export enum PosthogFeatureFlag {
AutocompleteTimeout = "autocomplete-timeout",
RecentlyVisitedRangesNumSurroundingLines = "recently-visited-ranges-num-surrounding-lines",
}
export const EXPERIMENTS: {
[key in PosthogFeatureFlag]: {
[key: string]: { value: any };
};
} = {
[PosthogFeatureFlag.AutocompleteTimeout]: {
control: { value: 150 },
"250": { value: 250 },
"350": { value: 350 },
"450": { value: 450 },
},
[PosthogFeatureFlag.RecentlyVisitedRangesNumSurroundingLines]: {
control: { value: null },
"5": { value: 5 },
"10": { value: 10 },
"15": { value: 15 },
"20": { value: 20 },
},
};
export class Telemetry {
// Set to undefined whenever telemetry is disabled
static client: PostHogType | undefined = undefined;
static uniqueId = "NOT_UNIQUE";
static os: string | undefined = undefined;
static ideInfo: IdeInfo | undefined = undefined;
/**
* Convenience method for capturing errors in a single event
*/
static async captureError(errorName: string, error: unknown) {
if (!(error instanceof Error)) {
return;
}
await Telemetry.capture(
"extension_error_caught",
{
errorName,
message: error.message,
stack: extractMinimalStackTraceInfo(error.stack),
},
false,
);
}
static async capture(
event: string,
properties: { [key: string]: any },
sendToTeam: boolean = false,
isExtensionActivationError: boolean = false,
) {
try {
const augmentedProperties = {
...properties,
os: Telemetry.os,
extensionVersion: Telemetry.ideInfo?.extensionVersion,
ideName: Telemetry.ideInfo?.name,
ideType: Telemetry.ideInfo?.ideType,
};
const payload = {
distinctId: Telemetry.uniqueId,
event,
properties: augmentedProperties,
sendFeatureFlags: true,
};
// In cases where an extremely early fatal error occurs, we may not have initialized yet
if (isExtensionActivationError && !Telemetry.client) {
const client = await Telemetry.getTelemetryClient();
client?.capture(payload);
return;
}
if (process.env.NODE_ENV === "test") {
return;
}
Telemetry.client?.capture(payload);
if (sendToTeam) {
void TeamAnalytics.capture(event, properties);
}
} catch (e) {
console.error(`Failed to capture event: ${e}`);
}
}
static shutdownPosthogClient() {
TokensBatchingService.getInstance().shutdown();
Telemetry.client?.shutdown();
}
static async getTelemetryClient(): Promise<PostHogType | undefined> {
try {
const { PostHog } = await import("posthog-node");
return new PostHog("phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs", {
host: "https://app.posthog.com",
});
} catch (e) {
console.error(`Failed to setup telemetry: ${e}`);
}
}
static async setup(allow: boolean, uniqueId: string, ideInfo: IdeInfo) {
Telemetry.uniqueId = uniqueId;
Telemetry.os = os.platform();
Telemetry.ideInfo = ideInfo;
if (!allow || process.env.NODE_ENV === "test") {
Telemetry.client = undefined;
} else if (!Telemetry.client) {
Telemetry.client = await Telemetry.getTelemetryClient();
}
}
private static featureValueCache: Record<string, any> = {};
static async getFeatureFlag(flag: PosthogFeatureFlag) {
const value = Telemetry.client?.getFeatureFlag(flag, Telemetry.uniqueId);
Telemetry.featureValueCache[flag] = value;
return value;
}
static async getValueForFeatureFlag(flag: PosthogFeatureFlag) {
try {
if (Telemetry.featureValueCache[flag]) {
return Telemetry.featureValueCache[flag];
}
const userGroup = await Telemetry.getFeatureFlag(flag);
if (typeof userGroup === "string") {
return EXPERIMENTS[flag][userGroup].value;
}
return undefined;
} catch {
return undefined;
}
}
}

View file

@ -1,886 +0,0 @@
import { IdeInfo } from "../../index.js";
import {
SentryLogger,
captureException,
captureLog,
createSpan,
initializeSentry,
} from "./SentryLogger";
import { anonymizeSentryEvent } from "./anonymization";
describe("SentryLogger Integration Tests", () => {
const mockIdeInfo: IdeInfo = {
extensionVersion: "1.0.0",
name: "vscode",
ideType: "vscode",
version: "1.0.0",
remoteName: "local",
isPrerelease: false,
};
beforeEach(() => {
// Reset SentryLogger state before each test
SentryLogger.client = undefined;
SentryLogger.scope = undefined;
SentryLogger.allowTelemetry = false;
SentryLogger.uniqueId = "NOT_UNIQUE";
SentryLogger.ideInfo = undefined;
});
afterEach(() => {
// Clean up after each test
SentryLogger.shutdownSentryClient();
});
describe("Telemetry Toggle Behavior", () => {
it("should not initialize when telemetry is disabled", async () => {
await SentryLogger.setup(
false,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
expect(SentryLogger.allowTelemetry).toBe(false);
expect(SentryLogger.client).toBeUndefined();
expect(SentryLogger.scope).toBeUndefined();
expect(SentryLogger.uniqueId).toBe("test-id");
expect(SentryLogger.ideInfo).toBe(mockIdeInfo);
});
it("should not initialize in test environment even when telemetry is enabled", async () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "test";
await SentryLogger.setup(
true,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
// In the updated implementation, the Continue team member check is used instead of NODE_ENV check
// so we're not setting allowTelemetry to false just because we're in test environment anymore
expect(SentryLogger.allowTelemetry).toBe(true);
// But client and scope should still be initialized
expect(SentryLogger.client).toBeDefined();
expect(SentryLogger.scope).toBeDefined();
process.env.NODE_ENV = originalNodeEnv;
});
it("should initialize when telemetry is enabled in non-test environment", async () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
await SentryLogger.setup(
true,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
expect(SentryLogger.allowTelemetry).toBe(true);
expect(SentryLogger.uniqueId).toBe("test-id");
expect(SentryLogger.ideInfo).toBe(mockIdeInfo);
expect(SentryLogger.client).toBeDefined();
expect(SentryLogger.scope).toBeDefined();
process.env.NODE_ENV = originalNodeEnv;
});
it("should handle telemetry being disabled after being enabled", async () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
// Enable telemetry first
await SentryLogger.setup(
true,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
expect(SentryLogger.allowTelemetry).toBe(true);
expect(SentryLogger.client).toBeDefined();
// Then disable it
await SentryLogger.setup(false, "test-id-2", mockIdeInfo);
expect(SentryLogger.allowTelemetry).toBe(false);
expect(SentryLogger.client).toBeUndefined();
expect(SentryLogger.scope).toBeUndefined();
process.env.NODE_ENV = originalNodeEnv;
});
it("should not reinitialize if client already exists", async () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
// First setup
await SentryLogger.setup(
true,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
const firstClient = SentryLogger.client;
const firstScope = SentryLogger.scope;
// Second setup should not change the client
await SentryLogger.setup(
true,
"test-id-2",
mockIdeInfo,
"test@continue.dev",
);
expect(SentryLogger.client).toBe(firstClient);
expect(SentryLogger.scope).toBe(firstScope);
expect(SentryLogger.uniqueId).toBe("test-id-2"); // ID should update
expect(SentryLogger.ideInfo).toBe(mockIdeInfo); // Info should update
process.env.NODE_ENV = originalNodeEnv;
});
});
describe("Lazy Initialization", () => {
it("should initialize when accessing lazyClient if conditions are met", () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
// Set up conditions for lazy initialization
SentryLogger.allowTelemetry = true;
SentryLogger.ideInfo = mockIdeInfo;
// Access lazy client should trigger initialization
const client = SentryLogger.lazyClient;
expect(client).toBeDefined();
expect(SentryLogger.client).toBe(client);
expect(SentryLogger.scope).toBeDefined();
process.env.NODE_ENV = originalNodeEnv;
});
it("should not initialize if telemetry is disabled", () => {
SentryLogger.allowTelemetry = false;
SentryLogger.ideInfo = mockIdeInfo;
const client = SentryLogger.lazyClient;
expect(client).toBeUndefined();
expect(SentryLogger.client).toBeUndefined();
expect(SentryLogger.scope).toBeUndefined();
});
it("should not initialize if ideInfo is missing", () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
SentryLogger.allowTelemetry = true;
SentryLogger.ideInfo = undefined;
const client = SentryLogger.lazyClient;
expect(client).toBeUndefined();
expect(SentryLogger.client).toBeUndefined();
process.env.NODE_ENV = originalNodeEnv;
});
});
describe("Shutdown Behavior", () => {
it("should properly shutdown when client exists", async () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
// Setup Sentry first
await SentryLogger.setup(
true,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
expect(SentryLogger.client).toBeDefined();
// Shutdown should clean up
SentryLogger.shutdownSentryClient();
expect(SentryLogger.client).toBeUndefined();
expect(SentryLogger.scope).toBeUndefined();
process.env.NODE_ENV = originalNodeEnv;
});
it("should handle shutdown gracefully when client is undefined", () => {
expect(() => SentryLogger.shutdownSentryClient()).not.toThrow();
expect(SentryLogger.client).toBeUndefined();
expect(SentryLogger.scope).toBeUndefined();
});
});
});
describe("Sentry Utility Functions", () => {
const mockIdeInfo: IdeInfo = {
extensionVersion: "1.0.0",
name: "vscode",
ideType: "vscode",
version: "1.0.0",
remoteName: "local",
isPrerelease: false,
};
beforeEach(() => {
// Reset SentryLogger state
SentryLogger.client = undefined;
SentryLogger.scope = undefined;
SentryLogger.allowTelemetry = false;
});
afterEach(() => {
SentryLogger.shutdownSentryClient();
});
describe("initializeSentry", () => {
it("should return undefined when telemetry is disabled", () => {
const result = initializeSentry();
expect(result.client).toBeUndefined();
expect(result.scope).toBeUndefined();
});
it("should return client and scope when telemetry is enabled", async () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
await SentryLogger.setup(
true,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
const result = initializeSentry();
expect(result.client).toBeDefined();
expect(result.scope).toBeDefined();
expect(result.client).toBe(SentryLogger.client);
expect(result.scope).toBe(SentryLogger.scope);
process.env.NODE_ENV = originalNodeEnv;
});
});
describe("createSpan", () => {
it("should execute callback normally when telemetry is disabled", () => {
const callback = jest.fn().mockReturnValue("test-result");
const result = createSpan("test.operation", "test span", callback);
expect(result).toBe("test-result");
expect(callback).toHaveBeenCalledTimes(1);
});
it("should execute callback with span when telemetry is enabled", async () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
await SentryLogger.setup(
true,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
const callback = jest.fn().mockReturnValue("test-result");
const result = createSpan("test.operation", "test span", callback);
expect(result).toBe("test-result");
expect(callback).toHaveBeenCalledTimes(1);
process.env.NODE_ENV = originalNodeEnv;
});
it("should handle async callbacks", async () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
await SentryLogger.setup(
true,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
const asyncCallback = jest.fn().mockResolvedValue("async-result");
const result = await createSpan(
"test.operation",
"test span",
asyncCallback,
);
expect(result).toBe("async-result");
expect(asyncCallback).toHaveBeenCalledTimes(1);
process.env.NODE_ENV = originalNodeEnv;
});
});
describe("captureException", () => {
it("should not throw when telemetry is disabled", () => {
const error = new Error("test error");
expect(() => captureException(error)).not.toThrow();
expect(() => captureException(error, { context: "test" })).not.toThrow();
});
it("should not throw when telemetry is enabled", async () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
await SentryLogger.setup(
true,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
const error = new Error("test error");
expect(() => captureException(error)).not.toThrow();
expect(() => captureException(error, { context: "test" })).not.toThrow();
process.env.NODE_ENV = originalNodeEnv;
});
it("should handle malformed context gracefully", async () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
await SentryLogger.setup(
true,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
const error = new Error("test error");
expect(() => captureException(error, null as any)).not.toThrow();
expect(() => captureException(error, undefined)).not.toThrow();
expect(() => captureException(error, { circular: {} })).not.toThrow();
process.env.NODE_ENV = originalNodeEnv;
});
});
describe("captureLog", () => {
it("should not throw when telemetry is disabled", () => {
expect(() => captureLog("test message")).not.toThrow();
expect(() =>
captureLog("test message", "info", { context: "test" }),
).not.toThrow();
});
it("should not throw when telemetry is enabled", async () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
await SentryLogger.setup(
true,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
expect(() => captureLog("test message")).not.toThrow();
expect(() =>
captureLog("test message", "error", { context: "test" }),
).not.toThrow();
process.env.NODE_ENV = originalNodeEnv;
});
it("should handle malformed context gracefully", async () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
await SentryLogger.setup(
true,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
expect(() =>
captureLog("test message", "info", null as any),
).not.toThrow();
expect(() =>
captureLog("test message", "warning", undefined),
).not.toThrow();
expect(() =>
captureLog("test message", "error", { circular: {} }),
).not.toThrow();
process.env.NODE_ENV = originalNodeEnv;
});
});
describe("Integration Tests", () => {
it("should maintain consistent state across utility functions", async () => {
const originalNodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = "development";
// Start with telemetry disabled
expect(initializeSentry().client).toBeUndefined();
const callback = jest.fn().mockReturnValue("result");
createSpan("test", "test", callback);
expect(callback).toHaveBeenCalled();
// Enable telemetry
await SentryLogger.setup(
true,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
// Now utility functions should work with Sentry
const sentryResult = initializeSentry();
expect(sentryResult.client).toBeDefined();
expect(sentryResult.scope).toBeDefined();
// Functions should work without throwing
const callback2 = jest.fn().mockReturnValue("result2");
const spanResult = createSpan("test2", "test2", callback2);
expect(spanResult).toBe("result2");
expect(callback2).toHaveBeenCalled();
const error = new Error("test error");
expect(() => captureException(error, { test: "context" })).not.toThrow();
expect(() =>
captureLog("test log message", "info", { test: "context" }),
).not.toThrow();
// Disable telemetry again
await SentryLogger.setup(
false,
"test-id",
mockIdeInfo,
"test@continue.dev",
);
expect(initializeSentry().client).toBeUndefined();
process.env.NODE_ENV = originalNodeEnv;
});
});
});
describe("Sentry Data Anonymization Tests", () => {
describe("anonymizeSentryEvent", () => {
it("should anonymize user file paths in stack traces", () => {
const event: any = {
exception: {
values: [
{
stacktrace: {
frames: [
{
filename: "/Users/john/workspace/my-project/src/app.js",
abs_path: "/Users/john/workspace/my-project/src/app.js",
function: "myFunction",
lineno: 42,
vars: { secret: "password123" },
pre_context: ["const secret = 'password123'"],
post_context: ["console.log(secret)"],
context_line: "throw new Error('test')",
},
],
},
},
],
},
};
const result = anonymizeSentryEvent(event);
expect(result).not.toBeNull();
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.filename,
).toBe("<file>");
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.abs_path,
).toBe("");
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.vars,
).toBeUndefined();
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.pre_context,
).toBeUndefined();
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.post_context,
).toBeUndefined();
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.context_line,
).toBe("<code>");
});
it("should anonymize all absolute file paths equally", () => {
const event: any = {
exception: {
values: [
{
stacktrace: {
frames: [
{
filename: "/Users/dev/continue/core/util/sentry.js",
abs_path: "/Users/dev/continue/core/util/sentry.js",
function: "captureException",
lineno: 42,
vars: { secret: "password123" },
pre_context: ["const secret = 'password123'"],
post_context: ["console.log(secret)"],
context_line: "throw new Error('test')",
},
],
},
},
],
},
};
const result = anonymizeSentryEvent(event);
expect(result).not.toBeNull();
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.filename,
).toBe("<file>");
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.abs_path,
).toBe("");
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.vars,
).toBeUndefined();
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.pre_context,
).toBeUndefined();
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.post_context,
).toBeUndefined();
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.context_line,
).toBe("<code>");
});
it("should preserve node_modules package names for debugging", () => {
const event: any = {
exception: {
values: [
{
stacktrace: {
frames: [
{
filename:
"/Users/dev/project/node_modules/@sentry/node/index.js",
abs_path:
"/Users/dev/project/node_modules/@sentry/node/index.js",
function: "init",
lineno: 123,
},
],
},
},
],
},
};
const result = anonymizeSentryEvent(event);
expect(result).not.toBeNull();
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.filename,
).toBe("node_modules/@sentry/<file>");
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.abs_path,
).toBe("");
});
it("should hash user IDs", () => {
const event: any = {
user: {
id: "real-machine-id-12345",
username: "john.doe",
email: "john@example.com",
ip_address: "192.168.1.100",
},
};
const result = anonymizeSentryEvent(event);
expect(result).not.toBeNull();
expect(result?.user?.id).not.toBe("real-machine-id-12345");
expect(result?.user?.id).toMatch(/^[a-f0-9]{8}$/); // Should be 8-char hash
expect(result?.user?.username).toBeUndefined();
expect(result?.user?.email).toBeUndefined();
expect(result?.user?.ip_address).toBeUndefined();
});
it("should preserve breadcrumbs unchanged", () => {
const event: any = {
breadcrumbs: [
{
message:
"File opened: /Users/john/Documents/secret-project/config.js",
category: "file",
data: {
filename: "/Users/john/Documents/secret-project/config.js",
action: "open",
},
},
{
message: "Error in module initialization",
category: "error",
data: {
module: "auth",
error: "Connection failed",
},
},
],
};
const result = anonymizeSentryEvent(event);
expect(result).not.toBeNull();
// Breadcrumbs are preserved as-is in our minimalist approach
expect(result?.breadcrumbs?.[0]?.message).toBe(
"File opened: /Users/john/Documents/secret-project/config.js",
);
expect(result?.breadcrumbs?.[0]?.data?.filename).toBe(
"/Users/john/Documents/secret-project/config.js",
);
expect(result?.breadcrumbs?.[0]?.data?.action).toBe("open");
expect(result?.breadcrumbs?.[1]?.message).toBe(
"Error in module initialization",
);
expect(result?.breadcrumbs?.[1]?.data?.module).toBe("auth");
expect(result?.breadcrumbs?.[1]?.data?.error).toBe("Connection failed");
});
it("should preserve tags unchanged", () => {
const event: any = {
tags: {
username: "john.doe",
user_id: "12345",
workspace: "/Users/john/workspace",
project_path: "/path/to/project",
environment: "production",
version: "1.2.3",
},
};
const result = anonymizeSentryEvent(event);
expect(result).not.toBeNull();
// Tags are preserved as-is in our minimalist approach
expect(result?.tags?.username).toBe("john.doe");
expect(result?.tags?.user_id).toBe("12345");
expect(result?.tags?.workspace).toBe("/Users/john/workspace");
expect(result?.tags?.project_path).toBe("/path/to/project");
expect(result?.tags?.environment).toBe("production");
expect(result?.tags?.version).toBe("1.2.3");
});
it("should preserve extra data unchanged", () => {
const event: any = {
extra: {
path: "/Users/john/secret-project",
filename: "config.js",
directory: "/home/user/workspace",
workspace: "/Users/john/workspace",
user: "john.doe",
home: "/Users/john",
config_file: "/some/long/path/to/config.json",
error_code: 500,
timestamp: "2023-01-01T00:00:00Z",
},
};
const result = anonymizeSentryEvent(event);
expect(result).not.toBeNull();
// Extra data is preserved as-is in our minimalist approach
expect(result?.extra?.path).toBe("/Users/john/secret-project");
expect(result?.extra?.filename).toBe("config.js");
expect(result?.extra?.directory).toBe("/home/user/workspace");
expect(result?.extra?.workspace).toBe("/Users/john/workspace");
expect(result?.extra?.user).toBe("john.doe");
expect(result?.extra?.home).toBe("/Users/john");
expect(result?.extra?.config_file).toBe("/some/long/path/to/config.json");
expect(result?.extra?.error_code).toBe(500);
expect(result?.extra?.timestamp).toBe("2023-01-01T00:00:00Z");
});
it("should anonymize thread stack traces", () => {
const event: any = {
threads: {
values: [
{
id: "main",
name: "MainThread",
stacktrace: {
frames: [
{
filename: "/Users/john/workspace/app.js",
abs_path: "/Users/john/workspace/app.js",
function: "main",
lineno: 1,
vars: { apiKey: "secret-key-123" },
context_line: "const apiKey = 'secret-key-123'",
},
],
},
},
],
},
};
const result = anonymizeSentryEvent(event);
expect(result).not.toBeNull();
expect(
result?.threads?.values?.[0]?.stacktrace?.frames?.[0]?.filename,
).toBe("<file>");
expect(
result?.threads?.values?.[0]?.stacktrace?.frames?.[0]?.abs_path,
).toBe("");
expect(
result?.threads?.values?.[0]?.stacktrace?.frames?.[0]?.vars,
).toBeUndefined();
expect(
result?.threads?.values?.[0]?.stacktrace?.frames?.[0]?.context_line,
).toBe("<code>");
});
it("should remove OS environment variables", () => {
const event: any = {
contexts: {
os: {
name: "macOS",
version: "12.6",
environment: {
HOME: "/Users/john",
USER: "john",
PATH: "/usr/local/bin:/usr/bin",
},
},
},
};
const result = anonymizeSentryEvent(event);
expect(result).not.toBeNull();
expect(result?.contexts?.os?.name).toBe("macOS");
expect(result?.contexts?.os?.version).toBe("12.6");
expect(result?.contexts?.os?.environment).toBeUndefined();
});
it("should handle events with no sensitive data", () => {
const event: any = {
message: "Simple error message",
level: "error",
timestamp: 1234567890,
tags: {
component: "auth",
level: "error",
},
extra: {
error_code: 404,
retry_count: 3,
},
};
const result = anonymizeSentryEvent(event);
expect(result).not.toBeNull();
expect(result?.message).toBe("Simple error message");
expect(result?.level).toBe("error");
expect(result?.timestamp).toBe(1234567890);
expect(result?.tags?.component).toBe("auth");
expect(result?.extra?.error_code).toBe(404);
});
it("should handle malformed events gracefully", () => {
const malformedEvent: any = {
exception: {
values: null,
},
user: null,
breadcrumbs: "not-an-array",
tags: null,
extra: null,
};
const result = anonymizeSentryEvent(malformedEvent);
expect(result).not.toBeNull();
});
it("should handle anonymization errors by returning null", () => {
// Create a circular reference that would cause JSON serialization issues
const circularEvent: any = {
message: "Test event",
};
circularEvent.circular = circularEvent;
// Mock the anonymization to throw an error
const originalConsoleError = console.error;
console.error = jest.fn();
const result = anonymizeSentryEvent(circularEvent);
// Should not throw, but should return null for safety
expect(result).not.toBeNull(); // Actually, our function might handle this case
console.error = originalConsoleError;
});
it("should anonymize all absolute paths regardless of format", () => {
const event: any = {
exception: {
values: [
{
stacktrace: {
frames: [
{
filename:
"C:\\Users\\dev\\continue\\extensions\\vscode\\src\\extension.js",
abs_path:
"C:\\Users\\dev\\continue\\extensions\\vscode\\src\\extension.js",
},
{
filename: "/home/dev/continue/core/util/sentry.js",
abs_path: "/home/dev/continue/core/util/sentry.js",
},
{
filename: "relative/path/file.js",
abs_path: "/absolute/path/file.js",
},
],
},
},
],
},
};
const result = anonymizeSentryEvent(event);
expect(result).not.toBeNull();
// All absolute paths get anonymized equally
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.filename,
).toBe("<file>");
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[1]?.filename,
).toBe("<file>");
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[2]?.filename,
).toBe("relative/path/file.js"); // Relative path preserved
// All abs_path fields cleared
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[0]?.abs_path,
).toBe("");
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[1]?.abs_path,
).toBe("");
expect(
result?.exception?.values?.[0]?.stacktrace?.frames?.[2]?.abs_path,
).toBe("");
});
});
});

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