Merge branch 'main' into windows-registry

This commit is contained in:
Nate Sesti 2025-05-19 18:53:15 -07:00 • committed by GitHub
commit d071de37e5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
95 changed files with 1862 additions and 1493 deletions

View file

@ -1,8 +0,0 @@
## 0.0.34 - 2024-03-03
### Added
* diff context provider
### Changed
* Allow LLM servers to handle templating
### Fixed
* Fix a few context providers / slash commands
* Fixed issues preventing proper extension startup

View file

@ -1,4 +0,0 @@
## 0.0.38 - 2024-03-15
### Added
* Remote config server support
* Autocomplete support in JetBrains

View file

@ -1,7 +0,0 @@
## 0.0.42 - 2024-04-12
### Added
* Inline cmd/ctrl+I in JetBrains
### Fixed
* Fixed character encoding error causing display issues
* Fixed error causing input to constantly demand focus
* Fixed automatic reloading of config.json

View file

@ -1,8 +0,0 @@
## 0.0.53 - 2024-07-10
### Added
* Support for .prompt files
* New onboarding experience
### Fixed
* Indexing fixes from VS Code versions merged into IntelliJ
* Improved codebase indexing reliability and testing
* Fixes for autocomplete text positioning and timing

View file

@ -1,6 +0,0 @@
## 0.0.54 - 2024-07-13
### Added
* Partial autocomplete acceptance
* Autocomplete status bar spinner
### Fixed
* Fixed duplicate completion bug and others

View file

@ -1,7 +0,0 @@
## 0.0.69 - 2024-09-22
### Added
* Support for the "search" context provider
### Fixed
* Fixed bug where only first module would be recognized
* Improved concurrency handling to avoid freezes
* Made compatible with latest JetBrains versions

View file

@ -1,7 +0,0 @@
## 0.0.72 - 2024-10-04
### Added
* Listen for changes to Intellij settings without requiring window reload
### Changed
* Updated tutorial file
### Fixed
* Fix ability to load config.ts in JetBrains IDEs

View file

@ -1,5 +0,0 @@
## 0.0.92 - 2025-02-26
### Fixed
* Off-screen rendering to solve white flash on load and lack of changing cursor type
* OSR-related fixes for non-Mac users
* Fixes for inline edit in JetBrains

View file

@ -1,7 +0,0 @@
## 1.0.0 - 2025-02-26
### Added
* Introduces hub.continue.dev
* Improved theme matching
### Fixed
* Fixes interference between SonarQube and Continue autocomplete
* Numerous reliability improvements

View file

