cmd+I improvements (#1728)

* Nate/control plane client (#1691)

* docs: add docs and schema for "OS" provider (#1536)

* ignore .env

* fix(gui): ctx rendering w/ renderInlineAs: "" (#1541)

* ✨ use and cache imports for autocomplete (#1456)

* ✨ use and cache imports for autocomplete

* fix tsc

* fix codeqwen autocomplete leading space

* add voyage rerank-1

* feat: `--noEmit` for tsc checks in CI (#1559)

* docs: update CustomContextProvider docs (#1557)

* add stop tokens to qwen prompt

* update docs to reflect 3.5 sonnet being best

* docs: comment out unused providers (#1561)

* import Handlebars

* feat: toast notification for config updates (#1560)

* feat: toast notification for config updates

* feat: only trigger toast on config.json save

* displayRawMarkdown option

* feat: open pane on install (#1564)

* feat: open pane on activation

* comment out testing code

* update to reflect 16 stop words limit for deepseek

* feat: only trigger config update toast in vscode (#1571)

* docs(prompt-files): fix typos + clarify (#1575)

* doc: prompt file typo + clarifications

* fix: add back correct docs

* chore: add telemetry for pageviews (#1576)

* feat: update onboarding w/ embeddings model (#1570)

* chore(gui): remove unused pages

* feat: add embeddings step

* feat: update styles

* feat: copy button updates

* fix: correct pull command for embed model

* fix: remove commented code

* fix: remove commented code

* feat: simplify copy btn props

* chore: rename onboarding selection event

* feat: add provider config

* fix: undo msg name

* remove dead code

* fix: invalid mode check

* fix: remove testing logic

* docs(telemetry): add pageviews to tracking list (#1581)

* Add reranker configuration options to codebase embedding docs (#1584)

- Introduce reranker concept
- List available reranker options
- Provide configuration instructions
- Update keywords to include "reranker"

* chore: update pr template with screenshots (#1590)

* Refactor ConfirmationDialog to use SecondaryButton for cancel action (#1586)

* Added instructions for running docs server locally (#1578)

- Added NPM script method
- Added VS Code task method
- Update contributing guidelines

* Update branch policy (#1577)

- Change PR target to `dev` branch
- Update `CONTRIBUTING.md` instructions

* Consolidate example configurations into the main configuration guide (#1579)

- Moved examples to configuration.md
- Deleted the separate examples.md file
- Updated sidebar order and links
- Improved readability and structure in configuration.md

* fix: fullscreen gui retains context when hidden, fixed fullscreen focusing (#1582)

* Update completionProvider.ts (warning tab-autocomplete models) (#1566)

* feat: enhanced IndexingProgressBar with blinking dot feature

- Integrated BlinkingDot component
- Added STATUS_COLORS for various states
- Replaced CircleDiv with BlinkingDot in UI
- Updated status messages and layout

* small UI tweaks

* feat(gui): enhance ModelCard, ModelProviderTag, and Toggle components (#1595)

- add styling and adjustments to ModelCard
- update ModelProviderTag font size
- remove box shadow from Toggle component
- tweak icon styles in ModelCard
- improve alignment and spacing

* media query

* feat: add best experience onboarding

* fix: file rename

* stop movement on button hover by keeping same border thickness

* fix mistake in setting cursor: pointer

* fix when free trial option is shown

* Support Node.js versions below 20 for streaming response handling (#1591)

- Add fallback for Node < 20
- Implement toAsyncIterable for streaming
- Use TextDecoder for manual decoding
- Maintain existing streaming for Node 20+

* small fixes

* feat: add free trial card to onboarding (#1600)

* feat: add free trial card to onboarding

* add import

* fix hasPassedFTL

* fix /edit cancellation from UI

* feat: add `applyCodeBlock` experimental prop (#1601)

* feat: add new model styling improvements (#1609)

* feat: add new model styling improvements

* better gap size

* feat: update bug_report.yml (#1610)

* chore: update bug_report.yml

* typo fix

* feat: add labels to "Add docs" dialog (#1612)

* feat: add labels to "Add docs" dialog

* remove autofocus

* don't double load config

* small fixes

* speed up directory traversal, and use correct native path module

* option not to show config update toast

* merge air-gapped and recommended setup pages

* chore: add telemetry for full screen toggle (#1618)

* Fix headings in codebase-embeddings.md (#1617)

* mention jetbrains

* docs: update changie  (#1619)

* feat: updated changie config

* hide toc and autogenerate

* Update changelog.mdx

* link to deeper explanation of embeddings models

* ensure target="_blank" for all links in sidebar

* fix gif links in intellij README.md

* don't require rust in dependency installation

* chore: fix padding on gh button (#1620)

* chore: adjust button padding

* Update tasks.json

* escape colons in diff path

* smoother lancedb indexing reporting

* smooth progress updates for indexing

* fix tsc err

* rerank-lite-1

* remove doccs

* basic tests for VS Code extension

* improved testing of VS Code extension

* docs: add docs and schema for "OS" provider (#1536)

* ignore .env

* 🚑 fix constant warnings when onboarding with Ollama

* ✨ use and cache imports for autocomplete (#1456)

* ✨ use and cache imports for autocomplete

* fix tsc

* team analytics

* apply control plane settings

* workos auth

* ide protocol get session info

* UI for auth

* profile switching

* small fixes

* updates

* refresh tokens

* updates

* fix tsc errs

* model select in toolbar to make room for profile selector

* prod client id

* link to prod URL

* internal beta option

* profiles change listener

---------

Co-authored-by: Patrick Erichsen <patrick.a.erichsen@gmail.com>
Co-authored-by: Priyash <38959321+priyashpatil@users.noreply.github.com>
Co-authored-by: Jonah Wagner <jonahwagner231@gmail.com>
Co-authored-by: YohannZe <99359799+YohannZe@users.noreply.github.com>
Co-authored-by: Dan Dascalescu <ddascalescu+github@gmail.com>

* temporary patch for type errs

* Dev (#1689)

* Fix an issue where CMD+K does not clear the terminal when the terminal has focus (#1671)

On MacOS, ⌘+K is bound, by default, to Terminal:Clear. Without this
change ⌘+K does not clear the terminal but instead iniates a chord
sequence and waits for the next stroke of the chord.

Co-authored-by: Rob Leidle <rleidle@tesla.com>

* Change treeSitter to cache the Language objects it loads from wasm (#1672)

Without this change, for a repository with 600 typescript files, the
indexer would fail to finish correctly and there would be many of the
following errors in the webview console log:

'Unable to load language for file ${path} RuntimeError: table index is out of bounds'

The following bash will create a repo that reproduces the problem:

current_path="."

for ((i=1; i<=20; i++)); do
    new_folder="folder-$i"
    mkdir -p "$current_path/$new_folder"
    current_path="$current_path/$new_folder"

    for ((a=1; a<=30; a++)); do
      head -c 10000 /dev/urandom | base64 > "$current_path/file-$a.ts"
    done
done

Co-authored-by: Rob Leidle <rleidle@tesla.com>

* acknowledge sourcemap flag in esbuild.js

* don't run jetbrains-release.yaml on vscode releases

* further testing for walkDir

* chore: add telemetry to commands (#1673)

* test: Add basic unit test to baseLLM (#1668)

* update version

* test: Add basic unit test to baseLLM

---------

Co-authored-by: Nate Sesti <sestinj@gmail.com>
Co-authored-by: inimaz <imaz@ai-verse.com>

* feat: add Quick Actions CodeLens feature (#1674)

* docs: add docs and schema for "OS" provider (#1536)

* ignore .env

* ✨ use and cache imports for autocomplete (#1456)

* ✨ use and cache imports for autocomplete

* fix tsc

* add voyage rerank-1

* import Handlebars

* feat: open pane on install (#1564)

* feat: open pane on activation

* comment out testing code

* chore: add telemetry for pageviews (#1576)

* feat: update onboarding w/ embeddings model (#1570)

* chore(gui): remove unused pages

* feat: add embeddings step

* feat: update styles

* feat: copy button updates

* fix: correct pull command for embed model

* fix: remove commented code

* fix: remove commented code

* feat: simplify copy btn props

* chore: rename onboarding selection event

* feat: add provider config

* fix: undo msg name

* remove dead code

* fix: invalid mode check

* fix: remove testing logic

* fix: fullscreen gui retains context when hidden, fixed fullscreen focusing (#1582)

* small UI tweaks

* media query

* feat: add best experience onboarding

* small fixes

* feat: add free trial card to onboarding (#1600)

* feat: add free trial card to onboarding

* add import

* chore: add telemetry for full screen toggle (#1618)

* rerank-lite-1

* remove doccs

* basic tests for VS Code extension

* improved testing of VS Code extension

* manually implement stop tokens for hf inference api

* chore: onboarding metrics (#1626)

* fix: pageview tracking

* feat: add onboarding telemetry

* create single `onboardingStatus` type

* improved var naming

* remove console logs

* fix windows performance issue

* rename vscodeExtension.ts

* migration of onboarding variables

* "stash" instead of "delete" in indexing progress

* fix preview.yaml

* also fix main.yaml

* Update troubleshooting.md (#1637)

* feat: add quick actions

* Update index.d.ts

* quick actions mvp

* update docs

* subscribe to vscode change settings

* Update commands.ts

* cleanup

* Update quick-actions.md

* Update VerticalPerLineCodeLensProvider.ts

* resolve feedback

---------

Co-authored-by: Nate Sesti <sestinj@gmail.com>
Co-authored-by: Nate Sesti <33237525+sestinj@users.noreply.github.com>
Co-authored-by: Jonah Wagner <jonahwagner231@gmail.com>

* chore: add `isCommandEvent` to command telemetry (#1675)

* chore: add `isCommandEvent` to command telemetry

* Update commands.ts

* Nate/better retrieval (#1677)

* deduplicatearray tests

* break out separate retrieval pipelines

* IConfigHandler

* tests for codebase indexer

* better .continueignore for continue

* indexing fixes

* ignore .gitignore and .continueignore when indexing

* retrieval pipeline improvements

* fix formatting err in out .continueignore

* add necessary filter to lance_db_cache

* update package.json version

* skip unused tests

* don't ignore .prompt files

* update version

* Update pull_request_template.md

* don't use multi-media format when there are multiple text items

* add free trial experience (#1685)

* fix: add code range for quick actions/fixes (#1687)

* fix: add code range for quick actions/fixes

* Update test.js

* add pathSep message type

* docs improvements

* jetbrains fix

* update package.json version

---------

Co-authored-by: Rob Leidle <rleidle@gmail.com>
Co-authored-by: Rob Leidle <rleidle@tesla.com>
Co-authored-by: Patrick Erichsen <patrick.a.erichsen@gmail.com>
Co-authored-by: inimaz <49730431+inimaz@users.noreply.github.com>
Co-authored-by: inimaz <imaz@ai-verse.com>
Co-authored-by: Jonah Wagner <jonahwagner231@gmail.com>
Co-authored-by: Priyash <38959321+priyashpatil@users.noreply.github.com>

* update package.json version

* skip extension tests

* update package.json version

* handlebars import

* don't push package.json version change from CI

* fix: scroll issues w/ code blocks (#1688)

* fix: scroll issues w/ code blocks

* chore: name offset

* chore: remove docs start

* chore: update headings on troubleshooting.md (#1696)

* ignore .svn folder for indexing (#1699)

* chore: clearer naming for `useSuffix` (#1702)

* chore: clearer naming for `useSuffix`

* schema updates

* fix: cmd+shft+l closes sidebar if focused (#1638)

* docs: add docs and schema for "OS" provider (#1536)

* ignore .env

* ✨ use and cache imports for autocomplete (#1456)

* ✨ use and cache imports for autocomplete

* fix tsc

* add voyage rerank-1

* import Handlebars

* feat: open pane on install (#1564)

* feat: open pane on activation

* comment out testing code

* chore: add telemetry for pageviews (#1576)

* feat: update onboarding w/ embeddings model (#1570)

* chore(gui): remove unused pages

* feat: add embeddings step

* feat: update styles

* feat: copy button updates

* fix: correct pull command for embed model

* fix: remove commented code

* fix: remove commented code

* feat: simplify copy btn props

* chore: rename onboarding selection event

* feat: add provider config

* fix: undo msg name

* remove dead code

* fix: invalid mode check

* fix: remove testing logic

* fix: fullscreen gui retains context when hidden, fixed fullscreen focusing (#1582)

* small UI tweaks

* media query

* feat: add best experience onboarding

* small fixes

* feat: add free trial card to onboarding (#1600)

* feat: add free trial card to onboarding

* add import

* chore: add telemetry for full screen toggle (#1618)

* rerank-lite-1

* remove doccs

* basic tests for VS Code extension

* improved testing of VS Code extension

* manually implement stop tokens for hf inference api

* chore: onboarding metrics (#1626)

* fix: pageview tracking

* feat: add onboarding telemetry

* create single `onboardingStatus` type

* improved var naming

* remove console logs

* fix windows performance issue

* rename vscodeExtension.ts

* migration of onboarding variables

* "stash" instead of "delete" in indexing progress

* fix preview.yaml

* also fix main.yaml

* Update troubleshooting.md (#1637)

* feat: close panel if main input is focused

* add skip param

* Update TipTapEditor.tsx

* merge dev

* Update commands.ts

---------

Co-authored-by: Nate Sesti <sestinj@gmail.com>
Co-authored-by: Nate Sesti <33237525+sestinj@users.noreply.github.com>
Co-authored-by: Jonah Wagner <jonahwagner231@gmail.com>

* bugfix: quick actions undefined array (#1704)

* feat: add rich quick pick for quick edit (#1706)

* feat: multistep quick pick

* fix: multi step for context provider

* Update test.js

* Create deepseek.md (#1708)

* style: add max height to model selector (#1712)

* update styling

* remove testing code

* remove comments

* feat: add tutorial card (#1716)

* feat: create tutorial card

* Update TutorialCard.tsx

* feat: add file search to quick edit (#1714)

* feat: multistep quick pick

* fix: multi step for context provider

* Update test.js

* add file search

* complete file search

* remove unused import

* add comments

* Update utils.ts

* update naming

* chore: move quick pick instantiation (#1723)

* Break out into NPM modules (#1726)

* config.json types

* export all schemas

* break out request logic into packages

* update openai adapters to export body types

* update packaging of npm modules

* update packages

* continue proxy

* mistral

* Fix typo in documentation (#1722)

In  set-up-codestral.md
"Trobleshooting" -> "Troubleshooting"

* update package.json version

* 🪄 model dropdown, control plane (#1692)

* Nate/control plane client (#1691)

* docs: add docs and schema for "OS" provider (#1536)

* ignore .env

* fix(gui): ctx rendering w/ renderInlineAs: "" (#1541)

* ✨ use and cache imports for autocomplete (#1456)

* ✨ use and cache imports for autocomplete

* fix tsc

* fix codeqwen autocomplete leading space

* add voyage rerank-1

* feat: `--noEmit` for tsc checks in CI (#1559)

* docs: update CustomContextProvider docs (#1557)

* add stop tokens to qwen prompt

* update docs to reflect 3.5 sonnet being best

* docs: comment out unused providers (#1561)

* import Handlebars

* feat: toast notification for config updates (#1560)

* feat: toast notification for config updates

* feat: only trigger toast on config.json save

* displayRawMarkdown option

* feat: open pane on install (#1564)

* feat: open pane on activation

* comment out testing code

* update to reflect 16 stop words limit for deepseek

* feat: only trigger config update toast in vscode (#1571)

* docs(prompt-files): fix typos + clarify (#1575)

* doc: prompt file typo + clarifications

* fix: add back correct docs

* chore: add telemetry for pageviews (#1576)

* feat: update onboarding w/ embeddings model (#1570)

* chore(gui): remove unused pages

* feat: add embeddings step

* feat: update styles

* feat: copy button updates

* fix: correct pull command for embed model

* fix: remove commented code

* fix: remove commented code

* feat: simplify copy btn props

* chore: rename onboarding selection event

* feat: add provider config

* fix: undo msg name

* remove dead code

* fix: invalid mode check

* fix: remove testing logic

* docs(telemetry): add pageviews to tracking list (#1581)

* Add reranker configuration options to codebase embedding docs (#1584)

- Introduce reranker concept
- List available reranker options
- Provide configuration instructions
- Update keywords to include "reranker"

* chore: update pr template with screenshots (#1590)

* Refactor ConfirmationDialog to use SecondaryButton for cancel action (#1586)

* Added instructions for running docs server locally (#1578)

- Added NPM script method
- Added VS Code task method
- Update contributing guidelines

* Update branch policy (#1577)

- Change PR target to `dev` branch
- Update `CONTRIBUTING.md` instructions

* Consolidate example configurations into the main configuration guide (#1579)

- Moved examples to configuration.md
- Deleted the separate examples.md file
- Updated sidebar order and links
- Improved readability and structure in configuration.md

* fix: fullscreen gui retains context when hidden, fixed fullscreen focusing (#1582)

* Update completionProvider.ts (warning tab-autocomplete models) (#1566)

* feat: enhanced IndexingProgressBar with blinking dot feature

- Integrated BlinkingDot component
- Added STATUS_COLORS for various states
- Replaced CircleDiv with BlinkingDot in UI
- Updated status messages and layout

* small UI tweaks

* feat(gui): enhance ModelCard, ModelProviderTag, and Toggle components (#1595)

- add styling and adjustments to ModelCard
- update ModelProviderTag font size
- remove box shadow from Toggle component
- tweak icon styles in ModelCard
- improve alignment and spacing

* media query

* feat: add best experience onboarding

* fix: file rename

* stop movement on button hover by keeping same border thickness

* fix mistake in setting cursor: pointer

* fix when free trial option is shown

* Support Node.js versions below 20 for streaming response handling (#1591)

- Add fallback for Node < 20
- Implement toAsyncIterable for streaming
- Use TextDecoder for manual decoding
- Maintain existing streaming for Node 20+

* small fixes

* feat: add free trial card to onboarding (#1600)

* feat: add free trial card to onboarding

* add import

* fix hasPassedFTL

* fix /edit cancellation from UI

* feat: add `applyCodeBlock` experimental prop (#1601)

* feat: add new model styling improvements (#1609)

* feat: add new model styling improvements

* better gap size

* feat: update bug_report.yml (#1610)

* chore: update bug_report.yml

* typo fix

* feat: add labels to "Add docs" dialog (#1612)

* feat: add labels to "Add docs" dialog

* remove autofocus

* don't double load config

* small fixes

* speed up directory traversal, and use correct native path module

* option not to show config update toast

* merge air-gapped and recommended setup pages

* chore: add telemetry for full screen toggle (#1618)

* Fix headings in codebase-embeddings.md (#1617)

* mention jetbrains

* docs: update changie  (#1619)

* feat: updated changie config

* hide toc and autogenerate

* Update changelog.mdx

* link to deeper explanation of embeddings models

* ensure target="_blank" for all links in sidebar

* fix gif links in intellij README.md

* don't require rust in dependency installation

* chore: fix padding on gh button (#1620)

* chore: adjust button padding

* Update tasks.json

* escape colons in diff path

* smoother lancedb indexing reporting

* smooth progress updates for indexing

* fix tsc err

* rerank-lite-1

* remove doccs

* basic tests for VS Code extension

* improved testing of VS Code extension

* docs: add docs and schema for "OS" provider (#1536)

* ignore .env

* 🚑 fix constant warnings when onboarding with Ollama

* ✨ use and cache imports for autocomplete (#1456)

* ✨ use and cache imports for autocomplete

* fix tsc

* team analytics

* apply control plane settings

* workos auth

* ide protocol get session info

* UI for auth

* profile switching

* small fixes

* updates

* refresh tokens

* updates

* fix tsc errs

* model select in toolbar to make room for profile selector

* prod client id

* link to prod URL

* internal beta option

* profiles change listener

---------

Co-authored-by: Patrick Erichsen <patrick.a.erichsen@gmail.com>
Co-authored-by: Priyash <38959321+priyashpatil@users.noreply.github.com>
Co-authored-by: Jonah Wagner <jonahwagner231@gmail.com>
Co-authored-by: YohannZe <99359799+YohannZe@users.noreply.github.com>
Co-authored-by: Dan Dascalescu <ddascalescu+github@gmail.com>

* temporary patch for type errs

---------

Co-authored-by: Patrick Erichsen <patrick.a.erichsen@gmail.com>
Co-authored-by: Priyash <38959321+priyashpatil@users.noreply.github.com>
Co-authored-by: Jonah Wagner <jonahwagner231@gmail.com>
Co-authored-by: YohannZe <99359799+YohannZe@users.noreply.github.com>
Co-authored-by: Dan Dascalescu <ddascalescu+github@gmail.com>

* skip extension tests

---------

Co-authored-by: Patrick Erichsen <patrick.a.erichsen@gmail.com>
Co-authored-by: Priyash <38959321+priyashpatil@users.noreply.github.com>
Co-authored-by: Jonah Wagner <jonahwagner231@gmail.com>
Co-authored-by: YohannZe <99359799+YohannZe@users.noreply.github.com>
Co-authored-by: Dan Dascalescu <ddascalescu+github@gmail.com>
Co-authored-by: Rob Leidle <rleidle@gmail.com>
Co-authored-by: Rob Leidle <rleidle@tesla.com>
Co-authored-by: inimaz <49730431+inimaz@users.noreply.github.com>
Co-authored-by: inimaz <imaz@ai-verse.com>
Co-authored-by: Anaël Bonnafous <71386173+AnaelBonnafous@users.noreply.github.com>
Co-authored-by: Huy Tran <119860259+tranquochuy645@users.noreply.github.com>
This commit is contained in:
Nate Sesti 2024-07-12 00:49:24 -07:00 • committed by GitHub
parent 3ebd3375ee
commit ed37dcfb7a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
71 changed files with 8842 additions and 638 deletions

View file

@ -231,22 +231,22 @@ jobs:
npx ovsx publish -p ${{ secrets.VSX_REGISTRY_TOKEN }} --packagePath ../../alpine-x64/*.vsix ../../darwin-arm64/*.vsix ../../darwin-x64/*.vsix ../../linux-arm64/*.vsix ../../linux-armhf/*.vsix ../../linux-x64/*.vsix ../../win32-x64/*.vsix ../../win32-arm64/*.vsix
# 4. Update the package.json version and push changes
- name: Update version in package.json
run: |
cd extensions/vscode
npm version patch
# - 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: 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 }}
# - name: Push changes
# uses: ad-m/github-push-action@master
# with:
# github_token: ${{ secrets.GITHUB_TOKEN }}
# branch: ${{ github.ref }}
# 5 Send to Discord Webhook
- name: Discord Commits

View file

@ -223,19 +223,19 @@ jobs:
npx ovsx publish --pre-release -p ${{ secrets.VSX_REGISTRY_TOKEN }} --packagePath ../../alpine-x64/*.vsix ../../darwin-arm64/*.vsix ../../darwin-x64/*.vsix ../../linux-arm64/*.vsix ../../linux-armhf/*.vsix ../../linux-x64/*.vsix ../../win32-x64/*.vsix ../../win32-arm64/*.vsix
# 4. Update the package.json version and push changes
- name: Update version in package.json
run: |
cd extensions/vscode
npm version patch
# - 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: 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 }}
# - name: Push changes
# uses: ad-m/github-push-action@master
# with:
# github_token: ${{ secrets.GITHUB_TOKEN }}
# branch: ${{ github.ref }}

View file

@ -90,7 +90,7 @@ This is just another object like the ones in the `"models"` array of `config.jso
This object allows you to customize the behavior of tab-autocomplete. The available options are:
- `useCopyBuffer`: Determines whether the copy buffer will be considered when constructing the prompt. (Boolean)
- `useSuffix`: Determines whether to use the file suffix in the prompt. (Boolean)
- `useFileSuffix`: Determines whether to use the file suffix in the prompt. (Boolean)
- `maxPromptTokens`: The maximum number of prompt tokens to use. A smaller number will yield faster completions, but less context. (Number)
- `debounceDelay`: The delay in milliseconds before triggering autocomplete after a keystroke. (Number)
- `maxSuffixPercentage`: The maximum percentage of the prompt that can be dedicated to the suffix. (Number)

View file

@ -1,3 +1,4 @@
import { ConfigJson } from "@continuedev/config-types";
import {
ContinueConfig,
IDE,
@ -5,8 +6,8 @@ import {
SerializedContinueConfig,
} from "../..";
import { ControlPlaneClient } from "../../control-plane/client";
import { ControlPlaneSettings } from "../../control-plane/schema";
import { TeamAnalytics } from "../../control-plane/TeamAnalytics";
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy";
import { Telemetry } from "../../util/posthog";
import {
defaultContextProvidersJetBrains,
@ -26,7 +27,7 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
readonly profileId: string;
profileTitle: string;
workspaceSettings: ControlPlaneSettings | undefined;
workspaceSettings: ConfigJson | undefined;
constructor(
private readonly workspaceId: string,
@ -55,13 +56,8 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
this.profileId,
)) as any);
// First construct a SerializedContinueConfig from the ControlPlaneSettings
const serializedConfig: SerializedContinueConfig = {
models: settings.models,
tabAutocompleteModel: settings.tabAutocompleteModel,
embeddingsProvider: settings.embeddingsModel,
reranker: settings.reranker,
};
// First construct a SerializedContinueConfig from the ControlPlaneSettings (TODO)
const serializedConfig: SerializedContinueConfig = settings;
serializedConfig.contextProviders ??=
ideInfo.ideType === "vscode"
@ -94,6 +90,16 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
ideInfo.extensionVersion,
);
[
...finalConfig.models,
...(finalConfig.tabAutocompleteModels ?? []),
].forEach(async (model) => {
if (model.providerName === "continue-proxy") {
const accessToken = await this.controlPlaneClient.getAccessToken();
(model as ContinueProxy).workOsAccessToken = accessToken;
}
});
return finalConfig;
}

View file

@ -676,7 +676,7 @@ declare global {
export interface TabAutocompleteOptions {
disable: boolean;
useCopyBuffer: boolean;
useSuffix: boolean;
useFileSuffix: boolean;
maxPromptTokens: number;
debounceDelay: number;
maxSuffixPercentage: number;

View file

@ -1,5 +1,5 @@
import { Analytics } from "@continuedev/config-types";
import os from "node:os";
import { ControlPlaneAnalytics } from "./schema";
export class TeamAnalytics {
static client: any = undefined;
@ -24,7 +24,7 @@ export class TeamAnalytics {
}
static async setup(
config: ControlPlaneAnalytics,
config: Analytics,
uniqueId: string,
extensionVersion: string,
) {

View file

@ -1,6 +1,6 @@
import { ConfigJson } from "@continuedev/config-types";
import fetch, { RequestInit, Response } from "node-fetch";
import { ModelDescription } from "..";
import { ControlPlaneSettings } from "./schema";
export interface ControlPlaneSessionInfo {
accessToken: string;
@ -13,7 +13,7 @@ export interface ControlPlaneSessionInfo {
export interface ControlPlaneWorkspace {
id: string;
name: string;
settings: ControlPlaneSettings;
settings: ConfigJson;
}
export interface ControlPlaneModelDescription extends ModelDescription {}
@ -40,7 +40,7 @@ export class ControlPlaneClient {
);
}
private async getAccessToken(): Promise<string | undefined> {
async getAccessToken(): Promise<string | undefined> {
return (await this.sessionInfoPromise)?.accessToken;
}
@ -78,9 +78,7 @@ export class ControlPlaneClient {
return (await resp.json()) as any;
}
async getSettingsForWorkspace(
workspaceId: string,
): Promise<ControlPlaneSettings> {
async getSettingsForWorkspace(workspaceId: string): Promise<ConfigJson> {
const userId = await this.userId;
if (!userId) {
throw new Error("No user id");

2
core/index.d.ts vendored
View file

@ -769,7 +769,7 @@ export interface Reranker {
export interface TabAutocompleteOptions {
disable: boolean;
useCopyBuffer: boolean;
useSuffix: boolean;
useFileSuffix: boolean;
maxPromptTokens: number;
debounceDelay: number;
maxSuffixPercentage: number;

View file

@ -65,7 +65,7 @@ export class LanceDbIndex implements CodebaseIndex {
"lancedb_sqlite_artifact_id_column",
async () => {
await db.exec(
`ALTER TABLE lance_db_cache ADD COLUMN artifact_id TEXT NOT NULL DEFAULT 'UNDEFINED'`,
"ALTER TABLE lance_db_cache ADD COLUMN artifact_id TEXT NOT NULL DEFAULT 'UNDEFINED'",
);
resolve(undefined);
},

View file

@ -69,6 +69,7 @@ export const DEFAULT_IGNORE_FILETYPES = [
export const defaultIgnoreFile = ignore().add(DEFAULT_IGNORE_FILETYPES);
export const DEFAULT_IGNORE_DIRS = [
".git",
".svn",
".vscode",
".idea",
".vs",

View file

@ -2,9 +2,22 @@ import type { LLMOptions, ModelProvider } from "../../..";
import OpenAI from "../OpenAI.js";
class ContinueProxy extends OpenAI {
private _workOsAccessToken: string | undefined = undefined;
get workOsAccessToken(): string | undefined {
return this._workOsAccessToken;
}
set workOsAccessToken(value: string | undefined) {
if (this._workOsAccessToken !== value) {
this._workOsAccessToken = value;
this.apiKey = value;
}
}
static providerName: ModelProvider = "continue-proxy";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "http://localhost:3000/proxy/v1",
apiBase:
"https://control-plane-api-service-i3dqylpbqa-uc.a.run.app/model-proxy/v1",
};
supportsFim(): boolean {

View file

@ -11,6 +11,7 @@
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.574.0",
"@aws-sdk/credential-providers": "^3.596.0",
"@continuedev/config-types": "^1.0.6",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@types/jsdom": "^21.1.6",
@ -3928,6 +3929,14 @@
"node": ">=14.21.3"
}
},
"node_modules/@continuedev/config-types": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/@continuedev/config-types/-/config-types-1.0.6.tgz",
"integrity": "sha512-JTlaGtsNW9vfSPcDJBn+I2vcs0wWRFIQcN3sa6pBFg2fj8W6qcMZoYUdzoU/+X+2ZT8OKcbomWfP2+qW0uuy6A==",
"dependencies": {
"zod": "^3.23.8"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.17.19",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.17.19.tgz",

View file

@ -31,6 +31,7 @@
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.574.0",
"@aws-sdk/credential-providers": "^3.596.0",
"@continuedev/config-types": "^1.0.6",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@types/jsdom": "^21.1.6",

View file

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/naming-convention */
import type {
BrowserSerializedContinueConfig,
ChatMessage,

View file

@ -54,5 +54,6 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
"indexProgress",
"addContextItem",
"refreshSubmenuItems",
"isContinueInputFocused",
"didChangeAvailableProfiles",
];

View file

@ -5,6 +5,7 @@ export type ToWebviewFromIdeOrCoreProtocol = {
getDefaultModelTitle: [undefined, string];
indexProgress: [IndexingProgressUpdate, void];
refreshSubmenuItems: [undefined, void];
isContinueInputFocused: [undefined, boolean];
addContextItem: [
{
historyIndex: number;

View file

@ -3,7 +3,7 @@ import { TabAutocompleteOptions } from "../index.js";
export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = {
disable: false,
useCopyBuffer: false,
useSuffix: true,
useFileSuffix: true,
maxPromptTokens: 1024,
prefixPercentage: 0.85,
maxSuffixPercentage: 0.25,

View file

@ -0,0 +1,16 @@
# DeepSeek
To setup DeepSeek, obtain an API key from [here](https://www.deepseek.com/) and add the following to your `config.json` file:
```json title="~/.continue/config.json"
{
"models": [
{
"title": "Deepseek",
"provider": "deepseek",
"model": "deepseek-code", // Or any other DeepSeek model
"apiKey": "YOUR_API_KEY"
}
]
}
```

View file

@ -67,11 +67,11 @@ If your keyboard shortcuts are not resolving, you may have other commands that a
- [VSCode keyboard shortcuts docs](https://code.visualstudio.com/docs/getstarted/keybindings)
- [IntelliJ keyboard shortcut docs](https://www.jetbrains.com/help/idea/configuring-keyboard-and-mouse-shortcuts.html)
# FAQs
## FAQs
## Networking Issues
### Networking Issues
### Configure Certificates
#### Configure Certificates
If you're seeing a `fetch failed` error and your network requires custom certificates, you will need to configure them in `config.json`. In each of the objects in the `"models"` array, add `requestOptions.caBundlePath` like this:
@ -92,22 +92,22 @@ If you're seeing a `fetch failed` error and your network requires custom certifi
You may also set `requestOptions.caBundlePath` to an array of paths to multiple certificates.
### VS Code Proxy Settings
#### VS Code Proxy Settings
If you are using VS Code and require requests to be made through a proxy, you are likely already set up through VS Code's [Proxy Server Support](https://code.visualstudio.com/docs/setup/network#_proxy-server-support). To double-check that this is enabled, use cmd/ctrl+, to open settings and search for "Proxy Support". Unless it is set to "off", then VS Code is responsible for making the request to the proxy.
### code-server
#### code-server
Continue can be used in [code-server](https://coder.com/), but if you are running across an error in the logs that includes "This is likely because the editor is not running in a secure context", please see [their documentation on securely exposing code-server](https://coder.com/docs/code-server/latest/guide#expose-code-server).
## I installed Continue, but don't see the sidebar window
### I installed Continue, but don't see the sidebar window
By default the Continue window is on the left side of VS Code, but it can be dragged to right side as well, which we recommend in our tutorial. In the situation where you have previously installed Continue and moved it to the right side, it may still be there. You can reveal Continue either by using cmd/ctrl+L or by clicking the button in the top right of VS Code to open the right sidebar.
## I'm getting a 404 error from OpenAI
### I'm getting a 404 error from OpenAI
If you have entered a valid API key and model, but are still getting a 404 error from OpenAI, this may be because you need to add credits to your billing account. You can do so from the [billing console](https://platform.openai.com/settings/organization/billing/overview). If you just want to check that this is in fact the cause of the error, you can try adding $1 to your account and checking whether the error persists.
# Still having trouble?
## Still having trouble?
Create a GitHub issue [here](https://github.com/continuedev/continue/issues/new?assignees=&labels=bug&projects=&template=bug-report-%F0%9F%90%9B.md&title=), leaving the details of your problem, and we'll be able to more quickly help you out.

View file

@ -39,7 +39,7 @@ keywords: [codestral, mistral, model setup]
5. If you run into any issues or have any questions, please join our Discord and post in the `#help` channel [here](https://discord.gg/EfJEfdFnDQ)
## Trobleshooting
## Troubleshooting
### Temporary workaround for JetBrains
@ -68,4 +68,4 @@ Mistral AI recently changed the API endpoint to `codestral.mistral.ai` instead o
### Ask for help on Discord
Please join our Discord and post in the `#help` channel [here](https://discord.gg/EfJEfdFnDQ) if you are having problems using Codestral
Please join our Discord and post in the `#help` channel [here](https://discord.gg/EfJEfdFnDQ) if you are having problems using Codestral

View file

@ -94,7 +94,7 @@ This object allows you to customize the behavior of tab-autocomplete. The availa
- `disable`: Disable autocomplete (can also be done from IDE settings)
- `template`: An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables. (String)
- `useCopyBuffer`: Determines whether the copy buffer will be considered when constructing the prompt. (Boolean)
- `useSuffix`: Determines whether to use the file suffix in the prompt. (Boolean)
- `useFileSuffix`: Determines whether to use the file suffix in the prompt. (Boolean)
- `maxPromptTokens`: The maximum number of prompt tokens to use. A smaller number will yield faster completions, but less context. (Number)
- `prefixPercentage`: The percentage of the input that should be dedicated to the prefix. (Number)
- `maxSuffixPercentage`: The maximum percentage of the prompt that can be dedicated to the suffix. (Number)

View file

@ -2071,7 +2071,7 @@
"type": "boolean",
"description": "Determines whether the copy buffer will be considered when contructing the prompt."
},
"useSuffix": {
"useFileSuffix": {
"type": "boolean",
"description": "Determines whether to use the file suffix in the prompt."
},

View file

@ -2071,7 +2071,7 @@
"type": "boolean",
"description": "Determines whether the copy buffer will be considered when contructing the prompt."
},
"useSuffix": {
"useFileSuffix": {
"type": "boolean",
"description": "Determines whether to use the file suffix in the prompt."
},

View file

@ -2071,7 +2071,7 @@
"type": "boolean",
"description": "Determines whether the copy buffer will be considered when contructing the prompt."
},
"useSuffix": {
"useFileSuffix": {
"type": "boolean",
"description": "Determines whether to use the file suffix in the prompt."
},

View file

@ -2326,7 +2326,7 @@
"type": "boolean",
"description": "Determines whether the copy buffer will be considered when contructing the prompt."
},
"useSuffix": {
"useFileSuffix": {
"type": "boolean",
"description": "Determines whether to use the file suffix in the prompt."
},

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "0.9.178",
"version": "0.9.181",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "0.9.178",
"version": "0.9.181",
"license": "Apache-2.0",
"dependencies": {
"@electron/rebuild": "^3.2.10",
@ -33,6 +33,7 @@
"https-proxy-agent": "^7.0.2",
"ignore": "^5.3.0",
"jsdom": "^24.0.0",
"minisearch": "^7.0.0",
"monaco-editor": "^0.45.0",
"monaco-vscode-textmate-theme-converter": "^0.1.7",
"ncp": "^2.0.0",
@ -96,6 +97,7 @@
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.574.0",
"@aws-sdk/credential-providers": "^3.596.0",
"@continuedev/config-types": "^1.0.6",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@types/jsdom": "^21.1.6",
@ -7592,6 +7594,11 @@
"node": ">=8"
}
},
"node_modules/minisearch": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/minisearch/-/minisearch-7.0.0.tgz",
"integrity": "sha512-0OIJ3hUE+YBJNruDCqbTMFmk/IoB1CpZzuGfl11khFIel66ew9UoLF/+gfq3bdyrneqr3P7BTjFZApUbmk+9Dg=="
},
"node_modules/minizlib": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz",

View file

@ -1,7 +1,7 @@
{
"name": "continue",
"icon": "media/icon.png",
"version": "0.9.181",
"version": "0.9.182",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -229,18 +229,6 @@
"category": "Continue",
"title": "Fix Grammar / Spelling",
"group": "Continue"
},
{
"command": "continue.quickEditHistoryUp",
"category": "Continue",
"title": "Quick Edit History Up",
"group": "Continue"
},
{
"command": "continue.quickEditHistoryDown",
"category": "Continue",
"title": "Quick Edit History Down",
"group": "Continue"
}
],
"keybindings": [
@ -572,6 +560,7 @@
"https-proxy-agent": "^7.0.2",
"ignore": "^5.3.0",
"jsdom": "^24.0.0",
"minisearch": "^7.0.0",
"monaco-editor": "^0.45.0",
"monaco-vscode-textmate-theme-converter": "^0.1.7",
"ncp": "^2.0.0",

View file

@ -25,6 +25,11 @@ export class ContinueGUIWebviewViewProvider
}
private _webview?: vscode.Webview;
private _webviewView?: vscode.WebviewView;
get isVisible() {
return this._webviewView?.visible;
}
get webview() {
return this._webview;

View file

@ -19,10 +19,10 @@ import {
quickPickStatusText,
setupStatusBar,
} from "./autocomplete/statusBar";
import { ContinueGUIWebviewViewProvider } from "./debugPanel";
import { ContinueGUIWebviewViewProvider } from "./ContinueGUIWebviewViewProvider";
import { DiffManager } from "./diff/horizontal";
import { VerticalPerLineDiffManager } from "./diff/verticalPerLine/manager";
import { QuickEdit } from "./quickEdit/QuickEdit";
import { QuickEdit } from "./quickEdit/QuickEditQuickPick";
import { Battery } from "./util/battery";
import type { VsCodeWebviewProtocol } from "./webviewProtocol";
@ -82,7 +82,6 @@ function addCodeToContextFromRange(
}
async function addHighlightedCodeToContext(
edit: boolean,
webviewProtocol: VsCodeWebviewProtocol | undefined,
) {
const editor = vscode.window.activeTextEditor;
@ -170,6 +169,7 @@ const commandsMap: (
verticalDiffManager: VerticalPerLineDiffManager,
continueServerClientPromise: Promise<ContinueServerClient>,
battery: Battery,
quickEdit: QuickEdit,
) => { [command: string]: (...args: any) => any } = (
ide,
extensionContext,
@ -179,6 +179,7 @@ const commandsMap: (
verticalDiffManager,
continueServerClientPromise,
battery,
quickEdit,
) => {
/**
* Streams an inline edit to the vertical diff manager.
@ -219,18 +220,6 @@ const commandsMap: (
);
}
const historyUpEventEmitter = new vscode.EventEmitter<void>();
const historyDownEventEmitter = new vscode.EventEmitter<void>();
const quickEdit = new QuickEdit(
verticalDiffManager,
configHandler,
sidebar.webviewProtocol,
ide,
extensionContext,
historyUpEventEmitter.event,
historyDownEventEmitter.event,
);
return {
"continue.acceptDiff": async (newFilepath?: string | vscode.Uri) => {
captureCommandTelemetry("acceptDiff");
@ -322,21 +311,44 @@ const commandsMap: (
fullScreenPanel?.reveal();
}
sidebar.webviewProtocol?.request("focusContinueInput", undefined);
await addHighlightedCodeToContext(false, sidebar.webviewProtocol);
await addHighlightedCodeToContext(sidebar.webviewProtocol);
},
"continue.focusContinueInputWithoutClear": async () => {
if (!getFullScreenTab()) {
vscode.commands.executeCommand("continue.continueGUIView.focus");
}
sidebar.webviewProtocol?.request(
"focusContinueInputWithoutClear",
const fullScreenTab = getFullScreenTab();
const isContinueInputFocused = await sidebar.webviewProtocol.request(
"isContinueInputFocused",
undefined,
);
await addHighlightedCodeToContext(true, sidebar.webviewProtocol);
if (isContinueInputFocused) {
// Handle closing the GUI only if we are focused on the input
if (fullScreenTab) {
fullScreenPanel?.dispose();
} else {
vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar");
}
} else {
// Handle opening the GUI otherwise
if (!fullScreenTab) {
// focus sidebar
vscode.commands.executeCommand("continue.continueGUIView.focus");
} else {
// focus fullscreen
fullScreenPanel?.reveal();
}
sidebar.webviewProtocol?.request(
"focusContinueInputWithoutClear",
undefined,
);
await addHighlightedCodeToContext(sidebar.webviewProtocol);
}
},
"continue.quickEdit": (injectedPrompt?: string) => {
"continue.quickEdit": async (initialPrompt?: string) => {
captureCommandTelemetry("quickEdit");
quickEdit.run(injectedPrompt);
quickEdit.show(initialPrompt);
},
"continue.writeCommentsForCode": async () => {
captureCommandTelemetry("writeCommentsForCode");
@ -659,14 +671,6 @@ const commandsMap: (
client.sendFeedback(feedback, lastLines);
}
},
"continue.quickEditHistoryUp": async () => {
captureCommandTelemetry("quickEditHistoryUp");
historyUpEventEmitter.fire();
},
"continue.quickEditHistoryDown": async () => {
captureCommandTelemetry("quickEditHistoryDown");
historyDownEventEmitter.fire();
},
};
};
@ -680,6 +684,7 @@ export function registerAllCommands(
verticalDiffManager: VerticalPerLineDiffManager,
continueServerClientPromise: Promise<ContinueServerClient>,
battery: Battery,
quickEdit: QuickEdit,
) {
for (const [command, callback] of Object.entries(
commandsMap(
@ -691,6 +696,7 @@ export function registerAllCommands(
verticalDiffManager,
continueServerClientPromise,
battery,
quickEdit,
),
)) {
context.subscriptions.push(

View file

@ -14,12 +14,13 @@ import {
setupStatusBar,
} from "../autocomplete/statusBar";
import { registerAllCommands } from "../commands";
import { ContinueGUIWebviewViewProvider } from "../ContinueGUIWebviewViewProvider";
import { registerDebugTracker } from "../debug/debug";
import { ContinueGUIWebviewViewProvider } from "../debugPanel";
import { DiffManager } from "../diff/horizontal";
import { VerticalPerLineDiffManager } from "../diff/verticalPerLine/manager";
import { VsCodeIde } from "../ideProtocol";
import { registerAllCodeLensProviders } from "../lang-server/codeLens";
import { QuickEdit } from "../quickEdit/QuickEditQuickPick";
import { setupRemoteConfigSync } from "../stubs/activation";
import { getControlPlaneSessionInfo } from "../stubs/WorkOsAuthProvider";
import { Battery } from "../util/battery";
@ -41,7 +42,6 @@ export class VsCodeExtension {
webviewProtocolPromise: Promise<VsCodeWebviewProtocol>;
private core: Core;
private battery: Battery;
private quickActionsCodeLensDisposable?: vscode.Disposable;
constructor(context: vscode.ExtensionContext) {
let resolveWebviewProtocol: any = undefined;
@ -55,9 +55,6 @@ export class VsCodeExtension {
this.extensionContext = context;
this.windowId = uuidv4();
const ideSettings = this.ide.getIdeSettingsSync();
const { remoteConfigServerUrl } = ideSettings;
// Dependencies of core
let resolveVerticalDiffManager: any = undefined;
const verticalDiffManagerPromise = new Promise<VerticalPerLineDiffManager>(
@ -179,6 +176,14 @@ export class VsCodeExtension {
context.subscriptions.push(this.battery);
context.subscriptions.push(monitorBatteryChanges(this.battery));
const quickEdit = new QuickEdit(
this.verticalDiffManager,
this.configHandler,
this.sidebar.webviewProtocol,
this.ide,
context,
);
// Commands
registerAllCommands(
context,
@ -190,6 +195,7 @@ export class VsCodeExtension {
this.verticalDiffManager,
this.core.continueServerClientPromise,
this.battery,
quickEdit,
);
registerDebugTracker(this.sidebar.webviewProtocol, this.ide);

View file

@ -115,9 +115,13 @@ export class QuickActionsCodeLensProvider implements vscode.CodeLensProvider {
}
const symbols = await vscode.commands.executeCommand<
Array<vscode.DocumentSymbol>
Array<vscode.DocumentSymbol> | undefined
>("vscode.executeDocumentSymbolProvider", document.uri);
if (!symbols) {
return [];
}
const filteredSmybols = symbols?.filter((def) =>
QuickActionsCodeLensProvider.quickActionSymbolKinds.includes(def.kind),
);

View file

@ -0,0 +1,88 @@
import { ContinueConfig, IDE } from "core";
import { QuickPickItem, window } from "vscode";
import { fetchwithRequestOptions } from "core/util/fetchWithOptions";
export async function getContextProviderItems({
contextProviders,
}: ContinueConfig): Promise<QuickPickItem[]> {
if (!contextProviders) {
return [];
}
const quickPickItems = contextProviders
.filter((provider) => provider.description.type === "normal")
.map((provider) => {
return {
label: provider.description.displayTitle,
detail: provider.description.description,
};
});
return quickPickItems;
}
export async function getContextProvidersString(
selectedProviders: QuickPickItem[] | undefined,
config: ContinueConfig,
ide: IDE,
): Promise<string> {
const contextItems = (
await Promise.all(
selectedProviders?.map((selectedProvider) => {
const provider = config.contextProviders?.find(
(provider) =>
provider.description.displayTitle === selectedProvider.label,
);
if (!provider) {
return [];
}
return provider.getContextItems("", {
ide,
embeddingsProvider: config.embeddingsProvider,
reranker: config.reranker,
llm: config.models[0],
fullInput: "",
selectedCode: [],
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
});
}) || [],
)
).flat();
return contextItems.map((item) => item.content).join("\n\n") + "\n\n---\n\n";
}
export async function getContextProviderQuickPickVal(
config: ContinueConfig,
ide: IDE,
) {
const contextProviderItems = await getContextProviderItems(config);
const quickPick = window.createQuickPick();
quickPick.items = contextProviderItems;
quickPick.title = "Context providers";
quickPick.placeholder = "Select a context provider to add to your prompt";
quickPick.canSelectMany = true;
quickPick.show();
const val = await new Promise<string>((resolve) => {
quickPick.onDidAccept(async () => {
const selectedItems = Array.from(quickPick.selectedItems);
const context = await getContextProvidersString(
selectedItems,
config,
ide,
);
resolve(context);
});
});
quickPick.dispose();
return val;
}

View file

@ -0,0 +1,42 @@
import { QuickPickItem, window, ExtensionContext } from "vscode";
const HISTORY_KEY = "quickEditHistory";
const MAX_HISTORY_LENGTH = 50;
export function appendToHistory(
prompt: string,
{ globalState }: ExtensionContext,
) {
let history: string[] = globalState.get(HISTORY_KEY, []);
// Remove duplicate if exists
if (history[history.length - 1] === prompt) {
history = history.slice(0, -1);
}
// Add new item
history.push(prompt);
// Truncate if over max size
if (history.length > MAX_HISTORY_LENGTH) {
history = history.slice(-MAX_HISTORY_LENGTH);
}
globalState.update(HISTORY_KEY, history);
}
export async function getHistoryQuickPickVal({
globalState,
}: ExtensionContext): Promise<string | undefined> {
const historyItems: QuickPickItem[] = globalState
.get(HISTORY_KEY, [])
.map((item) => ({ label: item }))
.reverse();
const selectedItem = await window.showQuickPick(historyItems, {
title: "History",
placeHolder: "Select a previous prompt",
});
return selectedItem?.label;
}

View file

@ -1,181 +0,0 @@
import * as vscode from "vscode";
// Because we have to hide and show the input box again to allow history, this class can act like a more contiguous input box.
export default class InputBoxWithHistory implements vscode.Disposable {
private static MaxSize = 50;
private static HistoryKey = "quickEditHistory";
private currentIndex: number;
private history: string[] = [];
private cancellationReason: "up" | "down" | undefined = undefined;
private readonly completionEventEmitter = new vscode.EventEmitter<
string | undefined
>();
private currentInputBoxCancellationTokenSource:
| vscode.CancellationTokenSource
| undefined = undefined;
private disposables: vscode.Disposable[] = [];
constructor(
private readonly context: vscode.ExtensionContext,
private readonly historyUpEvent: vscode.Event<void>,
private readonly historyDownEvent: vscode.Event<void>,
private readonly options: vscode.InputBoxOptions,
) {
this.history = this.context.globalState.get(
InputBoxWithHistory.HistoryKey,
[],
);
this.currentIndex = this.history.length;
this.disposables.push(
this.historyUpEvent(() => {
const value = this.up();
this.cancellationReason = "up";
if (typeof value === "undefined") {
return;
}
this._displayInputBox(value);
}),
);
this.disposables.push(
this.historyDownEvent(() => {
const value = this.down();
this.cancellationReason = "down";
if (typeof value === "undefined") {
return;
}
this._displayInputBox(value);
}),
);
}
dispose() {
if (this.currentInputBoxCancellationTokenSource) {
this.currentInputBoxCancellationTokenSource.dispose();
}
this.completionEventEmitter.dispose();
this.disposables.forEach((disposable) => disposable.dispose());
vscode.commands.executeCommand(
"setContext",
"continue.quickEditHistoryFocused",
false,
);
}
appendToHistory(item: string) {
let history = this.history;
// Remove duplicate if exists
if (history[history.length - 1] === item) {
history = history.slice(0, -1);
}
// Add new item
history.push(item);
// Truncate if over max size
if (history.length > InputBoxWithHistory.MaxSize) {
history = history.slice(-InputBoxWithHistory.MaxSize);
}
this.context.globalState.update(InputBoxWithHistory.HistoryKey, history);
}
up(): string | undefined {
if (this.currentIndex > 0) {
this.currentIndex--;
return this.history[this.currentIndex];
}
return undefined;
}
down(): string | undefined {
if (this.currentIndex < this.history.length - 1) {
this.currentIndex++;
return this.history[this.currentIndex];
} else if (this.currentIndex === this.history.length - 1) {
this.currentIndex++;
return "";
}
return undefined;
}
private _displayInputBox(value?: string) {
if (this.currentInputBoxCancellationTokenSource) {
this.currentInputBoxCancellationTokenSource.cancel();
}
this.currentInputBoxCancellationTokenSource =
new vscode.CancellationTokenSource();
this.currentInputBoxCancellationTokenSource.token.onCancellationRequested(
() => {
// Up/down will cancel the input box, but we don't want that to trigger everything to be disposed
if (
this.cancellationReason === "up" ||
this.cancellationReason === "down"
) {
return;
}
this.completionEventEmitter.fire(undefined);
},
);
const options = {
...this.options,
};
if (value) {
options.value = value;
}
vscode.window
.showInputBox(options, this.currentInputBoxCancellationTokenSource.token)
.then((input) => {
if (
(!input && this.cancellationReason === "up") ||
this.cancellationReason === "down"
) {
return;
}
this.completionEventEmitter.fire(input);
});
setTimeout(() => {
this.cancellationReason = undefined;
}, 100);
}
async getInput(): Promise<string | undefined> {
try {
vscode.commands.executeCommand(
"setContext",
"continue.quickEditHistoryFocused",
true,
);
return await new Promise((resolve, reject) => {
const completionDisposable = this.completionEventEmitter.event(
(input) => {
resolve(input);
completionDisposable.dispose();
if (input) {
this.appendToHistory(input);
}
this.dispose();
},
);
this._displayInputBox();
});
} catch (e) {
console.error(e);
} finally {
vscode.commands.executeCommand(
"setContext",
"continue.quickEditHistoryFocused",
false,
);
}
}
}

View file

@ -0,0 +1,32 @@
import { ContinueConfig } from "core";
import { QuickPickItem, window } from "vscode";
export async function getModelQuickPickVal(
curModelTitle: string,
config: ContinueConfig,
) {
const modelItems: QuickPickItem[] = config.models.map((model) => {
const isCurModel = curModelTitle === model.title;
return {
label: model.title
? `${isCurModel ? "$(check)" : " "} ${model.title}`
: "Model title not set",
};
});
const selectedItem = await window.showQuickPick(modelItems, {
title: "Models",
placeHolder: "Select a model",
});
if (!selectedItem) {
return undefined;
}
const selectedModelTitle = config.models.find(
(model) => model.title && selectedItem.label.includes(model.title),
)?.title;
return selectedModelTitle;
}

View file

@ -1,194 +0,0 @@
import { IDE } from "core";
import { ConfigHandler } from "core/config/ConfigHandler";
import { fetchwithRequestOptions } from "core/util/fetchWithOptions";
import * as vscode from "vscode";
import { VerticalPerLineDiffManager } from "../diff/verticalPerLine/manager";
import { getPlatform } from "../util/util";
import { VsCodeWebviewProtocol } from "../webviewProtocol";
import InputBoxWithHistory from "./InputBoxWithHistory";
interface QuickEditFlowStuff {
defaultModelTitle: string;
quickPickItems: vscode.QuickPickItem[];
previousInput: string | undefined;
injectedPrompt?: string | undefined;
}
export class QuickEdit {
constructor(
private readonly verticalDiffManager: VerticalPerLineDiffManager,
private readonly configHandler: ConfigHandler,
private readonly webviewProtocol: VsCodeWebviewProtocol,
private readonly ide: IDE,
private readonly context: vscode.ExtensionContext,
private readonly historyUpEvent: vscode.Event<void>,
private readonly historyDownEvent: vscode.Event<void>,
) {}
private async _getDefaultModelTitle(): Promise<string> {
const config = await this.configHandler.loadConfig();
let defaultModelTitle =
config.experimental?.modelRoles?.inlineEdit ??
(await this.webviewProtocol.request("getDefaultModelTitle", undefined));
if (!defaultModelTitle) {
defaultModelTitle = config.models[0]?.title!;
}
return defaultModelTitle;
}
private async _getQuickPickItems(): Promise<vscode.QuickPickItem[]> {
const contextProviders = (await this.configHandler.loadConfig())
.contextProviders;
const quickPickItems =
contextProviders
?.filter((provider) => provider.description.type === "normal")
.map((provider) => {
return {
label: provider.description.displayTitle,
description: provider.description.title,
detail: provider.description.description,
};
}) || [];
return quickPickItems;
}
private async _getStuff(
injectedPrompt: string | undefined,
): Promise<QuickEditFlowStuff> {
const editor = vscode.window.activeTextEditor;
const existingHandler = this.verticalDiffManager.getHandlerForFile(
editor?.document.uri.fsPath ?? "",
);
const previousInput = existingHandler?.input;
const stuff: QuickEditFlowStuff = {
defaultModelTitle: await this._getDefaultModelTitle(),
quickPickItems: await this._getQuickPickItems(),
previousInput,
injectedPrompt,
};
return stuff;
}
async _getTextInputOptions(stuff: QuickEditFlowStuff) {
const selectionEmpty = vscode.window.activeTextEditor?.selection.isEmpty;
const addContextMsg = stuff.quickPickItems.length
? " (or press enter to add context first)"
: "";
const textInputOptions: vscode.InputBoxOptions = {
placeHolder: selectionEmpty
? `Type instructions to generate code${addContextMsg}`
: `Describe how to edit the highlighted code${addContextMsg}`,
title: `${getPlatform() === "mac" ? "Cmd" : "Ctrl"}+I`,
prompt: `[${stuff.defaultModelTitle}]`,
value: stuff.injectedPrompt,
ignoreFocusOut: true,
};
if (stuff.previousInput) {
textInputOptions.value = stuff.previousInput + ", ";
textInputOptions.valueSelection = [
textInputOptions.value.length,
textInputOptions.value.length,
];
}
return textInputOptions;
}
async _collectTextInput(
stuff: QuickEditFlowStuff,
): Promise<string | undefined> {
const inputBox = new InputBoxWithHistory(
this.context,
this.historyUpEvent,
this.historyDownEvent,
await this._getTextInputOptions(stuff),
);
const input = await inputBox.getInput();
inputBox.dispose();
return input;
}
private async _runWithContextItems(stuff: QuickEditFlowStuff) {
const selectedProviders = await vscode.window.showQuickPick(
stuff.quickPickItems,
{
title: "Add Context",
canPickMany: true,
},
);
const input = await this._collectTextInput(stuff);
if (input) {
const inputWithContext = await this._addSelectedProvidersToInput(
input,
selectedProviders,
);
await this._sendRequest(inputWithContext, stuff);
}
}
private async _addSelectedProvidersToInput(
input: string,
selectedProviders: vscode.QuickPickItem[] | undefined,
): Promise<string> {
const llm = await this.configHandler.llmFromTitle();
const config = await this.configHandler.loadConfig();
const context = (
await Promise.all(
selectedProviders?.map((providerTitle) => {
const provider = config.contextProviders?.find(
(provider) =>
provider.description.title === providerTitle.description,
);
if (!provider) {
return [];
}
return provider.getContextItems("", {
embeddingsProvider: config.embeddingsProvider,
reranker: config.reranker,
ide: this.ide,
llm,
fullInput: input || "",
selectedCode: [],
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
});
}) || [],
)
).flat();
return (
context.map((item) => item.content).join("\n\n") + "\n\n---\n\n" + input
);
}
private async _handleInitialInput(
initialInput: string | undefined,
stuff: QuickEditFlowStuff,
) {
// If the user presses enter, we take them to context items selector
if (initialInput?.length === 0 && stuff.quickPickItems.length > 0) {
await this._runWithContextItems(stuff);
} else if (initialInput) {
// If there's input, then start generating the diff
await this._sendRequest(initialInput, stuff);
}
}
private async _sendRequest(input: string, stuff: QuickEditFlowStuff) {
this.webviewProtocol.request("incrementFtc", undefined);
await this.verticalDiffManager.streamEdit(
input,
stuff.defaultModelTitle,
undefined,
stuff.previousInput,
);
}
async run(injectedPrompt: string | undefined) {
const stuff = await this._getStuff(injectedPrompt);
const initialInput = await this._collectTextInput(stuff);
await this._handleInitialInput(initialInput, stuff);
}
}

View file

@ -0,0 +1,410 @@
/* eslint-disable @typescript-eslint/naming-convention */
import { IDE } from "core";
import * as vscode from "vscode";
import { VerticalPerLineDiffManager } from "../diff/verticalPerLine/manager";
import { VsCodeWebviewProtocol } from "../webviewProtocol";
import { Telemetry } from "core/util/posthog";
import { walkDir } from "core/indexing/walkDir";
import { appendToHistory, getHistoryQuickPickVal } from "./HistoryQuickPick";
import { getContextProviderQuickPickVal } from "./ContextProvidersQuickPick";
import { getModelQuickPickVal } from "./ModelSelectionQuickPick";
// @ts-ignore - error finding typings
import MiniSearch from "minisearch";
import { ConfigHandler } from "core/config/ConfigHandler";
/**
* Used to track what action to take after a user interacts
* with the initial Quick Pick
*/
enum QuickEditInitialItemLabels {
History = "History",
ContextProviders = "Context providers",
Model = "Model",
Submit = "Submit",
}
type FileMiniSearchResult = { filename: string };
/**
* Quick Edit is a collection of Quick Picks that allow the user to
* quickly edit a file.
*/
export class QuickEdit {
private static fileSearchChar = "@";
/**
* Matches the search char followed by non-space chars, excluding matches ending with a space.
* This is used to detect file search queries while allowing subsequent prompt text
*/
private static hasFileSearchQueryRegex = new RegExp(
`${QuickEdit.fileSearchChar}[^${QuickEdit.fileSearchChar}\\s]+(?!\\s)$`,
);
private static maxFileSearchResults = 20;
private miniSearch = new MiniSearch<FileMiniSearchResult>({
fields: ["filename"],
storeFields: ["filename"],
searchOptions: {
prefix: true,
fuzzy: 2,
},
});
private previousInput?: string;
/**
* Handles situations where the user navigates to a different editor
* while interacting with the Quick Pick
*/
private editorWhenOpened!: vscode.TextEditor;
/**
* Required to store the string content of a context provider
* while naviagting beween Quick Picks.
*/
private contextProviderStr?: string;
/**
* Stores the current model title for potential changes
*/
private _curModelTitle?: string;
constructor(
private readonly verticalDiffManager: VerticalPerLineDiffManager,
private readonly configHandler: ConfigHandler,
private readonly webviewProtocol: VsCodeWebviewProtocol,
private readonly ide: IDE,
private readonly context: vscode.ExtensionContext,
) {
this.intializeQuickEditState();
}
private async intializeQuickEditState() {
const editor = vscode.window.activeTextEditor!;
const existingHandler = this.verticalDiffManager.getHandlerForFile(
editor.document.uri.fsPath ?? "",
);
const workspaceDirs = await this.ide.getWorkspaceDirs();
const results = await Promise.all(
workspaceDirs.map((dir) => {
return walkDir(dir, this.ide);
}),
);
const filenames = results.flat().map((file) => ({
id: file,
filename: vscode.workspace.asRelativePath(file),
}));
this.miniSearch.addAll(filenames);
this.editorWhenOpened = editor;
this.previousInput = existingHandler?.input;
}
/**
* Gets the model title the user has chosen, or their default model
*/
private async _getCurModelTitle() {
const config = await this.configHandler.loadConfig();
if (this._curModelTitle) {
return this._curModelTitle;
}
let defaultModelTitle =
config.experimental?.modelRoles?.inlineEdit ??
(await this.webviewProtocol.request("getDefaultModelTitle", undefined));
if (!defaultModelTitle) {
defaultModelTitle = config.models[0]?.title!;
}
return defaultModelTitle;
}
/**
* Generates a title for the Quick Pick, including the
* file name and selected line(s) if available.
*
* @example
* // "Edit myFile.ts", "Edit myFile.ts:5-10", "Edit myFile.ts:15"
*/
_getQuickPickTitle = () => {
const uri = this.editorWhenOpened.document.uri;
if (!uri) {
return "Edit";
}
const fileName = vscode.workspace.asRelativePath(uri, true);
const { start, end } = this.editorWhenOpened.selection;
const selectionEmpty = this.editorWhenOpened.selection.isEmpty;
return selectionEmpty
? `Edit ${fileName}`
: `Edit ${fileName}:${start.line}${
end.line > start.line ? `-${end.line}` : ""
}`;
};
private async _streamEditWithInputAndContext(prompt: string) {
const modelTitle = await this._getCurModelTitle();
// Extracts all file references from the prompt string,
// which are denoted by an '@' symbol followed by
// one or more non-whitespace characters.
const fileReferences = prompt.match(/@[^\s]+/g) || [];
// Replace file references with the content of the file
for (const fileRef of fileReferences) {
const filePath = fileRef.slice(1); // Remove the '@' symbol
const fileContent = await this.ide.readFile(filePath);
prompt = prompt.replace(
fileRef,
`\`\`\`${filePath}\n${fileContent}\n\`\`\`\n\n`,
);
}
if (this.contextProviderStr) {
prompt = this.contextProviderStr + prompt;
}
this.webviewProtocol.request("incrementFtc", undefined);
await this.verticalDiffManager.streamEdit(
prompt,
modelTitle,
undefined,
this.previousInput,
);
}
async _getInitialQuickPickVal(
injectedPrompt?: string,
): Promise<string | undefined> {
const modelTitle = await this._getCurModelTitle();
const initialItems: vscode.QuickPickItem[] = [
{
label: QuickEditInitialItemLabels.History,
detail: "$(history) Select previous prompts",
},
{
label: QuickEditInitialItemLabels.ContextProviders,
detail: "$(add) Add context to your prompt",
},
{
label: QuickEditInitialItemLabels.Model,
detail: `$(chevron-down) ${modelTitle}`,
},
];
/**
* The user has to select an item to submit the prompt,
* so we add a "Submit" item once the user has begun to
* type their prompt that is always displayed
*/
const submitItem: vscode.QuickPickItem = {
label: "Submit",
alwaysShow: true,
};
/**
* Used to show the current file in the Quick Pick,
* as soon as the user types the search character
*/
const currentFileItem: vscode.QuickPickItem = {
label: vscode.workspace.asRelativePath(
this.editorWhenOpened.document.uri,
),
description: "Current file",
alwaysShow: true,
};
const noResultsItem: vscode.QuickPickItem = { label: "No results found" };
const quickPick = vscode.window.createQuickPick();
quickPick.items = initialItems;
quickPick.placeholder =
"Enter a prompt to edit your code (@ to search files, ⏎ to submit)";
quickPick.title = this._getQuickPickTitle();
quickPick.ignoreFocusOut = true;
quickPick.value = injectedPrompt ?? "";
quickPick.show();
/**
* Programatically modify the Quick Pick items based on the input value.
*
* Shows the current file for a new file search, performs a file search,
* or shows the submit option.
*
* If the input is empty, shows the initial items.
*/
quickPick.onDidChangeValue((value) => {
if (value !== "") {
switch (true) {
case value.endsWith(QuickEdit.fileSearchChar):
quickPick.items = [currentFileItem];
break;
case QuickEdit.hasFileSearchQueryRegex.test(value):
const lastAtIndex = value.lastIndexOf(QuickEdit.fileSearchChar);
// The search query is the last instance of the
// search character to the end of the string
const searchQuery = value.substring(lastAtIndex + 1);
const searchResults = this.miniSearch.search(
searchQuery,
) as FileMiniSearchResult[];
if (searchResults.length > 0) {
quickPick.items = searchResults
.map(({ filename }) => ({
label: filename,
alwaysShow: true,
}))
.slice(0, QuickEdit.maxFileSearchResults);
} else {
quickPick.items = [noResultsItem];
}
break;
default:
// The user does not have a file search in progress,
// tso only show the submit option
quickPick.items = [submitItem];
break;
}
} else {
quickPick.items = initialItems;
}
});
/**
* Waits for the user to select an item from the quick pick.
*
* If the selected item is a file, it replaces the file search query
* with the selected file path and allows further editing.
*
* If the selected item is an initial item, it closes the quick pick
* and returns the selected item label.
*
* @returns {Promise<string | undefined>} The label of the selected item, or undefined if no item was selected.
*/
const selectedItemLabel = await new Promise<string | undefined>(
(resolve) => {
quickPick.onDidAccept(() => {
const { label } = quickPick.selectedItems[0];
// If not an initial item, it's a file selection. Allow continued prompt editing.
const isFileSelection = !Object.values(
QuickEditInitialItemLabels,
).includes(label as QuickEditInitialItemLabels);
if (isFileSelection) {
// Replace the file search query with the selected file path
const curValue = quickPick.value;
const newValue =
curValue.substring(0, curValue.lastIndexOf("@") + 1) +
label +
" ";
quickPick.value = newValue;
quickPick.items = [submitItem];
} else {
// The user has selected one of the initial items, so we close the Quick Pick
resolve(label);
quickPick.dispose();
}
});
},
);
const shouldSubmitPrompt =
!selectedItemLabel ||
selectedItemLabel === QuickEditInitialItemLabels.Submit;
if (shouldSubmitPrompt) {
return quickPick.value;
}
return selectedItemLabel;
}
/**
* Shows the Quick Edit Quick Pick, allowing the user to select an initial item or enter a prompt.
* Displays a quick pick for "History" or "ContextProviders" to set the prompt or context provider string.
* Displays a quick pick for "Model" to set the current model title.
* Appends the entered prompt to the history and streams the edit with input and context.
*/
async show(initialPrompt?: string) {
const config = await this.configHandler.loadConfig();
const selectedLabelOrInputVal = await this._getInitialQuickPickVal(
initialPrompt,
);
Telemetry.capture("quickEditSelection", {
selection: selectedLabelOrInputVal,
});
let prompt: string | undefined = undefined;
switch (selectedLabelOrInputVal) {
case QuickEditInitialItemLabels.History:
const historyVal = await getHistoryQuickPickVal(this.context);
prompt = historyVal ?? "";
break;
case QuickEditInitialItemLabels.ContextProviders:
const contextProviderVal = await getContextProviderQuickPickVal(
config,
this.ide,
);
this.contextProviderStr = contextProviderVal ?? "";
// Recurse back to let the user write their prompt
this.show(initialPrompt);
break;
case QuickEditInitialItemLabels.Model:
const curModelTitle = await this._getCurModelTitle();
const selectedModelTitle = await getModelQuickPickVal(
curModelTitle,
config,
);
if (selectedModelTitle) {
this._curModelTitle = selectedModelTitle;
}
// Recurse back to let the user write their prompt
this.show(initialPrompt);
break;
default:
// If it wasn't a label we can assume it was user input
if (selectedLabelOrInputVal) {
prompt = selectedLabelOrInputVal;
appendToHistory(selectedLabelOrInputVal, this.context);
}
}
if (prompt) {
await this._streamEditWithInputAndContext(prompt);
}
}
}

View file

22
gui/package-lock.json generated
View file

@ -37,6 +37,7 @@
"react-dom": "^18.2.0",
"react-error-boundary": "^4.0.11",
"react-hook-form": "^7.47.0",
"react-intersection-observer": "^9.10.3",
"react-markdown": "^9.0.1",
"react-redux": "^8.0.5",
"react-remark": "^2.1.0",
@ -88,6 +89,7 @@
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.574.0",
"@aws-sdk/credential-providers": "^3.596.0",
"@continuedev/config-types": "^1.0.6",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@types/jsdom": "^21.1.6",
@ -919,9 +921,9 @@
}
},
"node_modules/@heroicons/react": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/@heroicons/react/-/react-2.1.3.tgz",
"integrity": "sha512-fEcPfo4oN345SoqdlCDdSa4ivjaKbk0jTd+oubcgNxnNgAfzysfwWfQUr+51wigiWHQQRiZNd1Ao0M5Y3M2EGg==",
"version": "2.1.5",
"resolved": "https://registry.npmjs.org/@heroicons/react/-/react-2.1.5.tgz",
"integrity": "sha512-FuzFN+BsHa+7OxbvAERtgBTNeZpUjgM/MIizfVkSCL2/edriN0Hx/DWRCR//aPYwO5QX/YlgLGXk+E3PcfZwjA==",
"peerDependencies": {
"react": ">= 16"
}
@ -6078,6 +6080,20 @@
"react": "^16.8.0 || ^17 || ^18"
}
},
"node_modules/react-intersection-observer": {
"version": "9.10.3",
"resolved": "https://registry.npmjs.org/react-intersection-observer/-/react-intersection-observer-9.10.3.tgz",
"integrity": "sha512-9NYfKwPZRovB6QJee7fDg0zz/SyYrqXtn5xTZU0vwLtLVBtfu9aZt1pVmr825REE49VPDZ7Lm5SNHjJBOTZHpA==",
"peerDependencies": {
"react": "^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"react-dom": "^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
},
"peerDependenciesMeta": {
"react-dom": {
"optional": true
}
}
},
"node_modules/react-is": {
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz",

View file

@ -39,6 +39,7 @@
"react-dom": "^18.2.0",
"react-error-boundary": "^4.0.11",
"react-hook-form": "^7.47.0",
"react-intersection-observer": "^9.10.3",
"react-markdown": "^9.0.1",
"react-redux": "^8.0.5",
"react-remark": "^2.1.0",

View file

@ -0,0 +1,32 @@
import { useEffect } from "react";
import { useInView } from "react-intersection-observer";
interface ChatScrollAnchorProps {
trackVisibility: boolean;
isAtBottom: boolean;
scrollAreaRef: React.RefObject<HTMLDivElement>;
}
export function ChatScrollAnchor({
trackVisibility,
isAtBottom,
scrollAreaRef,
}: ChatScrollAnchorProps) {
const { ref, inView, entry } = useInView({
trackVisibility,
delay: 100,
});
useEffect(() => {
if (isAtBottom && trackVisibility && !inView) {
if (!scrollAreaRef.current) return;
const scrollAreaElement = scrollAreaRef.current;
scrollAreaElement.scrollTop =
scrollAreaElement.scrollHeight - scrollAreaElement.clientHeight;
}
}, [inView, entry, isAtBottom, trackVisibility]);
return <div ref={ref} className="h-px w-full" />;
}

View file

@ -224,7 +224,7 @@ function ProfileSwitcher(props: {}) {
} else {
ideMessenger.post(
"openUrl",
`http://app.continue.dev/workspaces/${selectedProfileId}/settings`,
`http://app.continue.dev/workspaces/${selectedProfileId}/config`,
);
}
}}

View file

@ -17,6 +17,7 @@ interface ConfirmationDialogProps {
onConfirm: () => void;
onCancel?: () => void;
text: string;
title?: string;
}
function ConfirmationDialog(props: ConfirmationDialogProps) {
@ -24,7 +25,7 @@ function ConfirmationDialog(props: ConfirmationDialogProps) {
return (
<div className="p-4">
<h3>Confirmation</h3>
<h3>{props.title ?? "Confirmation"}</h3>
<p>{props.text}</p>
<GridDiv>

View file

@ -151,8 +151,6 @@ function TipTapEditor(props: TipTapEditorProps) {
);
const useActiveFile = useSelector(selectUseActiveFile);
const [inputFocused, setInputFocused] = useState(false);
const { saveSession } = useHistory(dispatch);
const inSubmenuRef = useRef<string | undefined>(undefined);
@ -655,16 +653,14 @@ function TipTapEditor(props: TipTapEditorProps) {
],
);
// On linux+jetbrains only was stealing focus
// useEffect(() => {
// if (props.isMainInput && editor && document.hasFocus()) {
// editor.commands.focus();
// // setTimeout(() => {
// // // https://github.com/continuedev/continue/pull/881
// // editor.commands.blur();
// // }, 0);
// }
// }, [editor, props.isMainInput, historyLength, ignoreHighlightedCode]);
useWebviewListener(
"isContinueInputFocused",
async () => {
return props.isMainInput && editorFocusedRef.current;
},
[editorFocusedRef, props.isMainInput],
!props.isMainInput,
);
const [showDragOverMsg, setShowDragOverMsg] = useState(false);
@ -748,22 +744,13 @@ function TipTapEditor(props: TipTapEditorProps) {
<EditorContent
spellCheck={false}
editor={editor}
onFocus={() => {
setInputFocused(true);
}}
onBlur={() => {
// hack to stop from cancelling press of "Enter"
setTimeout(() => {
setInputFocused(false);
}, 100);
}}
onClick={(event) => {
event.stopPropagation();
}}
/>
<InputToolbar
showNoContext={optionKeyHeld}
hidden={!(inputFocused || props.isMainInput)}
hidden={!(editorFocusedRef.current || props.isMainInput)}
onAddContextItem={() => {
if (editor.getText().endsWith("@")) {
} else {

View file

@ -0,0 +1,86 @@
import {
PencilSquareIcon,
Cog6ToothIcon,
BookOpenIcon,
ClipboardDocumentIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
import { getMetaKeyLabel } from "../../util";
import styled from "styled-components";
import { lightGray } from "..";
interface TutorialCardProps {
onClose: () => void;
}
const TutorialCardDiv = styled.div`
border: 1px solid ${lightGray};
border-radius: 0.125rem;
padding: 0.5rem;
margin: 1.5rem;
max-width: 28rem;
position: relative;
`;
export function TutorialCard({ onClose }: TutorialCardProps) {
return (
<TutorialCardDiv>
<div
onClick={onClose}
className="absolute top-2 right-2 p-1 text-gray-400 hover:text-gray-600 transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 bg-white rounded-full cursor-pointer shadow-sm"
role="button"
aria-label="Close"
>
<XMarkIcon width="1.4em" height="1.4em" />
</div>
<ul className="text-gray-300 space-y-4">
<li className="flex items-start">
<PencilSquareIcon
width="1.4em"
height="1.4em"
className="align-middle pr-3"
/>
<span>
Highlight code and press <code>{getMetaKeyLabel() + "I"}</code> to
quickly make natural language edits
</span>
</li>
<li className="flex items-start">
<ClipboardDocumentIcon
width="1.4em"
height="1.4em"
className="align-middle pr-3"
/>
<span>
Highlight code and press <code>{getMetaKeyLabel() + "L"}</code> o
add it to the chat window
</span>
</li>
<li className="flex items-start">
<Cog6ToothIcon
width="1.4em"
height="1.4em"
className="align-middle pr-3"
/>
<span>
Click the gear icon in the bottom right to configure Continue
</span>
</li>
<li className="flex items-start">
<BookOpenIcon
width="1.4em"
height="1.4em"
className="align-middle pr-3"
/>
<span>
<a href="https://docs.continue.dev" target="_blank">
Read our documentation
</a>{" "}
to learn more
</span>
</li>
</ul>
</TutorialCardDiv>
);
}

View file

@ -1,5 +1,10 @@
import { Listbox } from "@headlessui/react";
import { ChevronDownIcon, TrashIcon } from "@heroicons/react/24/outline";
import {
ChevronDownIcon,
CubeIcon,
PlusIcon,
TrashIcon,
} from "@heroicons/react/24/outline";
import { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
@ -26,9 +31,9 @@ const StyledListboxButton = styled(Listbox.Button)`
gap: 4px;
border: none;
cursor: pointer;
font-size: ${(props) => `${getFontSize() - 4}px`};
font-size: ${() => `${getFontSize() - 4}px`};
background: transparent;
color: ${(props) => lightGray};
color: ${() => lightGray};
&:focus {
outline: none;
}
@ -45,15 +50,15 @@ const StyledListboxOptions = styled(Listbox.Options)`
border-radius: ${defaultBorderRadius};
border: 0.5px solid ${lightGray};
background-color: ${vscInputBackground};
max-height: 300px;
overflow-y: auto;
`;
const StyledListboxOption = styled(Listbox.Option)`
cursor: pointer;
border-radius: ${defaultBorderRadius};
padding-left: 4px;
padding-right: 4px;
padding-top: 4px;
padding-bottom: 4px;
padding: 6px;
&:hover {
background: ${(props) => `${lightGray}33`};
@ -61,17 +66,20 @@ const StyledListboxOption = styled(Listbox.Option)`
`;
const StyledTrashIcon = styled(TrashIcon)`
position: absolute;
padding: 4px;
right: 0;
background: ${vscInputBackground};
border-radius: ${defaultBorderRadius};
cursor: pointer;
flex-shrink: 0;
margin-left: 8px;
&:hover {
color: red;
}
`;
const Divider = styled.div`
height: 1px;
background-color: ${lightGray};
margin: 4px;
`;
function ModelOption({
option,
idx,
@ -86,6 +94,26 @@ function ModelOption({
const dispatch = useDispatch();
const [hovered, setHovered] = useState(false);
function onClickDelete(e) {
e.stopPropagation();
e.preventDefault();
dispatch(setShowDialog(true));
dispatch(
setDialogMessage(
<ConfirmationDialog
title={`Delete ${option.title}`}
text={`Are you sure you want to remove ${option.title} from your configuration?`}
onConfirm={() => {
ideMessenger.post("config/deleteModel", {
title: option.title,
});
}}
/>,
),
);
}
return (
<StyledListboxOption
key={idx}
@ -97,31 +125,19 @@ function ModelOption({
setHovered(false);
}}
>
<div className="flex items-center justify-between gap-3 h-5 relative">
<span>{option.title}</span>
{hovered && showDelete && (
<StyledTrashIcon
width="1.2em"
height="1.2em"
onClick={(e) => {
dispatch(setShowDialog(true));
dispatch(
setDialogMessage(
<ConfirmationDialog
text={`Are you sure you want to delete this model? (${option.title})`}
onConfirm={() => {
ideMessenger.post("config/deleteModel", {
title: option.title,
});
}}
/>,
),
);
e.stopPropagation();
e.preventDefault();
}}
/>
)}
<div className="flex items-center justify-between w-full">
<div className="flex items-center pr-4">
<CubeIcon className="w-4 h-4 mr-2 flex-shrink-0" />
<span>{option.title}</span>
</div>
<StyledTrashIcon
style={{ visibility: hovered && showDelete ? "visible" : "hidden" }}
className="ml-auto"
width="1.2em"
height="1.2em"
onClick={onClickDelete}
/>
</div>
</StyledListboxOption>
);
@ -143,7 +159,7 @@ interface Option {
title: string;
}
function ModelSelect(props: {}) {
function ModelSelect() {
const dispatch = useDispatch();
const defaultModel = useSelector(defaultModelSelector);
const allModels = useSelector(
@ -210,6 +226,9 @@ function ModelSelect(props: {}) {
showDelete={options.length > 1}
/>
))}
<Divider />
<StyledListboxOption
key={options.length}
onClick={(e) => {
@ -218,12 +237,23 @@ function ModelSelect(props: {}) {
navigate("/addModel");
}}
value={"addModel" as any}
className="font-bold"
>
+ Add Model
<div className="flex items-center">
<PlusIcon className="w-4 h-4 mr-2" />
Add Model
</div>
</StyledListboxOption>
<i style={{ color: lightGray, padding: "4px", marginTop: "4px" }}>
<Divider />
<i
style={{
color: lightGray,
padding: "4px",
marginTop: "4px",
display: "block",
}}
>
{getMetaKeyLabel()}' to toggle
</i>
</StyledListboxOptions>

View file

@ -7,19 +7,31 @@ export function useWebviewListener<T extends keyof ToWebviewProtocol>(
messageType: T,
handler: (data: ToWebviewProtocol[T][0]) => Promise<ToWebviewProtocol[T][1]>,
dependencies?: any[],
skip?: boolean,
) {
const ideMessenger = useContext(IdeMessengerContext);
useEffect(() => {
const listener = async (event: { data: Message }) => {
if (event.data.messageType === messageType) {
const result = await handler(event.data.data);
ideMessenger.respond(messageType, result, event.data.messageId);
useEffect(
() => {
let listener;
if (!skip) {
listener = async (event: { data: Message }) => {
if (event.data.messageType === messageType) {
const result = await handler(event.data.data);
ideMessenger.respond(messageType, result, event.data.messageId);
}
};
window.addEventListener("message", listener);
}
};
window.addEventListener("message", listener);
return () => {
window.removeEventListener("message", listener);
};
}, dependencies ?? []);
return () => {
if (listener) {
window.removeEventListener("message", listener);
}
};
},
dependencies ? [...dependencies, skip] : [skip],
);
}

View file

@ -12,7 +12,6 @@ import {
useCallback,
useContext,
useEffect,
useLayoutEffect,
useRef,
useState,
} from "react";
@ -55,6 +54,8 @@ import {
} from "../util";
import { getLocalStorage, setLocalStorage } from "../util/localStorage";
import { FREE_TRIAL_LIMIT_REQUESTS } from "../util/freeTrial";
import { ChatScrollAnchor } from "../components/ChatScrollAnchor";
import { TutorialCard } from "../components/mainInput/TutorialCard";
const TopGuiDiv = styled.div`
overflow-y: scroll;
@ -143,79 +144,59 @@ function fallbackRender({ error, resetErrorBoundary }) {
);
}
interface GUIProps {
firstObservation?: any;
}
function GUI(props: GUIProps) {
// #region Hooks
function GUI() {
const posthog = usePostHog();
const dispatch = useDispatch();
const navigate = useNavigate();
const ideMessenger = useContext(IdeMessengerContext);
// #endregion
// #region Selectors
const sessionState = useSelector((state: RootState) => state.state);
const defaultModel = useSelector(defaultModelSelector);
const active = useSelector((state: RootState) => state.state.active);
// #endregion
// #region State
const [stepsOpen, setStepsOpen] = useState<(boolean | undefined)[]>([]);
const [showLoading, setShowLoading] = useState(false);
useEffect(() => {
setTimeout(() => {
setShowLoading(true);
}, 5000);
}, []);
// #endregion
const mainTextInputRef = useRef<HTMLInputElement>(null);
const topGuiDivRef = useRef<HTMLDivElement>(null);
// #region Effects
const [userScrolledAwayFromBottom, setUserScrolledAwayFromBottom] =
useState<boolean>(false);
const [isAtBottom, setIsAtBottom] = useState<boolean>(false);
const state = useSelector((state: RootState) => state.state);
const [showTutorialCard, setShowTutorialCard] = useState<boolean>(
getLocalStorage("showTutorialCard"),
);
const onCloseTutorialCard = () => {
posthog.capture("closedTutorialCard");
setLocalStorage("showTutorialCard", false);
setShowTutorialCard(false);
};
const handleScroll = () => {
// Temporary fix to account for additional height when code blocks are added
const OFFSET_HERUISTIC = 300;
if (!topGuiDivRef.current) return;
const { scrollTop, scrollHeight, clientHeight } = topGuiDivRef.current;
const atBottom =
scrollHeight - clientHeight <= scrollTop + OFFSET_HERUISTIC;
setIsAtBottom(atBottom);
};
useEffect(() => {
const handleScroll = () => {
// Scroll only if user is within 200 pixels of the bottom of the window.
const edgeOffset = -25;
const scrollPosition = topGuiDivRef.current?.scrollTop || 0;
const scrollHeight = topGuiDivRef.current?.scrollHeight || 0;
const clientHeight = window.innerHeight || 0;
if (!active || !topGuiDivRef.current) return;
if (scrollPosition + clientHeight + edgeOffset >= scrollHeight) {
setUserScrolledAwayFromBottom(false);
} else {
setUserScrolledAwayFromBottom(true);
}
};
const scrollAreaElement = topGuiDivRef.current;
topGuiDivRef.current?.addEventListener("scroll", handleScroll);
scrollAreaElement.scrollTop =
scrollAreaElement.scrollHeight - scrollAreaElement.clientHeight;
return () => {
window.removeEventListener("scroll", handleScroll);
};
}, [topGuiDivRef.current]);
useLayoutEffect(() => {
if (userScrolledAwayFromBottom) return;
topGuiDivRef.current?.scrollTo({
top: topGuiDivRef.current?.scrollHeight,
behavior: "instant" as any,
});
}, [topGuiDivRef.current?.scrollHeight, sessionState.history]);
setIsAtBottom(true);
}, [active]);
useEffect(() => {
// Cmd + Backspace to delete current step
@ -365,7 +346,7 @@ function GUI(props: GUIProps) {
return (
<>
<TopGuiDiv ref={topGuiDivRef}>
<TopGuiDiv ref={topGuiDivRef} onScroll={handleScroll}>
<div className="max-w-3xl m-auto">
<StepsDiv>
{state.history.map((item, index: number) => {
@ -463,7 +444,6 @@ function GUI(props: GUIProps) {
);
})}
</StepsDiv>
<ContinueInputBox
onEnter={(editorContent, modifiers) => {
sendInput(editorContent, modifiers);
@ -487,18 +467,34 @@ function GUI(props: GUIProps) {
>
New Session ({getMetaKeyLabel()} {isJetBrains() ? "J" : "L"})
</NewSessionButton>
) : getLastSessionId() ? (
<NewSessionButton
onClick={async () => {
loadLastSession();
}}
className="mr-auto flex items-center gap-1"
>
<ArrowLeftIcon width="11px" height="11px" />
Last Session
</NewSessionButton>
) : null}
) : (
<>
{getLastSessionId() ? (
<NewSessionButton
onClick={async () => {
loadLastSession();
}}
className="mr-auto flex items-center gap-1"
>
<ArrowLeftIcon width="11px" height="11px" />
Last Session
</NewSessionButton>
) : null}
{!!showTutorialCard && (
<div className="flex justify-center w-full">
<TutorialCard onClose={onCloseTutorialCard} />
</div>
)}
</>
)}
</div>
<ChatScrollAnchor
scrollAreaRef={topGuiDivRef}
isAtBottom={isAtBottom}
trackVisibility={active}
/>
</TopGuiDiv>
{active && (
<StopButton

View file

@ -35,6 +35,7 @@ export function useOnboarding() {
if (onboardingStatus === "Started") {
setLocalStorage("onboardingStatus", "Completed");
setLocalStorage("showTutorialCard", true);
posthog.capture("Onboarding Step", { status: "Completed" });
}

View file

@ -14,6 +14,7 @@ type LocalStorageTypes = {
indexingState: IndexingProgressUpdate;
signedInToGh: boolean;
isOnboardingInProgress: boolean;
showTutorialCard: boolean;
};
export function getLocalStorage<T extends keyof LocalStorageTypes>(

40
packages/config-types/package-lock.json generated Normal file
View file

@ -0,0 +1,40 @@
{
"name": "@continuedev/config-types",
"version": "1.0.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@continuedev/config-types",
"version": "1.0.4",
"license": "Apache-2.0",
"dependencies": {
"zod": "^3.23.8"
},
"devDependencies": {
"typescript": "^5.5.2"
}
},
"node_modules/typescript": {
"version": "5.5.2",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.5.2.tgz",
"integrity": "sha512-NcRtPEOsPFFWjobJEtfihkLCZCXZt/os3zf8nTxjVH3RvTSxjrCamJpbExGvYOF+tFHc3pA65qpdwPbzjohhew==",
"dev": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
},
"node_modules/zod": {
"version": "3.23.8",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.23.8.tgz",
"integrity": "sha512-XBx9AXhXktjUqnepgTiE5flcKIYWi/rme0Eaj+5Y0lftuGBq+jyRu/md4WnuxqgP1ubdpNCsYEYPxrzVHD8d6g==",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
}
}
}

View file

@ -0,0 +1,20 @@
{
"name": "@continuedev/config-types",
"version": "1.0.7",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "tsc"
},
"author": "Nate Sesti and Ty Dunn",
"license": "Apache-2.0",
"devDependencies": {
"typescript": "^5.5.2"
},
"dependencies": {
"zod": "^3.23.8"
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,207 @@
import { z } from "zod";
export const completionOptionsSchema = 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(),
keepAlive: z.number().optional(),
raw: z.boolean().optional(),
stream: z.boolean().optional(),
});
export type CompletionOptions = z.infer<typeof completionOptionsSchema>;
export const clientCertificateOptionsSchema = z.object({
cert: z.string(),
key: z.string(),
passphrase: z.string().optional(),
});
export type ClientCertificateOptions = z.infer<
typeof clientCertificateOptionsSchema
>;
export const requestOptionsSchema = 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(),
clientCertificate: clientCertificateOptionsSchema.optional(),
});
export type RequestOptions = z.infer<typeof requestOptionsSchema>;
export const modelDescriptionSchema = z.object({
title: z.string(),
provider: z.enum([
"openai",
"anthropic",
"cohere",
"ollama",
"huggingface-tgi",
"huggingface-inference-api",
"replicate",
"gemini",
"mistral",
"bedrock",
"cloudflare",
"azure",
"continue-proxy",
]),
model: z.string(),
apiKey: z.string().optional(),
apiBase: z.string().optional(),
contextLength: 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",
])
.optional(),
completionOptions: completionOptionsSchema.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(),
});
export type ModelDescription = z.infer<typeof modelDescriptionSchema>;
export const embeddingsProviderSchema = z.object({
provider: z.enum([
"transformers.js",
"ollama",
"openai",
"cohere",
"free-trial",
"gemini",
"continue-proxy",
]),
apiBase: z.string().optional(),
apiKey: z.string().optional(),
model: z.string().optional(),
engine: z.string().optional(),
apiType: z.string().optional(),
apiVersion: z.string().optional(),
requestOptions: requestOptionsSchema.optional(),
});
export type EmbeddingsProvider = z.infer<typeof embeddingsProviderSchema>;
export const uiOptionsSchema = z.object({
codeBlockToolbarPosition: z.enum(["top", "bottom"]).optional(),
fontSize: z.number().optional(),
displayRawMarkdown: z.boolean().optional(),
});
export type UiOptions = z.infer<typeof uiOptionsSchema>;
export const tabAutocompleteOptionsSchema = z.object({
disable: z.boolean(),
useCopyBuffer: z.boolean(),
useSuffix: z.boolean(),
maxPromptTokens: z.number(),
debounceDelay: z.number(),
maxSuffixPercentage: z.number(),
prefixPercentage: z.number(),
template: z.string().optional(),
multilineCompletions: z.enum(["always", "never", "auto"]),
slidingWindowPrefixPercentage: z.number(),
slidingWindowSize: z.number(),
maxSnippetPercentage: z.number(),
recentlyEditedSimilarityThreshold: z.number(),
useCache: z.boolean(),
onlyMyCode: z.boolean(),
useOtherFiles: z.boolean(),
useRecentlyEdited: z.boolean(),
recentLinePrefixMatchMinLength: z.number(),
disableInFiles: z.array(z.string()).optional(),
useImports: z.boolean().optional(),
});
export type TabAutocompleteOptions = z.infer<
typeof tabAutocompleteOptionsSchema
>;
export const slashCommandSchema = z.object({
name: z.string(),
description: z.string(),
params: z.record(z.any()).optional(),
});
export type SlashCommand = z.infer<typeof slashCommandSchema>;
export const customCommandSchema = z.object({
name: z.string(),
description: z.string(),
params: z.record(z.any()).optional(),
});
export type CustomCommand = z.infer<typeof customCommandSchema>;
export const contextProviderSchema = z.object({
name: z.string(),
params: z.record(z.string(), z.any()),
});
export type ContextProvider = z.infer<typeof contextProviderSchema>;
export const rerankerSchema = z.object({
name: z.enum(["cohere", "voyage", "llm", "continue-proxy"]),
params: z.record(z.any()).optional(),
});
export type Reranker = z.infer<typeof rerankerSchema>;
export const analyticsSchema = z.object({
url: z.string().optional(),
clientKey: z.string().optional(),
});
export type Analytics = z.infer<typeof analyticsSchema>;
export const devDataSchema = z.object({
url: z.string().optional(),
});
export type DevData = z.infer<typeof devDataSchema>;
export const configJsonSchema = z.object({
models: z.array(modelDescriptionSchema),
tabAutocompleteModel: modelDescriptionSchema.optional(),
embeddingsProvider: embeddingsProviderSchema.optional(),
reranker: rerankerSchema.optional(),
analytics: analyticsSchema,
devData: devDataSchema,
allowAnonymousTelemetry: z.boolean().optional(),
systemMessage: z.string().optional(),
completionOptions: completionOptionsSchema.optional(),
requestOptions: requestOptionsSchema.optional(),
slashCommands: z.array(slashCommandSchema).optional(),
customCommands: z.array(customCommandSchema).optional(),
contextProviders: z.array(contextProviderSchema).optional(),
disableIndexing: z.boolean().optional(),
tabAutocompleteOptions: tabAutocompleteOptionsSchema.optional(),
ui: uiOptionsSchema.optional(),
});
export type ConfigJson = z.infer<typeof configJsonSchema>;

View file

@ -0,0 +1,23 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "NodeNext",
"useDefineForClassFields": true,
"lib": ["DOM", "ESNext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "NodeNext",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmitOnError": false,
"types": ["node"],
"outDir": "dist",
"declaration": true
// "sourceMap": true
},
"include": ["src/**/*"]
}

7
packages/fetch/jest.config.d.ts vendored Normal file
View file

@ -0,0 +1,7 @@
/**
* For a detailed explanation regarding each configuration property, visit:
* https://jestjs.io/docs/configuration
*/
import type { Config } from 'jest';
declare const config: Config;
export default config;

View file

@ -0,0 +1,143 @@
/**
* For a detailed explanation regarding each configuration property, visit:
* https://jestjs.io/docs/configuration
*/
const config = {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
// bail: 0,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "/private/var/folders/n_/c3r8w0s95xl271j98y2lzhz80000gn/T/jest_dx",
// Automatically clear mock calls, instances, contexts and results before every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
collectCoverage: true,
// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,
// The directory where Jest should output its coverage files
coverageDirectory: "coverage",
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "/node_modules/"
// ],
// Indicates which provider should be used to instrument code for coverage
coverageProvider: "v8",
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// The default configuration for fake timers
// fakeTimers: {
// "enableGlobally": false
// },
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "mjs",
// "cjs",
// "jsx",
// "ts",
// "tsx",
// "json",
// "node"
// ],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
// preset: undefined,
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state before every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state and implementation before every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
// testEnvironment: "jest-environment-node",
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "/node_modules/"
// ],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
// This option allows use of a custom test runner
// testRunner: "jest-circus/runner",
// A map from regular expressions to paths to transformers
// transform: undefined,
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "/node_modules/",
// "\\.pnp\\.[^\\/]+$"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};
export default config;

View file

@ -0,0 +1,199 @@
/**
* For a detailed explanation regarding each configuration property, visit:
* https://jestjs.io/docs/configuration
*/
import type {Config} from 'jest';
const config: Config = {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
// bail: 0,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "/private/var/folders/n_/c3r8w0s95xl271j98y2lzhz80000gn/T/jest_dx",
// Automatically clear mock calls, instances, contexts and results before every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
collectCoverage: true,
// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,
// The directory where Jest should output its coverage files
coverageDirectory: "coverage",
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "/node_modules/"
// ],
// Indicates which provider should be used to instrument code for coverage
coverageProvider: "v8",
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// The default configuration for fake timers
// fakeTimers: {
// "enableGlobally": false
// },
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "mjs",
// "cjs",
// "jsx",
// "ts",
// "tsx",
// "json",
// "node"
// ],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
// preset: undefined,
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state before every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state and implementation before every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
// testEnvironment: "jest-environment-node",
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "/node_modules/"
// ],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
// This option allows use of a custom test runner
// testRunner: "jest-circus/runner",
// A map from regular expressions to paths to transformers
// transform: undefined,
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "/node_modules/",
// "\\.pnp\\.[^\\/]+$"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};
export default config;

3665
packages/fetch/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,25 @@
{
"name": "@continuedev/fetch",
"version": "1.0.2",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
"scripts": {
"test": "jest",
"build": "tsc"
},
"author": "Nate Sesti and Ty Dunn",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.5",
"follow-redirects": "^1.15.6",
"http-proxy-agent": "^7.0.2",
"https-proxy-agent": "^7.0.5",
"node-fetch": "^3.3.2"
},
"devDependencies": {
"@types/follow-redirects": "^1.14.4",
"jest": "^29.7.0"
}
}

117
packages/fetch/src/fetch.ts Normal file
View file

@ -0,0 +1,117 @@
import { RequestOptions } from "@continuedev/config-types/src/index.js";
import * as followRedirects from "follow-redirects";
import { HttpProxyAgent } from "http-proxy-agent";
import { globalAgent } from "https";
import { HttpsProxyAgent } from "https-proxy-agent";
import fetch, { RequestInit, Response } from "node-fetch";
import * as fs from "node:fs";
import tls from "node:tls";
const { http, https } = (followRedirects as any).default;
export function fetchwithRequestOptions(
url_: URL | string,
init?: RequestInit,
requestOptions?: RequestOptions,
): Promise<Response> {
let url = url_;
if (typeof url === "string") {
url = new URL(url);
}
const TIMEOUT = 7200; // 7200 seconds = 2 hours
let globalCerts: string[] = [];
if (process.env.IS_BINARY) {
if (Array.isArray(globalAgent.options.ca)) {
globalCerts = [...globalAgent.options.ca.map((cert) => cert.toString())];
} else if (typeof globalAgent.options.ca !== "undefined") {
globalCerts.push(globalAgent.options.ca.toString());
}
}
const ca = Array.from(new Set([...tls.rootCertificates, ...globalCerts]));
const customCerts =
typeof requestOptions?.caBundlePath === "string"
? [requestOptions?.caBundlePath]
: requestOptions?.caBundlePath;
if (customCerts) {
ca.push(
...customCerts.map((customCert) => fs.readFileSync(customCert, "utf8")),
);
}
const timeout = (requestOptions?.timeout ?? TIMEOUT) * 1000; // measured in ms
const agentOptions: { [key: string]: any } = {
ca,
rejectUnauthorized: requestOptions?.verifySsl,
timeout,
sessionTimeout: timeout,
keepAlive: true,
keepAliveMsecs: timeout,
};
// Handle ClientCertificateOptions
if (requestOptions?.clientCertificate) {
agentOptions.cert = fs.readFileSync(
requestOptions.clientCertificate.cert,
"utf8",
);
agentOptions.key = fs.readFileSync(
requestOptions.clientCertificate.key,
"utf8",
);
if (requestOptions.clientCertificate.passphrase) {
agentOptions.passphrase = requestOptions.clientCertificate.passphrase;
}
}
const proxy = requestOptions?.proxy;
// Create agent
const protocol = url.protocol === "https:" ? https : http;
const agent =
proxy && !requestOptions?.noProxy?.includes(url.hostname)
? protocol === https
? new HttpsProxyAgent(proxy, agentOptions)
: new HttpProxyAgent(proxy, agentOptions)
: new protocol.Agent(agentOptions);
let headers: { [key: string]: string } = {};
for (const [key, value] of Object.entries(init?.headers || {})) {
headers[key] = value as string;
}
headers = {
...headers,
...requestOptions?.headers,
};
// Replace localhost with 127.0.0.1
if (url.hostname === "localhost") {
url.hostname = "127.0.0.1";
}
// add extra body properties if provided
let updatedBody: string | undefined = undefined;
try {
if (requestOptions?.extraBodyProperties && typeof init?.body === "string") {
const parsedBody = JSON.parse(init.body);
updatedBody = JSON.stringify({
...parsedBody,
...requestOptions.extraBodyProperties,
});
}
} catch (e) {
console.log("Unable to parse HTTP request body: ", e);
}
// fetch the request with the provided options
const resp = fetch(url, {
...init,
body: updatedBody ?? init?.body,
headers: headers,
agent: agent,
});
return resp;
}

View file

@ -0,0 +1,8 @@
export {
streamJSON,
streamResponse,
streamSse,
toAsyncIterable,
} from "./stream.js";
export { fetchwithRequestOptions } from "./fetch.js";

View file

@ -0,0 +1,113 @@
export async function* toAsyncIterable(
nodeReadable: NodeJS.ReadableStream,
): AsyncGenerator<Uint8Array> {
for await (const chunk of nodeReadable) {
yield chunk as Uint8Array;
}
}
export async function* streamResponse(
response: Response,
): AsyncGenerator<string> {
if (response.status !== 200) {
throw new Error(await response.text());
}
if (!response.body) {
throw new Error("No response body returned.");
}
// Get the major version of Node.js
const nodeMajorVersion = parseInt(process.versions.node.split(".")[0], 10);
if (nodeMajorVersion >= 20) {
// Use the new API for Node 20 and above
const stream = (ReadableStream as any).from(response.body);
for await (const chunk of stream.pipeThrough(
new TextDecoderStream("utf-8"),
)) {
yield chunk;
}
} else {
// Fallback for Node versions below 20
// Streaming with this method doesn't work as version 20+ does
const decoder = new TextDecoder("utf-8");
const nodeStream = response.body as unknown as NodeJS.ReadableStream;
for await (const chunk of toAsyncIterable(nodeStream)) {
yield decoder.decode(chunk, { stream: true });
}
}
}
function parseDataLine(line: string): any {
const json = line.startsWith("data: ")
? line.slice("data: ".length)
: line.slice("data:".length);
try {
const data = JSON.parse(json);
if (data.error) {
throw new Error(`Error streaming response: ${data.error}`);
}
return data;
} catch (e) {
throw new Error(`Malformed JSON sent from server: ${json}`);
}
}
function parseSseLine(line: string): { done: boolean; data: any } {
if (line.startsWith("data: [DONE]")) {
return { done: true, data: undefined };
}
if (line.startsWith("data:")) {
return { done: false, data: parseDataLine(line) };
}
if (line.startsWith(": ping")) {
return { done: true, data: undefined };
}
return { done: false, data: undefined };
}
export async function* streamSse(response: Response): AsyncGenerator<any> {
let buffer = "";
for await (const value of streamResponse(response)) {
buffer += value;
let position: number;
while ((position = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, position);
buffer = buffer.slice(position + 1);
const { done, data } = parseSseLine(line);
if (done) {
break;
}
if (data) {
yield data;
}
}
}
if (buffer.length > 0) {
const { done, data } = parseSseLine(buffer);
if (!done && data) {
yield data;
}
}
}
export async function* streamJSON(response: Response): AsyncGenerator<any> {
let buffer = "";
for await (const value of streamResponse(response)) {
buffer += value;
let position;
while ((position = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, position);
const data = JSON.parse(line);
yield data;
buffer = buffer.slice(position + 1);
}
}
}

View file

@ -0,0 +1,23 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "NodeNext",
"useDefineForClassFields": true,
"lib": ["DOM", "ESNext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "NodeNext",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmitOnError": false,
"types": ["node"],
"outDir": "dist",
"declaration": true
// "sourceMap": true
},
"include": ["src/**/*"]
}

546
packages/openai-adapters/package-lock.json generated Normal file
View file

@ -0,0 +1,546 @@
{
"name": "@continuedev/openai-adapters",
"version": "1.0.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@continuedev/openai-adapters",
"version": "1.0.3",
"license": "Apache-2.0",
"dependencies": {
"@azure/openai": "^1.0.0-beta.12",
"@continuedev/config-types": "^1.0.5",
"@continuedev/fetch": "^1.0.1",
"node-fetch": "^3.3.2",
"openai": "^4.52.5"
},
"devDependencies": {
"@types/follow-redirects": "^1.14.4"
}
},
"node_modules/@azure-rest/core-client": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/@azure-rest/core-client/-/core-client-1.4.0.tgz",
"integrity": "sha512-ozTDPBVUDR5eOnMIwhggbnVmOrka4fXCs8n8mvUo4WLLc38kki6bAOByDoVZZPz/pZy2jMt2kwfpvy/UjALj6w==",
"dependencies": {
"@azure/abort-controller": "^2.0.0",
"@azure/core-auth": "^1.3.0",
"@azure/core-rest-pipeline": "^1.5.0",
"@azure/core-tracing": "^1.0.1",
"@azure/core-util": "^1.0.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/abort-controller": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/@azure/abort-controller/-/abort-controller-2.1.2.tgz",
"integrity": "sha512-nBrLsEWm4J2u5LpAPjxADTlq3trDgVZZXHNKabeXZtpq3d3AbN/KGO82R87rdDz5/lYB024rtEf10/q0urNgsA==",
"dependencies": {
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/core-auth": {
"version": "1.7.2",
"resolved": "https://registry.npmjs.org/@azure/core-auth/-/core-auth-1.7.2.tgz",
"integrity": "sha512-Igm/S3fDYmnMq1uKS38Ae1/m37B3zigdlZw+kocwEhh5GjyKjPrXKO2J6rzpC1wAxrNil/jX9BJRqBshyjnF3g==",
"dependencies": {
"@azure/abort-controller": "^2.0.0",
"@azure/core-util": "^1.1.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/core-rest-pipeline": {
"version": "1.16.2",
"resolved": "https://registry.npmjs.org/@azure/core-rest-pipeline/-/core-rest-pipeline-1.16.2.tgz",
"integrity": "sha512-Hnhm/PG9/SQ07JJyLDv3l9Qr8V3xgAe1hFoBYzt6LaalMxfL/ZqFaZf/bz5VN3pMcleCPwl8ivlS2Fjxq/iC8Q==",
"dependencies": {
"@azure/abort-controller": "^2.0.0",
"@azure/core-auth": "^1.4.0",
"@azure/core-tracing": "^1.0.1",
"@azure/core-util": "^1.9.0",
"@azure/logger": "^1.0.0",
"http-proxy-agent": "^7.0.0",
"https-proxy-agent": "^7.0.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/core-sse": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/@azure/core-sse/-/core-sse-2.1.2.tgz",
"integrity": "sha512-yf+pFIu8yCzXu9RbH2+8kp9vITIKJLHgkLgFNA6hxiDHK3fxeP596cHUj4c8Cm8JlooaUnYdHmF84KCZt3jbmw==",
"dependencies": {
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/core-tracing": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@azure/core-tracing/-/core-tracing-1.1.2.tgz",
"integrity": "sha512-dawW9ifvWAWmUm9/h+/UQ2jrdvjCJ7VJEuCJ6XVNudzcOwm53BFZH4Q845vjfgoUAM8ZxokvVNxNxAITc502YA==",
"dependencies": {
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/core-util": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/@azure/core-util/-/core-util-1.9.1.tgz",
"integrity": "sha512-OLsq0etbHO1MA7j6FouXFghuHrAFGk+5C1imcpQ2e+0oZhYF07WLA+NW2Vqs70R7d+zOAWiWM3tbE1sXcDN66g==",
"dependencies": {
"@azure/abort-controller": "^2.0.0",
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/logger": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/@azure/logger/-/logger-1.1.3.tgz",
"integrity": "sha512-J8/cIKNQB1Fc9fuYqBVnrppiUtW+5WWJPCj/tAokC5LdSTwkWWttN+jsRgw9BLYD7JDBx7PceiqOBxJJ1tQz3Q==",
"dependencies": {
"tslib": "^2.6.2"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@azure/openai": {
"version": "1.0.0-beta.12",
"resolved": "https://registry.npmjs.org/@azure/openai/-/openai-1.0.0-beta.12.tgz",
"integrity": "sha512-qKblxr6oVa8GsyNzY+/Ub9VmEsPYKhBrUrPaNEQiM+qrxnBPVm9kaeqGFFb/U78Q2zOabmhF9ctYt3xBW0nWnQ==",
"dependencies": {
"@azure-rest/core-client": "^1.1.7",
"@azure/core-auth": "^1.4.0",
"@azure/core-rest-pipeline": "^1.13.0",
"@azure/core-sse": "^2.0.0",
"@azure/core-util": "^1.4.0",
"@azure/logger": "^1.0.3",
"tslib": "^2.4.0"
},
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/@continuedev/config-types": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/@continuedev/config-types/-/config-types-1.0.5.tgz",
"integrity": "sha512-Uv3JWKmpgSo9cMhZb2hWoJgR2ezuAn3CenEziWT/5d7mddPLzvuuHgFX6aDjLVVMojS1ul0rpfAd2LGxEb6nDQ==",
"dependencies": {
"zod": "^3.23.8"
}
},
"node_modules/@continuedev/fetch": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.1.tgz",
"integrity": "sha512-vUFyP48WxdeAoVJUmN0nzk5FCiGfMWiW5SZEvJoSmzJMigHEfbsW/2kRCI9hu9LFRw4drN+Wo3fktG7Lb1MabA==",
"dependencies": {
"@continuedev/config-types": "^1.0.5",
"follow-redirects": "^1.15.6",
"http-proxy-agent": "^7.0.2",
"https-proxy-agent": "^7.0.5",
"node-fetch": "^3.3.2"
}
},
"node_modules/@types/follow-redirects": {
"version": "1.14.4",
"resolved": "https://registry.npmjs.org/@types/follow-redirects/-/follow-redirects-1.14.4.tgz",
"integrity": "sha512-GWXfsD0Jc1RWiFmMuMFCpXMzi9L7oPDVwxUnZdg89kDNnqsRfUKXEtUYtA98A6lig1WXH/CYY/fvPW9HuN5fTA==",
"dev": true,
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/node": {
"version": "18.19.39",
"resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.39.tgz",
"integrity": "sha512-nPwTRDKUctxw3di5b4TfT3I0sWDiWoPQCZjXhvdkINntwr8lcoVCKsTgnXeRubKIlfnV+eN/HYk6Jb40tbcEAQ==",
"dependencies": {
"undici-types": "~5.26.4"
}
},
"node_modules/@types/node-fetch": {
"version": "2.6.11",
"resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.11.tgz",
"integrity": "sha512-24xFj9R5+rfQJLRyM56qh+wnVSYhyXC2tkoBndtY0U+vubqNsYXGjufB2nn8Q6gt0LrARwL6UBtMCSVCwl4B1g==",
"dependencies": {
"@types/node": "*",
"form-data": "^4.0.0"
}
},
"node_modules/abort-controller": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz",
"integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==",
"dependencies": {
"event-target-shim": "^5.0.0"
},
"engines": {
"node": ">=6.5"
}
},
"node_modules/agent-base": {
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz",
"integrity": "sha512-H0TSyFNDMomMNJQBn8wFV5YC/2eJ+VXECwOadZJT554xP6cODZHPX3H9QMQECxvrgiSOP1pHjy1sMWQVYJOUOA==",
"dependencies": {
"debug": "^4.3.4"
},
"engines": {
"node": ">= 14"
}
},
"node_modules/agentkeepalive": {
"version": "4.5.0",
"resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.5.0.tgz",
"integrity": "sha512-5GG/5IbQQpC9FpkRGsSvZI5QYeSCzlJHdpBQntCsuTOxhKD8lqKhrleg2Yi7yvMIf82Ycmmqln9U8V9qwEiJew==",
"dependencies": {
"humanize-ms": "^1.2.1"
},
"engines": {
"node": ">= 8.0.0"
}
},
"node_modules/asynckit": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="
},
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
"dependencies": {
"delayed-stream": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/data-uri-to-buffer": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz",
"integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==",
"engines": {
"node": ">= 12"
}
},
"node_modules/debug": {
"version": "4.3.5",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.5.tgz",
"integrity": "sha512-pt0bNEmneDIvdL1Xsd9oDQ/wrQRkXDT4AUWlNZNPKvW5x/jyO9VFXkJUP07vQ2upmw5PlaITaPKc31jK13V+jg==",
"dependencies": {
"ms": "2.1.2"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/debug/node_modules/ms": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
},
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/event-target-shim": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",
"integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==",
"engines": {
"node": ">=6"
}
},
"node_modules/fetch-blob": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz",
"integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/jimmywarting"
},
{
"type": "paypal",
"url": "https://paypal.me/jimmywarting"
}
],
"dependencies": {
"node-domexception": "^1.0.0",
"web-streams-polyfill": "^3.0.3"
},
"engines": {
"node": "^12.20 || >= 14.13"
}
},
"node_modules/follow-redirects": {
"version": "1.15.6",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.6.tgz",
"integrity": "sha512-wWN62YITEaOpSK584EZXJafH1AGpO8RVgElfkuXbTOrPX4fIfOyEpW/CsiNd8JdYrAoOvafRTOEnvsO++qCqFA==",
"funding": [
{
"type": "individual",
"url": "https://github.com/sponsors/RubenVerborgh"
}
],
"engines": {
"node": ">=4.0"
},
"peerDependenciesMeta": {
"debug": {
"optional": true
}
}
},
"node_modules/form-data": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz",
"integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"mime-types": "^2.1.12"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/form-data-encoder": {
"version": "1.7.2",
"resolved": "https://registry.npmjs.org/form-data-encoder/-/form-data-encoder-1.7.2.tgz",
"integrity": "sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A=="
},
"node_modules/formdata-node": {
"version": "4.4.1",
"resolved": "https://registry.npmjs.org/formdata-node/-/formdata-node-4.4.1.tgz",
"integrity": "sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==",
"dependencies": {
"node-domexception": "1.0.0",
"web-streams-polyfill": "4.0.0-beta.3"
},
"engines": {
"node": ">= 12.20"
}
},
"node_modules/formdata-node/node_modules/web-streams-polyfill": {
"version": "4.0.0-beta.3",
"resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-4.0.0-beta.3.tgz",
"integrity": "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==",
"engines": {
"node": ">= 14"
}
},
"node_modules/formdata-polyfill": {
"version": "4.0.10",
"resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz",
"integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==",
"dependencies": {
"fetch-blob": "^3.1.2"
},
"engines": {
"node": ">=12.20.0"
}
},
"node_modules/http-proxy-agent": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",
"integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==",
"dependencies": {
"agent-base": "^7.1.0",
"debug": "^4.3.4"
},
"engines": {
"node": ">= 14"
}
},
"node_modules/https-proxy-agent": {
"version": "7.0.5",
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.5.tgz",
"integrity": "sha512-1e4Wqeblerz+tMKPIq2EMGiiWW1dIjZOksyHWSUm1rmuvw/how9hBHZ38lAGj5ID4Ik6EdkOw7NmWPy6LAwalw==",
"dependencies": {
"agent-base": "^7.0.2",
"debug": "4"
},
"engines": {
"node": ">= 14"
}
},
"node_modules/humanize-ms": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz",
"integrity": "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==",
"dependencies": {
"ms": "^2.0.0"
}
},
"node_modules/mime-db": {
"version": "1.52.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime-types": {
"version": "2.1.35",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
"dependencies": {
"mime-db": "1.52.0"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="
},
"node_modules/node-domexception": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz",
"integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/jimmywarting"
},
{
"type": "github",
"url": "https://paypal.me/jimmywarting"
}
],
"engines": {
"node": ">=10.5.0"
}
},
"node_modules/node-fetch": {
"version": "3.3.2",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz",
"integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==",
"dependencies": {
"data-uri-to-buffer": "^4.0.0",
"fetch-blob": "^3.1.4",
"formdata-polyfill": "^4.0.10"
},
"engines": {
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/node-fetch"
}
},
"node_modules/openai": {
"version": "4.52.5",
"resolved": "https://registry.npmjs.org/openai/-/openai-4.52.5.tgz",
"integrity": "sha512-qqH8GsyPE3z06took/2uWOGqRcrZNlRoPAsihpg4jsl0+2Dfelnw6HDDMep0EI2Cfzw75nn3vHRZehep/IZzxg==",
"dependencies": {
"@types/node": "^18.11.18",
"@types/node-fetch": "^2.6.4",
"abort-controller": "^3.0.0",
"agentkeepalive": "^4.2.1",
"form-data-encoder": "1.7.2",
"formdata-node": "^4.3.2",
"node-fetch": "^2.6.7",
"web-streams-polyfill": "^3.2.1"
},
"bin": {
"openai": "bin/cli"
}
},
"node_modules/openai/node_modules/node-fetch": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
"integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",
"dependencies": {
"whatwg-url": "^5.0.0"
},
"engines": {
"node": "4.x || >=6.0.0"
},
"peerDependencies": {
"encoding": "^0.1.0"
},
"peerDependenciesMeta": {
"encoding": {
"optional": true
}
}
},
"node_modules/tr46": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="
},
"node_modules/tslib": {
"version": "2.6.3",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.3.tgz",
"integrity": "sha512-xNvxJEOUiWPGhUuUdQgAJPKOOJfGnIyKySOc09XkKsgdUV/3E2zvwZYdejjmRgPCgcym1juLH3226yA7sEFJKQ=="
},
"node_modules/undici-types": {
"version": "5.26.5",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz",
"integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA=="
},
"node_modules/web-streams-polyfill": {
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz",
"integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==",
"engines": {
"node": ">= 8"
}
},
"node_modules/webidl-conversions": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="
},
"node_modules/whatwg-url": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
"integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
"dependencies": {
"tr46": "~0.0.3",
"webidl-conversions": "^3.0.0"
}
},
"node_modules/zod": {
"version": "3.23.8",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.23.8.tgz",
"integrity": "sha512-XBx9AXhXktjUqnepgTiE5flcKIYWi/rme0Eaj+5Y0lftuGBq+jyRu/md4WnuxqgP1ubdpNCsYEYPxrzVHD8d6g==",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
}
}
}

View file

@ -0,0 +1,24 @@
{
"name": "@continuedev/openai-adapters",
"version": "1.0.5",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "tsc"
},
"author": "Nate Sesti and Ty Dunn",
"license": "Apache-2.0",
"dependencies": {
"@azure/openai": "^1.0.0-beta.12",
"@continuedev/config-types": "^1.0.5",
"@continuedev/fetch": "^1.0.1",
"node-fetch": "^3.3.2",
"openai": "^4.52.5"
},
"devDependencies": {
"@types/follow-redirects": "^1.14.4"
}
}

View file

@ -0,0 +1,220 @@
import { AzureKeyCredential, OpenAIClient } from "@azure/openai";
import { ModelDescription } from "@continuedev/config-types/src/index.js";
import dotenv from "dotenv";
import {
Completion,
CompletionCreateParamsNonStreaming,
CompletionCreateParamsStreaming,
} from "openai/resources/completions.js";
import {
ChatCompletion,
ChatCompletionChunk,
ChatCompletionCreateParamsNonStreaming,
ChatCompletionCreateParamsStreaming,
} from "openai/resources/index.js";
import { BaseLlmApi, FimCreateParamsStreaming } from "./base.js";
dotenv.config();
const HTTPS_PROXY = process.env.HTTPS_PROXY;
const HTTP_PROXY = process.env.HTTP_PROXY;
const MS_TOKEN = 30;
export class AzureOpenAIApi implements BaseLlmApi {
private client: OpenAIClient;
private config: ModelDescription;
constructor(config: ModelDescription) {
this.config = config;
let proxyOptions;
const PROXY = HTTPS_PROXY ?? HTTP_PROXY;
if (PROXY) {
const url = new URL(PROXY);
proxyOptions = {
host: url.hostname,
port: Number(url.port),
};
}
if (!config.apiBase || !config.apiKey) {
throw new Error("Azure OpenAI API requires apiBase and apiKey");
}
this.client = new OpenAIClient(
config.apiBase,
new AzureKeyCredential(config.apiKey),
{
proxyOptions,
},
);
}
private _bodyToOptions(
body:
| ChatCompletionCreateParamsStreaming
| ChatCompletionCreateParamsNonStreaming,
) {
return {
maxTokens: body.max_tokens ?? undefined,
temperature: body.temperature ?? undefined,
topP: body.top_p ?? undefined,
frequencyPenalty: body.frequency_penalty ?? undefined,
presencePenalty: body.presence_penalty ?? undefined,
stop:
typeof body.stop === "string" ? [body.stop] : body.stop ?? undefined,
};
}
async chatCompletionNonStream(
body: ChatCompletionCreateParamsNonStreaming,
): Promise<ChatCompletion> {
const completion = await this.client.getChatCompletions(
this.config.model,
body.messages,
this._bodyToOptions(body),
);
return {
...completion,
object: "chat.completion",
model: this.config.model,
created: completion.created.getTime(),
usage: completion.usage
? {
total_tokens: completion.usage.totalTokens,
completion_tokens: completion.usage.completionTokens,
prompt_tokens: completion.usage.promptTokens,
}
: undefined,
choices: completion.choices.map((choice) => ({
...choice,
logprobs: null,
finish_reason: "stop",
message: {
role: "assistant",
content: choice.message?.content ?? null,
},
})),
};
}
async *chatCompletionStream(
body: ChatCompletionCreateParamsStreaming,
): AsyncGenerator<ChatCompletionChunk> {
const events = await this.client.streamChatCompletions(
this.config.model,
body.messages,
this._bodyToOptions(body),
);
const eventBuffer: ChatCompletionChunk[] = [];
let done = false;
let tokensOutput = 0;
const ms = MS_TOKEN;
(async () => {
for await (const event of events) {
eventBuffer.push({
...event,
object: "chat.completion.chunk",
model: this.config.model,
created: event.created.getTime(),
choices: event.choices.map((choice: any) => ({
...choice,
logprobs: undefined,
finish_reason: null,
delta: {
role: (choice.delta?.role as any) ?? "assistant",
content: choice.delta?.content ?? "",
},
})),
usage: undefined,
});
}
done = true;
})();
while (!done) {
if (eventBuffer.length > 0) {
const event = eventBuffer.shift()!;
yield event;
tokensOutput += event.choices[0]?.delta.content?.length ?? 0;
} else {
await new Promise((resolve) => setTimeout(resolve, 5));
continue;
}
if (tokensOutput < 100 && eventBuffer.length > 30) {
await new Promise((resolve) => setTimeout(resolve, ms / 3));
} else if (eventBuffer.length < 12) {
await new Promise((resolve) =>
setTimeout(resolve, ms + 20 * (12 - eventBuffer.length)),
);
} else if (eventBuffer.length > 40) {
await new Promise((resolve) => setTimeout(resolve, ms / 2));
} else {
// await new Promise((resolve) => setTimeout(resolve, Math.max(25, 50 - 2 * eventBuffer.length)));
await new Promise((resolve) => setTimeout(resolve, ms));
}
}
for (const event of eventBuffer) yield event;
}
async completionNonStream(
body: CompletionCreateParamsNonStreaming,
): Promise<Completion> {
const { prompt, logprobs, ...restOfBody } = body;
const messages = [
{
role: "user" as any,
content: prompt as any,
},
];
const resp = await this.chatCompletionNonStream({
messages,
...restOfBody,
});
return {
...resp,
object: "text_completion",
choices: resp.choices.map((choice) => ({
...choice,
text: choice.message.content ?? "",
finish_reason: "stop",
logprobs: null,
})),
};
}
async *completionStream(
body: CompletionCreateParamsStreaming,
): AsyncGenerator<Completion> {
const { prompt, logprobs, ...restOfBody } = body;
const messages = [
{
role: "user" as any,
content: prompt as any,
},
];
for await (const event of this.chatCompletionStream({
messages,
...restOfBody,
})) {
yield {
...event,
object: "text_completion",
choices: event.choices.map((choice) => ({
...choice,
text: choice.delta.content ?? "",
finish_reason: "stop",
logprobs: null,
})),
};
}
}
fimStream(
body: FimCreateParamsStreaming,
): AsyncGenerator<ChatCompletionChunk> {
throw new Error(
"Azure OpenAI does not support fill-in-the-middle (FIM) completions.",
);
}
}

View file

@ -0,0 +1,84 @@
import { ModelDescription } from "@continuedev/config-types";
import { streamSse } from "@continuedev/fetch";
import fetch from "node-fetch";
import { OpenAI } from "openai/index.mjs";
import {
ChatCompletion,
ChatCompletionChunk,
ChatCompletionCreateParamsNonStreaming,
ChatCompletionCreateParamsStreaming,
Completion,
CompletionCreateParamsNonStreaming,
CompletionCreateParamsStreaming,
} from "openai/resources/index.mjs";
import { BaseLlmApi, FimCreateParamsStreaming } from "./base.js";
export class OpenAIApi implements BaseLlmApi {
openai: OpenAI;
constructor(protected config: ModelDescription) {
this.openai = new OpenAI({
apiKey: config.apiKey,
baseURL: config.apiBase,
});
}
async chatCompletionNonStream(
body: ChatCompletionCreateParamsNonStreaming,
): Promise<ChatCompletion> {
const response = await this.openai.chat.completions.create(body);
return response;
}
async *chatCompletionStream(
body: ChatCompletionCreateParamsStreaming,
): AsyncGenerator<ChatCompletionChunk, any, unknown> {
const response = await this.openai.chat.completions.create(body);
for await (const result of response) {
yield result;
}
}
async completionNonStream(
body: CompletionCreateParamsNonStreaming,
): Promise<Completion> {
const response = await this.openai.completions.create(body);
return response;
}
async *completionStream(
body: CompletionCreateParamsStreaming,
): AsyncGenerator<Completion, any, unknown> {
const response = await this.openai.completions.create(body);
for await (const result of response) {
yield result;
}
}
async *fimStream(
body: FimCreateParamsStreaming,
): AsyncGenerator<ChatCompletionChunk, any, unknown> {
const endpoint = new URL("fim/completions", this.config.apiBase);
const resp = await fetch(endpoint, {
method: "POST",
body: JSON.stringify({
model: body.model,
prompt: body.prompt,
suffix: body.suffix,
max_tokens: body.max_tokens,
temperature: body.temperature,
top_p: body.top_p,
frequency_penalty: body.frequency_penalty,
presence_penalty: body.presence_penalty,
stop: body.stop,
stream: true,
}),
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"x-api-key": this.config.apiKey ?? "",
Authorization: `Bearer ${this.config.apiKey}`,
},
});
for await (const chunk of streamSse(resp as any)) {
if (chunk.choices && chunk.choices.length > 0) {
yield chunk;
}
}
}
}

View file

@ -0,0 +1,41 @@
import {
ChatCompletion,
ChatCompletionChunk,
ChatCompletionCreateParamsNonStreaming,
ChatCompletionCreateParamsStreaming,
Completion,
CompletionCreateParamsNonStreaming,
CompletionCreateParamsStreaming,
} from "openai/resources/index.mjs";
export interface FimCreateParamsStreaming
extends CompletionCreateParamsStreaming {
suffix: string;
}
export interface BaseLlmApi {
// Chat, no stream
chatCompletionNonStream(
body: ChatCompletionCreateParamsNonStreaming,
): Promise<ChatCompletion>;
// Chat, stream
chatCompletionStream(
body: ChatCompletionCreateParamsStreaming,
): AsyncGenerator<ChatCompletionChunk>;
// Completion, no stream
completionNonStream(
body: CompletionCreateParamsNonStreaming,
): Promise<Completion>;
// Completion, stream
completionStream(
body: CompletionCreateParamsStreaming,
): AsyncGenerator<Completion>;
// FIM, stream
fimStream(
body: FimCreateParamsStreaming,
): AsyncGenerator<ChatCompletionChunk>;
}

View file

@ -0,0 +1,35 @@
import { ModelDescription } from "@continuedev/config-types/src/index.js";
import dotenv from "dotenv";
import { AzureOpenAIApi } from "./apis/AzureOpenAI.js";
import { OpenAIApi } from "./apis/OpenAI.js";
import { BaseLlmApi } from "./apis/base.js";
dotenv.config();
export function constructLlmApi(config: ModelDescription): BaseLlmApi {
switch (config.provider) {
case "openai":
return new OpenAIApi(config);
case "mistral":
return new OpenAIApi({
...config,
apiBase: "https://api.mistral.ai/v1/",
});
case "azure":
return new AzureOpenAIApi(config);
default:
throw new Error(`Unsupported LLM API format: ${config.provider}`);
}
}
export {
type ChatCompletion,
type ChatCompletionChunk,
type ChatCompletionCreateParams,
type ChatCompletionCreateParamsNonStreaming,
type ChatCompletionCreateParamsStreaming,
type Completion,
type CompletionCreateParams,
type CompletionCreateParamsNonStreaming,
type CompletionCreateParamsStreaming,
} from "openai/resources/index.mjs";

View file

@ -0,0 +1,23 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "NodeNext",
"useDefineForClassFields": true,
"lib": ["DOM", "ESNext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "NodeNext",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmitOnError": false,
"types": ["node"],
"outDir": "dist",
"declaration": true
// "sourceMap": true
},
"include": ["src/**/*"]
}