Fix VS Code settings (#1882)

* 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

* JetBrains status bar spinner for autocomplete

* Remove unused images

* partial accept jetbrains

* fix double-rendering of jetbrains completions

* fix offset of multi-line jetbrains completions

* enable/disable actions

* upgrade to version 0.0.54

* fix: wrap editor buttons when out of space (#1727)

* Add .continuerc file to config directory on activation to prevent it's indexing. (#1733)

* Updated the content links that were deprecated in the document (#1709)

Co-authored-by: Ihe Fan <ih.fan.1027@gmail.com>

* Nate/dev (#1739)

* JetBrains status bar spinner for autocomplete

* Remove unused images

* partial accept jetbrains

* fix double-rendering of jetbrains completions

* fix offset of multi-line jetbrains completions

* enable/disable actions

* upgrade to version 0.0.54

* llm-info package

* small profile switching improvements

* instruct cmd+I not to leave placeholders

* @ files in context-providers docs

* onboarding fix

* update jetbrains ci to build gui

* feat: single default quick pick to edit (#1743)

* feat: single default quick pick to edit

* Update quick-actions.md

* Update quick-actions.md

* use defaultQuickAction

* quick fixes

* fix: handle line removal diff (#1744)

* fix: handle line removal diff

* remove comments

* Configurable `maxChunkSize` for embedding providers (#1746)

* Add `maxChunkSize` to `EmbeddingsProvider`

* Add `maxChunkSize` to schema

* add support for docs via config (#1594)

* mistral mamba (#1748)

* 🐍 mistral mamba

* autoscale retrieval based on context length

* autoscale retrieval based on context length

* fix input box movement

* update jetbrains build

* test: add myers diff tests (#1754)

* feat: enhance help center (#1755)

* feat: enhance help center

* Update help.tsx

* feat: add azure provider config (#1764)

* autocomplete reload fix

* logout of control plane

* Update QuickEditQuickPick.ts (#1772)

* Update QuickEditQuickPick.ts

* updates

* Update QuickEditQuickPick.ts

* pass refreshed access token to continue-proxy model

* test: add dir read check for walkDir (#1773)

* test: add dir read check for walkDir

* Update ignore.ts

* Update walkDir.test.ts

* Update walkDir.test.ts

* gpt-4o-mini

* gpt-4o-mini

* gpt4omini to ui selector

* fix: layout alignment (#1779)

* fix: delete old docs index on force re-index (#1778)

* add "Codebase Force Re-Index" command (#1757)

* Add `HuggingFaceTEIReranker` (#1711)

* Add `HuggingFaceTEIReranker`

* Add `huggingface-tei` to `config_schema.json`

* update package.json version

* update config schemas

* skip test failing only due to type error

* fix: convert `walkDir` to an async generator (#1783)

* walkdir to async generator

* add yields

* handle ignore files

* Update CodebaseIndexer.ts

* Update walkDir.ts

* chore: bump VS Code ext version

* fix completions support in ContinueProxy

* add test for walkDir

* IAnalyticsProvider

* feat: crawl `.mdx` docs

* update workspaces on session info change

* rename from profile to workspace (user-facing)

* update config schema files

* feat: improve chat thread ui for better readability (#1786)

* add "language" template variable for autocomplete

* Enable debug logs (#1800)

* Add an enableDebugLogs flag

* Send logs to VSCode

* Refresh index fixes (#1795)

* Use the resultType given to markComplete

This fixes an issue where if there were multiple result types in itemToAction such as an update with UpdateNewVersion and UpdateOldVersion, only the UpdateOldVersion would be hit (which is a noop) and the UpdateNewVersion would never be fired, causing us to never update the timestamp of the tag_catalog.

* Add a Compute and UpdateLastUpdated to refreshIndex

Removes the ability to insert duplicate rows if we're just computing the result. Instead we replace the existing row instead.

* Don't insert compute tags

They are REPLACEd in markComplete now.

* docs: change page heading to model providers (#1684)

* feat: allow JetBrains users to index docs (#1797)

* feat: allow JetBrains users to index docs

* update docs service

* update global context

* throw error popup on jetbrains + transformers

* update toast notifications

* update typings

* fix tsc errors

* Index on file change (#1785)

* Reload the submenu items when the context provider data is refreshed

* update version

* Just call refreshSubmenuItems

* remove log statements

* cleanup

* Remove the Promise declaration

* Copy currentFiles to a new dict since we're going to mutate it

Don't mutate the caller's currentFiles unexpectedly

* Remove reIndexFile and just call index/forceReIndex

* We MUST await the refreshCodebaseIndex call

* Expose send on core

* remove unused import

* Reindex the workspaces on save

* Call core.send

Ideally, we can implement externalRequest on the webview later so we don't have to expose messenger to the VSCode extension

* Always refreshSubmenuItems in refreshCodebaseIndex

* whitespace

* Change messenger back to private

* Add Pause Codebase On Start setting (#1788)

* Add a skipInitialSync function

* Add pauseInitialCodebaseIndex

* docs

* version bump

* Rename to pauseCodebaseIndexOnStart

* Un-shadow file context provider (#1801)

* allow FileContextProvider to handle files

* remove commented-out lines

* chore: add telemetry to alt-enter (#1805)

* Set the indexProgress indicator to paused on startup if pauseCodebaseIndexOnStart is set (#1804)

* Fix Input Toolbar layout (#1792)

* set to flex flex-column

* Remove fixed height and always show the StyledDivs content to hold its size

* Add a Delete Message button to the StepContainer (#1790)

* Add a delete button

* add a delete message action to the GUI

* Fix off by one error

* format

* This index should be less than length

* Update to trash icon

* Simplify walkDir(...) and improve performance by roughly 10x in larger repos (#1806)

The performance of WalkDir is improved by replacing the recursive DFS
with a stack based implementation (less memory in-use during peak
exploration). In addition, some unnecessary flags and options were
removed which allowed the code to be overall simplified. Much less rule
matching is occuring with the same files returned.

Some performance results on my linux host:

small repo:
- 649 files returned by walkDir()
- 9 .gitignore files
- walkDir() old vs new duration: 918 ms to 143 ms

medium sized repo:
- 9271 returned by walkDir()
- 35 .gitignore files
- walkDir() old vs new duration: 10,886 ms to 970ms

large sized repo:
- 197,900 files returned by walkDir()
- 929 .gitignore files
- walkDir() old vs new duration: 498,151 ms to 37,353 ms

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

* modified assistant indicator in UI

* update package.json version

* feat: add Llama 3.1 8B to cloudflare provider options (#1811)

Co-authored-by: jdelorey@cloudflare.com <jdelorey@cloudflare.com>

* increase gemini pro contextLength (#1809)

* fix indentation (#1808)

* Llama 3.1 405b model selection (#1813)

* add support for llama3 405b

* 3.1

* name mapping

* updates to model setup

* fix walkDir tests on windows

* chore: add docs as top level config (#1816)

* chore: add docs as top level config

* Update core.ts

* feat: make @codebase a hardcoded ctx provider (#1818)

* chore: add docs as top level config

* Update core.ts

* feat: make @codebase a hardcoded ctx provider

* docs schema

* Nate/dev (#1819)

* llm-info package

* small profile switching improvements

* instruct cmd+I not to leave placeholders

* @ files in context-providers docs

* onboarding fix

* jetbrains login

* fix jetbrains login

* change beta wording

* proxy context provider

* fix proxy context provider

* revert to prod id, url

* update package.json version

* Add CodeGeeX4 code completion support (#1815)

Includes support for context through code snippets and relative filename resolution.

* manually stop at stop tokens for all providers

* chore: bump tree-sitter (#1828)

* Add Missing Tokens for CodeGeeX4 AutoComplete (#1827)

Previous attempts at using the normal pipe char with CodeGeeX FIM tokens
resulted in empty completion output. However, this was due to <|user|>
and <|assistant|> tokens being necessary for completion. The earlier
working change ommitted these tokens, and its functionality using
deepseek pipes was merely coincidental. This change now properly follows
the CodeGeeX infill guides and should match what the model expects.

In addition to <|user|> and <|assistant|>, the <|endoftext|> token was
added as a stop token.

* additional analytics providers

* fix import error in jetbrains plugin

* explicitly include default context providers

* Remove a copy / pasta section that duplicated the work done in ChunkCodebaseIndexer (#1834)

This cuts the amount of time spent in this section of indexing in half

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

* respect VS Code isTelemetryEnabled

* Update OllamaEmbeddingsProvider.ts (#1839)

* feat: include recently + open files in codebase search (#1833)

* feat: include recently + open files in codebase search

* cleanup

* Update BaseRetrievalPipeline.ts

* add params object to chunkDocument

* Update package-lock.json

* Offload all token counting to worker processes as well as some optimizations to do more token counting in parallel

Adding the workerpool logic broke gui as vite does not support __dirname
or path.join(...). To work around this, moved the gui dependency of
stripImages out of countTokens.ts

* Create CODE_OF_CONDUCT.md (#1843)

* tweaks to new tokenizing

* temporarily skip code chunking tests due to worker files not being present

* update changelog

* update version

* jetbrains refresh token updates

* refresh submenu items on workspace switch

* OpenAI Adapters (#1859)

* embeddings support in openai-adapters

* rerank support in openai-adapters

* cohere embed/rerank

* continue-proxy reranker and embeddings providers

* test for openai-adapters

* embeddings provider and reranker for continue proxy

* fix: missing Content-Type header in OllamaEmbeddingsProvider (#1855)

* Add Language Name Param to AutocompleteTemplate (#1853)

Language name was previously added as a parameter only for string
autocomplete templates. This change provides this same information to
template functions that implement the AutocompleteTemplate interface.

Language name is explicitly supported for the CodeGeeX4 autocomplete
template, and is added here in this change. Explicit language awareness
could also be added for other templates in a future change, like the
holeFillerTemplate used for models without explicit completion support.

* update package.json version

* deepseek FIM endpoint (#1862)

* update package.json version

* continue teams beta setting

* update jetbrains version

* add prompt files

* Update prompts

* Update refreshIndex.ts (#1866)

* Update prompt files (#1867)

* Update prompt files

* Update .gitignore

* Moving Bedrock integration to Converse API to support all models (#1871)

Co-authored-by: Ruben Kostandyan <ruben.kostard@gmail.com>

* Feature support model capability (#1810)

* support capability field

* remove usless code

* support capability field

* add some doc

* support paste image

* support capability field

* remove usless code

* support capability field

* add some doc

* support paste image

* Update docs/docs/setup/configuration.md

add quote

Co-authored-by: Patrick Erichsen <patrick.a.erichsen@gmail.com>

* rename to capabilities

---------

Co-authored-by: jueinin <b1014397160@gmail.com>
Co-authored-by: Patrick Erichsen <patrick.a.erichsen@gmail.com>

* Added details to correlate parts of the Azure OpenAI endpoint URI to config parameters used by continue (#1846)

* Change the onDidSaveTextDocument handler to only reindex the single saved file (#1873)

This will improve scale as before the indexing process was restarted on
every file save.

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

* Copy-paste fix for `code-server` environments (#1844)

* first commit

* review fix

---------

Co-authored-by: Samir Abis <samir.abis@outlook.it>

* More OpenAI Adapters (#1875)

* anthropic adapter

* cohere oai adapter

* gemini oai adapter

* gemini embeddings adapter

* jina reranker

* more openai-compatible providers

* update package.json version

* Convert core/ to NodeNext (#1877)

* convert to nodenext in core

* experimental vm modules

* use imports

* a few ts-ignores

---------

Co-authored-by: Patrick Erichsen <patrick.a.erichsen@gmail.com>

* change vscode setting name

* skip WIP test

---------

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>
Co-authored-by: Gabriel Gordbegli <ggordbegli@gmail.com>
Co-authored-by: Raven-1027 <83693755+Raven-1027@users.noreply.github.com>
Co-authored-by: Ihe Fan <ih.fan.1027@gmail.com>
Co-authored-by: Lukas Kreussel <65088241+LLukas22@users.noreply.github.com>
Co-authored-by: Josh Vera <josh@joshvera.com>
Co-authored-by: Peter Zaback <pzaback@gmail.com>
Co-authored-by: James Delorey <deloreyjmi@gmail.com>
Co-authored-by: jdelorey@cloudflare.com <jdelorey@cloudflare.com>
Co-authored-by: ekatiyar <eashaank@gmail.com>
Co-authored-by: Simo <simo.paasisalo@syke.fi>
Co-authored-by: Ruben Kostandyan <30292877+KoStard@users.noreply.github.com>
Co-authored-by: Ruben Kostandyan <ruben.kostard@gmail.com>
Co-authored-by: Willetta Hegmann <1014397160@qq.com>
Co-authored-by: jueinin <b1014397160@gmail.com>
Co-authored-by: Jack Wong <jack.wong@uright.ca>
Co-authored-by: Samir Abis <158471628+samir-abis-everest@users.noreply.github.com>
Co-authored-by: Samir Abis <samir.abis@outlook.it>
This commit is contained in:
Nate Sesti 2024-07-31 19:49:39 -07:00 • committed by GitHub
parent 00d19e623f
commit a5f9a0d4ff
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
94 changed files with 2280 additions and 2089 deletions

4
.gitignore vendored
View file

@ -166,4 +166,6 @@ Icon?
.continue
# Sandbox env default file
extensions/vscode/manual-testing-sandbox/example.ts
extensions/vscode/manual-testing-sandbox/example.ts
.prompts/

View file

@ -0,0 +1,86 @@
<system>
You will be acting as a senior software engineer performing a code review for a colleague.
</system>
You will follow the guidelines for giving a great code review outlined below:
{{{ url "https://google.github.io/eng-practices/review/reviewer/looking-for.html" }}}
===
Here is the proposed code changes you will be reviewing:
{{{ diff }}}
===
Do not include a greeting. Immediately begin reviewing the changes.
For each file, decide if you need to provide any feedback on the changes.
If so, outline the feedback using one or two sentences.
If a code change is required, then mention the original code, and
then propose a code change to fix it.
Do not add any other text after the suggestion.
If you have no feedback on a file, do not add a comment for that file.
Lastly, provide a one to two summary of your feedback at the end.
Here are some examples.
<example>
### filename.js
The name of this variable is unclear.
Original:
```js
const x = getAllUsers();
```
Suggestion:
```js
const allUsers = getAllUsers();
```
</example>
<example>
### filename.js
This code is overly complex.
Original:
```py
class AgeCalculator:
def __init__(self, birth_year):
self.birth_year = birth_year
def calculate_age(self, current_year):
age = current_year - self.birth_year
return self._validate_and_format_age(age)
def _validate_and_format_age(self, age):
if age < 0:
raise ValueError("Invalid age calculated")
return f"User is {age} years old"
def get_user_age(birth_year, current_year):
calculator = AgeCalculator(birth_year)
return calculator.calculate_age(current_year)
```
Suggestion:
```python
def get_user_age(birth_year, current_year):
return current_year - birth_year
```
</example>
<example>
### Summary
Overall, these changes appear to be minor improvements to the
project structure and code cleanliness.
</example>
Here is the additional input from the code author:
{{ input }}
===
Think through your feedback step by step before replying.

View file

@ -0,0 +1,17 @@
<system>
You will be acting as a senior software engineer performing a code review for a colleague.
</system>
As part of your code review, you will be identifying "code smells". Here is an overview of what a code smell is:
{{{ url "https://martinfowler.com/bliki/CodeSmell.html"}}}
===
You will provide the 5 most important pieces of feedback on the code smells you have identified.
For each piece of feedback, you will provide a short explanation of the issue and suggest a solution.
If there are no code smells, you will write "No code smells were identified in the provided code."
Here is the proposed code changes you will be reviewing:
{{{ diff }}}

11
.prompts/comment.prompt Normal file
View file

@ -0,0 +1,11 @@
<system>
You will be acting as a senior software engineer helping a colleague document their code.
</system>
You will follow the guidelines for writing great code comments:
{{{ url "https://stackoverflow.blog/2021/12/23/best-practices-for-writing-code-comments/" }}}
===
Using this information, write a comment for the following code:
{{{ input }}}

View file

@ -0,0 +1,16 @@
<system>
You will be acting as a senior software engineer helping to debug
a terminal error.
</system>
Here is the error that the user received:
{{{ terminal }}}
Here is the documentation for Jest that you will use to help
the user troubleshoot the error:
{{{ docs "https://jestjs.io/docs/getting-started" }}}
===
Now, let's analyze the error message and the documentation to find a solution.
If there is a valid solution, explain it and provide working code.

View file

@ -0,0 +1,17 @@
<system>
You will be acting as a senior software engineer helping a colleague to create unit tests for their code.
</system>
You will follow the guidelines to understand what unit testing is, and how to generate useful unit tests:
{{{ url "https://aws.amazon.com/what-is/unit-testing/"}}}
===
To better understand how we perform unit testing for this codebase, use the following examples:
{{{ codebase }}}
===
Lastly, here is the additional input from the user on what should be tested, how to write the tests, etc.
{{{ input }}}

38
.vscode/launch.json vendored
View file

@ -114,25 +114,25 @@
"cwd": "${workspaceRoot}/core",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
},
{
"name": "[openai-adapters] Jest Test Debugger, Current Open File",
"type": "node",
"request": "launch",
"runtimeArgs": [
"--inspect-brk",
"${workspaceRoot}/packages/openai-adapters/node_modules/jest/bin/jest.js",
"--runInBand",
"--config",
"${workspaceRoot}/packages/openai-adapters/jest.config.mjs",
"${relativeFile}"
],
"cwd": "${workspaceRoot}/packages/openai-adapters",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"env": {
"NODE_OPTIONS": "--experimental-vm-modules"
}
}
// {
// "name": "[openai-adapters] Jest Test Debugger, Current Open File",
// "type": "node",
// "request": "launch",
// "runtimeArgs": [
// "--inspect-brk",
// "${workspaceRoot}/packages/openai-adapters/node_modules/jest/bin/jest.js",
// "--runInBand",
// "--config",
// "${workspaceRoot}/packages/openai-adapters/jest.config.mjs",
// "${relativeFile}"
// ],
// "cwd": "${workspaceRoot}/packages/openai-adapters",
// "console": "integratedTerminal",
// "internalConsoleOptions": "neverOpen",
// "env": {
// "NODE_OPTIONS": "--experimental-vm-modules"
// }
// }
]
}

View file

@ -44,8 +44,8 @@
"version": "1.0.13",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.574.0",
"@aws-sdk/credential-providers": "^3.596.0",
"@aws-sdk/client-bedrock-runtime": "^3.620.1",
"@aws-sdk/credential-providers": "^3.620.1",
"@continuedev/config-types": "^1.0.10",
"@continuedev/llm-info": "^1.0.1",
"@mozilla/readability": "^0.5.0",

View file

@ -1,6 +1,6 @@
import { IDE, Location } from "..";
import { LANGUAGES } from "./languages";
import { getSymbolsForSnippet } from "./ranking";
import { IDE, Location } from "../index.js";
import { LANGUAGES } from "./languages.js";
import { getSymbolsForSnippet } from "./ranking.js";
interface FileInfo {
filepath: string;

View file

@ -266,7 +266,8 @@ export class CompletionProvider {
filepath = getBasename(filepath);
}
const pattern = ignore().add(options.disableInFiles);
// @ts-ignore
const pattern = ignore.default().add(options.disableInFiles);
if (pattern.ignores(filepath)) {
return undefined;
}
@ -586,7 +587,14 @@ export class CompletionProvider {
});
} else {
// Let the template function format snippets
prompt = template(prefix, suffix, filepath, reponame, lang.name, snippets);
prompt = template(
prefix,
suffix,
filepath,
reponame,
lang.name,
snippets,
);
}
// Completion

View file

@ -1,4 +1,4 @@
import type { LineFilter } from "./lineStream";
import type { LineFilter } from "./lineStream.js";
export interface AutocompleteLanguageInfo {
name: string;

View file

@ -1,6 +1,6 @@
import type { ILLM } from "..";
import { longestCommonSubsequence } from "../util/lcs";
import { lineIsRepeated } from "./lineStream";
import type { ILLM } from "../index.js";
import { longestCommonSubsequence } from "../util/lcs.js";
import { lineIsRepeated } from "./lineStream.js";
function rewritesLineAbove(completion: string, prefix: string): boolean {
const lineAbove = prefix

View file

@ -61,9 +61,7 @@ import {
getPromptFiles,
slashCommandFromPromptFile,
} from "./promptFile.js";
const { execSync } = require("child_process");
import { execSync } from "child_process";
function resolveSerializedConfig(filepath: string): SerializedContinueConfig {
let content = fs.readFileSync(filepath, "utf8");
const config = JSONC.parse(content) as unknown as SerializedContinueConfig;
@ -465,6 +463,7 @@ function finalToBrowserConfig(
systemMessage: m.systemMessage,
requestOptions: m.requestOptions,
promptTemplates: m.promptTemplates as any,
capabilities: m.capabilities,
})),
systemMessage: final.systemMessage,
completionOptions: final.completionOptions,
@ -534,7 +533,7 @@ async function buildConfigTs() {
);
} else {
// Dynamic import esbuild so potentially disastrous errors can be caught
const esbuild = require("esbuild");
const esbuild = await import("esbuild");
await esbuild.build({
entryPoints: [getConfigTsPath()],
@ -586,7 +585,7 @@ async function loadFullConfigNode(
try {
// Try config.ts first
const configJsPath = getConfigJsPath();
const module = await require(configJsPath);
const module = await import(configJsPath);
delete require.cache[require.resolve(configJsPath)];
if (!module.modifyConfig) {
throw new Error("config.ts does not export a modifyConfig function.");
@ -603,7 +602,7 @@ async function loadFullConfigNode(
const configJsPathForRemote = getConfigJsPathForRemote(
ideSettings.remoteConfigServerUrl,
);
const module = await require(configJsPathForRemote);
const module = await import(configJsPathForRemote);
delete require.cache[require.resolve(configJsPathForRemote)];
if (!module.modifyConfig) {
throw new Error("config.ts does not export a modifyConfig function.");

View file

@ -1,13 +1,13 @@
import { ConfigJson } from "@continuedev/config-types";
import { ControlPlaneClient } from "../../control-plane/client.js";
import {
ContinueConfig,
IDE,
IdeSettings,
SerializedContinueConfig,
} from "../..";
import { ControlPlaneClient } from "../../control-plane/client";
import { IProfileLoader } from "./IProfileLoader";
import doLoadConfig from "./doLoadConfig";
} from "../../index.js";
import { IProfileLoader } from "./IProfileLoader.js";
import doLoadConfig from "./doLoadConfig.js";
export default class ControlPlaneProfileLoader implements IProfileLoader {
private static RELOAD_INTERVAL = 1000 * 60 * 15; // every 15 minutes

View file

@ -1,6 +1,6 @@
// ProfileHandlers manage the loading of a config, allowing us to abstract over different ways of getting to a ContinueConfig
import { ContinueConfig } from "../..";
import { ContinueConfig } from "../../index.js";
// After we have the ContinueConfig, the ConfigHandler takes care of everything else (loading models, lifecycle, etc.)
export interface IProfileLoader {

View file

@ -1,7 +1,7 @@
import { ContinueConfig, IDE, IdeSettings } from "../..";
import { ControlPlaneClient } from "../../control-plane/client";
import doLoadConfig from "./doLoadConfig";
import { IProfileLoader } from "./IProfileLoader";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { ContinueConfig, IDE, IdeSettings } from "../../index.js";
import doLoadConfig from "./doLoadConfig.js";
import { IProfileLoader } from "./IProfileLoader.js";
export default class LocalProfileLoader implements IProfileLoader {
static ID = "local";

View file

@ -1,16 +1,16 @@
import { ContinueProxyReranker } from "../../context/rerankers/ContinueProxyReranker.js";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js";
import {
ContinueRcJson,
IDE,
IdeSettings,
SerializedContinueConfig,
} from "../..";
import { ContinueProxyReranker } from "../../context/rerankers/ContinueProxyReranker";
import { ControlPlaneClient } from "../../control-plane/client";
import { TeamAnalytics } from "../../control-plane/TeamAnalytics";
import ContinueProxyEmbeddingsProvider from "../../indexing/embeddings/ContinueProxyEmbeddingsProvider";
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy";
import { Telemetry } from "../../util/posthog";
import { loadFullConfigNode } from "../load";
} from "../../index.js";
import ContinueProxyEmbeddingsProvider from "../../indexing/embeddings/ContinueProxyEmbeddingsProvider.js";
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy.js";
import { Telemetry } from "../../util/posthog.js";
import { loadFullConfigNode } from "../load.js";
export default async function doLoadConfig(
ide: IDE,

View file

@ -1,9 +1,9 @@
import Handlebars from "handlebars";
import path from "path";
import * as YAML from "yaml";
import type { IDE, SlashCommand } from "..";
import { walkDir } from "../indexing/walkDir";
import { stripImages } from "../llm/images";
import type { IDE, SlashCommand } from "../index.js";
import { walkDir } from "../indexing/walkDir.js";
import { stripImages } from "../llm/images.js";
import { renderTemplatedString } from "../llm/llms/index.js";
import { getBasename } from "../util/index.js";

View file

@ -30,7 +30,7 @@ class DatabaseContextProvider extends BaseContextProvider {
const [connectionName, table] = query.split(".");
const getDatabaseAdapter = await require("dbinfoz");
const { getDatabaseAdapter } = await import("dbinfoz");
for (const connection of connections) {
if (connection.name === connectionName) {
@ -87,7 +87,7 @@ class DatabaseContextProvider extends BaseContextProvider {
return contextItems;
}
const getDatabaseAdapter = await require("dbinfoz");
const { getDatabaseAdapter } = await import("dbinfoz");
for (const connection of connections) {
const adapter = getDatabaseAdapter(

View file

@ -1,6 +1,6 @@
import { RequestOptions } from "../../../index.js";
const { convert: adf2md } = require("adf-to-md");
// @ts-ignore
import adf2md from "adf-to-md";
interface JiraClientOptions {
domain: string;
username: string;

View file

@ -20,7 +20,9 @@ class PostgresContextProvider extends BaseContextProvider {
static DEFAULT_SAMPLE_ROWS = 3;
private async getPool() {
const pg = await require("pg");
// @ts-ignore
const pg = await import("pg");
return new pg.Pool({
host: this.options.host,
port: this.options.port,

View file

@ -1,5 +1,5 @@
import { Chunk } from "../..";
import { deduplicateArray } from "../../util";
import { Chunk } from "../../index.js";
import { deduplicateArray } from "../../util/index.js";
export function deduplicateChunks(chunks: Chunk[]): Chunk[] {
return deduplicateArray(chunks, (a, b) => {

View file

@ -1,5 +1,5 @@
import { constants, getTimestamp } from "../../deploy/constants";
import { Telemetry } from "../../util/posthog";
import { constants, getTimestamp } from "../../deploy/constants.js";
import { Telemetry } from "../../util/posthog.js";
export async function getHeaders() {
return {

View file

@ -1,9 +1,9 @@
import { Analytics } from "@continuedev/config-types";
import os from "node:os";
import ContinueProxyAnalyticsProvider from "./analytics/ContinueProxyAnalyticsProvider";
import { IAnalyticsProvider } from "./analytics/IAnalyticsProvider";
import LogStashAnalyticsProvider from "./analytics/LogStashAnalyticsProvider";
import PostHogAnalyticsProvider from "./analytics/PostHogAnalyticsProvider";
import ContinueProxyAnalyticsProvider from "./analytics/ContinueProxyAnalyticsProvider.js";
import { IAnalyticsProvider } from "./analytics/IAnalyticsProvider.js";
import LogStashAnalyticsProvider from "./analytics/LogStashAnalyticsProvider.js";
import PostHogAnalyticsProvider from "./analytics/PostHogAnalyticsProvider.js";
function createAnalyticsProvider(
config: Analytics,

View file

@ -1,7 +1,7 @@
import { Analytics } from "@continuedev/config-types";
import fetch from "node-fetch";
import { CONTROL_PLANE_URL } from "../client";
import { IAnalyticsProvider } from "./IAnalyticsProvider";
import { CONTROL_PLANE_URL } from "../client.js";
import { IAnalyticsProvider } from "./IAnalyticsProvider.js";
export default class ContinueProxyAnalyticsProvider
implements IAnalyticsProvider

View file

@ -1,6 +1,6 @@
import { Analytics } from "@continuedev/config-types";
import net from "node:net";
import { IAnalyticsProvider } from "./IAnalyticsProvider";
import { IAnalyticsProvider } from "./IAnalyticsProvider.js";
export default class LogStashAnalyticsProvider implements IAnalyticsProvider {
private host?: string;

View file

@ -1,5 +1,5 @@
import { Analytics } from "@continuedev/config-types";
import { IAnalyticsProvider } from "./IAnalyticsProvider";
import { IAnalyticsProvider } from "./IAnalyticsProvider.js";
export default class PostHogAnalyticsProvider implements IAnalyticsProvider {
client?: any;

View file

@ -1,6 +1,6 @@
import { ConfigJson } from "@continuedev/config-types";
import fetch, { RequestInit, Response } from "node-fetch";
import { ModelDescription } from "..";
import { ModelDescription } from "../index.js";
export interface ControlPlaneSessionInfo {
accessToken: string;

View file

@ -1,11 +1,4 @@
import { v4 as uuidv4 } from "uuid";
import type {
ContextItemId,
EmbeddingsProvider,
IDE,
IndexingProgressUpdate,
SiteIndexingConfig,
} from ".";
import { CompletionProvider } from "./autocomplete/completionProvider.js";
import { ConfigHandler } from "./config/ConfigHandler.js";
import {
@ -19,17 +12,24 @@ import { addModel, addOpenAIKey, deleteModel } from "./config/util.js";
import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache.js";
import { ContinueServerClient } from "./continueServer/stubs/client.js";
import { getAuthUrlForTokenPage } from "./control-plane/auth/index.js";
import { ControlPlaneClient } from "./control-plane/client";
import { ControlPlaneClient } from "./control-plane/client.js";
import type {
ContextItemId,
EmbeddingsProvider,
IDE,
IndexingProgressUpdate,
SiteIndexingConfig,
} from "./index.js";
import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer.js";
import { DocsService } from "./indexing/docs/DocsService.js";
import Ollama from "./llm/llms/Ollama.js";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol/index.js";
import { GlobalContext } from "./util/GlobalContext.js";
import { logDevData } from "./util/devdata.js";
import { DevDataSqliteDb } from "./util/devdataSqlite.js";
import { fetchwithRequestOptions } from "./util/fetchWithOptions.js";
import historyManager from "./util/history.js";
import type { IMessenger, Message } from "./util/messenger";
import type { IMessenger, Message } from "./util/messenger.js";
import { editConfigJson } from "./util/paths.js";
import { Telemetry } from "./util/posthog.js";
import { streamDiffLines } from "./util/verticalEdit.js";

6
core/index.d.ts vendored
View file

@ -339,6 +339,7 @@ export interface LLMOptions {
// GCP Options
region?: string;
projectId?: string;
capabilities?: ModelCapability
}
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
T,
@ -718,6 +719,10 @@ interface BaseCompletionOptions {
stream?: boolean;
}
export interface ModelCapability {
uploadImage?: boolean;
}
export interface ModelDescription {
title: string;
provider: ModelProvider;
@ -730,6 +735,7 @@ export interface ModelDescription {
systemMessage?: string;
requestOptions?: RequestOptions;
promptTemplates?: { [key: string]: string };
capabilities?: ModelCapability
}
export type EmbeddingsProviderName =

View file

@ -50,6 +50,40 @@ export class CodebaseIndexer {
return indexes;
}
public async refreshFile(file: string): Promise<void> {
if (this.pauseToken.paused) {
// NOTE: by returning here, there is a chance that while paused a file is modified and
// then after unpausing the file is not reindexed
return;
}
const workspaceDir = await this.getWorkspaceDir(file);
if (!workspaceDir) {
return;
}
const branch = await this.ide.getBranch(workspaceDir);
const repoName = await this.ide.getRepoName(workspaceDir);
const stats = await this.ide.getLastModified([file]);
const indexesToBuild = await this.getIndexesToBuild();
for (const codebaseIndex of indexesToBuild) {
const tag: IndexTag = {
directory: workspaceDir,
branch,
artifactId: codebaseIndex.artifactId,
};
const [results, lastUpdated, markComplete] = await getComputeDeleteAddRemove(
tag,
{ ...stats },
(filepath) => this.ide.readFile(filepath),
repoName,
);
for await (const _ of codebaseIndex.update(tag, results, markComplete, repoName)) {
lastUpdated.forEach((lastUpdated, path) => {
markComplete([lastUpdated], IndexResultType.UpdateLastUpdated);
});
}
}
}
async *refresh(
workspaceDirs: string[],
abortSignal: AbortSignal,
@ -206,4 +240,14 @@ export class CodebaseIndexer {
};
}
}
private async getWorkspaceDir(filepath: string): Promise<string | undefined> {
const workspaceDirs = await this.ide.getWorkspaceDirs();
for (const workspaceDir of workspaceDirs) {
if (filepath.startsWith(workspaceDir)) {
return workspaceDir;
}
}
return undefined;
}
}

View file

@ -1,6 +1,5 @@
import { Chunk } from "../../index.js";
const request = require("request");
import request from "request";
export async function downloadFromS3(
bucket: string,

View file

@ -1,6 +1,6 @@
import { EmbeddingsProviderName, EmbedOptions } from "../..";
import { CONTROL_PLANE_URL } from "../../control-plane/client";
import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider";
import { CONTROL_PLANE_URL } from "../../control-plane/client.js";
import { EmbeddingsProviderName, EmbedOptions } from "../../index.js";
import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider.js";
class ContinueProxyEmbeddingsProvider extends OpenAIEmbeddingsProvider {
static providerName: EmbeddingsProviderName = "continue-proxy";

View file

@ -1,7 +1,11 @@
import { Response } from "node-fetch";
import { EmbeddingsProviderName, EmbedOptions, FetchFunction } from "../..";
import { withExponentialBackoff } from "../../util/withExponentialBackoff";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider";
import {
EmbeddingsProviderName,
EmbedOptions,
FetchFunction,
} from "../../index.js";
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
class HuggingFaceTEIEmbeddingsProvider extends BaseEmbeddingsProvider {
static providerName: EmbeddingsProviderName = "huggingface-tei";

View file

@ -67,7 +67,9 @@ export const DEFAULT_IGNORE_FILETYPES = [
".csv",
// "*.prompt", // can be incredibly confusing for the LLM to have another set of instructions injected into the prompt
];
export const defaultIgnoreFile = ignore().add(DEFAULT_IGNORE_FILETYPES);
// @ts-ignore
export const defaultIgnoreFile = ignore.default().add(DEFAULT_IGNORE_FILETYPES);
export const DEFAULT_IGNORE_DIRS = [
".git",
".svn",
@ -94,7 +96,9 @@ export const DEFAULT_IGNORE_DIRS = [
"gems",
"vendor",
];
export const defaultIgnoreDir = ignore().add(DEFAULT_IGNORE_DIRS);
// @ts-ignore
export const defaultIgnoreDir = ignore.default().add(DEFAULT_IGNORE_DIRS);
export const DEFAULT_IGNORE =
DEFAULT_IGNORE_FILETYPES.join("\n") + "\n" + DEFAULT_IGNORE_DIRS.join("\n");

View file

@ -121,7 +121,7 @@ enum AddRemoveResultType {
UpdateNewVersion = "updateNewVersion",
UpdateOldVersion = "updateOldVersion",
UpdateLastUpdated = "updateLastUpdated",
Compute = "compute"
Compute = "compute",
}
async function getAddRemoveForTag(
@ -451,7 +451,7 @@ export class GlobalCacheCodeBaseIndex implements CodebaseIndex {
tag: IndexTag,
): Promise<void> {
await this.db.run(
"INSERT INTO global_cache (cacheKey, dir, branch, artifactId) VALUES (?, ?, ?, ?)",
"REPLACE INTO global_cache (cacheKey, dir, branch, artifactId) VALUES (?, ?, ?, ?)",
cacheKey,
tag.directory,
tag.branch,

View file

@ -1,15 +1,13 @@
import path from "path";
import { fileURLToPath } from "url";
process.env.NODE_OPTIONS = "--experimental-vm-modules";
export default {
transform: {
"\\.[jt]sx?$": ["ts-jest", { useESM: true }],
},
moduleNameMapper: {
"(.+)\\.js": "$1",
"^(\\.{1,2}/.*)\\.js$": "$1",
},
extensionsToTreatAsEsm: [".ts"],
preset: "ts-jest/presets/default-esm",

View file

@ -1,4 +1,4 @@
import { ModelProvider, TemplateType } from "../index.js";
import { ModelCapability, ModelProvider, TemplateType } from "../index.js";
import {
anthropicTemplateMessages,
chatmlTemplateMessages,
@ -76,7 +76,9 @@ function modelSupportsImages(
provider: ModelProvider,
model: string,
title: string | undefined,
capabilities: ModelCapability | undefined
): boolean {
if (capabilities?.uploadImage !== undefined) return capabilities.uploadImage
if (!PROVIDER_SUPPORTS_IMAGES.includes(provider)) {
return false;
}

View file

@ -7,6 +7,7 @@ import {
ILLM,
LLMFullCompletionOptions,
LLMOptions,
ModelCapability,
ModelName,
ModelProvider,
PromptLog,
@ -53,7 +54,7 @@ export abstract class BaseLLM implements ILLM {
}
supportsImages(): boolean {
return modelSupportsImages(this.providerName, this.model, this.title);
return modelSupportsImages(this.providerName, this.model, this.title, this.capabilities);
}
supportsCompletions(): boolean {
@ -94,6 +95,7 @@ export abstract class BaseLLM implements ILLM {
llmRequestHook?: (model: string, prompt: string) => any;
apiKey?: string;
apiBase?: string;
capabilities?: ModelCapability
engine?: string;
apiVersion?: string;
@ -158,6 +160,7 @@ export abstract class BaseLLM implements ILLM {
this.apiBase = `${this.apiBase}/`;
}
this.accountId = options.accountId;
this.capabilities = options.capabilities;
this.engine = options.engine;
this.apiVersion = options.apiVersion;

View file

@ -1,215 +1,128 @@
import {
BedrockRuntimeClient,
InvokeModelWithResponseStreamCommand,
} from "@aws-sdk/client-bedrock-runtime";
import { fromIni } from "@aws-sdk/credential-providers";
import {
ChatMessage,
CompletionOptions,
LLMOptions,
MessageContent,
ModelProvider,
} from "../../index.js";
import { stripImages } from "../images.js";
import { BaseLLM } from "../index.js";
class Bedrock extends BaseLLM {
private static PROFILE_NAME: string = "bedrock";
static providerName: ModelProvider = "bedrock";
static defaultOptions: Partial<LLMOptions> = {
region: "us-east-1",
model: "claude-3-sonnet-20240229",
contextLength: 200_000,
};
constructor(options: LLMOptions) {
super(options);
if (!options.apiBase) {
this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`;
}
}
protected async *_streamComplete(
prompt: string,
options: CompletionOptions,
): AsyncGenerator<string> {
const messages = [{ role: "user" as const, content: prompt }];
for await (const update of this._streamChat(messages, options)) {
yield stripImages(update.content);
}
}
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const credentials = await this._getCredentials();
const client = new BedrockRuntimeClient({
region: this.region,
credentials: {
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
sessionToken: credentials.sessionToken || "",
},
});
const toolkit = this._getToolkit(options.model);
const command = toolkit.generateCommand(messages, options);
const response = await client.send(command);
if (response.body) {
for await (const value of response.body) {
const text = toolkit.unwrapResponseChunk(value);
if (text) {
yield { role: "assistant", content: text };
}
BedrockRuntimeClient,
ConverseStreamCommand,
} from "@aws-sdk/client-bedrock-runtime";
import { fromIni } from "@aws-sdk/credential-providers";
import {
ChatMessage,
CompletionOptions,
LLMOptions,
MessageContent,
ModelProvider,
} from "../../index.js";
import { stripImages } from "../images.js";
import { BaseLLM } from "../index.js";
class Bedrock extends BaseLLM {
private static PROFILE_NAME: string = "bedrock";
static providerName: ModelProvider = "bedrock";
static defaultOptions: Partial<LLMOptions> = {
region: "us-east-1",
model: "anthropic.claude-3-sonnet-20240229-v1:0",
contextLength: 200_000,
};
constructor(options: LLMOptions) {
super(options);
if (!options.apiBase) {
this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`;
}
}
}
private async _getCredentials() {
try {
return await fromIni({
profile: Bedrock.PROFILE_NAME,
})();
} catch (e) {
console.warn(
`AWS profile with name ${Bedrock.PROFILE_NAME} not found in ~/.aws/credentials, using default profile`,
);
return await fromIni()();
}
}
private _getToolkit(model: string): BedrockModelToolkit {
if (model.includes("claude-3")) {
return new AnthropicClaude3Toolkit(this);
} else if (model.includes("llama")) {
return new Llama3Toolkit(this);
} else {
throw new Error(
`Model ${model} is currently not supported in Continue for Bedrock`,
);
}
}
}
interface BedrockModelToolkit {
generateCommand(
messages: ChatMessage[],
options: CompletionOptions,
): InvokeModelWithResponseStreamCommand;
unwrapResponseChunk(rawValue: any): string;
}
class AnthropicClaude3Toolkit implements BedrockModelToolkit {
constructor(private bedrock: Bedrock) {}
generateCommand(
messages: ChatMessage[],
options: CompletionOptions,
): InvokeModelWithResponseStreamCommand {
const payload = {
anthropic_version: "bedrock-2023-05-31",
max_tokens: options.maxTokens,
system: this.bedrock.systemMessage,
messages: this._convertMessages(messages),
temperature: options.temperature,
top_p: options.topP,
top_k: options.topK,
// each stop sequence must contain non-whitespace
stop_sequences: options.stop?.filter((stop) => stop.trim() !== ""),
};
return new InvokeModelWithResponseStreamCommand({
body: new TextEncoder().encode(JSON.stringify(payload)),
contentType: "application/json",
modelId: options.model,
});
}
private _convertMessages(msgs: ChatMessage[]): any[] {
return msgs
.filter((m) => m.role !== "system")
.map((message) => this._convertMessage(message));
}
private _convertMessage(message: ChatMessage): any {
return {
role: message.role,
content: this._convertMessageContent(message.content),
};
}
private _convertMessageContent(messageContent: MessageContent): any {
if (typeof messageContent === "string") {
return messageContent;
}
return messageContent.map((part) => {
if (part.type === "text") {
return part;
protected async *_streamComplete(
prompt: string,
options: CompletionOptions,
): AsyncGenerator<string> {
const messages = [{ role: "user" as const, content: prompt }];
for await (const update of this._streamChat(messages, options)) {
yield stripImages(update.content);
}
return {
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: part.imageUrl?.url.split(",")[1],
}
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const credentials = await this._getCredentials();
const client = new BedrockRuntimeClient({
region: this.region,
credentials: {
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
sessionToken: credentials.sessionToken || "",
},
};
});
}
unwrapResponseChunk(rawValue: any): string {
const binaryChunk = rawValue.chunk?.bytes;
const textChunk = new TextDecoder().decode(binaryChunk);
const chunk = JSON.parse(textChunk).delta?.text;
return chunk;
}
}
class Llama3Toolkit implements BedrockModelToolkit {
constructor(private bedrock: Bedrock) {}
generateCommand(
messages: ChatMessage[],
options: CompletionOptions,
): InvokeModelWithResponseStreamCommand {
let prompt = "<|begin_of_text|>";
if (this.bedrock.systemMessage) {
prompt += `<|start_header_id|>system<|end_header_id|>${this.bedrock.systemMessage}<|eot_id|>`;
}
for (const message of messages) {
let content = "";
if (typeof message.content === "string") {
content = message.content;
} else {
for (const part of message.content) {
if (part.type === "text") {
content += part.text || "";
} else {
console.warn("Skipping non-text message part", part);
});
const input = this._generateConverseInput(messages, options);
const command = new ConverseStreamCommand(input);
const response = await client.send(command);
if (response.stream) {
for await (const chunk of response.stream) {
if (chunk.contentBlockDelta?.delta?.text) {
yield { role: "assistant", content: chunk.contentBlockDelta.delta.text };
}
}
}
if (content) {
prompt += `<|start_header_id|>${message.role}<|end_header_id|>${content}<|eot_id|>`;
}
private _generateConverseInput(messages: ChatMessage[], options: CompletionOptions): any {
const convertedMessages = this._convertMessages(messages);
return {
modelId: options.model,
messages: convertedMessages,
system: this.systemMessage ? [{ text: this.systemMessage }] : undefined,
inferenceConfig: {
maxTokens: options.maxTokens,
temperature: options.temperature,
topP: options.topP,
stopSequences: options.stop?.filter((stop) => stop.trim() !== ""),
},
};
}
private _convertMessages(messages: ChatMessage[]): any[] {
return messages.map((message) => ({
role: message.role,
content: this._convertMessageContent(message.content),
}));
}
private _convertMessageContent(messageContent: MessageContent): any[] {
if (typeof messageContent === "string") {
return [{ text: messageContent }];
}
return messageContent.map((part) => {
if (part.type === "text") {
return { text: part.text };
}
if (part.type === "imageUrl" && part.imageUrl) {
return {
image: {
format: "jpeg",
source: {
bytes: Buffer.from(part.imageUrl.url.split(",")[1], "base64"),
},
},
};
}
return null;
}).filter(Boolean);
}
private async _getCredentials() {
try {
return await fromIni({
profile: Bedrock.PROFILE_NAME,
})();
} catch (e) {
console.warn(
`AWS profile with name ${Bedrock.PROFILE_NAME} not found in ~/.aws/credentials, using default profile`,
);
return await fromIni()();
}
}
prompt += "<|start_header_id|>assistant<|end_header_id|>";
const payload = {
prompt,
max_gen_len: options.maxTokens,
temperature: options.temperature,
top_p: options.topP,
};
return new InvokeModelWithResponseStreamCommand({
body: new TextEncoder().encode(JSON.stringify(payload)),
contentType: "application/json",
modelId: options.model,
});
}
unwrapResponseChunk(rawValue: any): string {
const binaryChunk = rawValue.chunk?.bytes;
const textChunk = new TextDecoder().decode(binaryChunk);
const chunk = JSON.parse(textChunk).generation;
return chunk;
}
}
export default Bedrock;
export default Bedrock;

View file

@ -202,7 +202,7 @@ class Gemini extends BaseLLM {
}
} else {
// Handle the case where the expected data structure is not found
console.warn('Unexpected response format:', data);
console.warn("Unexpected response format:", data);
}
}
if (foundIncomplete) {

View file

@ -1,5 +1,5 @@
import Ollama from "./Ollama";
import {LLMOptions, ModelProvider} from "../../index";
import { LLMOptions, ModelProvider } from "../../index.js";
import Ollama from "./Ollama.js";
class Msty extends Ollama {
static providerName: ModelProvider = "msty";

View file

@ -1,5 +1,5 @@
import type { LLMOptions, ModelProvider } from "../../..";
import { CONTROL_PLANE_URL } from "../../../control-plane/client";
import { CONTROL_PLANE_URL } from "../../../control-plane/client.js";
import type { LLMOptions, ModelProvider } from "../../../index.js";
import OpenAI from "../OpenAI.js";
class ContinueProxy extends OpenAI {

2490
core/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -3,7 +3,7 @@
"version": "1.0.13",
"description": "The Continue Core contains functionality that can be shared across web, VS Code, or Node.js server. It is written in TypeScript and contains much of the functionality that was previously inside of the legacy Continue Python Server.",
"scripts": {
"test": "jest",
"test": "NODE_OPTIONS=--experimental-vm-modules jest",
"build:npm": "tsc -p ./tsconfig.npm.json",
"lint": "eslint . --ext ts",
"lint:fix": "eslint . --ext ts --fix"
@ -19,7 +19,10 @@
"@types/jest": "^29.5.12",
"@types/jquery": "^3.5.29",
"@types/mustache": "^4.2.5",
"@types/pg": "^8.11.6",
"@types/request": "^2.48.12",
"@types/uuid": "^9.0.7",
"@types/win-ca": "^3.5.4",
"esbuild": "0.17.19",
"eslint": "^8",
"eslint-plugin-import": "^2.29.1",
@ -30,8 +33,8 @@
"ts-jest": "^29.1.1"
},
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.574.0",
"@aws-sdk/credential-providers": "^3.596.0",
"@aws-sdk/client-bedrock-runtime": "^3.620.1",
"@aws-sdk/credential-providers": "^3.620.1",
"@continuedev/config-types": "^1.0.10",
"@continuedev/llm-info": "^1.0.1",
"@mozilla/readability": "^0.5.0",

View file

@ -1,4 +1,6 @@
/* eslint-disable @typescript-eslint/naming-convention */
import type { AutocompleteInput } from "../autocomplete/completionProvider.js";
import { ProfileDescription } from "../config/ConfigHandler.js";
import type {
BrowserSerializedContinueConfig,
ChatMessage,
@ -14,9 +16,7 @@ import type {
SerializedContinueConfig,
SessionInfo,
SiteIndexingConfig,
} from "..";
import type { AutocompleteInput } from "../autocomplete/completionProvider";
import { ProfileDescription } from "../config/ConfigHandler";
} from "../index.js";
export type ProtocolGeneratorType<T> = AsyncGenerator<{
done?: boolean;

View file

@ -1,3 +1,4 @@
import { ControlPlaneSessionInfo } from "../control-plane/client.js";
import type {
ContinueRcJson,
DiffLine,
@ -10,8 +11,7 @@ import type {
Range,
RangeInFile,
Thread,
} from "..";
import { ControlPlaneSessionInfo } from "../control-plane/client";
} from "../index.js";
export type ToIdeFromWebviewOrCoreProtocol = {
// Methods from IDE type

View file

@ -1,5 +1,5 @@
import type { ContextSubmenuItem } from "..";
import type { RangeInFileWithContents } from "../commands/util";
import type { RangeInFileWithContents } from "../commands/util.js";
import type { ContextSubmenuItem } from "../index.js";
import { ToIdeFromWebviewOrCoreProtocol } from "./ide.js";
import { ToWebviewFromIdeOrCoreProtocol } from "./webview.js";

View file

@ -1,4 +1,4 @@
import type { ContextItemWithId, IndexingProgressUpdate } from "..";
import type { ContextItemWithId, IndexingProgressUpdate } from "../index.js";
export type ToWebviewFromIdeOrCoreProtocol = {
configUpdate: [undefined, void];

View file

@ -1,4 +1,4 @@
import { ChatMessage, LLMOptions, ModelProvider } from "../index";
import { ChatMessage, LLMOptions, ModelProvider } from "../index.js";
import { BaseLLM } from "../llm/index.js";
class DummyLLM extends BaseLLM {

View file

@ -1,10 +1,9 @@
import { IRetrievalPipeline } from "../../../context/retrieval/pipelines/BaseRetrievalPipeline";
import { IRetrievalPipeline } from "../../../context/retrieval/pipelines/BaseRetrievalPipeline.js";
function testRetrievalPipeline(pipeline: IRetrievalPipeline) {
test("should successfully run");
}
describe.skip("RetrievalPipeline", () => {
test.todo("should successfully run");
});

View file

@ -1,22 +1,25 @@
import fs from "node:fs";
import path from "node:path";
import { ConfigHandler } from "../../config/ConfigHandler";
import { ContinueServerClient } from "../../continueServer/stubs/client";
import { CodebaseIndexer, PauseToken } from "../../indexing/CodebaseIndexer";
import { LanceDbIndex } from "../../indexing/LanceDbIndex";
import TransformersJsEmbeddingsProvider from "../../indexing/embeddings/TransformersJsEmbeddingsProvider";
import FileSystemIde from "../../util/filesystem";
import { ConfigHandler } from "../../config/ConfigHandler.js";
import { ContinueServerClient } from "../../continueServer/stubs/client.js";
import { CodebaseIndexer, PauseToken } from "../../indexing/CodebaseIndexer.js";
import { LanceDbIndex } from "../../indexing/LanceDbIndex.js";
import TransformersJsEmbeddingsProvider from "../../indexing/embeddings/TransformersJsEmbeddingsProvider.js";
import FileSystemIde from "../../util/filesystem.js";
import {
getIndexFolderPath,
getIndexSqlitePath,
getLanceDbPath,
} from "../../util/paths";
} from "../../util/paths.js";
import {
addToTestDir,
setUpTestDir,
tearDownTestDir,
TEST_DIR,
} from "../testUtils/testDir";
} from "../testUtils/testDir.js";
import { jest } from "@jest/globals";
jest.useFakeTimers();
const TEST_TS = `\
function main() {

View file

@ -1,5 +1,5 @@
import { ChunkWithoutID } from "../../..";
import { codeChunker } from "../../../indexing/chunk/code";
import { ChunkWithoutID } from "../../../index.js";
import { codeChunker } from "../../../indexing/chunk/code.js";
async function genToArr<T>(generator: AsyncGenerator<T>): Promise<T[]> {
const result: T[] = [];

View file

@ -1,4 +1,4 @@
import { stopAtStopTokens } from "../../autocomplete/charStream";
import { stopAtStopTokens } from "../../autocomplete/charStream.js";
describe("stopAtStopTokens", () => {
async function* createMockStream(chunks: string[]): AsyncGenerator<string> {

View file

@ -1,5 +1,5 @@
// File generated by Continue
import { dedentAndGetCommonWhitespace } from "../../util";
import { dedentAndGetCommonWhitespace } from "../../util/index.js";
describe("dedentAndGetCommonWhitespace", () => {
let originalString: string;

View file

@ -1,4 +1,4 @@
import { deduplicateArray } from "../../util";
import { deduplicateArray } from "../../util/index.js";
describe("deduplicateArray", () => {
it("should return an empty array when given an empty array", () => {

View file

@ -1,5 +1,5 @@
// File generated by Continue
import { getLastNPathParts } from "../../util";
import { getLastNPathParts } from "../../util/index.js";
describe("getLastNPathParts", () => {
const SEP_REGEX = /[\\/]+/;

View file

@ -1,5 +1,5 @@
// This file is generated by Continue
import { longestCommonSubsequence } from "../../util/lcs";
import { longestCommonSubsequence } from "../../util/lcs.js";
describe("longestCommonSubsequence", () => {
beforeAll(() => {

View file

@ -1,5 +1,5 @@
// File generated by Continue
import { mergeJson } from "../../util/merge";
import { mergeJson } from "../../util/merge.js";
describe("mergeJson", () => {
it("should merge two simple JSON objects", () => {

View file

@ -1,6 +1,6 @@
// This file is generated by Continue
import { getRangeInString } from "../../../util/ranges";
import { getRangeInString } from "../../../util/ranges.js";
describe.skip("getRangeInString", () => {
let content: string;

View file

@ -1,6 +1,6 @@
// This file is generated by Continue
import { intersection } from "../../../util/ranges";
import { intersection } from "../../../util/ranges.js";
interface Position {
line: number;

View file

@ -1,4 +1,4 @@
import { maxPosition, minPosition } from "../../../util/ranges";
import { maxPosition, minPosition } from "../../../util/ranges.js";
// This file is generated by Continue
interface Position {

View file

@ -1,4 +1,4 @@
import { union } from "../../../util/ranges";
import { union } from "../../../util/ranges.js";
// This file is generated by Continue
interface Position {

View file

@ -9,8 +9,8 @@
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,

View file

@ -1,4 +1,5 @@
import { globalAgent } from "https";
// @ts-ignore
import { systemCertsAsync } from "system-ca";
export async function setupCa() {
@ -6,11 +7,13 @@ export async function setupCa() {
switch (process.platform) {
case "darwin":
// https://www.npmjs.com/package/mac-ca#usage
require("mac-ca").addToGlobalAgent();
const macCa = await import("mac-ca");
macCa.addToGlobalAgent();
break;
case "win32":
// https://www.npmjs.com/package/win-ca#caveats
require("win-ca").inject("+");
const winCa = await import("win-ca");
winCa.inject("+");
break;
default:
// https://www.npmjs.com/package/system-ca

View file

@ -1,5 +1,5 @@
import { v4 as uuidv4 } from "uuid";
import type { IProtocol } from "../protocol";
import type { IProtocol } from "../protocol/index.js";
export interface Message<T = any> {
messageType: string;

View file

@ -1,5 +1,5 @@
import os from "node:os";
import { TeamAnalytics } from "../control-plane/TeamAnalytics";
import { TeamAnalytics } from "../control-plane/TeamAnalytics.js";
export class Telemetry {
// Set to undefined whenever telemetry is disabled

View file

@ -1,6 +1,6 @@
import { IDE } from "..";
import { ToIdeFromWebviewOrCoreProtocol } from "../protocol/ide";
import { Message } from "./messenger";
import { IDE } from "../index.js";
import { ToIdeFromWebviewOrCoreProtocol } from "../protocol/ide.js";
import { Message } from "./messenger.js";
export class ReverseMessageIde {
private on<T extends keyof ToIdeFromWebviewOrCoreProtocol>(

View file

@ -15,7 +15,7 @@ You can configure Azure OpenAI service through the UI, or you can configure it m
```json title="~/.continue/config.json"
"models": [{
"title": "Azure OpenAI",
"provider": "azure",
"provider": "openai",
"model": "<YOUR_MODEL>",
"apiBase": "<YOUR_DEPLOYMENT_BASE>",
"engine": "<YOUR_ENGINE>",
@ -24,3 +24,11 @@ You can configure Azure OpenAI service through the UI, or you can configure it m
"apiKey": "<MY_API_KEY>"
}]
```
To find out the information from *Azure AI Studio*, select the model that you would like to connect. Under the *Endpoint* section and capture the Target URI.
For example, Target URI of https://just-an-example.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2023-13-15-preview
Maps to:
* model = gpt-4o
* engine = gpt-4o
* apiVersion = 2023-13-15-preview
* apiBase = just-an-example.openai.azure.com

View file

@ -322,3 +322,26 @@ export function modifyConfig(config: Config): Config {
return config;
}
```
## Customizing the LLM capability
Sometimes when you use certain third-party interface providers, such as [one api](https://github.com/songquanpeng/one-api), [openRouter](https://openrouter.ai/), etc., they offer openai-compatible interfaces, but the model names are highly different.
Continue cannot determine the capabilities of the model, whether it supports uploading images or files, etc. You can clearly inform Continue about the capabilities of the model.
```typescript title="~/.continue/config.json"
{
"models": [
{
"title": "kimi",
"provider": "openai",
"model": "moonshot-kimi",
"contextLength": 8192,
"apiBase": "https://any-your-thrid-part-OpenAI-compatible-api-provider/v1",
"capabilities": {
"uploadImage": true
}
}
]
}
```

View file

@ -321,6 +321,16 @@
"title": "Engine",
"description": "Azure OpenAI engine",
"type": "string"
},
"capabilities": {
"type": "object",
"description": "We will attempt to automatically detect the capabilities of the model based on its title and provider, but this may not always be accurate. You can override the model's capabilities here.",
"properties": {
"uploadImage": {
"type": "boolean",
"description": "Indicates whether the model can upload images."
}
}
}
},
"required": ["title", "provider", "model"],

View file

@ -321,6 +321,16 @@
"title": "Engine",
"description": "Azure OpenAI engine",
"type": "string"
},
"capabilities": {
"type": "object",
"description": "We will attempt to automatically detect the capabilities of the model based on its title and provider, but this may not always be accurate. You can override the model's capabilities here.",
"properties": {
"uploadImage": {
"type": "boolean",
"description": "Indicates whether the model can upload images."
}
}
}
},
"required": ["title", "provider", "model"],

View file

@ -321,6 +321,16 @@
"title": "Engine",
"description": "Azure OpenAI engine",
"type": "string"
},
"capabilities": {
"type": "object",
"description": "We will attempt to automatically detect the capabilities of the model based on its title and provider, but this may not always be accurate. You can override the model's capabilities here.",
"properties": {
"uploadImage": {
"type": "boolean",
"description": "Indicates whether the model can upload images."
}
}
}
},
"required": ["title", "provider", "model"],

View file

@ -327,6 +327,16 @@
"title": "Engine",
"description": "Azure OpenAI engine",
"type": "string"
},
"capabilities": {
"type": "object",
"description": "We will attempt to automatically detect the capabilities of the model based on its title and provider, but this may not always be accurate. You can override the model's capabilities here.",
"properties": {
"uploadImage": {
"type": "boolean",
"description": "Indicates whether the model can upload images."
}
}
}
},
"required": [

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "0.9.191",
"version": "0.9.192",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "0.9.191",
"version": "0.9.192",
"license": "Apache-2.0",
"dependencies": {
"@electron/rebuild": "^3.2.10",
@ -95,8 +95,8 @@
"version": "1.0.13",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.574.0",
"@aws-sdk/credential-providers": "^3.596.0",
"@aws-sdk/client-bedrock-runtime": "^3.620.1",
"@aws-sdk/credential-providers": "^3.620.1",
"@continuedev/config-types": "^1.0.10",
"@continuedev/llm-info": "^1.0.1",
"@mozilla/readability": "^0.5.0",
@ -157,7 +157,10 @@
"@types/jest": "^29.5.12",
"@types/jquery": "^3.5.29",
"@types/mustache": "^4.2.5",
"@types/pg": "^8.11.6",
"@types/request": "^2.48.12",
"@types/uuid": "^9.0.7",
"@types/win-ca": "^3.5.4",
"esbuild": "0.17.19",
"eslint": "^8",
"eslint-plugin-import": "^2.29.1",

View file

@ -1,7 +1,7 @@
{
"name": "continue",
"icon": "media/icon.png",
"version": "0.9.191",
"version": "0.9.192",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -74,7 +74,7 @@
"default": true,
"markdownDescription": "Continue collects anonymous usage data, cleaned of PII, to help us improve the product for our users. Read more at [continue.dev › Telemetry](https://docs.continue.dev/telemetry)."
},
"continue.enableContinueForTeamsBeta": {
"continue.enableContinueForTeams": {
"type": "boolean",
"default": false,
"markdownDescription": "Enable Continue for teams beta features (requires window reload)"

View file

@ -252,11 +252,13 @@ export class VsCodeExtension {
filepath.endsWith(".continueignore") ||
filepath.endsWith(".gitignore")
) {
// Update embeddings! (TODO)
// Reindex the workspaces
this.core.invoke("index/forceReIndex", undefined);
} else {
// Reindex the file
const indexer = await this.core.codebaseIndexerPromise;
indexer.refreshFile(filepath);
}
// Reindex the workspaces
this.core.invoke("index/forceReIndex", undefined);
});
// When GitHub sign-in status changes, reload config

View file

@ -523,7 +523,7 @@ class VsCodeIde implements IDE {
),
userToken: settings.get<string>("userToken", ""),
enableControlServerBeta: settings.get<boolean>(
"enableContinueForTeamsBeta",
"enableContinueForTeams",
false,
),
pauseCodebaseIndexOnStart: settings.get<boolean>(

7
gui/package-lock.json generated
View file

@ -88,8 +88,8 @@
"version": "1.0.13",
"license": "Apache-2.0",
"dependencies": {
"@aws-sdk/client-bedrock-runtime": "^3.574.0",
"@aws-sdk/credential-providers": "^3.596.0",
"@aws-sdk/client-bedrock-runtime": "^3.620.1",
"@aws-sdk/credential-providers": "^3.620.1",
"@continuedev/config-types": "^1.0.10",
"@continuedev/llm-info": "^1.0.1",
"@mozilla/readability": "^0.5.0",
@ -150,7 +150,10 @@
"@types/jest": "^29.5.12",
"@types/jquery": "^3.5.29",
"@types/mustache": "^4.2.5",
"@types/pg": "^8.11.6",
"@types/request": "^2.48.12",
"@types/uuid": "^9.0.7",
"@types/win-ca": "^3.5.4",
"esbuild": "0.17.19",
"eslint": "^8",
"eslint-plugin-import": "^2.29.1",

View file

@ -153,6 +153,7 @@ function InputToolbar(props: InputToolbarProps) {
defaultModel.provider,
defaultModel.model,
defaultModel.title,
defaultModel.capabilities
) && (
<span
className="ml-1 mt-0.5"

View file

@ -5,6 +5,7 @@ import Paragraph from "@tiptap/extension-paragraph";
import Placeholder from "@tiptap/extension-placeholder";
import Text from "@tiptap/extension-text";
import { Editor, EditorContent, JSONContent, useEditor } from "@tiptap/react";
import {Plugin} from "@tiptap/pm/state"
import {
ContextItemWithId,
ContextProviderDescription,
@ -42,6 +43,7 @@ import {
getFontSize,
isJetBrains,
isMetaEquivalentKeyPressed,
isWebEnvironment,
} from "../../util";
import CodeBlockExtension from "./CodeBlockExtension";
import { SlashCommand } from "./CommandsExtension";
@ -259,7 +261,34 @@ function TipTapEditor(props: TipTapEditorProps) {
extensions: [
Document,
History,
Image,
Image.extend({
addProseMirrorPlugins() {
const plugin = new Plugin({
props: {
handleDOMEvents: {
paste(view, event) {
const items = event.clipboardData.items;
for (const item of items) {
const file = item.getAsFile()
file &&
modelSupportsImages(defaultModel.provider, defaultModel.model, defaultModel.title, defaultModel.capabilities) &&
handleImageFile(file).then((resp) => {
if (!resp) return
const [img, dataUrl] = resp
const { schema } = view.state;
const node = schema.nodes.image.create({ src: dataUrl });
const tr = view.state.tr.insert(0, node);
view.dispatch(tr);
});
}
event.preventDefault();
}
}
}
})
return [plugin]
}
}),
Placeholder.configure({
placeholder: () =>
historyLengthRef.current === 0
@ -442,6 +471,41 @@ function TipTapEditor(props: TipTapEditorProps) {
return;
}
if (isWebEnvironment()) {
const handleKeyDown = async (event: KeyboardEvent) => {
if (!editor || !editorFocusedRef.current) return;
if ((event.metaKey || event.ctrlKey) && event.key === "x") {
// Cut
const selectedText = editor.state.doc.textBetween(
editor.state.selection.from,
editor.state.selection.to,
);
navigator.clipboard.writeText(selectedText);
editor.commands.deleteSelection();
event.preventDefault();
} else if ((event.metaKey || event.ctrlKey) && event.key === "c") {
// Copy
const selectedText = editor.state.doc.textBetween(
editor.state.selection.from,
editor.state.selection.to,
);
navigator.clipboard.writeText(selectedText);
event.preventDefault();
} else if ((event.metaKey || event.ctrlKey) && event.key === "v") {
// Paste
event.preventDefault(); // Prevent default paste behavior
const clipboardText = await navigator.clipboard.readText();
editor.commands.insertContent(clipboardText);
}
};
document.addEventListener("keydown", handleKeyDown);
return () => {
document.removeEventListener("keydown", handleKeyDown);
};
}
const handleKeyDown = async (event: KeyboardEvent) => {
if (!editor || !editorFocusedRef.current) return;
@ -732,6 +796,7 @@ function TipTapEditor(props: TipTapEditorProps) {
defaultModel.provider,
defaultModel.model,
defaultModel.title,
defaultModel.capabilities
)
) {
return;
@ -780,6 +845,7 @@ function TipTapEditor(props: TipTapEditorProps) {
defaultModel.provider,
defaultModel.model,
defaultModel.title,
defaultModel.capabilities
) && (
<>
<HoverDiv></HoverDiv>

View file

@ -1,13 +1,13 @@
import {
PencilSquareIcon,
Cog6ToothIcon,
BookOpenIcon,
ClipboardDocumentIcon,
Cog6ToothIcon,
PencilSquareIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
import { getMetaKeyLabel } from "../../util";
import styled from "styled-components";
import { lightGray } from "..";
import { defaultBorderRadius, lightGray } from "..";
import { getMetaKeyLabel } from "../../util";
interface TutorialCardProps {
onClose: () => void;
@ -15,7 +15,7 @@ interface TutorialCardProps {
const TutorialCardDiv = styled.div`
border: 1px solid ${lightGray};
border-radius: 0.125rem;
border-radius: ${defaultBorderRadius};
padding: 1rem 2.5rem 1rem 2rem;
margin: 1rem;
max-width: 28rem;

View file

@ -58,10 +58,19 @@ export function getAltKeyLabel(): string {
export function getFontSize(): number {
return getLocalStorage("fontSize") ?? (isJetBrains() ? 15 : 14);
}
export function isJetBrains() {
return getLocalStorage("ide") === "jetbrains";
}
export function isWebEnvironment(): boolean {
return (
typeof window !== "undefined" &&
window.navigator &&
window.navigator.userAgent.indexOf("Electron") === -1
);
}
export function isPrerelease() {
const extensionVersion = getLocalStorage("extensionVersion");
if (!extensionVersion) {

View file

@ -1,8 +1,6 @@
import path from "path";
import { fileURLToPath } from "url";
process.env.NODE_OPTIONS = "--experimental-vm-modules";
export default {
transform: {
"\\.[jt]sx?$": ["ts-jest", { useESM: true }],

View file

@ -1,12 +1,12 @@
{
"name": "@continuedev/openai-adapters",
"version": "1.0.5",
"version": "1.0.8",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@continuedev/openai-adapters",
"version": "1.0.5",
"version": "1.0.8",
"license": "Apache-2.0",
"dependencies": {
"@azure/openai": "^1.0.0-beta.12",

View file

@ -1,6 +1,6 @@
{
"name": "@continuedev/openai-adapters",
"version": "1.0.7",
"version": "1.0.8",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",

View file

@ -0,0 +1,184 @@
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 { ChatCompletionCreateParams } from "openai/src/resources/index.js";
import { LlmApiConfig } from "../index.js";
import {
BaseLlmApi,
CreateRerankResponse,
FimCreateParamsStreaming,
RerankCreateParams,
} from "./base.js";
export class AnthropicApi implements BaseLlmApi {
apiBase: string = "https://api.anthropic.com/v1/";
constructor(protected config: LlmApiConfig) {
this.apiBase = config.apiBase ?? this.apiBase;
if (!this.apiBase.endsWith("/")) {
this.apiBase += "/";
}
}
private _convertBody(oaiBody: ChatCompletionCreateParams) {
let stop = undefined;
if (oaiBody.stop && Array.isArray(oaiBody.stop)) {
stop = oaiBody.stop.filter((x) => x.trim() !== "");
} else if (typeof oaiBody.stop === "string" && oaiBody.stop.trim() !== "") {
stop = [oaiBody.stop];
}
const anthropicBody = {
messages: this._convertMessages(
oaiBody.messages.filter((msg) => msg.role !== "system"),
),
system: oaiBody.messages.find((msg) => msg.role === "system")?.content,
top_p: oaiBody.top_p,
temperature: oaiBody.temperature,
max_tokens: oaiBody.max_tokens ?? 4096, // max_tokens is required
model: oaiBody.model,
stop_sequences: stop,
stream: oaiBody.stream,
};
return anthropicBody;
}
private _convertMessages(
msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[],
): any[] {
const messages = msgs.map((message) => {
if (!Array.isArray(message.content)) {
return message;
}
return {
...message,
content: message.content.map((part) => {
if (part.type === "text") {
return part;
}
return {
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: part.image_url.url.split(",")[1],
},
};
}),
};
});
return messages;
}
async chatCompletionNonStream(
body: ChatCompletionCreateParamsNonStreaming,
): Promise<ChatCompletion> {
const response = await fetch(new URL("messages", this.apiBase), {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": this.config.apiKey,
},
body: JSON.stringify(this._convertBody(body)),
});
const completion = (await response.json()) as any;
return {
id: completion.id,
object: "chat.completion",
model: body.model,
created: Date.now(),
usage: {
total_tokens:
completion.usage.input_tokens + completion.usage.output_tokens,
completion_tokens: completion.usage.output_tokens,
prompt_tokens: completion.usage.input_tokens,
},
choices: [
{
logprobs: null,
finish_reason: "stop",
message: {
role: "assistant",
content: completion.content[0].text,
},
index: 0,
},
],
};
}
async *chatCompletionStream(
body: ChatCompletionCreateParamsStreaming,
): AsyncGenerator<ChatCompletionChunk, any, unknown> {
body.messages;
const response = await fetch(new URL("messages", this.apiBase), {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": this.config.apiKey,
},
body: JSON.stringify(this._convertBody(body)),
});
for await (const value of streamSse(response as any)) {
if (value.delta?.text) {
yield {
id: value.id,
object: "chat.completion.chunk",
model: body.model,
created: Date.now(),
choices: [
{
index: 0,
logprobs: undefined,
finish_reason: null,
delta: {
role: "assistant",
content: value.delta.text,
},
},
],
usage: undefined,
};
}
}
}
async completionNonStream(
body: CompletionCreateParamsNonStreaming,
): Promise<Completion> {
throw new Error("Method not implemented.");
}
async *completionStream(
body: CompletionCreateParamsStreaming,
): AsyncGenerator<Completion, any, unknown> {
throw new Error("Method not implemented.");
}
async *fimStream(
body: FimCreateParamsStreaming,
): AsyncGenerator<ChatCompletionChunk, any, unknown> {
throw new Error("Method not implemented.");
}
async embed(
body: OpenAI.Embeddings.EmbeddingCreateParams,
): Promise<OpenAI.Embeddings.CreateEmbeddingResponse> {
throw new Error("Method not implemented.");
}
async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> {
throw new Error("Method not implemented.");
}
}

View file

@ -1,16 +1,17 @@
import { streamJSON } from "@continuedev/fetch";
import fetch from "node-fetch";
import {
CreateEmbeddingResponse,
EmbeddingCreateParams,
} from "openai/resources/embeddings.mjs";
import { OpenAI } from "openai/index.mjs";
import {
ChatCompletion,
ChatCompletionChunk,
ChatCompletionCreateParams,
ChatCompletionCreateParamsNonStreaming,
ChatCompletionCreateParamsStreaming,
Completion,
CompletionCreateParamsNonStreaming,
CompletionCreateParamsStreaming,
CreateEmbeddingResponse,
EmbeddingCreateParams,
} from "openai/resources/index.mjs";
import { LlmApiConfig } from "../index.js";
import {
@ -20,10 +21,11 @@ import {
RerankCreateParams,
} from "./base.js";
// Cohere is OpenAI-compatible
export class CohereApi implements BaseLlmApi {
apiBase: string = "https://api.cohere.com/v1";
static maxStopSequences = 5;
constructor(protected config: LlmApiConfig) {
this.apiBase = config.apiBase ?? this.apiBase;
if (!this.apiBase.endsWith("/")) {
@ -31,15 +33,109 @@ export class CohereApi implements BaseLlmApi {
}
}
chatCompletionNonStream(
private _convertMessages(
msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[],
): any[] {
return msgs.map((m) => ({
role: m.role === "assistant" ? "CHATBOT" : "USER",
message: m.content,
}));
}
private _convertBody(oaiBody: ChatCompletionCreateParams) {
return {
message: oaiBody.messages.pop()?.content,
chat_history: this._convertMessages(
oaiBody.messages.filter((msg) => msg.role !== "system"),
),
preamble: oaiBody.messages.find((msg) => msg.role === "system")?.content,
model: oaiBody.model,
stream: oaiBody.stream,
temperature: oaiBody.temperature,
max_tokens: oaiBody.max_tokens,
p: oaiBody.top_p,
stop_sequences: oaiBody.stop?.slice(0, CohereApi.maxStopSequences),
frequency_penalty: oaiBody.frequency_penalty,
presence_penalty: oaiBody.presence_penalty,
};
}
async chatCompletionNonStream(
body: ChatCompletionCreateParamsNonStreaming,
): Promise<ChatCompletion> {
throw new Error("Method not implemented.");
const headers = {
"Content-Type": "application/json",
Authorization: `Bearer ${this.config.apiKey}`,
};
const resp = await fetch(new URL("chat", this.apiBase), {
method: "POST",
headers,
body: JSON.stringify(this._convertBody(body)),
});
const data = (await resp.json()) as any;
const { input_tokens, output_tokens } = data.meta.tokens;
return {
id: data.id,
object: "chat.completion",
model: body.model,
created: Date.now(),
usage: {
total_tokens: input_tokens + output_tokens,
completion_tokens: output_tokens,
prompt_tokens: input_tokens,
},
choices: [
{
logprobs: null,
finish_reason: "stop",
message: {
role: "assistant",
content: data.text,
},
index: 0,
},
],
};
}
chatCompletionStream(
async *chatCompletionStream(
body: ChatCompletionCreateParamsStreaming,
): AsyncGenerator<ChatCompletionChunk> {
throw new Error("Method not implemented.");
const headers = {
"Content-Type": "application/json",
Authorization: `Bearer ${this.config.apiKey}`,
};
const resp = await fetch(new URL("chat", this.apiBase), {
method: "POST",
headers,
body: JSON.stringify(this._convertBody(body)),
});
for await (const value of streamJSON(resp as any)) {
if (value.event_type === "text-generation") {
yield {
id: value.id,
object: "chat.completion.chunk",
model: body.model,
created: Date.now(),
choices: [
{
index: 0,
logprobs: undefined,
finish_reason: null,
delta: {
role: "assistant",
content: value.text,
},
},
],
usage: undefined,
};
}
}
}
completionNonStream(
body: CompletionCreateParamsNonStreaming,

View file

@ -0,0 +1,57 @@
import { streamSse } from "@continuedev/fetch";
import fetch from "node-fetch";
import { ChatCompletionChunk } from "openai/resources/index.mjs";
import { LlmApiConfig } from "../index.js";
import { OpenAIApi } from "./OpenAI.js";
import { FimCreateParamsStreaming } from "./base.js";
export class DeepSeekApi extends OpenAIApi {
constructor(config: LlmApiConfig) {
super(config);
this.apiBase = "https://api.deepseek.com/";
}
async *fimStream(
body: FimCreateParamsStreaming,
): AsyncGenerator<ChatCompletionChunk, any, unknown> {
const endpoint = new URL("beta/completions", this.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",
Authorization: `Bearer ${this.config.apiKey}`,
},
});
for await (const chunk of streamSse(resp as any)) {
yield {
choices: [
{
delta: {
content: chunk.choices[0].text,
role: "assistant",
},
finish_reason: chunk.finish_reason,
index: 0,
logprobs: null,
},
],
created: Date.now(),
id: "",
model: body.model,
object: "chat.completion.chunk",
};
}
}
}

View file

@ -0,0 +1,270 @@
import { streamResponse } from "@continuedev/fetch";
import fetch from "node-fetch";
import { OpenAI } from "openai/index.mjs";
import {
ChatCompletion,
ChatCompletionChunk,
ChatCompletionCreateParams,
ChatCompletionCreateParamsNonStreaming,
ChatCompletionCreateParamsStreaming,
Completion,
CompletionCreateParamsNonStreaming,
CompletionCreateParamsStreaming,
CreateEmbeddingResponse,
EmbeddingCreateParams,
} from "openai/resources/index.mjs";
import { LlmApiConfig } from "../index.js";
import {
BaseLlmApi,
CreateRerankResponse,
FimCreateParamsStreaming,
RerankCreateParams,
} from "./base.js";
export class GeminiApi implements BaseLlmApi {
apiBase: string = "https://generativelanguage.googleapis.com/v1beta/";
static maxStopSequences = 5;
constructor(protected config: LlmApiConfig) {
this.apiBase = config.apiBase ?? this.apiBase;
if (!this.apiBase.endsWith("/")) {
this.apiBase += "/";
}
}
private _convertMessages(
msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[],
): any[] {
return msgs.map((m) => ({
role: m.role === "assistant" ? "CHATBOT" : "USER",
message: m.content,
}));
}
private _oaiPartToGeminiPart(
part: OpenAI.Chat.Completions.ChatCompletionContentPart,
) {
return part.type === "text"
? {
text: part.text,
}
: {
inlineData: {
mimeType: "image/jpeg",
data: part.image_url?.url.split(",")[1],
},
};
}
private _convertBody(oaiBody: ChatCompletionCreateParams, url: string) {
const generationConfig: any = {};
if (oaiBody.top_p) {
generationConfig.topP = oaiBody.top_p;
}
if (oaiBody.temperature !== undefined && oaiBody.temperature !== null) {
generationConfig.temperature = oaiBody.temperature;
}
if (oaiBody.max_tokens) {
generationConfig.maxOutputTokens = oaiBody.max_tokens;
}
if (oaiBody.stop) {
const stop = Array.isArray(oaiBody.stop) ? oaiBody.stop : [oaiBody.stop];
generationConfig.stopSequences = stop.filter((x) => x.trim() !== "");
}
const isV1API = url.includes("/v1/");
const contents = oaiBody.messages
.map((msg) => {
if (msg.role === "system" && !isV1API) {
return null; // Don't include system message in contents
}
if (!msg.content) {
return null;
}
return {
role: msg.role === "assistant" ? "model" : "user",
parts:
typeof msg.content === "string"
? [{ text: msg.content }]
: msg.content.map(this._oaiPartToGeminiPart),
};
})
.filter((c) => c !== null);
const sysMsg = oaiBody.messages.find((msg) => msg.role === "system");
const finalBody = {
generationConfig,
contents,
// if this.systemMessage is defined, reformat it for Gemini API
...(sysMsg &&
!isV1API && {
systemInstruction: { parts: [{ text: sysMsg.content }] },
}),
};
return finalBody;
}
async chatCompletionNonStream(
body: ChatCompletionCreateParamsNonStreaming,
): Promise<ChatCompletion> {
let completion = "";
for await (const chunk of this.chatCompletionStream({
...body,
stream: true,
})) {
completion += chunk.choices[0].delta.content;
}
return {
id: "",
object: "chat.completion",
model: body.model,
created: Date.now(),
choices: [
{
index: 0,
logprobs: null,
finish_reason: "stop",
message: {
role: "assistant",
content: completion,
},
},
],
usage: undefined,
};
}
async *chatCompletionStream(
body: ChatCompletionCreateParamsStreaming,
): AsyncGenerator<ChatCompletionChunk> {
const apiURL = new URL(
`models/${body.model}:streamGenerateContent?key=${this.config.apiKey}`,
this.apiBase,
).toString();
const resp = await fetch(apiURL, {
method: "POST",
body: JSON.stringify(this._convertBody(body, apiURL)),
});
let buffer = "";
for await (const chunk of streamResponse(resp as any)) {
buffer += chunk;
if (buffer.startsWith("[")) {
buffer = buffer.slice(1);
}
if (buffer.endsWith("]")) {
buffer = buffer.slice(0, -1);
}
if (buffer.startsWith(",")) {
buffer = buffer.slice(1);
}
const parts = buffer.split("\n,");
let foundIncomplete = false;
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
let data;
try {
data = JSON.parse(part);
} catch (e) {
foundIncomplete = true;
continue; // yo!
}
if (data.error) {
throw new Error(data.error.message);
}
// Check for existence of each level before accessing the final 'text' property
if (data?.candidates?.[0]?.content?.parts?.[0]?.text) {
yield {
id: "",
object: "chat.completion.chunk",
model: body.model,
created: Date.now(),
choices: [
{
index: 0,
logprobs: undefined,
finish_reason: null,
delta: {
role: "assistant",
content: data.candidates[0].content.parts[0].text,
},
},
],
usage: undefined,
};
} else {
// Handle the case where the expected data structure is not found
console.warn("Unexpected response format:", data);
}
}
if (foundIncomplete) {
buffer = parts[parts.length - 1];
} else {
buffer = "";
}
}
}
completionNonStream(
body: CompletionCreateParamsNonStreaming,
): Promise<Completion> {
throw new Error("Method not implemented.");
}
completionStream(
body: CompletionCreateParamsStreaming,
): AsyncGenerator<Completion> {
throw new Error("Method not implemented.");
}
fimStream(
body: FimCreateParamsStreaming,
): AsyncGenerator<ChatCompletionChunk> {
throw new Error("Method not implemented.");
}
async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> {
throw new Error("Method not implemented.");
}
async embed(body: EmbeddingCreateParams): Promise<CreateEmbeddingResponse> {
const inputs = Array.isArray(body.input) ? body.input : [body.input];
const response = await fetch(
new URL(`${body.model}:batchEmbedContents`, this.apiBase),
{
method: "POST",
body: JSON.stringify({
requests: inputs.map((input) => ({
model: body.model,
content: {
role: "user",
parts: [{ text: input }],
},
})),
}),
headers: {
// eslint-disable-next-line @typescript-eslint/naming-convention
"x-goog-api-key": this.config.apiKey,
// eslint-disable-next-line @typescript-eslint/naming-convention
"Content-Type": "application/json",
},
},
);
const data = (await response.json()) as any;
return {
object: "list",
model: body.model,
usage: {
total_tokens: 0,
prompt_tokens: 0,
},
data: data.embeddings.map((embedding: any, index: number) => ({
object: "embedding",
index,
embedding: embedding.values,
})),
};
}
}

View file

@ -0,0 +1,87 @@
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 { LlmApiConfig } from "../index.js";
import {
BaseLlmApi,
CreateRerankResponse,
FimCreateParamsStreaming,
RerankCreateParams,
} from "./base.js";
export class JinaApi implements BaseLlmApi {
apiBase: string = "https://api.jina.ai/v1/";
constructor(protected config: LlmApiConfig) {
this.apiBase = config.apiBase ?? this.apiBase;
if (!this.apiBase.endsWith("/")) {
this.apiBase += "/";
}
}
async chatCompletionNonStream(
body: ChatCompletionCreateParamsNonStreaming,
): Promise<ChatCompletion> {
throw new Error("Method not implemented.");
}
async *chatCompletionStream(
body: ChatCompletionCreateParamsStreaming,
): AsyncGenerator<ChatCompletionChunk, any, unknown> {
throw new Error("Method not implemented.");
}
async completionNonStream(
body: CompletionCreateParamsNonStreaming,
): Promise<Completion> {
throw new Error("Method not implemented.");
}
async *completionStream(
body: CompletionCreateParamsStreaming,
): AsyncGenerator<Completion, any, unknown> {
throw new Error("Method not implemented.");
}
async *fimStream(
body: FimCreateParamsStreaming,
): AsyncGenerator<ChatCompletionChunk, any, unknown> {
throw new Error("Method not implemented.");
}
async embed(
body: OpenAI.Embeddings.EmbeddingCreateParams,
): Promise<OpenAI.Embeddings.CreateEmbeddingResponse> {
throw new Error("Method not implemented.");
}
async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> {
const endpoint = new URL("rerank", this.apiBase);
const response = await fetch(endpoint, {
method: "POST",
body: JSON.stringify(body),
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"x-api-key": this.config.apiKey ?? "",
Authorization: `Bearer ${this.config.apiKey}`,
},
});
const data = (await response.json()) as any;
return {
object: "list",
data: data.results.map((result: any) => ({
index: result.index,
relevance_score: result.relevance_score,
})),
model: body.model,
usage: {
total_tokens: 0,
},
};
}
}

View file

@ -1,7 +1,11 @@
import dotenv from "dotenv";
import { AnthropicApi } from "./apis/Anthropic.js";
import { AzureOpenAIApi } from "./apis/AzureOpenAI.js";
import { BaseLlmApi } from "./apis/base.js";
import { CohereApi } from "./apis/Cohere.js";
import { DeepSeekApi } from "./apis/DeepSeek.js";
import { GeminiApi } from "./apis/Gemini.js";
import { JinaApi } from "./apis/Jina.js";
import { OpenAIApi } from "./apis/OpenAI.js";
dotenv.config();
@ -30,8 +34,34 @@ export function constructLlmApi(config: LlmApiConfig): BaseLlmApi {
apiBase: "https://api.voyageai.com/v1/",
});
case "cohere":
return new CohereApi({
return new CohereApi(config);
case "anthropic":
return new AnthropicApi(config);
case "gemini":
return new GeminiApi(config);
case "jina":
return new JinaApi(config);
case "deepinfra":
return new OpenAIApi({
...config,
apiBase: "https://api.deepinfra.com/v1/openai/",
});
case "deepseek":
return new DeepSeekApi(config);
case "groq":
return new OpenAIApi({
...config,
apiBase: "https://api.groq.com/openai/v1/",
});
case "fireworks":
return new OpenAIApi({
...config,
apiBase: "https://api.fireworks.ai/inference/v1",
});
case "together":
return new OpenAIApi({
...config,
apiBase: "https://api.together.xyz/v1/",
});
default:
throw new Error(`Unsupported LLM API format: ${config.provider}`);

View file

@ -133,6 +133,26 @@ function testConfig(config: LlmApiConfig, chatOnly: boolean = false) {
expect(typeof completion).toBe("string");
expect(completion?.length).toBeGreaterThan(0);
});
test("should acknowledge system message in chat", async () => {
const response = await api.chatCompletionNonStream({
model: config.model,
messages: [
{
role: "system",
content:
"Regardless of what is asked of you, your answer should start with 'RESPONSE: '.",
},
{ role: "user", content: "Who are you?" },
],
stream: false,
});
expect(response.choices.length).toBeGreaterThan(0);
const completion = response.choices[0].message.content;
expect(typeof completion).toBe("string");
expect(completion?.length).toBeGreaterThan(0);
expect(completion?.startsWith("RESPONSE: ")).toBe(true);
});
}
const COMPLETION_TESTS: ({ chatOnly?: boolean } & LlmApiConfig)[] = [
@ -142,6 +162,48 @@ const COMPLETION_TESTS: ({ chatOnly?: boolean } & LlmApiConfig)[] = [
apiKey: process.env.OPENAI_API_KEY!,
chatOnly: true,
},
{
provider: "anthropic",
model: "claude-3-haiku-20240307",
apiKey: process.env.ANTHROPIC_API_KEY!,
chatOnly: true,
},
{
provider: "gemini",
model: "gemini-1.5-flash-latest",
apiKey: process.env.GEMINI_API_KEY!,
chatOnly: true,
},
{
provider: "cohere",
model: "command-r",
apiKey: process.env.COHERE_API_KEY!,
chatOnly: true,
},
{
provider: "fireworks",
model: "accounts/fireworks/models/llama-v3p1-8b-instruct",
apiKey: process.env.FIREWORKS_API_KEY!,
chatOnly: true,
},
{
provider: "groq",
model: "llama3-8b-8192",
apiKey: process.env.GROQ_API_KEY!,
chatOnly: true,
},
{
provider: "deepinfra",
model: "meta-llama/Meta-Llama-3.1-8B-Instruct",
apiKey: process.env.DEEP_INFRA_API_KEY!,
chatOnly: true,
},
{
provider: "together",
model: "meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo",
apiKey: process.env.TOGETHER_API_KEY!,
chatOnly: true,
},
];
const FIM_TESTS: LlmApiConfig[] = [
@ -151,6 +213,11 @@ const FIM_TESTS: LlmApiConfig[] = [
apiKey: process.env.MISTRAL_API_KEY!,
apiBase: "https://api.mistral.ai/v1",
},
{
provider: "deepseek",
model: "deepseek-coder",
apiKey: process.env.DEEPSEEK_API_KEY!,
},
];
const EMBEDDINGS_TESTS: LlmApiConfig[] = [
@ -170,6 +237,11 @@ const EMBEDDINGS_TESTS: LlmApiConfig[] = [
model: "embed-english-v3.0",
apiKey: process.env.COHERE_API_KEY!,
},
{
provider: "gemini",
model: "models/text-embedding-004",
apiKey: process.env.GEMINI_API_KEY!,
},
];
const RERANK_TESTS: LlmApiConfig[] = [
@ -184,6 +256,11 @@ const RERANK_TESTS: LlmApiConfig[] = [
model: "rerank-english-v3.0",
apiKey: process.env.COHERE_API_KEY!,
},
{
provider: "jina",
model: "jina-reranker-v2-base-multilingual",
apiKey: process.env.JINA_API_KEY!,
},
];
describe("should successfully call all adapters", () => {
@ -200,7 +277,7 @@ describe("should successfully call all adapters", () => {
testRerank(config);
});
// FIM_TESTS.forEach((config) => {
// testFim(config);
// });
FIM_TESTS.forEach((config) => {
testFim(config);
});
});

View file

@ -12,7 +12,7 @@
"forceConsistentCasingInFileNames": true,
"moduleResolution": "NodeNext",
"resolveJsonModule": true,
"isolatedModules": true,
"isolatedModules": false,
"noEmitOnError": false,
"types": ["node", "jest"],
"outDir": "dist",