@ -1,5 +0,0 @@
## v0.0.1 - 2023-09-01
### Added
- Initial scaffold created from [IntelliJ Platform Plugin Template](https://github.com/JetBrains/intellij-platform-plugin-template)

View file

@ -1,5 +0,0 @@
## v0.0.19 - 2023-11-19
### Changed
- migrated to .json config file format

View file

@ -1,5 +0,0 @@
## v0.0.21 - 2023-12-05
### Added
- updated to match latest VS Code updates

View file

@ -1,5 +0,0 @@
## v0.0.25 - 2023-12-25
### Changed
- Intellij extension no longer relies on the Continue Python server

View file

@ -1,5 +0,0 @@
## v0.0.26 - 2023-12-28
### Added
* auto-reloading of config on save
### Fixed
* Fixed /edit bug for versions without Python server

View file

@ -1,10 +0,0 @@
## 0.8.14 - 2024-03-03
### Added
* Image support
* Full-text search index for retrieval
* Docs context provider
* CodeLlama-70b support
### Changed
* config.ts only runs in NodeJS, not browser
### Fixed
* Fixed proxy setting in config.json

View file

@ -1,3 +0,0 @@
## 0.8.15 - 2024-03-05
### Added
* Tab-autocomplete in beta

View file

@ -1,5 +0,0 @@
## 0.8.24 - 2024-04-12
### Added
* Support for improved retrieval models (Voyage embeddings/reranking)
* New @code context provider
* Personal usage analytics

View file

@ -1,16 +0,0 @@
## 0.8.42 - 2024-07-02
### Added
- Support for Gemini 1.5 Pro
- Link to code in the sidebar when using codebase retrieval
- Smoother onboarding experience
- .prompt files, a way of saving and sharing slash commands
- Support for Claude 3.5 Sonnet, Deepseek Coder v2, and other new models
- Support for comments in config.json
- Specify multiple autocomplete models and switch between them
- Improved bracket matching strategy reduces noisy completions
### Fixed
- Numerous reliability upgrades to codebase indexing

View file

@ -1,4 +0,0 @@
## 0.8.43 - 2024-07-08
### Added
* Improved indexing reliability and testing
* Quick Actions: use CodeLens to quickly take common actions like adding docstrings

View file

@ -1,12 +0,0 @@
## 0.8.45 - 2024-08-05
### Added
* Support for Llama 3.1 and gpt-4o-mini
* Support for WatsonX+Granite models
### Changed
* Significant improvements to indexing performance
* Improved @codebase quality by more accurately searching over file names and paths
* Improved @codebase accuracy
* Further improvements to indexing performance
### Fixed
* Improved docs indexing and management
* Fixed Gemini embeddings provider

View file

@ -1,6 +0,0 @@
## 0.8.46 - 2024-08-11
### Added
* new /onboard slash command
### Fixed
* Fixed problem loading config.ts
* Fixed bug causing duplicate indexing work

View file

@ -1,8 +0,0 @@
## 0.8.47 - 2024-08-27
### Added
* Use headless browser for crawling to get better results
* TTS support in the chat window
### Changed
* Improved support for WatsonX models
### Fixed
* Fixed several small indexing bugs

View file

@ -1,8 +0,0 @@
## 0.8.48 - 2024-09-01
### Added
* Improved indexing progress UI
* Improved @codebase using repomap
* Repo map context provider
### Fixed
* Many small UI improvements
* Fixes db.search not a function

View file

@ -1,3 +0,0 @@
## 0.8.49 - 2024-09-01
### Fixed
* Hotfix: submenu context providers

View file

@ -1,3 +0,0 @@
## 0.8.50 - 2024-09-02
### Fixed
* Hotfix for ability to use more than one inline context provider

View file

@ -1,3 +0,0 @@
## 0.8.51 - 2024-09-05
### Fixed
* Fixed CRLF bug causing diff streams to treat every line as changed on Windows

View file

@ -1,4 +0,0 @@
## 0.8.52 - 2024-09-16
### Changed
* Use Chromium only as a fallback after asking user
* Redesigned onboarding flow

View file

@ -1,12 +0,0 @@
## 0.8.53 - 2024-10-11
### Added
* Improved loading/accept/reject UI for apply
* Polished chat sidebar, especially context dropdown
* Further prompt caching with Anthropic
### Changed
* Updated tutorial file
* Improved styling on "More" page
### Fixed
* Continue for teams auth bug fix
* Fixed a number of apply bugs
* Fixed autoscrolling behavior

View file

@ -1,3 +0,0 @@
## 0.8.54 - 2024-10-15
### Fixed
* Hotfix: throttle transformers.js embeddings provider

View file

@ -1,9 +0,0 @@
## 0.8.55 - 2024-10-25
### Added
* Web context provider
* Cerebras inference provider
* Automatic descriptions for previous chats
* Discord context provider
* Improved full screen UI
### Changed
* Easier way to accept/reject/re-prompt after cmd/ctrl+I

View file

@ -1,4 +0,0 @@
## 0.8.56 - 2024-11-08
### Added
* New Edit mode in sidebar (cmd/ctrl+I)
* Significantly faster and more accurate docs crawler by default

View file

@ -1,25 +0,0 @@
## 0.8.58 - 2024-11-22
### Added
* OpenAI predicted outputs support
* Improve codebase retrieval with BM25
* Support for Grok from xAI
* Chat enhancements including sticking input to bottom
* New UI for cmd+I in sidebar
* Support for Nebius LLM provider
* Support for Ask Sage LLM provider
* Improved reference for config.json
* New @web context provider
* Updates for llama3.2
* .continuerules file to set system prompt
* .prompt files v2
* Dedicated UI for docs indexing
* Clickable code symbols in chat
* Use clipboard content as autocomplete context
### Changed
* Improved @docs crawler
* Many improvements to make autocomplete more eager
* Near complete type definition retrieval for TypeScript autocomplete
* Remove footer from chat sidebar
### Fixed
* Brought back the Apply button for all code blocks
* Automatically update codebase index on removed files

View file

@ -1,3 +0,0 @@
## 0.8.59 - 2024-11-25
### Fixed
* Hotfix for Ollama onboarding

View file

@ -1,6 +0,0 @@
## 0.8.62 - 2024-12-10
### Added
* Tool use
* Support for Model Context Protocol
### Fixed
* hotfix: context providers no longer hidden when not in edit mode

View file

@ -1,9 +0,0 @@
## 0.8.66 - 2024-12-20
### Changed
* Improved autocomplete in untitled files
### Fixed
* Display more mid-line completions
* Restored syntax highlighting
* Fix tool use bug for models that don't support tools
* Autodetect mistral API key type
* Fixes Azure OpenAI regressions

View file

@ -1,6 +0,0 @@
## 1.0.0 - 2025-02-26
### Added
* Introduces hub.continue.dev
* Improved apply quality
### Fixed
* Numerous reliability improvements

View file

@ -1,9 +0,0 @@
## v0.5.0 - 2023-11-09
### Added
- Codebase Retrieval: Use /codebase or cmd+enter and Continue will automatically gather the most important context
### Changed
- Switch from Websockets to Socket.io

View file

@ -1,11 +0,0 @@
## v0.6.0 - 2023-11-10
### Added
- Full screen mode
- StackOverflow slash command to augment with web search
- VS Code context menus: right click to add code to context, debug the terminal, or share your Continue session
### Fixed
- Reliability improvements to JetBrains by bringing up-to-date with the socket.io refactor

View file

@ -1,6 +0,0 @@
## v0.6.16 - 2023-12-25
### Changed
- Context items are now kept around as a part of past messages, instead of staying at the main input
- No more Python server - Continue runs entirely in Typescript

View file

@ -1,11 +0,0 @@
## v0.6.19 - 2024-01-05
### Added
- support for .continuerc.json in root of workspace to override config.json
- Inline context providers
- cmd+shift+L with new diff streaming UI for edits
### Changed
- Allow certain LLM servers to handle templating

View file

@ -1,5 +0,0 @@
## v0.6.4 - 2023-11-19
### Changed
- migrated to .json config file format

View file

@ -1,9 +0,0 @@
## v0.8.1 - 2024-01-08
### Added
- disableSessionTitles option in config.json
### Changed
- Use Ollama /chat endpoint instead of raw completions by default, and /show endpoint to gather model parameters like context length and stop tokens

View file

@ -1,8 +0,0 @@
## v0.8.2 - 2024-01-23
### Added
* Add codellama and gemini to free trial, using new server
* Local codebase syncing and embeddings using LanceDB
* Improved VS Code theme matching
### Changed
* Updates to packaging to download native modules for current platform (lancedb, sqlite, onnxruntime, tree-sitter wasms)
* Context providers now run from the extension side (in Node.js instead of browser javascript)

View file

@ -1,5 +0,0 @@
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html),
and is generated by [Changie](https://github.com/miniscruff/changie).

View file

@ -1,35 +0,0 @@
changesDir: .changes
unreleasedDir: unreleased
headerPath: header.tpl.md
changelogPath: CHANGELOG.md
versionExt: md
versionFormat: '## {{.Version}} - {{.Time.Format "2006-01-02"}}'
kindFormat: "### {{.Kind}}"
changeFormat: "* {{.Body}}"
kinds:
- label: Added
auto: minor
- label: Changed
auto: major
- label: Deprecated
auto: minor
- label: Removed
auto: major
- label: Fixed
auto: patch
- label: Security
auto: patch
newlines:
afterChangelogHeader: 1
beforeChangelogVersion: 1
endOfVersion: 1
envPrefix: CHANGIE_
projects:
- label: extensions/intellij
key: extensions/intellij
changelog: extensions/intellij/CHANGELOG.md
- label: extensions/vscode
key: extensions/vscode
changelog: extensions/vscode/CHANGELOG.md

View file

@ -1,9 +1,9 @@
name: "CLA Assistant"
on:
issue_comment:
types: [ created ]
types: [created]
pull_request_target:
types: [ opened, closed, synchronize ]
types: [opened, closed, synchronize]
permissions:
actions: write
@ -26,4 +26,5 @@ jobs:
path-to-signatures: "signatures/version1/cla.json"
path-to-document: "https://github.com/continuedev/continue/blob/main/docs/docs/CLA.md"
branch: cla-signatures
allowlist: dependabot[bot]
allowlist: dependabot[bot]
signed-commit-message: "CLA signed in $pullRequestNo"

View file

@ -1,6 +0,0 @@
# Changelog
Separate changelogs are kept for each extension:
- [VS Code Extension](./extensions/vscode/CHANGELOG.md)
- [JetBrains Extension](./extensions/intellij/CHANGELOG.md)

View file

@ -8,7 +8,10 @@
<div align="center">
**[Continue](https://docs.continue.dev) enables developers to create, share, and use custom AI code assistants with our open-source [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions and [hub of models, rules, prompts, docs, and other building blocks](https://hub.continue.dev)**
**[Continue](https://docs.continue.dev) enables developers to create, share, and use custom AI code assistants with our
open-source [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue)
and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension) extensions
and [hub of models, rules, prompts, docs, and other building blocks](https://hub.continue.dev)**
</div>
@ -20,15 +23,25 @@
<a target="_blank" href="https://docs.continue.dev" style="background:none">
<img src="https://img.shields.io/badge/continue_docs-%23BE1B55" style="height: 22px;" />
</a>
<a target="_blank" href="https://changelog.continue.dev" style="background:none">
<img src="https://img.shields.io/badge/changelog-%96EFF3" style="height: 22px;" />
</a>
<a target="_blank" href="https://discord.gg/vapESyrFmJ" style="background:none">
<img src="https://img.shields.io/badge/discord-join-continue.svg?labelColor=191937&color=6F6FF7&logo=discord" style="height: 22px;" />
</a>
<p></p>
## Agent
[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
![agent](docs/static/img/agent.gif)
## Chat
[Chat](https://continue.dev/docs/chat/how-to-use-it) makes it easy to ask for help from an LLM without needing to leave the IDE
[Chat](https://continue.dev/docs/chat/how-to-use-it) makes it easy to ask for help from an LLM without needing to leave
the IDE
![chat](docs/static/img/chat.gif)
@ -40,15 +53,11 @@
## Edit
[Edit](https://continue.dev/docs/edit/how-to-use-it) is a convenient way to modify code without leaving your current file
[Edit](https://continue.dev/docs/edit/how-to-use-it) is a convenient way to modify code without leaving your current
file
![edit](docs/static/img/edit.gif)
## Agent
[Agent](https://continue.dev/docs/agent/how-to-use-it) enables you to make more substantial changes to your codebase
![agent](docs/static/img/agent.gif)
</div>
@ -58,7 +67,8 @@ Learn about how to install and use Continue in the docs [here](https://continue.
## Contributing
Read the [contributing guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md), and join [#contribute on Discord](https://discord.gg/vapESyrFmJ).
Read the [contributing guide](https://github.com/continuedev/continue/blob/main/CONTRIBUTING.md), and
join [#contribute on Discord](https://discord.gg/vapESyrFmJ).
## License

View file

@ -3,6 +3,7 @@ import { StreamTransformPipeline } from "../filtering/streamTransforms/StreamTra
import { HelperVars } from "../util/HelperVars";
import { GeneratorReuseManager } from "./GeneratorReuseManager";
import { stopAfterMaxProcessingTime } from "./utils";
export class CompletionStreamer {
private streamTransformPipeline = new StreamTransformPipeline();
@ -22,23 +23,37 @@ export class CompletionStreamer {
completionOptions: Partial<CompletionOptions> | undefined,
helper: HelperVars,
) {
// Full stop means to stop the LLM's generation, instead of just truncating the displayed completion
const fullStop = () =>
this.generatorReuseManager.currentGenerator?.cancel();
// Try to reuse pending requests if what the user typed matches start of completion
const generator = this.generatorReuseManager.getGenerator(
prefix,
(abortSignal: AbortSignal) =>
llm.supportsFim()
(abortSignal: AbortSignal) => {
const generator = llm.supportsFim()
? llm.streamFim(prefix, suffix, abortSignal, completionOptions)
: llm.streamComplete(prompt, abortSignal, {
...completionOptions,
raw: true,
}),
});
/**
* This transformer applies even on reused generator. We are deliberately
* not using streamTransformPipeline because we want to capture and stop
* the request even if the generator is being reused.
*/
return helper.options.transform
? stopAfterMaxProcessingTime(
generator,
helper.options.modelTimeout * 2.5,
fullStop,
)
: generator;
},
multiline,
);
// Full stop means to stop the LLM's generation, instead of just truncating the displayed completion
const fullStop = () =>
this.generatorReuseManager.currentGenerator?.cancel();
// LLM
const generatorWithCancellation = async function* () {
for await (const update of generator) {

View file

@ -0,0 +1,138 @@
import { jest } from "@jest/globals";
import { stopAfterMaxProcessingTime } from "./utils";
describe("stopAfterMaxProcessingTime", () => {
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
async function* createMockStream(chunks: string[]): AsyncGenerator<string> {
for (const chunk of chunks) {
yield chunk;
}
}
async function streamToString(
stream: AsyncGenerator<string>,
): Promise<string> {
let result = "";
for await (const chunk of stream) {
result += chunk;
}
return result;
}
it("should yield all chunks when maxTimeMs is not reached", async () => {
const mockStream = createMockStream(["Hello", " world", "!"]);
const fullStop = jest.fn();
const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop);
const output = await streamToString(result);
expect(output).toBe("Hello world!");
expect(fullStop).not.toHaveBeenCalled();
});
it.only("should stop processing after max time is reached", async () => {
// Mock implementation of Date.now
let currentTime = 0;
const originalDateNow = Date.now;
Date.now = jest.fn(() => currentTime);
// Create a generator that we can control
async function* controlledGenerator(): AsyncGenerator<string> {
for (let i = 0; i < 100; i++) {
// After yielding 10 chunks, simulate time passing beyond our limit
if (i === 10) {
currentTime = 1000; // This exceeds our 500ms limit
}
yield `chunk-${i}`;
}
}
const fullStop = jest.fn();
const maxTimeMs = 500;
const transformedGenerator = stopAfterMaxProcessingTime(
controlledGenerator(),
maxTimeMs,
fullStop,
);
// Consume the generator and collect outputs
const outputs: string[] = [];
for await (const chunk of transformedGenerator) {
outputs.push(chunk);
}
// We expect:
// 1. Not all chunks were processed (less than 100)
// 2. fullStop was called
// 3. We processed at least the chunks before time was exceeded
expect(outputs.length).toBeLessThan(100);
expect(outputs.length).toBeGreaterThanOrEqual(10); // We should get at least the first 10 chunks
expect(fullStop).toHaveBeenCalled();
// Restore Date.now
Date.now = originalDateNow;
});
it("should check time only periodically based on checkInterval", async () => {
const chunks = Array(100).fill("x");
const mockStream = createMockStream(chunks);
const fullStop = jest.fn();
// Spy on Date.now to count how many times it's called
const dateSpy = jest.spyOn(Date, "now");
// Stream should complete normally (not hitting the timeout)
await streamToString(
stopAfterMaxProcessingTime(mockStream, 10000, fullStop),
);
// The first call is to set startTime, then once every checkInterval (10) chunks
// So for 100 chunks, we expect startTime + ~10 checks = ~11 calls
// We use a range because implementation details might vary slightly
expect(dateSpy.mock.calls.length).toBeGreaterThanOrEqual(1);
expect(dateSpy.mock.calls.length).toBeLessThanOrEqual(15);
dateSpy.mockRestore();
});
it("should handle empty stream gracefully", async () => {
const mockStream = createMockStream([]);
const fullStop = jest.fn();
const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop);
const output = await streamToString(result);
expect(output).toBe("");
expect(fullStop).not.toHaveBeenCalled();
});
it("should pass through all chunks if there's no timeout", async () => {
const chunks = Array(100).fill("test chunk");
const mockStream = createMockStream(chunks);
const fullStop = jest.fn();
// Use undefined as timeout to simulate no timeout
const result = stopAfterMaxProcessingTime(
mockStream,
undefined as any,
fullStop,
);
// Process the stream
const processedChunks = [];
for await (const chunk of result) {
processedChunks.push(chunk);
}
expect(processedChunks.length).toBe(chunks.length);
expect(fullStop).not.toHaveBeenCalled();
});
});

View file

@ -0,0 +1,27 @@
export async function* stopAfterMaxProcessingTime(
stream: AsyncGenerator<string>,
maxTimeMs: number,
fullStop: () => void,
): AsyncGenerator<string> {
const startTime = Date.now();
/**
* Check every 10 chunks to avoid performance overhead.
*/
const checkInterval = 10;
let chunkCount = 0;
let totalCharCount = 0;
for await (const chunk of stream) {
yield chunk;
chunkCount++;
totalCharCount += chunk.length;
if (chunkCount % checkInterval === 0) {
if (Date.now() - startTime > maxTimeMs) {
fullStop();
return;
}
}
}
}

View file

@ -173,6 +173,13 @@ export function migrateJsonSharedConfig(filepath: string, ide: IDE): void {
effected = true;
}
const { autoAcceptEditToolDiffs, ...withoutAutoApply } = migratedUI;
if (autoAcceptEditToolDiffs !== undefined) {
shareConfigUpdates.autoAcceptEditToolDiffs = autoAcceptEditToolDiffs;
migratedUI = withoutAutoApply;
effected = true;
}
const { showChatScrollbar, ...withoutShowChatScrollbar } = migratedUI;
if (showChatScrollbar !== undefined) {
shareConfigUpdates.showChatScrollbar = showChatScrollbar;

View file

@ -26,6 +26,7 @@ export const sharedConfigSchema = z
codeWrap: z.boolean(),
displayRawMarkdown: z.boolean(),
showChatScrollbar: z.boolean(),
autoAcceptEditToolDiffs: z.boolean(),
// `tabAutocompleteOptions` in `ContinueConfig`
useAutocompleteCache: z.boolean(),
@ -106,8 +107,7 @@ export function modifyAnyConfigWithSharedConfig<
sharedConfig.disableAutocompleteInFiles;
}
if (sharedConfig.modelTimeout !== undefined) {
configCopy.tabAutocompleteOptions.modelTimeout =
sharedConfig.modelTimeout;
configCopy.tabAutocompleteOptions.modelTimeout = sharedConfig.modelTimeout;
}
if (sharedConfig.debounceDelay !== undefined) {
configCopy.tabAutocompleteOptions.debounceDelay =
@ -134,6 +134,10 @@ export function modifyAnyConfigWithSharedConfig<
if (sharedConfig.showChatScrollbar !== undefined) {
configCopy.ui.showChatScrollbar = sharedConfig.showChatScrollbar;
}
if (sharedConfig.autoAcceptEditToolDiffs !== undefined) {
configCopy.ui.autoAcceptEditToolDiffs =
sharedConfig.autoAcceptEditToolDiffs;
}
if (sharedConfig.allowAnonymousTelemetry !== undefined) {
configCopy.allowAnonymousTelemetry = sharedConfig.allowAnonymousTelemetry;

View file

@ -13,6 +13,7 @@ import {
MCPServerStatus,
MCPTool,
} from "../..";
import { getEnvPathFromUserShell } from "../../util/shellPath";
const DEFAULT_MCP_TIMEOUT = 20_000; // 20 seconds
@ -29,17 +30,14 @@ const WINDOWS_BATCH_COMMANDS = [
class MCPConnection {
public client: Client;
private transport: Transport;
private connectionPromise: Promise<unknown> | null = null;
public abortController: AbortController;
public status: MCPConnectionStatus = "not-connected";
public errors: string[] = [];
public prompts: MCPPrompt[] = [];
public tools: MCPTool[] = [];
public resources: MCPResource[] = [];
private transport: Transport;
private connectionPromise: Promise<unknown> | null = null;
constructor(public options: MCPOptions) {
this.transport = this.constructTransport(options);
@ -63,80 +61,6 @@ class MCPConnection {
await this.transport.close();
}
/**
* Resolves the command and arguments for the current platform
* On Windows, batch script commands need to be executed via cmd.exe
* @param originalCommand The original command
* @param originalArgs The original command arguments
* @returns An object with the resolved command and arguments
*/
private resolveCommandForPlatform(
originalCommand: string,
originalArgs: string[],
): { command: string; args: string[] } {
// If not on Windows or not a batch command, return as-is
if (
process.platform !== "win32" ||
!WINDOWS_BATCH_COMMANDS.includes(originalCommand)
) {
return { command: originalCommand, args: originalArgs };
}
// On Windows, we need to execute batch commands via cmd.exe
// Format: cmd.exe /c command [args]
return {
command: "cmd.exe",
args: ["/c", originalCommand, ...originalArgs],
};
}
private constructTransport(options: MCPOptions): Transport {
switch (options.transport.type) {
case "stdio":
const env: Record<string, string> = options.transport.env
? { ...options.transport.env }
: {};
if (process.env.PATH !== undefined) {
env.PATH = process.env.PATH;
}
// Resolve the command and args for the current platform
const { command, args } = this.resolveCommandForPlatform(
options.transport.command,
options.transport.args || [],
);
return new StdioClientTransport({
command,
args,
env,
});
case "websocket":
return new WebSocketClientTransport(new URL(options.transport.url));
case "sse":
return new SSEClientTransport(new URL(options.transport.url), {
eventSourceInit: {
fetch: (input, init) =>
fetch(input, {
...init,
headers: {
...init?.headers,
...(options.transport.requestOptions?.headers as
| Record<string, string>
| undefined),
},
}),
},
requestInit: { headers: options.transport.requestOptions?.headers },
});
default:
throw new Error(
`Unsupported transport type: ${(options.transport as any).type}`,
);
}
}
getStatus(): MCPServerStatus {
return {
...this.options,
@ -302,6 +226,93 @@ class MCPConnection {
await this.connectionPromise;
}
/**
* Resolves the command and arguments for the current platform
* On Windows, batch script commands need to be executed via cmd.exe
* @param originalCommand The original command
* @param originalArgs The original command arguments
* @returns An object with the resolved command and arguments
*/
private resolveCommandForPlatform(
originalCommand: string,
originalArgs: string[],
): { command: string; args: string[] } {
// If not on Windows or not a batch command, return as-is
if (
process.platform !== "win32" ||
!WINDOWS_BATCH_COMMANDS.includes(originalCommand)
) {
return { command: originalCommand, args: originalArgs };
}
// On Windows, we need to execute batch commands via cmd.exe
// Format: cmd.exe /c command [args]
return {
command: "cmd.exe",
args: ["/c", originalCommand, ...originalArgs],
};
}
private constructTransport(options: MCPOptions): Transport {
switch (options.transport.type) {
case "stdio":
const env: Record<string, string> = options.transport.env
? { ...options.transport.env }
: {};
if (process.env.PATH !== undefined) {
// Set the initial PATH from process.env
env.PATH = process.env.PATH;
// For non-Windows platforms, try to get the PATH from user shell
if (process.platform !== "win32") {
try {
const shellEnvPath = getEnvPathFromUserShell();
if (shellEnvPath && shellEnvPath !== process.env.PATH) {
env.PATH = shellEnvPath;
}
} catch (err) {
console.error("Error getting PATH:", err);
}
}
}
// Resolve the command and args for the current platform
const { command, args } = this.resolveCommandForPlatform(
options.transport.command,
options.transport.args || [],
);
return new StdioClientTransport({
command,
args,
env,
});
case "websocket":
return new WebSocketClientTransport(new URL(options.transport.url));
case "sse":
return new SSEClientTransport(new URL(options.transport.url), {
eventSourceInit: {
fetch: (input, init) =>
fetch(input, {
...init,
headers: {
...init?.headers,
...(options.transport.requestOptions?.headers as
| Record<string, string>
| undefined),
},
}),
},
requestInit: { headers: options.transport.requestOptions?.headers },
});
default:
throw new Error(
`Unsupported transport type: ${(options.transport as any).type}`,
);
}
}
}
export default MCPConnection;

View file

@ -68,22 +68,20 @@ function extractConfigFromArray(config: any[]): Record<string, string> {
return configObj;
}
const MACOS_MDM_PATHS = [
// Organization-specific MDM plist
"/Library/Managed Preferences/dev.continue.app.plist",
// User-specific MDM plist
path.join(os.homedir(), "Library/Managed Preferences/dev.continue.app.plist"),
];
function readMdmKeysMacOS(): MdmKeys | undefined {
try {
// MDM configuration is typically stored in /Library/Managed Preferences/ on macOS
// The filename is often the bundle identifier of the application
const mdmPaths = [
// Organization-specific MDM plist
"/Library/Managed Preferences/dev.continue.app.plist",
// User-specific MDM plist
path.join(
os.homedir(),
"Library/Managed Preferences/dev.continue.app.plist",
),
];
// Try to find a valid MDM configuration file
for (const mdmPath of mdmPaths) {
for (const mdmPath of MACOS_MDM_PATHS) {
if (fs.existsSync(mdmPath)) {
// Read the file content
const fileContent = fs.readFileSync(mdmPath, "utf8");
@ -180,19 +178,19 @@ function extractRegValue(output: string): string | undefined {
return match ? match[1].trim() : undefined;
}
// Common locations for MDM configurations in Linux systems
const LINUX_MDM_PATHS = [
// System-wide configuration
"/etc/continue/mdm.json",
"/var/lib/continue/mdm.json",
// User-specific configuration
path.join(os.homedir(), ".config/continue/mdm.json"),
];
function readMdmKeysLinux(): MdmKeys | undefined {
try {
// Common locations for MDM configurations in Linux systems
const mdmPaths = [
// System-wide configuration
"/etc/continue/mdm.json",
"/var/lib/continue/mdm.json",
// User-specific configuration
path.join(os.homedir(), ".config/continue/mdm.json"),
];
// Try to find a valid MDM configuration file
for (const mdmPath of mdmPaths) {
for (const mdmPath of LINUX_MDM_PATHS) {
if (fs.existsSync(mdmPath)) {
// Read the file content
const fileContent = fs.readFileSync(mdmPath, "utf8");

192
core/data/log.test.ts Normal file
View file

@ -0,0 +1,192 @@
import { DevDataLogEvent } from "@continuedev/config-yaml";
import fs from "fs";
import path from "path";
import { IdeInfo, IdeSettings } from "..";
import { Core } from "../core";
import { getDevDataFilePath } from "../util/paths";
import { DataLogger } from "./log";
// Only mock fetch, not fs
jest.mock("@continuedev/fetch");
const TEST_EVENT: DevDataLogEvent = {
name: "tokensGenerated",
data: {
generatedTokens: 100,
model: "gpt-4",
promptTokens: 50,
provider: "openai",
},
};
const SCHEMA = "0.2.0";
describe("DataLogger", () => {
let dataLogger: DataLogger;
const tempDir = path.join(process.cwd(), "temp-test-data");
const testFilePath = path.join(tempDir, "tokensGenerated-test.jsonl");
// Create temp directory for test files
beforeAll(() => {
if (!fs.existsSync(tempDir)) {
fs.mkdirSync(tempDir, { recursive: true });
}
});
// Clean up temp directory after tests
afterAll(() => {
if (fs.existsSync(tempDir)) {
fs.rmSync(tempDir, { recursive: true, force: true });
}
});
beforeEach(() => {
// Reset mocks
jest.clearAllMocks();
// Remove test file if it exists
if (fs.existsSync(testFilePath)) {
fs.unlinkSync(testFilePath);
}
// Get singleton instance
dataLogger = DataLogger.getInstance();
// Mock core and required promises
dataLogger.core = {
configHandler: {
loadConfig: jest.fn().mockResolvedValue({
config: {
data: [],
},
}),
currentProfile: {
profileDescription: {
id: "test-profile-id",
},
},
controlPlaneClient: {
getAccessToken: jest.fn().mockResolvedValue("test-access-token"),
},
},
} as unknown as Core;
dataLogger.ideSettingsPromise = Promise.resolve({
userToken: "test-user-token",
} as IdeSettings);
dataLogger.ideInfoPromise = Promise.resolve({
name: "VSCode",
version: "1.0.0",
extensionVersion: "0.1.0",
} as IdeInfo);
});
describe("getInstance", () => {
it("should return the same instance when called multiple times", () => {
const instance1 = DataLogger.getInstance();
const instance2 = DataLogger.getInstance();
expect(instance1).toBe(instance2);
});
});
describe("addBaseValues", () => {
it("should add base values to event data based on schema", async () => {
const mockZodSchema = {
shape: {
eventName: true,
timestamp: true,
schema: true,
userAgent: true,
selectedProfileId: true,
userId: true,
},
};
const result = await dataLogger.addBaseValues(
{ customField: "value" },
"testEvent",
SCHEMA,
mockZodSchema as any,
);
expect(result).toEqual({
customField: "value",
eventName: "testEvent",
timestamp: expect.any(String),
schema: SCHEMA,
userAgent: "VSCode/1.0.0 (Continue/0.1.0)",
selectedProfileId: "test-profile-id",
userId: "test-user-token",
});
});
it("should not add fields not present in schema shape", async () => {
const mockZodSchema = {
shape: {
eventName: true,
// No other fields
},
};
const result = await dataLogger.addBaseValues(
{ customField: "value" },
"testEvent",
SCHEMA,
mockZodSchema as any,
);
expect(result).toEqual({
customField: "value",
eventName: "testEvent",
});
});
});
describe("logLocalData", () => {
it("should actually write data to the local file", async () => {
// Call the method to log data locally
await dataLogger.logLocalData(TEST_EVENT);
// Verify the file was created
const filepath = getDevDataFilePath(TEST_EVENT.name, SCHEMA);
expect(fs.existsSync(filepath)).toBe(true);
// Read file contents and verify
const fileContent = fs.readFileSync(filepath, "utf8");
expect(fileContent).toContain('"generatedTokens":100');
expect(fileContent).toContain('"model":"gpt-4"');
expect(fileContent).toContain('"eventName":"tokensGenerated"');
});
});
describe("logDevData", () => {
it("should log data locally and to configured destinations", async () => {
// Spy on logLocalData and logToOneDestination
const logLocalDataSpy = jest
.spyOn(dataLogger, "logLocalData")
.mockResolvedValue();
const logToOneDestinationSpy = jest
.spyOn(dataLogger, "logToOneDestination")
.mockResolvedValue();
// Mock config with multiple data destinations
const mockConfig = {
config: {
data: [
{ destination: "https://example.com/logs", schema: SCHEMA },
{ destination: "file:///logs", schema: SCHEMA },
],
},
};
dataLogger.core!.configHandler.loadConfig = jest
.fn()
.mockResolvedValue(mockConfig);
await dataLogger.logDevData(TEST_EVENT);
expect(logLocalDataSpy).toHaveBeenCalledWith(TEST_EVENT);
expect(logToOneDestinationSpy).toHaveBeenCalledTimes(2);
});
});
});

View file

@ -12,7 +12,7 @@ import * as URI from "uri-js";
import { fileURLToPath } from "url";
import { AnyZodObject } from "zod";
import { Core } from "../core.js";
import { IdeInfo, IdeSettings } from "../index.js";
import { ContinueConfig, IdeInfo, IdeSettings } from "../index.js";
import { getDevDataFilePath } from "../util/paths.js";
import { joinPathsToUri } from "../util/uri.js";
@ -68,8 +68,7 @@ export class DataLogger {
return newBody;
}
async logDevData(event: DevDataLogEvent) {
// Local logs (always on for all levels)
async logLocalData(event: DevDataLogEvent) {
try {
const filepath: string = getDevDataFilePath(
event.name,
@ -100,126 +99,144 @@ export class DataLogger {
} catch (error) {
console.error("Error logging local dev data:", error);
}
}
async logDevData(event: DevDataLogEvent) {
// Local logs (always on for all levels)
await this.logLocalData(event);
// Remote logs
const config = (await this.core?.configHandler.loadConfig())?.config;
if (config?.data?.length) {
await Promise.allSettled(
config.data.map(async (dataConfig) => {
try {
// First extract the data schema based on the version and level
const { schema } = dataConfig;
config.data.map((dataConfig) =>
this.logToOneDestination(dataConfig, event),
),
);
}
}
const level = dataConfig.level ?? DEFAULT_DEV_DATA_LEVEL;
async parseEventData(
event: DevDataLogEvent,
schema: string,
level: "all" | "noCode",
) {
const versionSchemas = devDataVersionedSchemas[schema];
if (!versionSchemas) {
throw new Error(
`Attempting to log dev data to non-existent version ${schema}`,
);
}
// Skip event if `events` is specified and does not include the event
const events = dataConfig.events ?? allDevEventNames;
if (!events.includes(event.name)) {
return;
}
const levelSchemas = versionSchemas[level];
if (!levelSchemas) {
throw new Error(
`Attempting to log dev data at level ${level} for version ${schema} which does not exist`,
);
}
const versionSchemas = devDataVersionedSchemas[schema];
if (!versionSchemas) {
throw new Error(
`Attempting to log dev data to non-existent version ${schema}`,
);
}
const zodSchema = levelSchemas[event.name];
if (!zodSchema) {
throw new Error(
`Attempting to log dev data for event ${event.name} at level ${level} for version ${schema}: no schema found`,
);
}
const levelSchemas = versionSchemas[level];
if (!levelSchemas) {
throw new Error(
`Attempting to log dev data at level ${level} for version ${schema} which does not exist`,
);
}
const eventDataWithBaseValues = await this.addBaseValues(
event.data,
event.name,
schema,
zodSchema,
);
const zodSchema = levelSchemas[event.name];
if (!zodSchema) {
throw new Error(
`Attempting to log dev data for event ${event.name} at level ${level} for version ${schema}: no schema found`,
);
}
const parsed = zodSchema.safeParse(eventDataWithBaseValues);
if (!parsed.success) {
throw new Error(
`Failed to parse event data for event ${event.name} and schema ${schema}\n:${parsed.error.toString()}`,
);
}
const eventDataWithBaseValues = await this.addBaseValues(
event.data,
event.name,
return parsed.data;
}
async logToOneDestination(
dataConfig: NonNullable<ContinueConfig["data"]>[number],
event: DevDataLogEvent,
) {
try {
if (!dataConfig) {
return;
}
// First extract the data schema based on the version and level
const { schema } = dataConfig;
const level = dataConfig.level ?? DEFAULT_DEV_DATA_LEVEL;
// Skip event if `events` is specified and does not include the event
const events = dataConfig.events ?? allDevEventNames;
if (!events.includes(event.name)) {
return;
}
// Parse the event data, throwing if it fails
const parsed = await this.parseEventData(event, schema, level);
const uriComponents = URI.parse(dataConfig.destination);
// Send to remote server
if (uriComponents.scheme === "https" || uriComponents.scheme === "http") {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
// If an API key is provided, use it, otherwise use the Continue access token
if (dataConfig.apiKey) {
headers["Authorization"] = `Bearer ${dataConfig.apiKey}`;
} else {
const accessToken =
await this.core?.configHandler.controlPlaneClient.getAccessToken();
headers["Authorization"] = `Bearer ${accessToken}`;
}
const profileId =
this.core?.configHandler.currentProfile?.profileDescription.id ?? "";
const response = await fetchwithRequestOptions(
dataConfig.destination,
{
method: "POST",
headers,
body: JSON.stringify({
name: event.name,
data: parsed,
schema,
zodSchema,
);
level,
profileId,
}),
},
dataConfig.requestOptions,
);
if (!response.ok) {
throw new Error(
`Post request failed. ${response.status}: ${response.statusText}`,
);
}
} else if (uriComponents.scheme === "file") {
// Write to jsonc file for local file URIs
const dirUri = joinPathsToUri(dataConfig.destination, schema);
const dirPath = fileURLToPath(dirUri);
const parsed = zodSchema.safeParse(eventDataWithBaseValues);
if (!parsed.success) {
throw new Error(
`Failed to parse event data for event ${event.name} and schema ${schema}\n:${parsed.error.toString()}`,
);
}
const uriComponents = URI.parse(dataConfig.destination);
// Send to remote server
if (
uriComponents.scheme === "https" ||
uriComponents.scheme === "http"
) {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (dataConfig.apiKey) {
headers["Authorization"] = `Bearer ${dataConfig.apiKey}`;
}
// For events going to Continue, overwrite the access token
if (
uriComponents.host?.endsWith(".continue.dev") ||
uriComponents.host === "continue.dev"
) {
//
const accessToken =
await this.core?.configHandler.controlPlaneClient.getAccessToken();
headers["Authorization"] = `Bearer ${accessToken}`;
}
const profileId =
this.core?.configHandler.currentProfile?.profileDescription
.id ?? "";
const response = await fetchwithRequestOptions(
dataConfig.destination,
{
method: "POST",
headers,
body: JSON.stringify({
name: event.name,
data: parsed.data,
schema,
level,
profileId,
}),
},
dataConfig.requestOptions,
);
if (!response.ok) {
throw new Error(
`Post request failed. ${response.status}: ${response.statusText}`,
);
}
} else if (uriComponents.scheme === "file") {
// Write to jsonc file for local file URIs
const dirUri = joinPathsToUri(dataConfig.destination, schema);
const dirPath = fileURLToPath(dirUri);
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
}
const filepath = path.join(dirPath, `${event.name}.jsonl`);
const jsonLine = JSON.stringify(event.data);
fs.writeFileSync(filepath, `${jsonLine}\n`, { flag: "a" });
} else {
throw new Error(`Unsupported URI scheme ${uriComponents.scheme}`);
}
} catch (error) {
console.error(
`Error logging data to ${dataConfig.destination}: ${error instanceof Error ? error.message : error}`,
);
}
}),
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
}
const filepath = path.join(dirPath, `${event.name}.jsonl`);
const jsonLine = JSON.stringify(event.data);
fs.writeFileSync(filepath, `${jsonLine}\n`, { flag: "a" });
} else {
throw new Error(`Unsupported URI scheme ${uriComponents.scheme}`);
}
} catch (error) {
console.error(
`Error logging data to ${dataConfig.destination}: ${error instanceof Error ? error.message : error}`,
);
}
}

2
core/index.d.ts vendored
View file

@ -842,6 +842,7 @@ export interface SlashCommand {
description: string;
prompt?: string;
params?: { [key: string]: any };
promptFile?: string
run: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>;
}
@ -1193,6 +1194,7 @@ export interface ContinueUIConfig {
showChatScrollbar?: boolean;
codeWrap?: boolean;
showSessionTabs?: boolean;
autoAcceptEditToolDiffs?: boolean;
}
export interface ContextMenuConfig {

View file

@ -22,6 +22,20 @@ const COMPLETION_OPTIONS: Partial<CompletionOptions> = {
// maxTokens: 5,
};
/**
* Retries a test function if it fails on the first attempt
* @param testFn The test function to run
* @returns A function that will retry once if the test fails
*/
const retryOnce = (testFn: () => Promise<any>) => async () => {
try {
return await testFn();
} catch (error) {
console.log("Test failed on first attempt, retrying once...");
return await testFn();
}
};
function testLLM(
llm: BaseLLM,
{
@ -47,7 +61,7 @@ function testLLM(
describe(llm.providerName + "/" + llm.model, () => {
test(
"Stream Chat works",
async () => {
retryOnce(async () => {
let total = "";
for await (const chunk of llm.streamChat(
[{ role: "user", content: "Hi" }],
@ -58,13 +72,13 @@ function testLLM(
expect(total.length).toBeGreaterThan(0);
return;
},
}),
timeout,
);
test(
"Stream Complete works",
async () => {
retryOnce(async () => {
let total = "";
for await (const chunk of llm.streamComplete(
"Hi",
@ -75,13 +89,13 @@ function testLLM(
expect(total.length).toBeGreaterThan(0);
return;
},
}),
timeout,
);
test(
"Complete works",
async () => {
retryOnce(async () => {
const completion = await llm.complete(
"Hi",
new AbortController().signal,
@ -89,14 +103,14 @@ function testLLM(
expect(completion.length).toBeGreaterThan(0);
return;
},
}),
timeout,
);
if (testFim) {
test(
"FIM works",
async () => {
retryOnce(async () => {
let total = "";
for await (const chunk of llm.streamFim(
"Hi",
@ -108,7 +122,7 @@ function testLLM(
expect(total.length).toBeGreaterThan(0);
return;
},
}),
timeout,
);
}
@ -116,7 +130,7 @@ function testLLM(
if (testToolCall) {
test(
"Tool Call works",
async () => {
retryOnce(async () => {
let args = "";
let isFirstChunk = true;
for await (const chunk of llm.streamChat(
@ -175,7 +189,7 @@ function testLLM(
const parsedArgs = JSON.parse(args);
expect(parsedArgs.name).toBe("Nate");
},
}),
timeout,
);
}

72
core/llm/stream.test.ts Normal file
View file

@ -0,0 +1,72 @@
import { Readable } from "stream";
import { streamSse } from "./stream";
function createMockResponse(sseLines: string[]): Response {
// Create a Readable stream that emits the SSE lines
const stream = new Readable({
read() {
for (const line of sseLines) {
this.push(line + "\n\n");
}
this.push(null); // End of stream
}
}) as any;
// Minimal Response mock
return {
status: 200,
body: stream,
text: async () => "",
} as unknown as Response;
}
describe("streamSse", () => {
it("yields parsed SSE data objects that ends with `data:[DONE]`", async () => {
const sseLines = [
'data: {"foo": "bar"}',
'data: {"baz": 42}',
'data:[DONE]'
];
const response = createMockResponse(sseLines);
const results = [];
for await (const data of streamSse(response)) {
results.push(data);
}
expect(results).toEqual([
{ foo: "bar" },
{ baz: 42 }
]);
});
it("yields parsed SSE data objects that ends with `data: [DONE]` (with a space before [DONE]", async () => {
const sseLines = [
'data: {"foo": "bar"}',
'data: {"baz": 42}',
'data: [DONE]'
];
const response = createMockResponse(sseLines);
const results = [];
for await (const data of streamSse(response)) {
results.push(data);
}
expect(results).toEqual([
{ foo: "bar" },
{ baz: 42 }
]);
});
it("throws on malformed JSON", async () => {
const sseLines = [
'data: {"foo": "bar"',
'data:[DONE]'
];
const response = createMockResponse(sseLines);
const iterator = streamSse(response)[Symbol.asyncIterator]();
await expect(iterator.next()).rejects.toThrow(/Malformed JSON/);
});
});

View file

@ -58,7 +58,7 @@ function parseDataLine(line: string): any {
}
function parseSseLine(line: string): { done: boolean; data: any } {
if (line.startsWith("data: [DONE]")) {
if (line.startsWith("data:[DONE]") || line.startsWith("data: [DONE]")) {
return { done: true, data: undefined };
}
if (line.startsWith("data:")) {

View file

@ -63,6 +63,7 @@ export function slashCommandFromPromptFileV1(
name,
description,
prompt,
promptFile: path,
run: async function* (context) {
const userInput = extractUserInput(context.input, name);
const [_, renderedPrompt] = await renderPromptFileV2(prompt, {

View file

@ -13,7 +13,7 @@ export const createRuleBlock: Tool = {
function: {
name: BuiltInToolNames.CreateRuleBlock,
description:
"Creates a persistent rule for all future conversations. For establishing code standards or preferences that should be applied consistently.",
"Creates a persistent rule for all future conversations. For establishing code standards or preferences that should be applied consistently. To modify existing rules, use the edit tool instead.",
parameters: {
type: "object",
required: ["name", "rule"],

29
core/util/shellPath.ts Normal file
View file

@ -0,0 +1,29 @@
import { execSync } from "child_process";
/**
* Gets the PATH env var from the user's login shell on non-Windows platforms.
* Windows is not implemented primarily because it is not needed at the moment.
* @returns The enhanced PATH from the user's shell, or the current PATH if it cannot be determined
*/
export function getEnvPathFromUserShell(): string | undefined {
if (process.platform === "win32") {
console.warn(`${getEnvPathFromUserShell.name} not implemented for Windows`);
return undefined;
}
if (!process.env.SHELL) {
return undefined;
}
try {
const command = `${process.env.SHELL} -l -c 'echo $PATH'`;
const stdout = execSync(command, {
encoding: "utf8",
});
return stdout.trim();
} catch (error) {
return process.env.PATH; // Fallback to current PATH
}
}

View file

@ -1,7 +0,0 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html),
and is generated by [Changie](https://github.com/miniscruff/changie).

View file

@ -0,0 +1,13 @@
---
title: Continue Changelog
description: Redirecting to our Changelog
hide_table_of_contents: true
---
# Redirecting to Changelog
If you are not redirected automatically, follow this [link to the changelog](https://changelog.continue.dev).
<head>
<meta http-equiv="refresh" content="0;url=https://changelog.continue.dev" />
</head>

View file

@ -1,30 +0,0 @@
---
title: Changelog
description: Changelogs for the latest releases of the VSCode and JetBrains extensions
keywords: [changelog]
hide_table_of_contents: true
---
import VSCodeChangelog from "../../../extensions/vscode/CHANGELOG.md";
import JetBrainsChangelog from "../../../extensions/intellij/CHANGELOG.md";
Below are the changelogs for the latest releases of the VSCode and JetBrains extensions. Prior to 2024-07-02, the changelogs do not reflect all updates.
import TOCInline from "@theme/TOCInline";
<TOCInline
toc={toc.filter(
(node) =>
node.value === "VSCode Changelog" || node.value === "JetBrains Changelog",
)}
/>
<hr />
## VSCode Changelog
<VSCodeChangelog />
## JetBrains Changelog
<JetBrainsChangelog />

View file

@ -6,11 +6,11 @@ keywords: [config, settings, configuration, customize, customization, sidebar]
# The User Settings Page
The **User Settings page** can be accessed by clicking the gear icon in the header of the Continue sidebar.
The **User Settings page** can be accessed by clicking the gear icon in the header of the Continue sidebar and then selecting the "Settings" tab.
![slash-commands](/img/header-buttons.png)
![settings](/img/settings-header.png)
Which takes you to this page:
Which takes you to this page (select the "Settings" tab):
![User Settings Page](/img/settings-page.png)
@ -26,7 +26,15 @@ Below that, the following settings which are not part of a configuration file ar
- `Enable Indexing`: Enables indexing of the codebase for the @codebase and @code context providers. **On** by default.
- `Font Size`: Specifies base font size for UI elements
- `Multiline Autocompletions`: Controls multiline completions for autocomplete. Can be set to `always`, `never`, or `auto`. Defaults to `auto`
- `Disable autocomplete in files`: List of comma-separated glob pattern to disable autocomplete in matching files. E.g., "\_/.md, \*/.txt"
- `Autocomplete timeout`: Maximum time in milliseconds for autocomplete request/retreival. Defaults to 150
- `Autocomplete debounce`: Minimum time in milliseconds to trigger an autocomplete request after a change. Defaults to 250
- `Disable autocomplete in files`: List of comma-separated glob pattern to disable autocomplete in matching files. E.g., `**/*.{txt,md}`
### Experimental settings
At the bottom of the User Settings page there is an "Experimental Settings" section which contains new or otherwise experimental settings, including:
- `Auto-Accept Agent Edits`: **CAUTION: Be very careful with this setting. When turned on, Agent mode's edit tool can make changes to files with no manual review or guaranteed stopping point. If on, diffs generated by the edit tool are automatically accepted and Agent proceeds with the next conversational turn.** Off by default.
<!-- - `Use autocomplete cache`: If on, caches completions. -->
<!-- - `Use Chromium for Docs Crawling`: Use Chromium to crawl docs locally. Useful if the default Cheerio crawler fails on sites that require JavaScript rendering. Downloads and installs Chromium to ~/.continue/.utils. Off by default -->

View file

@ -1,30 +0,0 @@
---
title: 变更日志
description: VSCode 和 JetBrains 扩展最新版本的变更日志
keywords: [变更日志]
hide_table_of_contents: true
---
import VSCodeChangelog from "../../../../../../extensions/vscode/CHANGELOG.md";
import JetBrainsChangelog from "../../../../../../extensions/intellij/CHANGELOG.md";
以下是 VSCode 和 JetBrains 扩展最新版本的变更日志。在 2024-07-02 之前,变更日志没有反映所有更新。
import TOCInline from "@theme/TOCInline";
<TOCInline
toc={toc.filter(
(node) =>
node.value === "VSCode Changelog" || node.value === "JetBrains Changelog",
)}
/>
<hr />
## VSCode 变更日志
<VSCodeChangelog />
## JetBrains 变更日志
<JetBrainsChangelog />

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.2 KiB

BIN
docs/static/img/settings-header.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

View file

@ -1,104 +0,0 @@
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html),
and is generated by [Changie](https://github.com/miniscruff/changie).
## 1.0.0 - 2025-02-26
### Added
* Introduces hub.continue.dev
* Improved theme matching
### Fixed
* Fixes interference between SonarQube and Continue autocomplete
* Numerous reliability improvements
## 0.0.92 - 2025-02-26
### Fixed
* Off-screen rendering to solve white flash on load and lack of changing cursor type
* OSR-related fixes for non-Mac users
* Fixes for inline edit in JetBrains
## 0.0.72 - 2024-10-04
### Added
* Listen for changes to Intellij settings without requiring window reload
### Changed
* Updated tutorial file
### Fixed
* Fix ability to load config.ts in JetBrains IDEs
## 0.0.69 - 2024-09-22
### Added
* Support for the "search" context provider
### Fixed
* Fixed bug where only first module would be recognized
* Improved concurrency handling to avoid freezes
* Made compatible with latest JetBrains versions
## 0.0.54 - 2024-07-13
### Added
* Partial autocomplete acceptance
* Autocomplete status bar spinner
### Fixed
* Fixed duplicate completion bug and others
## 0.0.53 - 2024-07-10
### Added
* Support for .prompt files
* New onboarding experience
### Fixed
* Indexing fixes from VS Code versions merged into IntelliJ
* Improved codebase indexing reliability and testing
* Fixes for autocomplete text positioning and timing
## 0.0.42 - 2024-04-12
### Added
* Inline cmd/ctrl+I in JetBrains
### Fixed
* Fixed character encoding error causing display issues
* Fixed error causing input to constantly demand focus
* Fixed automatic reloading of config.json
## 0.0.38 - 2024-03-15
### Added
* Remote config server support
* Autocomplete support in JetBrains
## 0.0.34 - 2024-03-03
### Added
* diff context provider
### Changed
* Allow LLM servers to handle templating
### Fixed
* Fix a few context providers / slash commands
* Fixed issues preventing proper extension startup
## v0.0.26 - 2023-12-28
### Added
* auto-reloading of config on save
### Fixed
* Fixed /edit bug for versions without Python server
## v0.0.25 - 2023-12-25
### Changed
- Intellij extension no longer relies on the Continue Python server
## v0.0.21 - 2023-12-05
### Added
- updated to match latest VS Code updates
## v0.0.19 - 2023-11-19
### Changed
- migrated to .json config file format
## v0.0.1 - 2023-09-01
### Added
- Initial scaffold created from [IntelliJ Platform Plugin Template](https://github.com/JetBrains/intellij-platform-plugin-template)

View file

@ -1,256 +0,0 @@
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html),
and is generated by [Changie](https://github.com/miniscruff/changie).
## 1.0.0 - 2025-02-26
### Added
* Introduces hub.continue.dev
* Improved apply quality
### Fixed
* Numerous reliability improvements
## 0.8.66 - 2024-12-20
### Changed
* Improved autocomplete in untitled files
### Fixed
* Display more mid-line completions
* Restored syntax highlighting
* Fix tool use bug for models that don't support tools
* Autodetect mistral API key type
* Fixes Azure OpenAI regressions
## 0.8.62 - 2024-12-10
### Added
* Tool use
* Support for Model Context Protocol
### Fixed
* hotfix: context providers no longer hidden when not in edit mode
## 0.8.59 - 2024-11-25
### Fixed
* Hotfix for Ollama onboarding
## 0.8.58 - 2024-11-22
### Added
* OpenAI predicted outputs support
* Improve codebase retrieval with BM25
* Support for Grok from xAI
* Chat enhancements including sticking input to bottom
* New UI for cmd+I in sidebar
* Support for Nebius LLM provider
* Support for Ask Sage LLM provider
* Improved reference for config.json
* New @web context provider
* Updates for llama3.2
* .continuerules file to set system prompt
* .prompt files v2
* Dedicated UI for docs indexing
* Clickable code symbols in chat
* Use clipboard content as autocomplete context
### Changed
* Improved @docs crawler
* Many improvements to make autocomplete more eager
* Near complete type definition retrieval for TypeScript autocomplete
* Remove footer from chat sidebar
### Fixed
* Brought back the Apply button for all code blocks
* Automatically update codebase index on removed files
## 0.8.56 - 2024-11-08
### Added
* New Edit mode in sidebar (cmd/ctrl+I)
* Significantly faster and more accurate docs crawler by default
## 0.8.55 - 2024-10-25
### Added
* Web context provider
* Cerebras inference provider
* Automatic descriptions for previous chats
* Discord context provider
* Improved full screen UI
### Changed
* Easier way to accept/reject/re-prompt after cmd/ctrl+I
## 0.8.54 - 2024-10-15
### Fixed
* Hotfix: throttle transformers.js embeddings provider
## 0.8.53 - 2024-10-11
### Added
* Improved loading/accept/reject UI for apply
* Polished chat sidebar, especially context dropdown
* Further prompt caching with Anthropic
### Changed
* Updated tutorial file
* Improved styling on "More" page
### Fixed
* Continue for teams auth bug fix
* Fixed a number of apply bugs
* Fixed autoscrolling behavior
## 0.8.52 - 2024-09-16
### Changed
* Use Chromium only as a fallback after asking user
* Redesigned onboarding flow
## 0.8.51 - 2024-09-05
### Fixed
* Fixed CRLF bug causing diff streams to treat every line as changed on Windows
## 0.8.50 - 2024-09-02
### Fixed
* Hotfix for ability to use more than one inline context provider
## 0.8.49 - 2024-09-01
### Fixed
* Hotfix: submenu context providers
## 0.8.48 - 2024-09-01
### Added
* Improved indexing progress UI
* Improved @codebase using repomap
* Repo map context provider
### Fixed
* Many small UI improvements
* Fixes db.search not a function
## 0.8.47 - 2024-08-27
### Added
* Use headless browser for crawling to get better results
* TTS support in the chat window
### Changed
* Improved support for WatsonX models
### Fixed
* Fixed several small indexing bugs
## 0.8.46 - 2024-08-11
### Added
* new /onboard slash command
### Fixed
* Fixed problem loading config.ts
* Fixed bug causing duplicate indexing work
## 0.8.45 - 2024-08-05
### Added
* Support for Llama 3.1 and gpt-4o-mini
* Support for WatsonX+Granite models
### Changed
* Significant improvements to indexing performance
* Improved @codebase quality by more accurately searching over file names and paths
* Improved @codebase accuracy
* Further improvements to indexing performance
### Fixed
* Improved docs indexing and management
* Fixed Gemini embeddings provider
## 0.8.43 - 2024-07-08
### Added
* Improved indexing reliability and testing
* Quick Actions: use CodeLens to quickly take common actions like adding docstrings
## 0.8.42 - 2024-07-02
### Added
- Support for Gemini 1.5 Pro
- Link to code in the sidebar when using codebase retrieval
- Smoother onboarding experience
- .prompt files, a way of saving and sharing slash commands
- Support for Claude 3.5 Sonnet, Deepseek Coder v2, and other new models
- Support for comments in config.json
- Specify multiple autocomplete models and switch between them
- Improved bracket matching strategy reduces noisy completions
### Fixed
- Numerous reliability upgrades to codebase indexing
## 0.8.24 - 2024-04-12
### Added
* Support for improved retrieval models (Voyage embeddings/reranking)
* New @code context provider
* Personal usage analytics
## 0.8.15 - 2024-03-05
### Added
* Tab-autocomplete in beta
## 0.8.14 - 2024-03-03
### Added
* Image support
* Full-text search index for retrieval
* Docs context provider
* CodeLlama-70b support
### Changed
* config.ts only runs in NodeJS, not browser
### Fixed
* Fixed proxy setting in config.json
## v0.8.2 - 2024-01-23
### Added
* Add codellama and gemini to free trial, using new server
* Local codebase syncing and embeddings using LanceDB
* Improved VS Code theme matching
### Changed
* Updates to packaging to download native modules for current platform (lancedb, sqlite, onnxruntime, tree-sitter wasms)
* Context providers now run from the extension side (in Node.js instead of browser javascript)
## v0.8.1 - 2024-01-08
### Added
- disableSessionTitles option in config.json
### Changed
- Use Ollama /chat endpoint instead of raw completions by default, and /show endpoint to gather model parameters like context length and stop tokens
## v0.6.19 - 2024-01-05
### Added
- support for .continuerc.json in root of workspace to override config.json
- Inline context providers
- cmd+shift+L with new diff streaming UI for edits
### Changed
- Allow certain LLM servers to handle templating
## v0.6.16 - 2023-12-25
### Changed
- Context items are now kept around as a part of past messages, instead of staying at the main input
- No more Python server - Continue runs entirely in Typescript
## v0.6.4 - 2023-11-19
### Changed
- migrated to .json config file format
## v0.6.0 - 2023-11-10
### Added
- Full screen mode
- StackOverflow slash command to augment with web search
- VS Code context menus: right click to add code to context, debug the terminal, or share your Continue session
### Fixed
- Reliability improvements to JetBrains by bringing up-to-date with the socket.io refactor
## v0.5.0 - 2023-11-09
### Added
- Codebase Retrieval: Use /codebase or cmd+enter and Continue will automatically gather the most important context
### Changed
- Switch from Websockets to Socket.io

View file

@ -1,6 +1,7 @@
// Feel free to add more!
// See gui/node_modules/highlight.js/lib/languages for the full available list
import clojure from "highlight.js/lib/languages/clojure";
import delphi from "highlight.js/lib/languages/delphi";
import elixir from "highlight.js/lib/languages/elixir";
import julia from "highlight.js/lib/languages/julia";
import lisp from "highlight.js/lib/languages/lisp";
@ -19,6 +20,7 @@ export function rehypeHighlightPlugin() {
languages: {
...common,
clojure,
delphi,
elixir,
julia,
protobuf,

View file

@ -1,4 +1,4 @@
import { useEffect, useRef } from "react";
import { useEffect, useRef, useState } from "react";
import { LLMInteraction } from "../../hooks/useLLMLog";
import useLLMSummary from "../../hooks/useLLMSummary";
import End from "./End";
@ -50,6 +50,18 @@ export default function Details({ interaction }: DetailsProps) {
const scrollTop = useRef<HTMLDivElement>(null);
const lastResult = useRef<any>(null);
const summary = useLLMSummary(interaction);
const [isAtBottom, setIsAtBottom] = useState(true);
// Handler to check if user is at the bottom
function handleScroll() {
const elt = scrollTop.current;
if (!elt) {
return;
}
// Allow a small threshold for floating point errors
const threshold = 5;
setIsAtBottom((elt.scrollHeight - elt.scrollTop - elt.clientHeight) < threshold);
}
useEffect(() => {
if (interaction.end) {
@ -59,15 +71,17 @@ export default function Details({ interaction }: DetailsProps) {
const last = interaction.results[interaction.results.length - 1];
if (last != lastResult.current) {
lastResult.current = last;
const lastChild = scrollTop.current?.lastChild;
if (lastChild) {
(lastChild as HTMLElement).scrollIntoView({
behavior: "auto",
block: "end",
});
if (isAtBottom) {
const lastChild = scrollTop.current?.lastChild;
if (lastChild) {
(lastChild as HTMLElement).scrollIntoView({
behavior: "auto",
block: "end",
});
}
}
}
});
}, [interaction, isAtBottom]);
return (
<div className="m-0 flex min-w-0 flex-1 shrink grow flex-col">
@ -102,7 +116,11 @@ export default function Details({ interaction }: DetailsProps) {
></Cell>
</div>
</div>
<div ref={scrollTop} className="grow overflow-auto">
<div
ref={scrollTop}
className="grow overflow-auto"
onScroll={handleScroll}
>
{interaction.start ? <Start item={interaction.start}></Start> : ""}
<div className="whitespace-pre-wrap p-2">
{interaction.results.map((group, i) => {

View file

@ -34,7 +34,7 @@ const NumberInput: React.FC<NumberInputProps> = ({
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newInputValue = e.target.value;
setInputValue(newInputValue);
// Only update the actual value if it's a valid number
const numValue = parseInt(newInputValue, 10);
if (!isNaN(numValue)) {
@ -63,10 +63,12 @@ const NumberInput: React.FC<NumberInputProps> = ({
WebkitAppearance: "none",
MozAppearance: "none",
}}
min={min}
max={max}
/>
<div className="flex flex-col">
<button
style={{ fontSize: "10px" }}
style={{ fontSize: "9px" }}
onClick={handleIncrement}
disabled={value >= max}
className="text-vsc-foreground m-0 mb-0.5 cursor-pointer border-none bg-inherit px-1.5 py-0 hover:opacity-80"
@ -74,7 +76,7 @@ const NumberInput: React.FC<NumberInputProps> = ({
▲
</button>
<button
style={{ fontSize: "10px" }}
style={{ fontSize: "9px" }}
className="text-vsc-foreground m-0 mb-0.5 cursor-pointer border-none bg-inherit px-1.5 py-0 hover:opacity-80"
onClick={handleDecrement}
disabled={value <= min}

View file

@ -1,4 +1,4 @@
import React from "react";
import React, { ReactNode } from "react";
import { vscButtonBackground } from "..";
type ToggleSwitchProps = {
@ -6,6 +6,7 @@ type ToggleSwitchProps = {
onToggle: () => void;
text: string;
size?: number;
showIfToggled?: ReactNode;
};
const ToggleSwitch: React.FC<ToggleSwitchProps> = ({
@ -13,11 +14,13 @@ const ToggleSwitch: React.FC<ToggleSwitchProps> = ({
onToggle,
text,
size = 16,
showIfToggled,
}) => {
return (
<div className="flex cursor-pointer select-none items-center justify-between gap-3">
<span className="truncate-right">{text}</span>
<div>
<div className="flex flex-row items-center gap-1">
{isToggled && !!showIfToggled && showIfToggled}
<div
className={`border-vsc-input-border bg-vsc-input-background flex items-center rounded-full border border-solid`}
onClick={onToggle}

View file

@ -1,10 +1,12 @@
import { parseConfigYaml } from "@continuedev/config-yaml";
import {
BookmarkIcon as BookmarkOutline,
PencilIcon,
} from "@heroicons/react/24/outline";
import { BookmarkIcon as BookmarkSolid } from "@heroicons/react/24/solid";
import { SlashCommandDescription } from "core";
import { useContext } from "react";
import { useContext, useMemo } from "react";
import { useAuth } from "../../../../context/Auth";
import { IdeMessengerContext } from "../../../../context/IdeMessenger";
import { useBookmarkedSlashCommands } from "../../../../hooks/useBookmarkedSlashCommands";
import { useAppSelector } from "../../../../redux/hooks";
@ -13,8 +15,10 @@ import { useMainEditor } from "../../TipTapEditor";
import { useLump } from "../LumpContext";
import { ExploreBlocksButton } from "./ExploreBlocksButton";
type PromptWithSlug = SlashCommandDescription & { slug?: string };
interface PromptRowProps {
prompt: SlashCommandDescription;
prompt: PromptWithSlug;
isBookmarked: boolean;
setIsBookmarked: (isBookmarked: boolean) => void;
onEdit?: () => void;
@ -90,6 +94,7 @@ function PromptRow({
* Section that displays all available prompts with bookmarking functionality
*/
export function PromptsSection() {
const { selectedProfile } = useAuth();
const { isCommandBookmarked, toggleBookmark } = useBookmarkedSlashCommands();
const ideMessenger = useContext(IdeMessengerContext);
@ -97,19 +102,56 @@ export function PromptsSection() {
(state) => state.config.config.slashCommands ?? [],
);
const handleEdit = (_prompt: SlashCommandDescription) => {
ideMessenger.post("config/openProfile", {
profileId: undefined,
});
const handleEdit = (prompt: PromptWithSlug) => {
if (prompt.promptFile) {
ideMessenger.post("openFile", {
path: prompt.promptFile,
});
} else if (prompt.slug) {
void ideMessenger.request("controlPlane/openUrl", {
path: `${prompt.slug}/new-version`,
orgSlug: undefined,
});
} else {
ideMessenger.post("config/openProfile", {
profileId: undefined,
});
}
};
const sortedCommands = [...slashCommands].sort((a, b) => {
const aBookmarked = isCommandBookmarked(a.name);
const bBookmarked = isCommandBookmarked(b.name);
if (aBookmarked && !bBookmarked) return -1;
if (!aBookmarked && bBookmarked) return 1;
return 0;
});
const sortedCommands = useMemo(() => {
const promptsWithSlug: PromptWithSlug[] = structuredClone(slashCommands);
// get the slugs from rawYaml
if (selectedProfile?.rawYaml) {
const parsed = parseConfigYaml(selectedProfile.rawYaml);
const parsedPrompts = parsed.prompts ?? [];
let index = 0;
for (const prompt of promptsWithSlug) {
// skip for local prompt files
if (prompt.promptFile) continue;
const yamlPrompt = parsedPrompts[index];
if (yamlPrompt) {
if ("uses" in yamlPrompt) {
prompt.slug = yamlPrompt.uses;
} else {
prompt.slug =
`${selectedProfile?.fullSlug.ownerSlug}/${selectedProfile?.fullSlug.packageSlug}`;
}
}
index = index + 1;
}
}
return promptsWithSlug.sort((a, b) => {
const aBookmarked = isCommandBookmarked(a.name);
const bBookmarked = isCommandBookmarked(b.name);
if (aBookmarked && !bBookmarked) return -1;
if (!aBookmarked && bBookmarked) return 1;
return 0;
});
}, [slashCommands, isCommandBookmarked, selectedProfile]);
return (
<div className="flex flex-col">

View file

@ -1,4 +1,9 @@
import { CheckIcon, XMarkIcon } from "@heroicons/react/24/outline";
import {
CheckIcon,
ChevronRightIcon,
ExclamationTriangleIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
import {
SharedConfigSchema,
modifyAnyConfigWithSharedConfig,
@ -8,16 +13,19 @@ import { Input } from "../../components";
import NumberInput from "../../components/gui/NumberInput";
import { Select } from "../../components/gui/Select";
import ToggleSwitch from "../../components/gui/Switch";
import { ToolTip } from "../../components/gui/Tooltip";
import { useFontSize } from "../../components/ui/font";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { updateConfig } from "../../redux/slices/configSlice";
import { getFontSize } from "../../util";
import { setLocalStorage } from "../../util/localStorage";
export function UserSettingsForm() {
/////// User settings section //////
const dispatch = useAppDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const config = useAppSelector((state) => state.config.config);
const [showExperimental, setShowExperimental] = useState(false);
function handleUpdate(sharedConfig: SharedConfigSchema) {
// Optimistic update
@ -65,6 +73,7 @@ export function UserSettingsForm() {
const codeWrap = config.ui?.codeWrap ?? false;
const showChatScrollbar = config.ui?.showChatScrollbar ?? false;
const readResponseTTS = config.experimental?.readResponseTTS ?? false;
const autoAcceptEditToolDiffs = config.ui?.autoAcceptEditToolDiffs ?? false;
const displayRawMarkdown = config.ui?.displayRawMarkdown ?? false;
const disableSessionTitles = config.disableSessionTitles ?? false;
@ -79,7 +88,7 @@ export function UserSettingsForm() {
config.tabAutocompleteOptions?.multilineCompletions ?? "auto";
const modelTimeout = config.tabAutocompleteOptions?.modelTimeout ?? 150;
const debounceDelay = config.tabAutocompleteOptions?.debounceDelay ?? 250;
const fontSize = getFontSize();
const fontSize = useFontSize();
const cancelChangeDisableAutocomplete = () => {
setFormDisableAutocomplete(disableAutocompleteInFiles);
@ -162,7 +171,6 @@ export function UserSettingsForm() {
}
text="Text-to-Speech Output"
/>
{/* <ToggleSwitch
isToggled={useChromiumForDocsCrawling}
onToggle={() =>
@ -225,11 +233,12 @@ export function UserSettingsForm() {
<span className="text-left">Font Size</span>
<NumberInput
value={fontSize}
onChange={(val) =>
onChange={(val) => {
setLocalStorage("fontSize", val);
handleUpdate({
fontSize: val,
})
}
});
}}
min={7}
max={50}
/>
@ -255,7 +264,7 @@ export function UserSettingsForm() {
</Select>
</label>
<label className="flex items-center justify-between gap-3">
<span className="text-left">Model Timeout (ms)</span>
<span className="text-left">Autocomplete Timeout (ms)</span>
<NumberInput
value={modelTimeout}
onChange={(val) =>
@ -268,7 +277,7 @@ export function UserSettingsForm() {
/>
</label>
<label className="flex items-center justify-between gap-3">
<span className="text-left">Model Debounce (ms)</span>
<span className="text-left">Autocomplete Debounce (ms)</span>
<NumberInput
value={debounceDelay}
onChange={(val) =>
@ -326,6 +335,48 @@ export function UserSettingsForm() {
</span>
</form>
</div>
<div className="flex flex-col gap-2">
<div
className="flex cursor-pointer items-center gap-2 text-left text-sm font-semibold"
onClick={() => setShowExperimental(!showExperimental)}
>
<ChevronRightIcon
className={`h-4 w-4 transition-transform ${
showExperimental ? "rotate-90" : ""
}`}
/>
<span>Experimental Settings</span>
</div>
<div
className={`duration-400 overflow-hidden transition-all ease-in-out ${
showExperimental ? "max-h-40" : "max-h-0"
}`}
>
<div className="flex flex-col gap-1 pl-6">
<ToggleSwitch
isToggled={autoAcceptEditToolDiffs}
onToggle={() =>
handleUpdate({
autoAcceptEditToolDiffs: !autoAcceptEditToolDiffs,
})
}
text="Auto-Accept Agent Edits"
showIfToggled={
<>
<ExclamationTriangleIcon
data-tooltip-id={`auto-accept-diffs-warning-tooltip`}
className="h-3 w-3 text-yellow-500"
/>
<ToolTip id={`auto-accept-diffs-warning-tooltip`}>
{`Be very careful with this setting. When turned on, Agent mode's edit tool can make changes to files with no manual review or guaranteed stopping point`}
</ToolTip>
</>
}
/>
</div>
</div>
</div>
</div>
) : null}
</div>

View file

@ -25,7 +25,21 @@ export const editToolImpl: ClientToolImpl = async (
if (apply.status === "error") {
throw new Error(apply.error);
}
const state = extras.getState();
const autoAccept = !!state.config.config.ui?.autoAcceptEditToolDiffs;
if (autoAccept) {
const out = await extras.ideMessenger.request("acceptDiff", {
streamId: extras.streamId,
filepath: firstUriMatch,
});
if (out.status === "error") {
throw new Error(out.error);
}
return {
respondImmediately: true,
output: undefined, // TODO - feed edit results back to model (also in parallel listeners)
};
}
return {
respondImmediately: false,
output: undefined, // No immediate output.

View file

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

View file

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

View file

@ -0,0 +1,20 @@
import path from "path";
import { fileURLToPath } from "url";
export default {
transform: {
"\\.[jt]sx?$": ["ts-jest", { useESM: true }],
},
moduleNameMapper: {
"(.+)\\.js": "$1",
},
extensionsToTreatAsEsm: [".ts"],
preset: "ts-jest/presets/default-esm",
testTimeout: 10000,
testEnvironment: "node",
globals: {
__dirname: path.dirname(fileURLToPath(import.meta.url)),
__filename: path.resolve(fileURLToPath(import.meta.url)),
},
};

View file

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

View file

@ -17,7 +17,11 @@
},
"devDependencies": {
"@types/follow-redirects": "^1.14.4",
"jest": "^29.7.0"
"@types/jest": "^29.5.14",
"cross-env": "^7.0.3",
"jest": "^29.7.0",
"ts-jest": "^29.3.4",
"ts-node": "^10.9.2"
}
},
"node_modules/@ampproject/remapping": {
@ -597,6 +601,28 @@
"zod": "^3.23.8"
}
},
"node_modules/@cspotcode/source-map-support": {
"version": "0.8.1",
"resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz",
"integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==",
"dev": true,
"dependencies": {
"@jridgewell/trace-mapping": "0.3.9"
},
"engines": {
"node": ">=12"
}
},
"node_modules/@cspotcode/source-map-support/node_modules/@jridgewell/trace-mapping": {
"version": "0.3.9",
"resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz",
"integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==",
"dev": true,
"dependencies": {
"@jridgewell/resolve-uri": "^3.0.3",
"@jridgewell/sourcemap-codec": "^1.4.10"
}
},
"node_modules/@istanbuljs/load-nyc-config": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz",
@ -972,6 +998,30 @@
"@sinonjs/commons": "^3.0.0"
}
},
"node_modules/@tsconfig/node10": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.11.tgz",
"integrity": "sha512-DcRjDCujK/kCk/cUe8Xz8ZSpm8mS3mNNpta+jGCA6USEDfktlNvm1+IuZ9eTcDbNk41BHwpHHeW+N1lKCz4zOw==",
"dev": true
},
"node_modules/@tsconfig/node12": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz",
"integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==",
"dev": true
},
"node_modules/@tsconfig/node14": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz",
"integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==",
"dev": true
},
"node_modules/@tsconfig/node16": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz",
"integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==",
"dev": true
},
"node_modules/@types/babel__core": {
"version": "7.20.5",
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
@ -1055,6 +1105,16 @@
"@types/istanbul-lib-report": "*"
}
},
"node_modules/@types/jest": {
"version": "29.5.14",
"resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.5.14.tgz",
"integrity": "sha512-ZN+4sdnLUbo8EVvVc2ao0GFW6oVrQRPn4K2lglySj7APvSrgzxHiNNK99us4WDMi57xxA2yggblIAMNhXOotLQ==",
"dev": true,
"dependencies": {
"expect": "^29.0.0",
"pretty-format": "^29.0.0"
}
},
"node_modules/@types/node": {
"version": "20.14.10",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.14.10.tgz",
@ -1085,6 +1145,30 @@
"integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==",
"dev": true
},
"node_modules/acorn": {
"version": "8.14.1",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.1.tgz",
"integrity": "sha512-OvQ/2pUDKmgfCg++xsTX1wGxfTaszcHVcTctW4UJB4hibJx2HXxxO5UmVgyjMa+ZDsiaf5wWLXYpRWMmBI0QHg==",
"dev": true,
"bin": {
"acorn": "bin/acorn"
},
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/acorn-walk": {
"version": "8.3.4",
"resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.4.tgz",
"integrity": "sha512-ueEepnujpqee2o5aIYnvHU6C0A42MNdsIDeqy5BydrkuC5R1ZuUFnm27EeFJGoEHJQgn3uleRvmTXaJgfXbt4g==",
"dev": true,
"dependencies": {
"acorn": "^8.11.0"
},
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/agent-base": {
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.1.tgz",
@ -1148,6 +1232,12 @@
"node": ">= 8"
}
},
"node_modules/arg": {
"version": "4.1.3",
"resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz",
"integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==",
"dev": true
},
"node_modules/argparse": {
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz",
@ -1157,6 +1247,12 @@
"sprintf-js": "~1.0.2"
}
},
"node_modules/async": {
"version": "3.2.6",
"resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz",
"integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==",
"dev": true
},
"node_modules/babel-jest": {
"version": "29.7.0",
"resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-29.7.0.tgz",
@ -1324,6 +1420,18 @@
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
}
},
"node_modules/bs-logger": {
"version": "0.2.6",
"resolved": "https://registry.npmjs.org/bs-logger/-/bs-logger-0.2.6.tgz",
"integrity": "sha512-pd8DCoxmbgc7hyPKOvxtqNcjYoOsABPQdcCUjGp3d42VR2CX1ORhk2A87oqqu5R1kk+76nsxZupkmyd+MVtCog==",
"dev": true,
"dependencies": {
"fast-json-stable-stringify": "2.x"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/bser": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/bser/-/bser-2.1.1.tgz",
@ -1504,6 +1612,30 @@
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
}
},
"node_modules/create-require": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz",
"integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==",
"dev": true
},
"node_modules/cross-env": {
"version": "7.0.3",
"resolved": "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz",
"integrity": "sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==",
"dev": true,
"dependencies": {
"cross-spawn": "^7.0.1"
},
"bin": {
"cross-env": "src/bin/cross-env.js",
"cross-env-shell": "src/bin/cross-env-shell.js"
},
"engines": {
"node": ">=10.14",
"npm": ">=6",
"yarn": ">=1"
}
},
"node_modules/cross-spawn": {
"version": "7.0.3",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz",
@ -1574,6 +1706,15 @@
"node": ">=8"
}
},
"node_modules/diff": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz",
"integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==",
"dev": true,
"engines": {
"node": ">=0.3.1"
}
},
"node_modules/diff-sequences": {
"version": "29.6.3",
"resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz",
@ -1583,6 +1724,21 @@
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
}
},
"node_modules/ejs": {
"version": "3.1.10",
"resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.10.tgz",
"integrity": "sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA==",
"dev": true,
"dependencies": {
"jake": "^10.8.5"
},
"bin": {
"ejs": "bin/cli.js"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/electron-to-chromium": {
"version": "1.4.824",
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.824.tgz",
@ -1732,6 +1888,36 @@
"node": "^12.20 || >= 14.13"
}
},
"node_modules/filelist": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.4.tgz",
"integrity": "sha512-w1cEuf3S+DrLCQL7ET6kz+gmlJdbq9J7yXCSjK/OZCPA+qEN1WyF4ZAf0YYJa4/shHJra2t/d/r8SV4Ji+x+8Q==",
"dev": true,
"dependencies": {
"minimatch": "^5.0.1"
}
},
"node_modules/filelist/node_modules/brace-expansion": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz",
"integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==",
"dev": true,
"dependencies": {
"balanced-match": "^1.0.0"
}
},
"node_modules/filelist/node_modules/minimatch": {
"version": "5.1.6",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.6.tgz",
"integrity": "sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==",
"dev": true,
"dependencies": {
"brace-expansion": "^2.0.1"
},
"engines": {
"node": ">=10"
}
},
"node_modules/fill-range": {
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
@ -2140,6 +2326,24 @@
"node": ">=8"
}
},
"node_modules/jake": {
"version": "10.9.2",
"resolved": "https://registry.npmjs.org/jake/-/jake-10.9.2.tgz",
"integrity": "sha512-2P4SQ0HrLQ+fw6llpLnOaGAvN2Zu6778SJMrCUwns4fOoG9ayrTiZk3VV8sCPkVZF8ab0zksVpS8FDY5pRCNBA==",
"dev": true,
"dependencies": {
"async": "^3.2.3",
"chalk": "^4.0.2",
"filelist": "^1.0.4",
"minimatch": "^3.1.2"
},
"bin": {
"jake": "bin/cli.js"
},
"engines": {
"node": ">=10"
}
},
"node_modules/jest": {
"version": "29.7.0",
"resolved": "https://registry.npmjs.org/jest/-/jest-29.7.0.tgz",
@ -2792,6 +2996,12 @@
"node": ">=8"
}
},
"node_modules/lodash.memoize": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz",
"integrity": "sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag==",
"dev": true
},
"node_modules/lru-cache": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
@ -2828,6 +3038,12 @@
"node": ">=10"
}
},
"node_modules/make-error": {
"version": "1.3.6",
"resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz",
"integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==",
"dev": true
},
"node_modules/makeerror": {
"version": "1.0.12",
"resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz",
@ -3460,6 +3676,122 @@
"node": ">=8.0"
}
},
"node_modules/ts-jest": {
"version": "29.3.4",
"resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.3.4.tgz",
"integrity": "sha512-Iqbrm8IXOmV+ggWHOTEbjwyCf2xZlUMv5npExksXohL+tk8va4Fjhb+X2+Rt9NBmgO7bJ8WpnMLOwih/DnMlFA==",
"dev": true,
"dependencies": {
"bs-logger": "^0.2.6",
"ejs": "^3.1.10",
"fast-json-stable-stringify": "^2.1.0",
"jest-util": "^29.0.0",
"json5": "^2.2.3",
"lodash.memoize": "^4.1.2",
"make-error": "^1.3.6",
"semver": "^7.7.2",
"type-fest": "^4.41.0",
"yargs-parser": "^21.1.1"
},
"bin": {
"ts-jest": "cli.js"
},
"engines": {
"node": "^14.15.0 || ^16.10.0 || ^18.0.0 || >=20.0.0"
},
"peerDependencies": {
"@babel/core": ">=7.0.0-beta.0 <8",
"@jest/transform": "^29.0.0",
"@jest/types": "^29.0.0",
"babel-jest": "^29.0.0",
"jest": "^29.0.0",
"typescript": ">=4.3 <6"
},
"peerDependenciesMeta": {
"@babel/core": {
"optional": true
},
"@jest/transform": {
"optional": true
},
"@jest/types": {
"optional": true
},
"babel-jest": {
"optional": true
},
"esbuild": {
"optional": true
}
}
},
"node_modules/ts-jest/node_modules/semver": {
"version": "7.7.2",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz",
"integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==",
"dev": true,
"bin": {
"semver": "bin/semver.js"
},
"engines": {
"node": ">=10"
}
},
"node_modules/ts-jest/node_modules/type-fest": {
"version": "4.41.0",
"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.41.0.tgz",
"integrity": "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==",
"dev": true,
"engines": {
"node": ">=16"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/ts-node": {
"version": "10.9.2",
"resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz",
"integrity": "sha512-f0FFpIdcHgn8zcPSbf1dRevwt047YMnaiJM3u2w2RewrB+fob/zePZcrOyQoLMMO7aBIddLcQIEK5dYjkLnGrQ==",
"dev": true,
"dependencies": {
"@cspotcode/source-map-support": "^0.8.0",
"@tsconfig/node10": "^1.0.7",
"@tsconfig/node12": "^1.0.7",
"@tsconfig/node14": "^1.0.0",
"@tsconfig/node16": "^1.0.2",
"acorn": "^8.4.1",
"acorn-walk": "^8.1.1",
"arg": "^4.1.0",
"create-require": "^1.1.0",
"diff": "^4.0.1",
"make-error": "^1.1.1",
"v8-compile-cache-lib": "^3.0.1",
"yn": "3.1.1"
},
"bin": {
"ts-node": "dist/bin.js",
"ts-node-cwd": "dist/bin-cwd.js",
"ts-node-esm": "dist/bin-esm.js",
"ts-node-script": "dist/bin-script.js",
"ts-node-transpile-only": "dist/bin-transpile.js",
"ts-script": "dist/bin-script-deprecated.js"
},
"peerDependencies": {
"@swc/core": ">=1.2.50",
"@swc/wasm": ">=1.2.50",
"@types/node": "*",
"typescript": ">=2.7"
},
"peerDependenciesMeta": {
"@swc/core": {
"optional": true
},
"@swc/wasm": {
"optional": true
}
}
},
"node_modules/type-detect": {
"version": "4.0.8",
"resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz",
@ -3481,6 +3813,20 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/typescript": {
"version": "5.8.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz",
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
"dev": true,
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
},
"node_modules/undici-types": {
"version": "5.26.5",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz",
@ -3517,6 +3863,12 @@
"browserslist": ">= 4.21.0"
}
},
"node_modules/v8-compile-cache-lib": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz",
"integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==",
"dev": true
},
"node_modules/v8-to-istanbul": {
"version": "9.3.0",
"resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.3.0.tgz",
@ -3641,6 +3993,15 @@
"node": ">=12"
}
},
"node_modules/yn": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz",
"integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==",
"dev": true,
"engines": {
"node": ">=6"
}
},
"node_modules/yocto-queue": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",

View file

@ -1,12 +1,12 @@
{
"name": "@continuedev/fetch",
"version": "1.0.6",
"version": "1.0.9",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"type": "module",
"scripts": {
"test": "jest",
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest",
"build": "tsc"
},
"author": "Nate Sesti and Ty Dunn",
@ -20,6 +20,10 @@
},
"devDependencies": {
"@types/follow-redirects": "^1.14.4",
"jest": "^29.7.0"
"@types/jest": "^29.5.14",
"cross-env": "^7.0.3",
"jest": "^29.7.0",
"ts-jest": "^29.3.4",
"ts-node": "^10.9.2"
}
}

View file

@ -0,0 +1,172 @@
import { globalAgent } from "https";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { getAgentOptions } from "./getAgentOptions.js";
// Store original env
const originalEnv = process.env;
const originalGlobalAgentOptions = { ...globalAgent.options };
// Temporary directory for test certificate files
let tempDir: string;
beforeEach(() => {
// Create a temporary directory for test files
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "fetch-test-"));
process.env = { ...originalEnv };
// Reset globalAgent for each test
globalAgent.options = { ...originalGlobalAgentOptions };
});
afterEach(() => {
process.env = originalEnv;
globalAgent.options = originalGlobalAgentOptions;
// Clean up temporary directory
try {
fs.rmSync(tempDir, { recursive: true, force: true });
} catch (error) {
console.error(`Failed to remove temp directory: ${error}`);
}
});
// Helper function to create test certificate files
function createTestCertFile(filename: string, content: string): string {
const filePath = path.join(tempDir, filename);
fs.writeFileSync(filePath, content, "utf8");
return filePath;
}
test("getAgentOptions returns basic configuration with default values", () => {
const options = getAgentOptions();
// Check default timeout (7200 seconds = 2 hours = 7,200,000 ms)
expect(options.timeout).toBe(7200000);
expect(options.sessionTimeout).toBe(7200000);
expect(options.keepAliveMsecs).toBe(7200000);
expect(options.keepAlive).toBe(true);
// Verify certificates array exists and contains items
expect(options.ca).toBeInstanceOf(Array);
expect(options.ca.length).toBeGreaterThan(0);
// Verify at least one of the real TLS root certificates is included
// This assumes there's at least one certificate with "CERTIFICATE" in it
expect(options.ca.some((cert: any) => cert.includes("CERTIFICATE"))).toBe(
true,
);
});
test("getAgentOptions respects custom timeout", () => {
const customTimeout = 300; // 5 minutes
const options = getAgentOptions({ timeout: customTimeout });
// Check timeout values (300 seconds = 300,000 ms)
expect(options.timeout).toBe(300000);
expect(options.sessionTimeout).toBe(300000);
expect(options.keepAliveMsecs).toBe(300000);
});
test("getAgentOptions uses verifySsl setting", () => {
// With verifySsl true
let options = getAgentOptions({ verifySsl: true });
expect(options.rejectUnauthorized).toBe(true);
// With verifySsl false
options = getAgentOptions({ verifySsl: false });
expect(options.rejectUnauthorized).toBe(false);
});
test("getAgentOptions incorporates custom CA bundle paths", () => {
// Create a test CA bundle file
const caBundleContent =
"-----BEGIN CERTIFICATE-----\nMIIDtTCCAp2gAwIBAgIJAMcuSp7chAYdMA==\n-----END CERTIFICATE-----";
const caBundlePath = createTestCertFile("ca-bundle.pem", caBundleContent);
// Single string path
let options = getAgentOptions({ caBundlePath });
// Verify that our test certificate is included in the CA list
expect(options.ca).toContain(caBundleContent);
// Create multiple test CA bundle files
const caContent1 =
"-----BEGIN CERTIFICATE-----\nABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\n-----END CERTIFICATE-----";
const caContent2 =
"-----BEGIN CERTIFICATE-----\n0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\n-----END CERTIFICATE-----";
const caPath1 = createTestCertFile("ca1.pem", caContent1);
const caPath2 = createTestCertFile("ca2.pem", caContent2);
// Array of paths
options = getAgentOptions({
caBundlePath: [caPath1, caPath2],
});
// Verify that both test certificates are included in the CA list
expect(options.ca).toContain(caContent1);
expect(options.ca).toContain(caContent2);
});
test("getAgentOptions includes global certs when running as binary", () => {
// Set up test certs in globalAgent
globalAgent.options.ca = ["global-cert-1", "global-cert-2"];
// Set IS_BINARY environment variable
process.env.IS_BINARY = "true";
const options = getAgentOptions();
// Test for global certs
expect(options.ca).toContain("global-cert-1");
expect(options.ca).toContain("global-cert-2");
});
test("getAgentOptions handles client certificate configuration", () => {
// Create test certificate files
const clientCertContent =
"-----BEGIN CERTIFICATE-----\nCLIENTCERT\n-----END CERTIFICATE-----";
const clientKeyContent =
"-----BEGIN PRIVATE KEY-----\nCLIENTKEY\n-----END PRIVATE KEY-----";
const certPath = createTestCertFile("client.cert", clientCertContent);
const keyPath = createTestCertFile("client.key", clientKeyContent);
const clientCertOptions = {
clientCertificate: {
cert: certPath,
key: keyPath,
passphrase: "secret-passphrase",
},
};
const options = getAgentOptions(clientCertOptions);
expect(options.cert).toBe(clientCertContent);
expect(options.key).toBe(clientKeyContent);
expect(options.passphrase).toBe("secret-passphrase");
});
test("getAgentOptions handles client certificate without passphrase", () => {
// Create test certificate files
const clientCertContent =
"-----BEGIN CERTIFICATE-----\nCLIENTCERT2\n-----END CERTIFICATE-----";
const clientKeyContent =
"-----BEGIN PRIVATE KEY-----\nCLIENTKEY2\n-----END PRIVATE KEY-----";
const certPath = createTestCertFile("client2.cert", clientCertContent);
const keyPath = createTestCertFile("client2.key", clientKeyContent);
const clientCertOptions = {
clientCertificate: {
cert: certPath,
key: keyPath,
},
};
const options = getAgentOptions(clientCertOptions);
expect(options.cert).toBe(clientCertContent);
expect(options.key).toBe(clientKeyContent);
expect(options.passphrase).toBeUndefined();
});

View file

@ -1,12 +1,10 @@
import { globalAgent } from "https";
import * as fs from "node:fs";
import tls from "node:tls";
import { RequestOptions } from "@continuedev/config-types";
import * as followRedirects from "follow-redirects";
import { HttpProxyAgent } from "http-proxy-agent";
import { HttpsProxyAgent } from "https-proxy-agent";
import fetch, { RequestInit, Response } from "node-fetch";
import { getAgentOptions } from "./getAgentOptions.js";
import { getProxyFromEnv, shouldBypassProxy } from "./util.js";
const { http, https } = (followRedirects as any).default;
@ -20,59 +18,23 @@ export async function fetchwithRequestOptions(
url.host = "127.0.0.1";
}
const TIMEOUT = 7200; // 7200 seconds = 2 hours
const agentOptions = getAgentOptions(requestOptions);
let globalCerts: string[] = [];
if (process.env.IS_BINARY) {
if (Array.isArray(globalAgent.options.ca)) {
globalCerts = [...globalAgent.options.ca.map((cert) => cert.toString())];
} else if (typeof globalAgent.options.ca !== "undefined") {
globalCerts.push(globalAgent.options.ca.toString());
}
}
const ca = Array.from(new Set([...tls.rootCertificates, ...globalCerts]));
const customCerts =
typeof requestOptions?.caBundlePath === "string"
? [requestOptions?.caBundlePath]
: requestOptions?.caBundlePath;
if (customCerts) {
ca.push(
...customCerts.map((customCert) => fs.readFileSync(customCert, "utf8")),
);
// Get proxy from options or environment variables
let proxy = requestOptions?.proxy;
if (!proxy) {
proxy = getProxyFromEnv(url.protocol);
}
const timeout = (requestOptions?.timeout ?? TIMEOUT) * 1000; // measured in ms
const agentOptions: { [key: string]: any } = {
ca,
rejectUnauthorized: requestOptions?.verifySsl,
timeout,
sessionTimeout: timeout,
keepAlive: true,
keepAliveMsecs: timeout,
};
// Handle ClientCertificateOptions
if (requestOptions?.clientCertificate) {
agentOptions.cert = fs.readFileSync(
requestOptions.clientCertificate.cert,
"utf8",
);
agentOptions.key = fs.readFileSync(
requestOptions.clientCertificate.key,
"utf8",
);
if (requestOptions.clientCertificate.passphrase) {
agentOptions.passphrase = requestOptions.clientCertificate.passphrase;
}
}
const proxy = requestOptions?.proxy;
// Check if should bypass proxy based on requestOptions or NO_PROXY env var
const shouldBypass =
requestOptions?.noProxy?.includes(url.hostname) ||
shouldBypassProxy(url.hostname);
// Create agent
const protocol = url.protocol === "https:" ? https : http;
const agent =
proxy && !requestOptions?.noProxy?.includes(url.hostname)
proxy && !shouldBypass
? protocol === https
? new HttpsProxyAgent(proxy, agentOptions)
: new HttpProxyAgent(proxy, agentOptions)
@ -107,19 +69,30 @@ export async function fetchwithRequestOptions(
}
// fetch the request with the provided options
const resp = await fetch(url, {
...init,
body: updatedBody ?? init?.body,
headers: headers,
agent: agent,
});
try {
const resp = await fetch(url, {
...init,
body: updatedBody ?? init?.body,
headers: headers,
agent: agent,
});
if (!resp.ok) {
const requestId = resp.headers.get("x-request-id");
if (requestId) {
console.log(`Request ID: ${requestId}, Status: ${resp.status}`);
if (!resp.ok) {
const requestId = resp.headers.get("x-request-id");
if (requestId) {
console.log(`Request ID: ${requestId}, Status: ${resp.status}`);
}
}
}
return resp;
return resp;
} catch (error) {
if (error instanceof Error && error.name === "AbortError") {
// Return a Response object that streamResponse etc can handle
return new Response(null, {
status: 499, // Client Closed Request
statusText: "Client Closed Request",
});
}
throw error;
}
}

View file

@ -0,0 +1,62 @@
import { globalAgent } from "https";
import * as fs from "node:fs";
import tls from "node:tls";
import { RequestOptions } from "@continuedev/config-types";
/**
* Prepares agent options based on request options and certificates
*/
export function getAgentOptions(requestOptions?: RequestOptions): {
[key: string]: any;
} {
const TIMEOUT = 7200; // 7200 seconds = 2 hours
const timeout = (requestOptions?.timeout ?? TIMEOUT) * 1000; // measured in ms
// Get root certificates
let globalCerts: string[] = [];
if (process.env.IS_BINARY) {
if (Array.isArray(globalAgent.options.ca)) {
globalCerts = [...globalAgent.options.ca.map((cert) => cert.toString())];
} else if (typeof globalAgent.options.ca !== "undefined") {
globalCerts.push(globalAgent.options.ca.toString());
}
}
const ca = Array.from(new Set([...tls.rootCertificates, ...globalCerts]));
const customCerts =
typeof requestOptions?.caBundlePath === "string"
? [requestOptions?.caBundlePath]
: requestOptions?.caBundlePath;
if (customCerts) {
ca.push(
...customCerts.map((customCert) => fs.readFileSync(customCert, "utf8")),
);
}
const agentOptions: { [key: string]: any } = {
ca,
rejectUnauthorized: requestOptions?.verifySsl,
timeout,
sessionTimeout: timeout,
keepAlive: true,
keepAliveMsecs: timeout,
};
// Handle ClientCertificateOptions
if (requestOptions?.clientCertificate) {
agentOptions.cert = fs.readFileSync(
requestOptions.clientCertificate.cert,
"utf8",
);
agentOptions.key = fs.readFileSync(
requestOptions.clientCertificate.key,
"utf8",
);
if (requestOptions.clientCertificate.passphrase) {
agentOptions.passphrase = requestOptions.clientCertificate.passphrase;
}
}
return agentOptions;
}

View file

@ -0,0 +1,49 @@
// The parseDataLine function is not exported, so we need to import it
// indirectly by re-exporting it for testing purposes
import { parseDataLine } from "./stream.js";
describe("parseDataLine", () => {
test("parseDataLine should parse valid JSON data with 'data: ' prefix", () => {
const line = 'data: {"message":"hello","status":"ok"}';
const result = parseDataLine(line);
expect(result).toEqual({ message: "hello", status: "ok" });
});
test("parseDataLine should parse valid JSON data with 'data:' prefix (no space)", () => {
const line = 'data:{"message":"hello","status":"ok"}';
const result = parseDataLine(line);
expect(result).toEqual({ message: "hello", status: "ok" });
});
test("parseDataLine should throw error for malformed JSON", () => {
const line = "data: {invalid json}";
expect(() => parseDataLine(line)).toThrow(
"Malformed JSON sent from server",
);
});
test("parseDataLine should throw error when data contains error field", () => {
const line = 'data: {"error":"something went wrong"}';
expect(() => parseDataLine(line)).toThrow(
"Error streaming response: something went wrong",
);
});
test("parseDataLine should handle empty objects", () => {
const line = "data: {}";
const result = parseDataLine(line);
expect(result).toEqual({});
});
test("parseDataLine should handle arrays", () => {
const line = "data: [1,2,3]";
const result = parseDataLine(line);
expect(result).toEqual([1, 2, 3]);
});
test("parseDataLine should handle nested objects", () => {
const line = 'data: {"user":{"name":"John","age":30}}';
const result = parseDataLine(line);
expect(result).toEqual({ user: { name: "John", age: 30 } });
});
});

View file

@ -10,6 +10,9 @@ export async function* toAsyncIterable(
export async function* streamResponse(
response: Response,
): AsyncGenerator<string> {
if (response.status === 499) {
return; // In case of client-side cancellation, just return
}
if (response.status !== 200) {
throw new Error(await response.text());
}
@ -21,26 +24,34 @@ export async function* streamResponse(
// Get the major version of Node.js
const nodeMajorVersion = parseInt(process.versions.node.split(".")[0], 10);
if (nodeMajorVersion >= 20) {
// Use the new API for Node 20 and above
const stream = (ReadableStream as any).from(response.body);
for await (const chunk of stream.pipeThrough(
new TextDecoderStream("utf-8"),
)) {
yield chunk;
try {
if (nodeMajorVersion >= 20) {
// Use the new API for Node 20 and above
const stream = (ReadableStream as any).from(response.body);
for await (const chunk of stream.pipeThrough(
new TextDecoderStream("utf-8"),
)) {
yield chunk;
}
} else {
// Fallback for Node versions below 20
// Streaming with this method doesn't work as version 20+ does
const decoder = new TextDecoder("utf-8");
const nodeStream = response.body as unknown as NodeJS.ReadableStream;
for await (const chunk of toAsyncIterable(nodeStream)) {
yield decoder.decode(chunk, { stream: true });
}
}
} else {
// Fallback for Node versions below 20
// Streaming with this method doesn't work as version 20+ does
const decoder = new TextDecoder("utf-8");
const nodeStream = response.body as unknown as NodeJS.ReadableStream;
for await (const chunk of toAsyncIterable(nodeStream)) {
yield decoder.decode(chunk, { stream: true });
} catch (e) {
if (e instanceof Error && e.name.startsWith("AbortError")) {
return; // In case of client-side cancellation, just return
}
throw e;
}
}
function parseDataLine(line: string): any {
// Export for testing purposes
export function parseDataLine(line: string): any {
const json = line.startsWith("data: ")
? line.slice("data: ".length)
: line.slice("data:".length);
@ -53,12 +64,20 @@ function parseDataLine(line: string): any {
return data;
} catch (e) {
// If the error was thrown by our error check, rethrow it
if (
e instanceof Error &&
e.message.startsWith("Error streaming response:")
) {
throw e;
}
// Otherwise it's a JSON parsing error
throw new Error(`Malformed JSON sent from server: ${json}`);
}
}
function parseSseLine(line: string): { done: boolean; data: any } {
if (line.startsWith("data: [DONE]")) {
if (line.startsWith("data:[DONE]") || line.startsWith("data: [DONE]")) {
return { done: true, data: undefined };
}
if (line.startsWith("data:")) {

View file

@ -0,0 +1,102 @@
import { jest } from "@jest/globals";
import { getProxyFromEnv, shouldBypassProxy } from "./util.js";
// Reset environment variables after each test
afterEach(() => {
jest.resetModules();
process.env = {};
});
// Tests for getProxyFromEnv
test("getProxyFromEnv returns undefined when no proxy is set", () => {
expect(getProxyFromEnv("http:")).toBeUndefined();
expect(getProxyFromEnv("https:")).toBeUndefined();
});
test("getProxyFromEnv returns HTTP_PROXY for http protocol", () => {
process.env.HTTP_PROXY = "http://proxy.example.com";
expect(getProxyFromEnv("http:")).toBe("http://proxy.example.com");
});
test("getProxyFromEnv returns lowercase http_proxy for http protocol", () => {
process.env.http_proxy = "http://proxy.example.com";
expect(getProxyFromEnv("http:")).toBe("http://proxy.example.com");
});
test("getProxyFromEnv prefers HTTP_PROXY over http_proxy for http protocol", () => {
process.env.HTTP_PROXY = "http://upper.example.com";
process.env.http_proxy = "http://lower.example.com";
expect(getProxyFromEnv("http:")).toBe("http://upper.example.com");
});
test("getProxyFromEnv returns HTTPS_PROXY for https protocol", () => {
process.env.HTTPS_PROXY = "https://secure.example.com";
expect(getProxyFromEnv("https:")).toBe("https://secure.example.com");
});
test("getProxyFromEnv returns lowercase https_proxy for https protocol", () => {
process.env.https_proxy = "https://secure.example.com";
expect(getProxyFromEnv("https:")).toBe("https://secure.example.com");
});
test("getProxyFromEnv falls back to HTTP_PROXY for https protocol when HTTPS_PROXY is not set", () => {
process.env.HTTP_PROXY = "http://fallback.example.com";
expect(getProxyFromEnv("https:")).toBe("http://fallback.example.com");
});
test("getProxyFromEnv prefers HTTPS_PROXY over other env vars for https protocol", () => {
process.env.HTTPS_PROXY = "https://preferred.example.com";
process.env.https_proxy = "https://notused1.example.com";
process.env.HTTP_PROXY = "http://notused2.example.com";
process.env.http_proxy = "http://notused3.example.com";
expect(getProxyFromEnv("https:")).toBe("https://preferred.example.com");
});
// Tests for shouldBypassProxy
test("shouldBypassProxy returns false when NO_PROXY is not set", () => {
expect(shouldBypassProxy("example.com")).toBe(false);
});
test("shouldBypassProxy returns true for exact hostname match", () => {
process.env.NO_PROXY = "example.com,another.com";
expect(shouldBypassProxy("example.com")).toBe(true);
});
test("shouldBypassProxy returns false when hostname doesn't match any NO_PROXY entry", () => {
process.env.NO_PROXY = "example.com,another.com";
expect(shouldBypassProxy("different.com")).toBe(false);
});
test("shouldBypassProxy handles lowercase no_proxy", () => {
process.env.no_proxy = "example.com";
expect(shouldBypassProxy("example.com")).toBe(true);
});
test("shouldBypassProxy works with wildcard domains", () => {
process.env.NO_PROXY = "*.example.com";
expect(shouldBypassProxy("sub.example.com")).toBe(true);
expect(shouldBypassProxy("example.com")).toBe(false);
expect(shouldBypassProxy("different.com")).toBe(false);
});
test("shouldBypassProxy works with domain suffix", () => {
process.env.NO_PROXY = ".example.com";
expect(shouldBypassProxy("sub.example.com")).toBe(true);
expect(shouldBypassProxy("example.com")).toBe(true);
expect(shouldBypassProxy("different.com")).toBe(false);
});
test("shouldBypassProxy handles multiple entries with different patterns", () => {
process.env.NO_PROXY = "internal.local,*.example.com,.test.com";
expect(shouldBypassProxy("internal.local")).toBe(true);
expect(shouldBypassProxy("sub.example.com")).toBe(true);
expect(shouldBypassProxy("sub.test.com")).toBe(true);
expect(shouldBypassProxy("test.com")).toBe(true);
expect(shouldBypassProxy("example.org")).toBe(false);
});
test("shouldBypassProxy ignores whitespace in NO_PROXY", () => {
process.env.NO_PROXY = " example.com , *.test.org ";
expect(shouldBypassProxy("example.com")).toBe(true);
expect(shouldBypassProxy("subdomain.test.org")).toBe(true);
});

View file

@ -0,0 +1,43 @@
/**
* Gets the proxy settings from environment variables
* @param protocol The URL protocol (http: or https:)
* @returns The proxy URL if available, otherwise undefined
*/
export function getProxyFromEnv(protocol: string): string | undefined {
if (protocol === "https:") {
return (
process.env.HTTPS_PROXY ||
process.env.https_proxy ||
process.env.HTTP_PROXY ||
process.env.http_proxy
);
} else {
return process.env.HTTP_PROXY || process.env.http_proxy;
}
}
/**
* Checks if a hostname should bypass proxy based on NO_PROXY environment variable
* @param hostname The hostname to check
* @returns True if the hostname should bypass proxy
*/
export function shouldBypassProxy(hostname: string): boolean {
const noProxy = process.env.NO_PROXY || process.env.no_proxy;
if (!noProxy) return false;
const noProxyItems = noProxy.split(",").map((item) => item.trim());
return noProxyItems.some((item) => {
// Exact match
if (item === hostname) return true;
// Wildcard domain match (*.example.com)
if (item.startsWith("*.") && hostname.endsWith(item.substring(1)))
return true;
// Domain suffix match (.example.com)
if (item.startsWith(".") && hostname.endsWith(item.slice(1))) return true;
return false;
});
}

View file

@ -14,7 +14,7 @@
"resolveJsonModule": true,
"isolatedModules": true,
"noEmitOnError": false,
"types": ["node"],
"types": ["node", "jest"],
"outDir": "dist",
"declaration": true
// "sourceMap": true