Merge branch 'main' into cmmoran1130/main

This commit is contained in:
Nate 2025-05-25 17:44:39 -07:00
commit fbf3d18e79
86 changed files with 1403 additions and 763 deletions

View file

@ -1,6 +1,6 @@
import { streamResponse } from "@continuedev/fetch";
import { SlashCommand } from "../../index.js";
import { removeQuotesAndEscapes } from "../../util/index.js";
import { streamResponse } from "../../llm/stream.js";
const HttpSlashCommand: SlashCommand = {
name: "http",

View file

@ -151,4 +151,24 @@ This is a test rule without a heading.`;
);
expect(result.name).toBe("custom-rule");
});
it("should include description from frontmatter", () => {
const content = `---
globs: "**/test/**/*.kt"
name: Test Rule
description: This is a rule description from frontmatter
---
# Test Rule
This is the content of the rule.`;
const result = convertMarkdownRuleToContinueRule(
"/path/to/rule.md",
content,
);
expect(result.description).toBe(
"This is a rule description from frontmatter",
);
});
});

View file

@ -59,9 +59,10 @@ export function convertMarkdownRuleToContinueRule(
}
return {
name,
rule: markdown,
globs: frontmatter.globs,
name,
description: frontmatter.description,
source: "rules-block",
ruleFile: path,
};

View file

@ -77,6 +77,7 @@ export function addModel(
model: model.model,
apiKey: model.apiKey,
apiBase: model.apiBase,
maxStopWords: model.maxStopWords,
defaultCompletionOptions: model.completionOptions,
};
if (model.systemMessage) {

View file

@ -71,7 +71,7 @@ function convertYamlMcpToContinueMcp(
command: server.command,
args: server.args ?? [],
env: server.env,
},
} as any, // TODO: Fix the mcpServers types in config-yaml (discriminated union)
timeout: server.connectionTimeout,
};
}
@ -458,7 +458,7 @@ async function configYamlToContinueConfig(options: {
transport: {
type: "stdio",
args: [],
...server,
...(server as any), // TODO: fix the types on mcpServers in config-yaml
},
timeout: server.connectionTimeout,
})),

View file

@ -26,6 +26,7 @@ const modelDescriptionSchema = z.object({
apiKey: z.string().optional(),
apiBase: z.string().optional(),
contextLength: z.number().optional(),
maxStopWords: z.number().optional(),
template: z
.enum([
"llama2",

View file

@ -35,7 +35,6 @@ import { TTS } from "./util/tts";
import {
ContextItemWithId,
DiffLine,
IdeSettings,
ModelDescription,
RangeInFile,
@ -62,61 +61,7 @@ import { LLMLogger } from "./llm/logger";
import { llmStreamChat } from "./llm/streamChat";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import type { IMessenger, Message } from "./protocol/messenger";
// This function is used for jetbrains inline edit and apply
async function* streamDiffLinesGenerator(
configHandler: ConfigHandler,
abortedMessageIds: Set<string>,
msg: Message<ToCoreProtocol["streamDiffLines"][0]>,
): AsyncGenerator<DiffLine> {
const {
highlighted,
prefix,
suffix,
input,
language,
modelTitle,
includeRulesInSystemMessage,
} = msg.data;
const { config } = await configHandler.loadConfig();
if (!config) {
throw new Error("Failed to load config");
}
// Title can be an edit, chat, or apply model
// Fall back to chat
const llm =
config.modelsByRole.edit.find((m) => m.title === modelTitle) ??
config.modelsByRole.apply.find((m) => m.title === modelTitle) ??
config.modelsByRole.chat.find((m) => m.title === modelTitle) ??
config.selectedModelByRole.chat;
if (!llm) {
throw new Error("No model selected");
}
// rules included for edit, NOT apply
const rules = includeRulesInSystemMessage ? config.rules : undefined;
for await (const diffLine of streamDiffLines({
highlighted,
prefix,
suffix,
llm,
rulesToInclude: rules,
input,
language,
onlyOneInsertion: false,
overridePrompt: undefined,
})) {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
break;
}
yield diffLine;
}
}
import { StreamAbortManager } from "./util/abortManager";
export class Core {
configHandler: ConfigHandler;
@ -132,7 +77,18 @@ export class Core {
this.globalContext.get("indexingPaused") === true,
);
private abortedMessageIds: Set<string> = new Set();
private messageAbortControllers = new Map<string, AbortController>();
private addMessageAbortController(id: string): AbortController {
const controller = new AbortController();
this.messageAbortControllers.set(id, controller);
controller.signal.addEventListener("abort", () => {
this.messageAbortControllers.delete(id);
});
return controller;
}
private abortById(messageId: string) {
this.messageAbortControllers.get(messageId)?.abort();
}
invoke<T extends keyof ToCoreProtocol>(
messageType: T,
@ -301,7 +257,7 @@ export class Core {
});
on("abort", (msg) => {
this.abortedMessageIds.add(msg.messageId);
this.abortById(msg.data ?? msg.messageId);
});
on("ping", (msg) => {
@ -470,27 +426,28 @@ export class Core {
}
});
on("llm/streamChat", (msg) =>
llmStreamChat(
on("llm/streamChat", (msg) => {
const abortController = this.addMessageAbortController(msg.messageId);
return llmStreamChat(
this.configHandler,
this.abortedMessageIds,
abortController,
msg,
this.ide,
this.messenger,
),
);
);
});
on("llm/complete", async (msg) => {
const model = (await this.configHandler.loadConfig()).config
?.selectedModelByRole.chat;
const { config } = await this.configHandler.loadConfig();
const model = config?.selectedModelByRole.chat;
if (!model) {
throw new Error("No chat model selected");
}
const abortController = this.addMessageAbortController(msg.messageId);
const completion = await model.complete(
msg.data.prompt,
new AbortController().signal,
abortController.signal,
msg.data.completionOptions,
);
return completion;
@ -532,9 +489,47 @@ export class Core {
this.completionProvider.cancel();
});
on("streamDiffLines", (msg) =>
streamDiffLinesGenerator(this.configHandler, this.abortedMessageIds, msg),
);
on("streamDiffLines", async (msg) => {
const { config } = await this.configHandler.loadConfig();
if (!config) {
throw new Error("Failed to load config");
}
const { data } = msg;
// Title can be an edit, chat, or apply model
// Fall back to chat
const llm =
config.modelsByRole.edit.find((m) => m.title === data.modelTitle) ??
config.modelsByRole.apply.find((m) => m.title === data.modelTitle) ??
config.modelsByRole.chat.find((m) => m.title === data.modelTitle) ??
config.selectedModelByRole.chat;
if (!llm) {
throw new Error("No model selected");
}
return streamDiffLines({
highlighted: data.highlighted,
prefix: data.prefix,
suffix: data.suffix,
llm,
// rules included for edit, NOT apply
rulesToInclude: data.includeRulesInSystemMessage
? config.rules
: undefined,
input: data.input,
language: data.language,
onlyOneInsertion: false,
overridePrompt: undefined,
abortControllerId: data.fileUri ?? "current-file-stream", // not super important since currently cancelling apply will cancel all streams it's one file at a time
});
});
on("cancelApply", async (msg) => {
const abortManager = StreamAbortManager.getInstance();
abortManager.clear();
});
on("completeOnboarding", this.handleCompleteOnboarding.bind(this));

View file

@ -16,6 +16,7 @@ const RECURSIVE_PROMPT = `Continue EXACTLY where you left`;
export async function* recursiveStream(
llm: ILLM,
abortController: AbortController,
prompt: ChatMessage[] | string,
prediction: Prediction | undefined,
currentBuffer = "",
@ -28,7 +29,7 @@ export async function* recursiveStream(
// let whiteSpaceAtEndOfBuffer = buffer.match(/\s*$/)?.[0] ?? ""; // attempts at fixing whitespace bug with recursive boundaries
if (typeof prompt === "string") {
const generator = llm.streamComplete(prompt, new AbortController().signal, {
const generator = llm.streamComplete(prompt, abortController.signal, {
raw: true,
prediction: undefined,
reasoning: false,
@ -50,6 +51,7 @@ export async function* recursiveStream(
// // TODO - Prediction capabilities lost because of partial input
// yield* recursiveStream(
// llm,
// abortController,
// continuationPrompt,
// undefined,
// buffer,
@ -60,7 +62,7 @@ export async function* recursiveStream(
}
}
} else {
const generator = llm.streamChat(prompt, new AbortController().signal, {
const generator = llm.streamChat(prompt, abortController.signal, {
prediction,
reasoning: false,
});
@ -90,6 +92,7 @@ export async function* recursiveStream(
// await generator.return(DUD_PROMPT_LOG);
// yield* recursiveStream(
// llm,
// abortController,
// continuationPrompt,
// undefined,
// buffer,

View file

@ -20,6 +20,7 @@ import { streamDiff } from "../diff/streamDiff";
import { streamLines } from "../diff/util";
import { getSystemMessageWithRules } from "../llm/rules/getSystemMessageWithRules";
import { gptEditPrompt } from "../llm/templates/edit";
import { StreamAbortManager } from "../util/abortManager";
import { findLast } from "../util/findLast";
import { Telemetry } from "../util/posthog";
import { recursiveStream } from "./recursiveStream";
@ -63,6 +64,7 @@ export async function* streamDiffLines({
highlighted,
suffix,
llm,
abortControllerId,
input,
language,
onlyOneInsertion,
@ -73,12 +75,15 @@ export async function* streamDiffLines({
highlighted: string;
suffix: string;
llm: ILLM;
abortControllerId: string;
input: string;
language: string | undefined;
onlyOneInsertion: boolean;
overridePrompt: ChatMessage[] | undefined;
rulesToInclude: RuleWithSource[] | undefined;
}): AsyncGenerator<DiffLine> {
const abortManager = StreamAbortManager.getInstance();
const abortController = abortManager.get(abortControllerId);
void Telemetry.capture(
"inlineEdit",
{
@ -158,7 +163,7 @@ export async function* streamDiffLines({
content: highlighted,
};
const completion = recursiveStream(llm, prompt, prediction);
const completion = recursiveStream(llm, abortController, prompt, prediction);
let lines = streamLines(completion);

1
core/index.d.ts vendored
View file

@ -1240,6 +1240,7 @@ export interface StreamDiffLinesPayload {
language: string | undefined;
modelTitle: string | undefined;
includeRulesInSystemMessage: boolean;
fileUri?: string;
}
export interface HighlightedCodePayload {

View file

@ -382,6 +382,9 @@ export abstract class BaseLLM implements ILLM {
// Error mapping to be more helpful
if (!resp.ok) {
if (resp.status === 499) {
return resp; // client side cancellation
}
let text = await resp.text();
if (resp.status === 404 && !resp.url.includes("/v1")) {
const error = JSON.parse(text)?.error?.replace(/"/g, "'");

View file

@ -1,7 +1,7 @@
import { streamSse } from "@continuedev/fetch";
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamSse } from "../stream.js";
class Anthropic extends BaseLLM {
static providerName = "anthropic";
@ -213,6 +213,10 @@ class Anthropic extends BaseLLM {
signal,
});
if (response.status === 499) {
return; // Aborted by user
}
if (!response.ok) {
const json = await response.json();
if (json.type === "error") {

View file

@ -134,10 +134,8 @@ class Asksage extends BaseLLM {
body: JSON.stringify(args),
});
if (!response.ok) {
throw new Error(
`API request failed with status ${response.status}: ${response.statusText}`,
);
if (response.status === 499) {
return ""; // Aborted by user
}
const data = await response.json();
@ -167,10 +165,8 @@ class Asksage extends BaseLLM {
signal,
});
if (!response.ok) {
throw new Error(
`API request failed with status ${response.status}: ${response.statusText}`,
);
if (response.status === 499) {
return; // Aborted by user
}
const data = await response.json();

View file

@ -306,7 +306,7 @@ class Bedrock extends BaseLLM {
}
const supportsTools =
PROVIDER_TOOL_SUPPORT.bedrock?.(options.model || "") ?? false;
(this.capabilities?.tools || PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ?? false;
let toolConfig = supportsTools && options.tools
? {

View file

@ -1,7 +1,7 @@
import { streamSse } from "@continuedev/fetch";
import { ChatMessage, CompletionOptions } from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamSse } from "../stream.js";
export default class Cloudflare extends BaseLLM {
static providerName = "cloudflare";

View file

@ -1,3 +1,4 @@
import { streamJSON } from "@continuedev/fetch";
import {
ChatMessage,
Chunk,
@ -6,7 +7,6 @@ import {
} from "../../index.js";
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamJSON } from "../stream.js";
class Cohere extends BaseLLM {
static providerName = "cohere";
@ -84,6 +84,10 @@ class Cohere extends BaseLLM {
signal,
});
if (resp.status === 499) {
return; // Aborted by user
}
if (options.stream === false) {
const data = await resp.json();
yield { role: "assistant", content: data.text };

View file

@ -1,5 +1,5 @@
import { streamSse } from "@continuedev/fetch";
import { CompletionOptions, LLMOptions } from "../../index.js";
import { streamSse } from "../stream.js";
import { osModelsEditPrompt } from "../templates/edit.js";
import OpenAI from "./OpenAI.js";

View file

@ -132,12 +132,16 @@ class Flowise extends BaseLLM {
): AsyncGenerator<ChatMessage> {
const requestBody = this._getRequestBody(messages, options);
const { socket, socketInfo } = await this._initializeSocket();
const request = this.fetch(this._getChatUrl(), {
const response = await this.fetch(this._getChatUrl(), {
method: "POST",
headers: this._getHeaders(),
body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id }),
signal,
}).then((res) => res.json());
});
if (response.status === 499) {
return; // Aborted by user
}
while (await socketInfo.hasNextToken()) {
yield { role: "assistant", content: socketInfo.getCurrentMessage() };
@ -145,7 +149,7 @@ class Flowise extends BaseLLM {
if (socketInfo.error) {
socket.disconnect();
try {
yield { role: "assistant", content: (await request).text };
yield { role: "assistant", content: await response.text() };
} catch (error: any) {
yield { role: "assistant", content: (error as Error).message ?? error };
}

View file

@ -1,3 +1,4 @@
import { streamResponse } from "@continuedev/fetch";
import { TRIAL_FIM_MODEL } from "../../config/onboarding.js";
import { getHeaders } from "../../continueServer/stubs/headers.js";
import { TRIAL_PROXY_URL } from "../../control-plane/client.js";
@ -8,7 +9,6 @@ import {
LLMOptions,
} from "../../index.js";
import { BaseLLM } from "../index.js";
import { streamResponse } from "../stream.js";
class FreeTrial extends BaseLLM {
static providerName = "free-trial";

View file

@ -1,3 +1,4 @@
import { streamResponse } from "@continuedev/fetch";
import { v4 as uuidv4 } from "uuid";
import {
AssistantChatMessage,
@ -10,7 +11,6 @@ import {
} from "../../index.js";
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamResponse } from "../stream.js";
import {
GeminiChatContent,
GeminiChatContentPart,
@ -438,6 +438,9 @@ class Gemini extends BaseLLM {
body: JSON.stringify(body),
signal,
});
if (response.status === 499) {
return; // Aborted by user
}
const data = await response.json();
yield { role: "assistant", content: data.candidates[0].content };
}

View file

@ -1,6 +1,6 @@
import { streamSse } from "@continuedev/fetch";
import { CompletionOptions } from "../../index.js";
import { BaseLLM } from "../index.js";
import { streamSse } from "../stream.js";
class HuggingFaceInferenceAPI extends BaseLLM {
static providerName = "huggingface-inference-api";

View file

@ -1,6 +1,6 @@
import { streamSse } from "@continuedev/fetch";
import { CompletionOptions, LLMOptions } from "../../index.js";
import { BaseLLM } from "../index.js";
import { streamSse } from "../stream.js";
class HuggingFaceTGI extends BaseLLM {
private static MAX_STOP_TOKENS = 4;

View file

@ -1,5 +1,5 @@
import { streamSse } from "@continuedev/fetch";
import { CompletionOptions, LLMOptions } from "../../index.js";
import { streamSse } from "../stream.js";
import OpenAI from "./OpenAI.js";

View file

@ -1,6 +1,6 @@
import { streamSse } from "@continuedev/fetch";
import { CompletionOptions, LLMOptions } from "../../index.js";
import { BaseLLM } from "../index.js";
import { streamSse } from "../stream.js";
class LlamaCpp extends BaseLLM {
static providerName = "llama.cpp";

View file

@ -1,5 +1,5 @@
import { streamSse } from "@continuedev/fetch";
import { CompletionOptions, LLMOptions } from "../../index.js";
import { streamSse } from "../stream.js";
import { osModelsEditPrompt } from "../templates/edit.js";
import OpenAI from "./OpenAI.js";

View file

@ -2,6 +2,7 @@ import { Mutex } from "async-mutex";
import { JSONSchema7, JSONSchema7Object } from "json-schema";
import { v4 as uuidv4 } from "uuid";
import { streamResponse } from "@continuedev/fetch";
import {
ChatMessage,
ChatMessageRole,
@ -12,7 +13,6 @@ import {
import { renderChatMessage } from "../../util/messageContent.js";
import { getRemoteModelInfo } from "../../util/ollamaHelper.js";
import { BaseLLM } from "../index.js";
import { streamResponse } from "../stream.js";
type OllamaChatMessage = {
role: ChatMessageRole;
@ -457,6 +457,9 @@ class Ollama extends BaseLLM implements ModelInstaller {
}
if (chatOptions.stream === false) {
if (response.status === 499) {
return; // Aborted by user
}
const json = (await response.json()) as OllamaChatResponse;
yield convertChatMessage(json);
} else {

View file

@ -3,6 +3,7 @@ import {
ChatCompletionMessageParam,
} from "openai/resources/index";
import { streamSse } from "@continuedev/fetch";
import {
ChatMessage,
CompletionOptions,
@ -16,7 +17,6 @@ import {
LlmApiRequestType,
toChatBody,
} from "../openaiTypeConverters.js";
import { streamSse } from "../stream.js";
const NON_CHAT_MODELS = [
"text-davinci-002",
@ -352,6 +352,9 @@ class OpenAI extends BaseLLM {
// Handle non-streaming response
if (body.stream === false) {
if (response.status === 499) {
return; // Aborted by user
}
const data = await response.json();
yield data.choices[0].message;
return;

View file

@ -1,5 +1,5 @@
import { streamSse } from "@continuedev/fetch";
import { Chunk, CompletionOptions, LLMOptions } from "../../index.js";
import { streamSse } from "../stream.js";
import { osModelsEditPrompt } from "../templates/edit.js";
import OpenAI from "./OpenAI.js";
@ -58,7 +58,7 @@ class SiliconFlow extends OpenAI {
console.warn("[SiliconFlow] rerank: query is empty");
return [];
}
if (!chunks || chunks.length === 0) {
console.warn("[SiliconFlow] rerank: chunks is empty");
return [];

View file

@ -1,9 +1,9 @@
import { GoogleAuth } from "google-auth-library";
import { streamResponse, streamSse } from "@continuedev/fetch";
import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamResponse, streamSse } from "../stream.js";
import Anthropic from "./Anthropic.js";
import Gemini from "./Gemini.js";
@ -95,6 +95,7 @@ class VertexAI extends BaseLLM {
protected async *StreamChatAnthropic(
messages: ChatMessage[],
options: CompletionOptions,
signal: AbortSignal,
): AsyncGenerator<ChatMessage> {
const systemMessage = stripImages(
messages.filter((m) => m.role === "system")[0]?.content ?? "",
@ -128,8 +129,13 @@ class VertexAI extends BaseLLM {
]
: systemMessage,
}),
signal,
});
if (response.status === 499) {
return; // Aborted by user
}
if (options.stream === false) {
const data = await response.json();
yield { role: "assistant", content: data.content[0].text };
@ -150,6 +156,7 @@ class VertexAI extends BaseLLM {
private async *streamChatGemini(
messages: ChatMessage[],
options: CompletionOptions,
signal: AbortSignal,
): AsyncGenerator<ChatMessage> {
const apiURL = new URL(
`publishers/google/models/${options.model}:streamGenerateContent`,
@ -160,6 +167,7 @@ class VertexAI extends BaseLLM {
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
signal,
});
for await (const message of this.geminiInstance.processGeminiResponse(
streamResponse(response),
@ -171,6 +179,7 @@ class VertexAI extends BaseLLM {
private async *streamChatBison(
messages: ChatMessage[],
options: CompletionOptions,
signal: AbortSignal,
): AsyncGenerator<ChatMessage> {
const instances = messages.map((message) => ({ prompt: message.content }));
@ -193,7 +202,11 @@ class VertexAI extends BaseLLM {
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
signal,
});
if (response.status === 499) {
return; // Aborted by user
}
const data = await response.json();
yield { role: "assistant", content: data.predictions[0].content };
}
@ -203,6 +216,7 @@ class VertexAI extends BaseLLM {
protected async *StreamChatMistral(
messages: ChatMessage[],
options: CompletionOptions,
signal: AbortSignal,
): AsyncGenerator<ChatMessage> {
const apiBase = this.apiBase!;
const apiURL = new URL(
@ -228,6 +242,7 @@ class VertexAI extends BaseLLM {
const response = await this.fetch(apiURL, {
method: "POST",
body: JSON.stringify(body),
signal,
});
for await (const chunk of streamSse(response)) {
@ -304,6 +319,9 @@ class VertexAI extends BaseLLM {
}),
signal,
});
if (resp.status === 499) {
return; // Aborted by user
}
// Streaming is not supported by code-gecko
// TODO: convert to non-streaming fim method when one exist in continue.
yield (await resp.json()).predictions[0].content;
@ -323,14 +341,14 @@ class VertexAI extends BaseLLM {
? this.geminiInstance.removeSystemMessage(messages)
: messages;
if (this.vertexProvider === "gemini") {
yield* this.streamChatGemini(convertedMsgs, options);
yield* this.streamChatGemini(convertedMsgs, options, signal);
} else if (this.vertexProvider === "mistral") {
yield* this.StreamChatMistral(messages, options);
yield* this.StreamChatMistral(messages, options, signal);
} else if (this.vertexProvider === "anthropic") {
yield* this.StreamChatAnthropic(messages, options);
yield* this.StreamChatAnthropic(messages, options, signal);
} else {
if (options.model.includes("bison")) {
yield* this.streamChatBison(convertedMsgs, options);
yield* this.streamChatBison(convertedMsgs, options, signal);
} else {
throw new Error(`Unsupported model: ${options.model}`);
}

View file

@ -1,15 +1,12 @@
import { streamResponse, streamSse } from "@continuedev/fetch";
import {
ChatMessage,
Chunk,
CompletionOptions,
LLMOptions,
} from "../../index.js";
import {
fromChatCompletionChunk,
} from "../openaiTypeConverters.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { BaseLLM } from "../index.js";
import { streamResponse, streamSse } from "../stream.js";
import { fromChatCompletionChunk } from "../openaiTypeConverters.js";
let watsonxToken = {
expiration: 0,
@ -86,7 +83,7 @@ class WatsonX extends BaseLLM {
}
_getEndpoint(endpoint: string): string {
return `${this.apiBase}/ml/v1/${this.deploymentId ? `deployments/${this.deploymentId}/` : ""}text/${endpoint}_stream?version=${this.apiVersion}`
return `${this.apiBase}/ml/v1/${this.deploymentId ? `deployments/${this.deploymentId}/` : ""}text/${endpoint}_stream?version=${this.apiVersion}`;
}
static providerName = "watsonx";
@ -182,7 +179,6 @@ class WatsonX extends BaseLLM {
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
await this.updateWatsonxToken();
const stopSequences = options.stop?.slice(0, 6) ?? [];
@ -214,44 +210,38 @@ class WatsonX extends BaseLLM {
payload.project_id = this.projectId;
}
var response = await this.fetch(url, {
const response = await this.fetch(url, {
method: "POST",
headers: headers,
body: JSON.stringify(payload),
signal,
});
if (!response.ok || response.body === null) {
throw new Error(
"Something went wrong. No response received, check your connection",
);
} else {
for await (const value of streamResponse(response)) {
const lines = value.split("\n");
let generatedChunk = "";
let generatedTextIndex = undefined;
lines.forEach((el: string) => {
// console.log(`${el}`);
if (el.startsWith("id:")) {
generatedTextIndex = parseInt(el.replace(/^id:\s+/, ""));
if (isNaN(generatedTextIndex)) {
console.error(`Unable to parse stream chunk ID: ${el}`);
}
} else if (el.startsWith("data:")) {
const dataStr = el.replace(/^data:\s+/, "");
try {
const data = JSON.parse(dataStr);
data.results.forEach((result: any) => {
generatedChunk += result.generated_text || "";
});
} catch (e) {
// parsing error is expected with streaming response
// console.error(`Error parsing JSON string: ${dataStr}`, e);
}
for await (const value of streamResponse(response)) {
const lines = value.split("\n");
let generatedChunk = "";
let generatedTextIndex = undefined;
lines.forEach((el: string) => {
// console.log(`${el}`);
if (el.startsWith("id:")) {
generatedTextIndex = parseInt(el.replace(/^id:\s+/, ""));
if (isNaN(generatedTextIndex)) {
console.error(`Unable to parse stream chunk ID: ${el}`);
}
});
yield generatedChunk
}
} else if (el.startsWith("data:")) {
const dataStr = el.replace(/^data:\s+/, "");
try {
const data = JSON.parse(dataStr);
data.results.forEach((result: any) => {
generatedChunk += result.generated_text || "";
});
} catch (e) {
// parsing error is expected with streaming response
// console.error(`Error parsing JSON string: ${dataStr}`, e);
}
}
});
yield generatedChunk;
}
}
@ -267,7 +257,7 @@ class WatsonX extends BaseLLM {
const headers = this._getHeaders();
const payload: any = {
messages: messages,
messages: messages,
max_tokens: options.maxTokens ?? 1024,
stop: stopSequences,
frequency_penalty: options.frequencyPenalty || 1,
@ -281,36 +271,30 @@ class WatsonX extends BaseLLM {
if (!!options.temperature) {
payload.temperature = options.temperature;
}
}
if (!!options.topP) {
payload.top_p = options.topP;
}
if (!!options.tools) {
payload.tools = options.tools;
if (options.toolChoice) {
payload.tool_choice = options.toolChoice;
payload.tool_choice = options.toolChoice;
} else {
payload.tool_choice_option = "auto";
payload.tool_choice_option = "auto";
}
}
var response = await this.fetch(url, {
const response = await this.fetch(url, {
method: "POST",
headers: headers,
body: JSON.stringify(payload),
signal,
});
if (!response.ok || response.body === null) {
throw new Error(
"Something went wrong. No response received, check your connection",
);
} else {
for await (const value of streamSse(response)) {
const chunk = fromChatCompletionChunk(value);
if (chunk) {
yield chunk;
}
for await (const value of streamSse(response)) {
const chunk = fromChatCompletionChunk(value);
if (chunk) {
yield chunk;
}
}
}

View file

@ -27,8 +27,12 @@ class ContinueProxy extends OpenAI {
// to call whatever LLM API is chosen
private actualApiBase?: string;
// Contains extra properties that we pass along to the proxy. Originally from `env` property on LLMOptions
private configEnv?: Record<string, any>;
constructor(options: LLMOptions) {
super(options);
this.configEnv = options.env;
this.actualApiBase = options.apiBase;
this.apiKeyLocation = options.apiKeyLocation;
this.orgScopeId = options.orgScopeId;
@ -48,6 +52,7 @@ class ContinueProxy extends OpenAI {
apiKeyLocation: this.apiKeyLocation,
apiBase: this.actualApiBase,
orgScopeId: this.orgScopeId ?? null,
env: this.configEnv,
};
return {
continueProperties,

View file

@ -1,72 +0,0 @@
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

@ -1,4 +1,4 @@
async function* toAsyncIterable(
export async function* toAsyncIterable(
nodeReadable: NodeJS.ReadableStream,
): AsyncGenerator<Uint8Array> {
for await (const chunk of nodeReadable) {

View file

@ -8,7 +8,7 @@ import { TTS } from "../util/tts";
export async function* llmStreamChat(
configHandler: ConfigHandler,
abortedMessageIds: Set<string>,
abortController: AbortController,
msg: Message<ToCoreProtocol["llm/streamChat"][0]>,
ide: IDE,
messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
@ -75,52 +75,44 @@ export async function* llmStreamChat(
selectedCode,
config,
fetch: (url, init) =>
fetchwithRequestOptions(url, init, config.requestOptions),
fetchwithRequestOptions(
url,
{
...init,
signal: abortController.signal,
},
config.requestOptions,
),
completionOptions,
});
const checkActiveInterval = setInterval(() => {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
clearInterval(checkActiveInterval);
let next = await gen.next();
while (!next.done) {
if (abortController.signal.aborted) {
next = await gen.return(errorPromptLog);
break;
}
}, 100);
try {
let next = await gen.next();
while (!next.done) {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
next = await gen.return(errorPromptLog);
clearInterval(checkActiveInterval);
break;
}
if (next.value) {
yield {
role: "assistant",
content: next.value,
};
}
next = await gen.next();
if (next.value) {
yield {
role: "assistant",
content: next.value,
};
}
if (!next.done) {
throw new Error("Will never happen");
}
return next.value;
} catch (e) {
throw e;
} finally {
clearInterval(checkActiveInterval);
next = await gen.next();
}
if (!next.done) {
throw new Error("Will never happen");
}
return next.value;
} else {
const gen = model.streamChat(
messages,
new AbortController().signal,
abortController.signal,
completionOptions,
);
let next = await gen.next();
while (!next.done) {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
if (abortController.signal.aborted) {
next = await gen.return(errorPromptLog);
break;
}

View file

@ -17,6 +17,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<
"claude-3.5",
"claude-3-7",
"claude-3.7",
"claude-sonnet-4",
"gpt-4",
"o3",
"gemini",
@ -24,7 +25,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<
},
anthropic: (model) => {
if (
["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7"].some((part) =>
["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7","claude-sonnet-4"].some((part) =>
model.toLowerCase().startsWith(part),
)
) {
@ -76,7 +77,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<
// For Bedrock, only support Claude Sonnet models with versions 3.5/3-5 and 3.7/3-7
if (
model.toLowerCase().includes("sonnet") &&
["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7"].some((part) =>
["claude-3-5", "claude-3.5", "claude-3-7", "claude-3.7","claude-sonnet-4"].some((part) =>
model.toLowerCase().includes(part),
)
) {

22
core/package-lock.json generated
View file

@ -14,9 +14,9 @@
"@aws-sdk/credential-providers": "^3.778.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.6",
"@continuedev/fetch": "^1.0.10",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.19",
"@continuedev/openai-adapters": "^1.0.25",
"@modelcontextprotocol/sdk": "^1.5.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
@ -138,7 +138,7 @@
},
"../packages/config-yaml": {
"name": "@continuedev/config-yaml",
"version": "1.0.87",
"version": "1.0.88",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",
@ -2927,9 +2927,10 @@
"link": true
},
"node_modules/@continuedev/fetch": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.6.tgz",
"integrity": "sha512-QpB9cHgEw5avoouFR0qm7/XTo44SrVfkGAmzbDTui2P9djj+DYvj+0yaJ8e/Ubyc5PUjFTUS2YnRar7NfYpHIg==",
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.10.tgz",
"integrity": "sha512-RBUXtm/VDz+9Itgw+CxrHXwVXoHCAedGzPOgA7gS5HZ9lObaeCJgEfzmfbln1ocFsfqSFmn5X5wSE7DHgfxpVA==",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.5",
"follow-redirects": "^1.15.6",
@ -2944,14 +2945,15 @@
"integrity": "sha512-/htL7p4li3zQSwn9bXkI23WRpZNklWTPzRSSG3Fd5gvYW8cizjhlf7OzeDdKxBfi1S0lpqMm0VwHlx3KjMKLpw=="
},
"node_modules/@continuedev/openai-adapters": {
"version": "1.0.19",
"resolved": "https://registry.npmjs.org/@continuedev/openai-adapters/-/openai-adapters-1.0.19.tgz",
"integrity": "sha512-9bfgTHPThRZAIn5T/zaWvKhMgVDFgpP3zr9DIkBT5THRNIrbbWd6VrguNEp9ASlX85ohNiXnk+jiC/FfFcH++w==",
"version": "1.0.25",
"resolved": "https://registry.npmjs.org/@continuedev/openai-adapters/-/openai-adapters-1.0.25.tgz",
"integrity": "sha512-YG7bcAlUk3BnqIOZw+ClmxmZU6G3OaaZqbhfqgiCnJem5i7oDy0pkAVHjig4iRTQkpvDokKmBXCH9wmQNRbWNw==",
"license": "Apache-2.0",
"dependencies": {
"@azure/openai": "^1.0.0-beta.12",
"@continuedev/config-types": "^1.0.5",
"@continuedev/config-yaml": "^1.0.51",
"@continuedev/fetch": "^1.0.3",
"@continuedev/fetch": "^1.0.10",
"dotenv": "^16.5.0",
"json-schema": "^0.4.0",
"node-fetch": "^3.3.2",

View file

@ -49,9 +49,9 @@
"@aws-sdk/credential-providers": "^3.778.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.6",
"@continuedev/fetch": "^1.0.10",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.19",
"@continuedev/openai-adapters": "^1.0.25",
"@modelcontextprotocol/sdk": "^1.5.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",

View file

@ -46,6 +46,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
// Special
ping: [string, string];
abort: [undefined, void];
cancelApply: [undefined, void];
// History
"history/list": [ListHistoryOptions, SessionMetadata[]];

View file

@ -28,6 +28,10 @@ export const createRuleBlock: Tool = {
description:
"Clear, imperative instruction for future code generation (e.g. 'Use named exports', 'Add Python type hints'). Each rule should focus on one specific standard.",
},
description: {
type: "string",
description: "Short description of the rule",
},
globs: {
type: "string",
description:

View file

@ -1,4 +1,4 @@
import * as YAML from "yaml";
import { parseMarkdownRule } from "../../config/markdown/parseMarkdownRule";
import { createRuleBlockImpl } from "./createRuleBlock";
// Mock the extras parameter with necessary functions
@ -17,33 +17,6 @@ describe("createRuleBlockImpl", () => {
jest.clearAllMocks();
});
it("should create a basic rule with name and rule content", async () => {
const args = {
name: "Test Rule",
rule: "Always write tests",
};
const result = await createRuleBlockImpl(args, mockExtras as any);
// Verify that writeFile was called with the correct YAML
expect(mockIde.writeFile).toHaveBeenCalled();
const yamlContent = mockIde.writeFile.mock.calls[0][1];
const parsedYaml = YAML.parse(yamlContent);
// Verify the structure of the YAML
expect(parsedYaml).toEqual({
name: "Test Rule",
version: "0.0.1",
schema: "v1",
rules: [
{
name: "Test Rule",
rule: "Always write tests",
},
],
});
});
it("should create a rule with glob pattern", async () => {
const args = {
name: "TypeScript Rule",
@ -53,14 +26,16 @@ describe("createRuleBlockImpl", () => {
await createRuleBlockImpl(args, mockExtras as any);
// Verify the YAML structure with globs
const yamlContent = mockIde.writeFile.mock.calls[0][1];
const parsedYaml = YAML.parse(yamlContent);
expect(parsedYaml.rules[0]).toEqual({
name: "TypeScript Rule",
rule: "Use interfaces for object shapes",
const fileContent = mockIde.writeFile.mock.calls[0][1];
const { frontmatter, markdown } = parseMarkdownRule(fileContent);
expect(frontmatter).toEqual({
globs: "**/*.{ts,tsx}",
});
expect(markdown).toContain("# TypeScript Rule");
expect(markdown).toContain("Use interfaces for object shapes");
});
it("should create a filename based on sanitized rule name", async () => {
@ -71,8 +46,51 @@ describe("createRuleBlockImpl", () => {
await createRuleBlockImpl(args, mockExtras as any);
// Check that the filename is sanitized
const fileUri = mockIde.writeFile.mock.calls[0][0];
expect(fileUri).toContain("special-chracters-spaces.yaml");
expect(fileUri).toContain("special-chracters-spaces.md");
});
it("should create a rule with description pattern", async () => {
const args = {
name: "Description Test",
rule: "This is the rule content",
description: "This is a detailed explanation of the rule",
};
await createRuleBlockImpl(args, mockExtras as any);
const fileContent = mockIde.writeFile.mock.calls[0][1];
const { frontmatter, markdown } = parseMarkdownRule(fileContent);
expect(frontmatter).toEqual({
description: "This is a detailed explanation of the rule",
});
expect(markdown).toContain("# Description Test");
expect(markdown).toContain("This is the rule content");
});
it("should include both globs and description in frontmatter", async () => {
const args = {
name: "Complete Rule",
rule: "Follow this standard",
description: "This rule enforces our team standards",
globs: "**/*.js",
};
await createRuleBlockImpl(args, mockExtras as any);
const fileContent = mockIde.writeFile.mock.calls[0][1];
const { frontmatter, markdown } = parseMarkdownRule(fileContent);
expect(frontmatter).toEqual({
description: "This rule enforces our team standards",
globs: "**/*.js",
});
expect(markdown).toContain("# Complete Rule");
expect(markdown).toContain("Follow this standard");
});
});

View file

@ -1,4 +1,3 @@
import { ConfigYaml } from "@continuedev/config-yaml";
import * as YAML from "yaml";
import { ToolImpl } from ".";
import { joinPathsToUri } from "../../util/uri";
@ -6,8 +5,8 @@ import { joinPathsToUri } from "../../util/uri";
export interface CreateRuleBlockArgs {
name: string;
rule: string;
description: string;
globs?: string;
format?: "yaml" | "markdown"; // Add format option with yaml as default
}
export const createRuleBlockImpl: ToolImpl = async (
@ -20,26 +19,19 @@ export const createRuleBlockImpl: ToolImpl = async (
.replace(/[^a-z0-9\s-]/g, "")
.replace(/\s+/g, "-");
// Default to YAML format
const format = args.format ?? "yaml";
const fileExtension = format === "markdown" ? "md" : "yaml";
const fileExtension = "md";
const ruleObject = {
name: args.name,
rule: args.rule,
...(args.globs ? { globs: args.globs.trim() } : {}),
};
const frontmatter: Record<string, string> = {};
let fileContent: string;
if (args.globs) {
frontmatter.globs = args.globs.trim();
}
if (format === "markdown") {
// Generate markdown format with frontmatter
const frontmatter = {
...(args.globs ? { globs: args.globs.trim() } : {}),
};
const frontmatterYaml = YAML.stringify(frontmatter).trim();
fileContent = `---
if (args.description) {
frontmatter.description = args.description.trim();
}
const frontmatterYaml = YAML.stringify(frontmatter).trim();
let fileContent = `---
${frontmatterYaml}
---
@ -47,18 +39,6 @@ ${frontmatterYaml}
${args.rule}
`;
} else {
// Generate YAML format
const ruleBlock: ConfigYaml = {
name: args.name,
version: "0.0.1",
schema: "v1",
rules: [ruleObject],
};
fileContent = YAML.stringify(ruleBlock);
}
const [localContinueDir] = await extras.ide.getWorkspaceDirs();
const rulesDirUri = joinPathsToUri(
localContinueDir,
@ -73,12 +53,12 @@ ${args.rule}
return [
{
name: "New Rule Block",
description: "", // No description throws an error in the GUI
description: args.description || "",
uri: {
type: "file",
value: rulesDirUri,
},
content: `Rule created successfully in ${format} format`,
content: `Rule created successfully`,
},
];
};

37
core/util/abortManager.ts Normal file
View file

@ -0,0 +1,37 @@
export class StreamAbortManager {
private static instance: StreamAbortManager;
private controllers: Map<string, AbortController>;
private constructor() {
this.controllers = new Map();
}
public static getInstance(): StreamAbortManager {
if (!StreamAbortManager.instance) {
StreamAbortManager.instance = new StreamAbortManager();
}
return StreamAbortManager.instance;
}
public get(id: string): AbortController {
let controller = this.controllers.get(id);
if (!controller) {
controller = new AbortController();
this.controllers.set(id, controller);
}
return controller;
}
public abort(id: string): void {
const controller = this.controllers.get(id);
if (controller) {
controller.abort();
this.controllers.delete(id);
}
}
public clear(): void {
this.controllers.forEach((controller) => controller.abort());
this.controllers.clear();
}
}

View file

@ -188,6 +188,7 @@ chat, editing, and summarizing.
not currently used.
- `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on
provider and model. Supported capabilities include `tool_use` and `image_input`.
- `maxStopWords`: Maximum number of stop words allowed, to avoid API errors with extensive lists.
- `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are
`chat`, [`edit`](./customize/model-roles/edit.mdx#prompt-templating), [
`apply`](./customize/model-roles/apply.mdx#prompt-templating) and [
@ -406,7 +407,7 @@ Destinations to which [development data](./customize/deep-dives/development-data
- `destination` (**required**): The destination/endpoint that will receive the data. Can be:
- an HTTP endpoint that will receive a POST request with a JSON blob
- a file URL to a directory in which events will be dumpted to `.jsonl` files
- `schema` (**required**): the schema version of the JSON blobs to be sent
- `schema` (**required**): the schema version of the JSON blobs to be sent. Options include `0.1.0` and `0.2.0`
- `events`: an array of event names to include. Defaults to all events if not specified.
- `level`: a pre-defined filter for event fields. Options include `all` and `noCode`; the latter excludes data like file
contents, prompts, and completions. Defaults to `all`

View file

@ -66,7 +66,9 @@ const config = {
],
scripts: [
'!function(){var e,t,n;e="7aa28ed11570734",t=function(){Reo.init({clientID:"7aa28ed11570734"})},(n=document.createElement("script")).src="https://static.reo.dev/"+e+"/reo.js",n.defer=!0,n.onload=t,document.head.appendChild(n)}();',
{
src: "/scripts/custom-reo.js", // it references from static folder
},
],
themeConfig:

1
docs/static/scripts/custom-reo.js vendored Normal file
View file

@ -0,0 +1 @@
!function(){var e,t,n;e="7aa28ed11570734",t=function(){Reo.init({clientID:"7aa28ed11570734"})},(n=document.createElement("script")).src="https://static.reo.dev/"+e+"/reo.js",n.async=!0,n.onload=t,document.head.appendChild(n)}();

View file

@ -108,7 +108,7 @@ class DiffManager(private val project: Project) : DumbAware {
)
continuePluginService.ideProtocolClient?.deleteAtIndex(diffInfo.stepIndex)
continuePluginService.ideProtocolClient?.sendAcceptRejectDiff(false, diffInfo.stepIndex)
continuePluginService.coreMessenger?.request("cancelApply", null, null) {}
cleanUpFile(file)
}

View file

@ -111,7 +111,8 @@ class DiffStreamHandler(
suffix = suffix,
language = virtualFile?.fileType?.name,
modelTitle = modelTitle,
includeRulesInSystemMessage = includeRulesInSystemMessage
includeRulesInSystemMessage = includeRulesInSystemMessage,
fileUri = virtualFile?.url
),
null
) { response ->
@ -289,7 +290,6 @@ class DiffStreamHandler(
}
}
private fun handleFinishedResponse() {
ApplicationManager.getApplication().invokeLater {
// Since we only call onLastDiffLine() when we reach a "same" line, we need to handle the case where

View file

@ -244,7 +244,8 @@ data class StreamDiffLinesPayload(
val input: String,
val language: String?,
val modelTitle: String?,
val includeRulesInSystemMessage: Boolean
val includeRulesInSystemMessage: Boolean,
val fileUri: String?
)
data class AcceptOrRejectDiffPayload(

View file

@ -1,16 +1,16 @@
{
"name": "continue",
"version": "1.1.37",
"version": "1.1.39",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "1.1.37",
"version": "1.1.39",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",
"@continuedev/fetch": "^1.0.3",
"@continuedev/fetch": "^1.0.10",
"@electron/rebuild": "^3.2.10",
"@reduxjs/toolkit": "^1.9.3",
"@types/node-fetch": "^2.6.11",
@ -64,7 +64,7 @@
"devDependencies": {
"@biomejs/biome": "1.6.4",
"@nestjs/common": "^11.0.16",
"@openapitools/openapi-generator-cli": "^2.5.2",
"@openapitools/openapi-generator-cli": "^2.20.0",
"@types/chai": "^5.0.1",
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
@ -107,9 +107,9 @@
"@aws-sdk/credential-providers": "^3.778.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.6",
"@continuedev/fetch": "^1.0.10",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.19",
"@continuedev/openai-adapters": "^1.0.25",
"@modelcontextprotocol/sdk": "^1.5.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
@ -708,9 +708,10 @@
}
},
"node_modules/@continuedev/fetch": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.3.tgz",
"integrity": "sha512-cGNCUEVnDfC+3O/n1PV+oYhS5yZRLR1Q7Njg929kVbA8kRHe5a3VdKINfFzWdKprOU4wipsXSliciZHCpbJJ9g==",
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.10.tgz",
"integrity": "sha512-RBUXtm/VDz+9Itgw+CxrHXwVXoHCAedGzPOgA7gS5HZ9lObaeCJgEfzmfbln1ocFsfqSFmn5X5wSE7DHgfxpVA==",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.5",
"follow-redirects": "^1.15.6",

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "1.1.38",
"version": "1.1.39",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -631,7 +631,7 @@
"devDependencies": {
"@biomejs/biome": "1.6.4",
"@nestjs/common": "^11.0.16",
"@openapitools/openapi-generator-cli": "^2.5.2",
"@openapitools/openapi-generator-cli": "^2.20.0",
"@types/chai": "^5.0.1",
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
@ -661,7 +661,7 @@
},
"dependencies": {
"@continuedev/config-types": "^1.0.14",
"@continuedev/fetch": "^1.0.3",
"@continuedev/fetch": "^1.0.10",
"@electron/rebuild": "^3.2.10",
"@reduxjs/toolkit": "^1.9.3",
"@types/node-fetch": "^2.6.11",

View file

@ -97,6 +97,7 @@ async function processDiff(
action: "accept" | "reject",
sidebar: ContinueGUIWebviewViewProvider,
ide: VsCodeIde,
core: Core,
verticalDiffManager: VerticalDiffManager,
newFileUri?: string,
streamId?: string,
@ -121,6 +122,9 @@ async function processDiff(
// Clear vertical diffs depending on action
verticalDiffManager.clearForfileUri(newOrCurrentUri, action === "accept");
if (action === "reject") {
core.invoke("cancelApply", undefined);
}
if (streamId) {
const fileContent = await ide.readFile(newOrCurrentUri);
@ -236,18 +240,20 @@ const getCommandsMap: (
"accept",
sidebar,
ide,
core,
verticalDiffManager,
newFileUri,
streamId,
),
"continue.rejectDiff": async (newFilepath?: string, streamId?: string) =>
"continue.rejectDiff": async (newFileUri?: string, streamId?: string) =>
processDiff(
"reject",
sidebar,
ide,
core,
verticalDiffManager,
newFilepath,
newFileUri,
streamId,
),
"continue.acceptVerticalDiffBlock": (fileUri?: string, index?: number) => {
@ -573,11 +579,15 @@ const getCommandsMap: (
await addEntireFileToContext(
vscode.Uri.parse(fileUri),
sidebar.webviewProtocol,
ide.ideUtils
ide.ideUtils,
);
}
} else {
await addEntireFileToContext(uri, sidebar.webviewProtocol, ide.ideUtils);
await addEntireFileToContext(
uri,
sidebar.webviewProtocol,
ide.ideUtils,
);
}
}
},

View file

@ -1,5 +1,4 @@
import { ChatMessage, DiffLine, ILLM, RuleWithSource } from "core";
import { ConfigHandler } from "core/config/ConfigHandler";
import { streamDiffLines } from "core/edit/streamDiffLines";
import { pruneLinesFromBottom, pruneLinesFromTop } from "core/llm/countTokens";
import { getMarkdownLanguageTagForFile } from "core/util";
@ -31,7 +30,6 @@ export class VerticalDiffManager {
logDiffs: DiffLine[] | undefined;
constructor(
private readonly configHandler: ConfigHandler,
private readonly webviewProtocol: VsCodeWebviewProtocol,
private readonly editDecorationManager: EditDecorationManager,
) {
@ -43,12 +41,12 @@ export class VerticalDiffManager {
startLine: number,
endLine: number,
options: VerticalDiffHandlerOptions,
) {
): VerticalDiffHandler | undefined {
if (this.fileUriToHandler.has(fileUri)) {
this.fileUriToHandler.get(fileUri)?.clear(false);
this.fileUriToHandler.delete(fileUri);
}
const editor = vscode.window.activeTextEditor; // TODO
const editor = vscode.window.activeTextEditor; // TODO might cause issues if user switches files
if (editor && URI.equal(editor.document.uri.toString(), fileUri)) {
const handler = new VerticalDiffHandler(
startLine,
@ -453,6 +451,7 @@ export class VerticalDiffManager {
language: getMarkdownLanguageTagForFile(fileUri),
onlyOneInsertion: !!onlyOneInsertion,
overridePrompt,
abortControllerId: fileUri,
});
for await (const line of stream) {

View file

@ -130,7 +130,6 @@ export class VsCodeExtension {
this.configHandler.loadConfig();
this.verticalDiffManager = new VerticalDiffManager(
this.configHandler,
this.sidebar.webviewProtocol,
this.editDecorationManager,
);

6
gui/package-lock.json generated
View file

@ -111,9 +111,9 @@
"@aws-sdk/credential-providers": "^3.778.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.6",
"@continuedev/fetch": "^1.0.10",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.19",
"@continuedev/openai-adapters": "^1.0.25",
"@modelcontextprotocol/sdk": "^1.5.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
@ -211,7 +211,7 @@
},
"../packages/config-yaml": {
"name": "@continuedev/config-yaml",
"version": "1.0.87",
"version": "1.0.88",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",

View file

@ -1,5 +1,5 @@
import { XMarkIcon } from "@heroicons/react/24/outline";
import { useCallback, useEffect } from "react";
import React, { useCallback, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import styled from "styled-components";
import { defaultBorderRadius } from "..";
@ -35,6 +35,8 @@ const TabBarContainer = styled.div`
border-bottom: none;
position: relative;
margin-top: 2px;
max-height: 100px;
overflow: auto;
/* Hide scrollbar but keep functionality */
scrollbar-width: none;
@ -125,7 +127,7 @@ const TabBarSpace = styled.div`
background-color: ${tabBackgroundVar};
`;
export function TabBar() {
export const TabBar = React.forwardRef<HTMLDivElement>((_, ref) => {
const dispatch = useDispatch<AppDispatch>();
const currentSessionId = useSelector((state: RootState) => state.session.id);
const currentSessionTitle = useSelector(
@ -141,7 +143,6 @@ export function TabBar() {
return Date.now().toString(36) + Math.random().toString(36).substring(2);
}, []);
// Handle session changes
useEffect(() => {
if (!currentSessionId) return;
@ -224,10 +225,13 @@ export function TabBar() {
}
};
return tabs.length === 1 ? (
<></>
) : (
<TabBarContainer>
return (
<TabBarContainer
ref={ref}
style={{
display: tabs.length === 1 ? "none" : "flex",
}}
>
{tabs.map((tab) => (
<Tab
key={tab.id}
@ -253,4 +257,4 @@ export function TabBar() {
</TabBarSpace>
</TabBarContainer>
);
}
});

View file

@ -12,36 +12,25 @@ import {
useState,
} from "react";
import { HeaderButton, Input } from "..";
import { useAppSelector } from "../../redux/hooks";
import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
import {
Rectangle,
SearchMatch,
searchWithinContainer,
} from "./findWidgetSearch";
import useDebounceValue from "./useDebounce";
import { useElementSize } from "./useElementSize";
interface SearchMatch {
index: number;
textNode: Text;
overlayRectangle: Rectangle;
}
type ScrollToMatchOption = "closest" | "first" | "none";
const SEARCH_DEBOUNCE = 300;
const RESIZE_DEBOUNCE = 200;
interface Rectangle {
top: number;
left: number;
width: number;
height: number;
}
interface HighlightOverlayProps extends Rectangle {
interface HighlightOverlayProps {
rectangle: Rectangle;
isCurrent: boolean;
}
const HighlightOverlay = (props: HighlightOverlayProps) => {
const { isCurrent, top, left, width, height } = props;
const { top, left, width, height } = props.rectangle;
return (
<div
className={isCurrent ? "bg-findMatch-selected/50" : "bg-findMatch/50"}
className={props.isCurrent ? "bg-findMatch-selected" : "bg-findMatch"}
key={`highlight-${top}-${left}`}
style={{
position: "absolute",
@ -56,6 +45,8 @@ const HighlightOverlay = (props: HighlightOverlayProps) => {
);
};
type ScrollToMatchOption = "closest" | "first" | "none";
/*
useFindWidget takes a container ref and returns
1. A widget that can be placed anywhere to search the contents of that container
@ -64,18 +55,22 @@ const HighlightOverlay = (props: HighlightOverlayProps) => {
Container must have relative positioning
*/
export const useFindWidget = (searchRef: RefObject<HTMLDivElement>) => {
export const useFindWidget = (
searchRef: RefObject<HTMLDivElement>,
headerRef: RefObject<HTMLDivElement>,
disabled: boolean,
) => {
// Search input, debounced
const [input, setInput] = useState<string>("");
const debouncedInput = useRef<string>("");
const inputRef = useRef<HTMLInputElement>(null);
const [currentValue, setCurrentValue] = useState<string>("");
const searchTerm = useDebounceValue(currentValue, 300);
// Widget open/closed state
const [open, setOpen] = useState<boolean>(false);
const openWidget = useCallback(() => {
setOpen(true);
inputRef?.current?.select();
}, [setOpen, inputRef]);
}, [inputRef]);
// Search settings and results
const [caseSensitive, setCaseSensitive] = useState<boolean>(false);
@ -97,7 +92,7 @@ export const useFindWidget = (searchRef: RefObject<HTMLDivElement>) => {
behavior: "smooth",
});
},
[searchRef.current],
[searchRef],
);
const nextMatch = useCallback(() => {
@ -143,327 +138,166 @@ export const useFindWidget = (searchRef: RefObject<HTMLDivElement>) => {
}, [inputRef, matches, nextMatch]);
// Handle container resize changes - highlight positions must adjust
const [isResizing, setIsResizing] = useState(false);
useEffect(() => {
let timeoutId: NodeJS.Timeout | null = null;
if (!searchRef?.current) return;
const resizeObserver = new ResizeObserver((entries) => {
if (timeoutId) {
clearTimeout(timeoutId);
}
setIsResizing(true);
timeoutId = setTimeout(() => {
setIsResizing(false);
}, RESIZE_DEBOUNCE);
});
resizeObserver.observe(searchRef.current);
return () => {
if (timeoutId) {
clearTimeout(timeoutId);
}
if (searchRef.current) resizeObserver.unobserve(searchRef.current);
};
}, [searchRef.current]);
const { clientHeight: headerHeight, isResizing: headerResizing } =
useElementSize(headerRef);
const { isResizing: containerResizing } = useElementSize(searchRef);
const isResizing = useMemo(() => {
return containerResizing || headerResizing;
}, [containerResizing, headerResizing]);
// Main function for finding matches and generating highlight overlays
const refreshSearch = useCallback(
(scrollTo: ScrollToMatchOption = "none", clearFirst = false) => {
if (clearFirst) setMatches([]);
const searchContainer = searchRef.current;
const _query = debouncedInput.current; // trimStart - decided no because spaces should be fully searchable
if (!searchContainer || !_query) {
setMatches([]);
return;
}
const query = caseSensitive ? _query : _query.toLowerCase();
// First grab all text nodes
// Skips any elements with the "find-widget-skip" class
const textNodes: Text[] = [];
const walker = document.createTreeWalker(
searchRef.current,
NodeFilter.SHOW_ALL,
(scrollTo: ScrollToMatchOption = "none") => {
const { results, closestToMiddle } = searchWithinContainer(
searchRef,
searchTerm,
{
acceptNode: (node) => {
if (node.nodeType === Node.ELEMENT_NODE) {
if ((node as Element).classList.contains("find-widget-skip"))
return NodeFilter.FILTER_REJECT;
return NodeFilter.FILTER_ACCEPT;
} else if (node.nodeType === Node.TEXT_NODE) {
if (!node.nodeValue) return NodeFilter.FILTER_REJECT;
const nodeValue = caseSensitive
? node.nodeValue
: node.nodeValue.toLowerCase();
if (nodeValue.includes(query)) return NodeFilter.FILTER_ACCEPT;
}
return NodeFilter.FILTER_REJECT;
},
caseSensitive,
useRegex,
offsetHeight: headerHeight,
},
);
while (walker.nextNode()) {
if (walker.currentNode.nodeType === Node.ELEMENT_NODE) continue;
textNodes.push(walker.currentNode as Text);
}
// Now walk through each node match and extract search results
// One node can have several matches
const newMatches: SearchMatch[] = [];
textNodes.forEach((textNode, idx) => {
// Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail
const highlightFullLine =
textNode.parentElement?.className.includes("hljs");
let nodeTextValue = caseSensitive
? textNode.nodeValue
: textNode.nodeValue.toLowerCase();
let startIndex = 0;
while ((startIndex = nodeTextValue.indexOf(query, startIndex)) !== -1) {
// Create a range to measure the size and position of the match
const range = document.createRange();
range.setStart(textNode, startIndex);
const endIndex = startIndex + query.length;
range.setEnd(textNode, endIndex);
const rect = range.getBoundingClientRect();
range.detach();
startIndex = endIndex;
const top =
rect.top + searchContainer.clientTop + searchContainer.scrollTop;
const left =
rect.left + searchContainer.clientLeft + searchContainer.scrollLeft;
// Build a match result and push to matches
const newMatch: SearchMatch = {
index: 0, // will set later
textNode,
overlayRectangle: {
top,
left: highlightFullLine ? 2 : left,
width: highlightFullLine
? searchContainer.clientWidth - 4
: rect.width, // equivalent of adding 2 px x padding
height: rect.height,
},
};
newMatches.push(newMatch);
if (highlightFullLine) {
break; // Since highlighting full line no need for multiple overlays, will cause darker highlight
}
}
});
// There will still be duplicate full lines when multiple text nodes are in the same line (e.g. Code highlights)
// Filter them out by using the overlay rectangle as a hash key
const matchHash = Object.fromEntries(
newMatches.map((match) => [
JSON.stringify(match.overlayRectangle),
match,
]),
);
const filteredMatches = Object.values(matchHash).map((match, index) => ({
...match,
index,
}));
setMatches(results);
// Find match closest to the middle of the view
const verticalMiddle =
searchRef.current.scrollTop + searchRef.current.clientHeight / 2;
let closestDist = Infinity;
let closestMatchToMiddle: SearchMatch | null = null;
filteredMatches.forEach((match) => {
const dist = Math.abs(verticalMiddle - match.overlayRectangle.top);
if (dist < closestDist) {
closestDist = dist;
closestMatchToMiddle = match;
}
});
// Update matches and scroll to the closest or first match
setMatches(filteredMatches);
if (query.length > 1 && filteredMatches.length) {
if (searchTerm.length > 1 && results.length) {
if (scrollTo === "first") {
scrollToMatch(filteredMatches[0]);
scrollToMatch(results[0]);
}
if (scrollTo === "closest") {
if (closestMatchToMiddle) {
scrollToMatch(closestMatchToMiddle);
if (closestToMiddle) {
scrollToMatch(closestToMiddle);
}
}
if (scrollTo === "none") {
if (closestMatchToMiddle) {
setCurrentMatch(closestMatchToMiddle);
if (closestToMiddle) {
setCurrentMatch(closestToMiddle);
} else {
setCurrentMatch(filteredMatches[0]);
setCurrentMatch(results[0]);
}
}
}
},
[searchRef.current, debouncedInput, scrollToMatch, caseSensitive, useRegex],
[
searchTerm,
caseSensitive,
useRegex,
searchRef,
headerHeight,
scrollToMatch,
],
);
// Triggers that should cause immediate refresh of results to closest search value:
// Input change (debounced) and window click
const lastUpdateRef = useRef(0);
useEffect(() => {
const debounce = () => {
debouncedInput.current = input;
lastUpdateRef.current = Date.now();
refreshSearch("closest");
};
const timeSinceLastUpdate = Date.now() - lastUpdateRef.current;
if (timeSinceLastUpdate >= SEARCH_DEBOUNCE) {
debounce();
if (disabled || isResizing || !open) {
setMatches([]);
} else {
const handler = setTimeout(() => {
debounce();
}, SEARCH_DEBOUNCE - timeSinceLastUpdate);
return () => {
clearTimeout(handler);
};
refreshSearch("closest");
}
}, [refreshSearch, input]);
}, [refreshSearch, open, disabled, isResizing]);
// Could consider doing any window click but I only handled search div here
// Since usually only clicks in search div will cause content changes in search div
// Clicks in search div can cause content changes that for some reason don't trigger resize
// Refresh clicking within container
useEffect(() => {
const searchContainer = searchRef.current;
if (!open || !searchContainer) return;
const handleSearchRefClick = () => {
refreshSearch("none");
setTimeout(() => {
refreshSearch("none");
}, 150);
};
searchContainer.addEventListener("click", handleSearchRefClick);
return () => {
searchContainer.removeEventListener("click", handleSearchRefClick);
};
}, [searchRef.current, refreshSearch, open]);
// Triggers that should cause results to temporarily disappear and then reload
// Active = LLM is generating, etc.
const active = useAppSelector((state) => state.session.isStreaming);
useEffect(() => {
if (active || isResizing) setMatches([]);
else refreshSearch("none");
}, [refreshSearch, active]);
useEffect(() => {
if (!open) setMatches([]);
else refreshSearch("closest");
}, [refreshSearch, open]);
useEffect(() => {
refreshSearch("closest");
}, [refreshSearch, caseSensitive, useRegex]);
}, [searchRef, refreshSearch, open]);
// Find widget component
const widget = useMemo(() => {
return (
<div
className={`fixed top-0 z-50 transition-all ${open ? "" : "-translate-y-full"} bg-vsc-background right-0 flex flex-row items-center gap-1.5 rounded-bl-lg border-0 border-b border-l border-solid border-zinc-700 pl-[3px] pr-3 sm:gap-2`}
>
<Input
disabled={active}
type="text"
ref={inputRef}
value={input}
onChange={(e) => {
setInput(e.target.value);
}}
placeholder="Search..."
/>
<p className="xs:block hidden min-w-12 whitespace-nowrap px-1 text-center text-xs">
{matches.length === 0
? "No results"
: `${(currentMatch?.index ?? 0) + 1} of ${matches.length}`}
</p>
<div className="hidden flex-row gap-0.5 sm:flex">
<HeaderButtonWithToolTip
tooltipPlacement="top-end"
text={"Previous Match"}
onClick={(e) => {
e.stopPropagation();
previousMatch();
}}
className="h-4 w-4 focus:ring"
disabled={matches.length < 2 || active}
>
<ArrowUpIcon className="h-4 w-4" />
</HeaderButtonWithToolTip>
<HeaderButtonWithToolTip
tooltipPlacement="top-end"
text={"Next Match"}
onClick={(e) => {
e.stopPropagation();
nextMatch();
}}
className="h-4 w-4 focus:ring"
disabled={matches.length < 2 || active}
>
<ArrowDownIcon className="h-4 w-4" />
</HeaderButtonWithToolTip>
</div>
const widget = (
<div
className={`fixed top-0 z-50 transition-all ${open ? "" : "-translate-y-full"} bg-vsc-background right-0 flex flex-row items-center gap-1.5 rounded-bl-lg border-0 border-b border-l border-solid border-zinc-700 pl-[3px] pr-3 sm:gap-2`}
>
<Input
disabled={disabled}
type="text"
ref={inputRef}
value={currentValue}
onChange={(e) => {
setCurrentValue(e.target.value);
}}
placeholder="Search..."
/>
<p className="xs:block hidden min-w-12 whitespace-nowrap px-1 text-center text-xs">
{matches.length === 0
? "No results"
: `${(currentMatch?.index ?? 0) + 1} of ${matches.length}`}
</p>
<div className="hidden flex-row gap-0.5 sm:flex">
<HeaderButtonWithToolTip
disabled={active}
inverted={caseSensitive}
tooltipPlacement="top-end"
text={
caseSensitive
? "Turn off case sensitivity"
: "Turn on case sensitivity"
}
text={"Previous Match"}
onClick={(e) => {
e.stopPropagation();
setCaseSensitive((curr) => !curr);
previousMatch();
}}
className="h-5 w-6 rounded-full border text-xs focus:outline-none focus:ring"
className="h-4 w-4 focus:ring"
disabled={matches.length < 2 || disabled}
>
Aa
<ArrowUpIcon className="h-4 w-4" />
</HeaderButtonWithToolTip>
{/* TODO - add useRegex functionality */}
<HeaderButton
inverted={false}
onClick={() => setOpen(false)}
className="focus:ring"
<HeaderButtonWithToolTip
tooltipPlacement="top-end"
text={"Next Match"}
onClick={(e) => {
e.stopPropagation();
nextMatch();
}}
className="h-4 w-4 focus:ring"
disabled={matches.length < 2 || disabled}
>
<XMarkIcon className="h-4 w-4" />
</HeaderButton>
<ArrowDownIcon className="h-4 w-4" />
</HeaderButtonWithToolTip>
</div>
);
}, [
open,
input,
inputRef,
caseSensitive,
matches,
currentMatch,
previousMatch,
nextMatch,
]);
<HeaderButtonWithToolTip
disabled={disabled}
inverted={caseSensitive}
tooltipPlacement="top-end"
text={
caseSensitive
? "Turn off case sensitivity"
: "Turn on case sensitivity"
}
onClick={(e) => {
e.stopPropagation();
setCaseSensitive((curr) => !curr);
}}
className="h-5 w-6 rounded-full border text-xs focus:outline-none focus:ring"
>
Aa
</HeaderButtonWithToolTip>
{/* TODO - add useRegex functionality */}
<HeaderButton
inverted={false}
onClick={() => setOpen(false)}
className="focus:ring"
>
<XMarkIcon className="h-4 w-4" />
</HeaderButton>
</div>
);
// Generate the highlight overlay elements
const highlights = useMemo(() => {
return matches.map((match) => (
<HighlightOverlay
{...match.overlayRectangle}
rectangle={match.overlayRectangle}
isCurrent={currentMatch?.index === match.index}
/>
));
}, [matches, currentMatch]);
return {
matches,
highlights,
inputRef,
input: debouncedInput,
setInput,
open,
setOpen,
widget,
};
};

View file

@ -0,0 +1,146 @@
export interface Rectangle {
top: number;
left: number;
width: number;
height: number;
}
export interface SearchMatch {
index: number;
textNode: Text;
overlayRectangle: Rectangle;
}
interface SearchOptions {
caseSensitive: boolean;
useRegex: boolean;
offsetHeight: number;
}
export const searchWithinContainer = (
containerRef: React.RefObject<HTMLDivElement>,
searchQuery: string,
options: SearchOptions,
): {
results: SearchMatch[];
closestToMiddle: SearchMatch | null;
} => {
const searchContainer = containerRef.current;
if (!searchContainer || !searchQuery) {
return {
results: [],
closestToMiddle: null,
};
}
const query = options.caseSensitive ? searchQuery : searchQuery.toLowerCase();
// First grab all text nodes
// Skips any elements with the "find-widget-skip" class
const textNodes: Text[] = [];
const walker = document.createTreeWalker(
searchContainer,
NodeFilter.SHOW_ALL,
{
acceptNode: (node) => {
if (node.nodeType === Node.ELEMENT_NODE) {
if ((node as Element).classList.contains("find-widget-skip"))
return NodeFilter.FILTER_REJECT;
return NodeFilter.FILTER_ACCEPT;
} else if (node.nodeType === Node.TEXT_NODE) {
if (!node.nodeValue) return NodeFilter.FILTER_REJECT;
const nodeValue = options.caseSensitive
? node.nodeValue
: node.nodeValue.toLowerCase();
if (nodeValue.includes(query)) return NodeFilter.FILTER_ACCEPT;
}
return NodeFilter.FILTER_REJECT;
},
},
);
while (walker.nextNode()) {
if (walker.currentNode.nodeType === Node.ELEMENT_NODE) continue;
textNodes.push(walker.currentNode as Text);
}
// Now walk through each node match and extract search results
// One node can have several matches
const newMatches: SearchMatch[] = [];
textNodes.forEach((textNode, idx) => {
// Hacky way to detect code blocks that be wider than client and cause absolute positioning to fail
const highlightFullLine =
textNode.parentElement?.className.includes("hljs");
let nodeTextValue = options.caseSensitive
? textNode.nodeValue
: textNode.nodeValue.toLowerCase();
let startIndex = 0;
while ((startIndex = nodeTextValue.indexOf(query, startIndex)) !== -1) {
// Create a range to measure the size and position of the match
const range = document.createRange();
range.setStart(textNode, startIndex);
const endIndex = startIndex + query.length;
range.setEnd(textNode, endIndex);
const rect = range.getBoundingClientRect();
range.detach();
startIndex = endIndex;
const top =
rect.top +
searchContainer.clientTop +
searchContainer.scrollTop -
options.offsetHeight;
const left =
rect.left + searchContainer.clientLeft + searchContainer.scrollLeft;
// Build a match result and push to matches
const newMatch: SearchMatch = {
index: 0, // will set later
textNode,
overlayRectangle: {
top,
left: highlightFullLine ? 2 : left,
width: highlightFullLine
? searchContainer.clientWidth - 4
: rect.width, // equivalent of adding 2 px x padding
height: rect.height,
},
};
newMatches.push(newMatch);
if (highlightFullLine) {
break; // Since highlighting full line no need for multiple overlays, will cause darker highlight
}
}
});
// There will still be duplicate full lines when multiple text nodes are in the same line (e.g. Code highlights)
// Filter them out by using the overlay rectangle as a hash key
const matchHash = Object.fromEntries(
newMatches.map((match) => [JSON.stringify(match.overlayRectangle), match]),
);
const filteredMatches = Object.values(matchHash).map((match, index) => ({
...match,
index,
}));
// Find the match closest to the vertical middle of the container
const verticalMiddle =
searchContainer.scrollTop + searchContainer.clientHeight / 2;
let closestDist = Infinity;
let closestMatchToMiddle: SearchMatch | null = null;
filteredMatches.forEach((match) => {
const dist = Math.abs(verticalMiddle - match.overlayRectangle.top);
if (dist < closestDist) {
closestDist = dist;
closestMatchToMiddle = match;
}
});
return {
results: filteredMatches,
closestToMiddle: closestMatchToMiddle,
};
};

View file

@ -0,0 +1,19 @@
import { useEffect, useState } from "react";
function useDebounceValue<T>(value: T, delay: number = 500): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value);
useEffect(() => {
const timer = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(timer);
};
}, [value, delay]);
return debouncedValue;
}
export default useDebounceValue;

View file

@ -0,0 +1,81 @@
import { RefObject, useCallback, useEffect, useState } from "react";
interface ElementSize {
clientWidth: number;
clientHeight: number;
scrollWidth: number;
scrollHeight: number;
isResizing: boolean;
}
interface UseElementSizeOptions {
debounceMs?: number;
}
export const useElementSize = (
ref: RefObject<HTMLElement>,
debounceMs = 250,
): ElementSize => {
const [size, setSize] = useState<ElementSize>({
clientWidth: 0,
clientHeight: 0,
scrollWidth: 0,
scrollHeight: 0,
isResizing: false,
});
// Debounced update function
const debouncedSetSize = useCallback(
(measurements: Omit<ElementSize, "isResizing">) => {
let timeoutId: NodeJS.Timeout;
setSize((prev) => ({ ...prev, isResizing: true }));
timeoutId = setTimeout(() => {
setSize({
...measurements,
isResizing: false,
});
}, debounceMs);
return () => clearTimeout(timeoutId);
},
[debounceMs],
);
useEffect(() => {
if (!ref.current) return;
const updateSize = () => {
const element = ref.current;
if (!element) return;
const measurements = {
clientWidth: element.clientWidth,
clientHeight: element.clientHeight,
scrollWidth: element.scrollWidth,
scrollHeight: element.scrollHeight,
};
debouncedSetSize(measurements);
};
// Create ResizeObserver instance
const resizeObserver = new ResizeObserver(() => {
updateSize();
});
// Start observing the element
resizeObserver.observe(ref.current);
// Initial size calculation
updateSize();
// Cleanup
return () => {
resizeObserver.disconnect();
};
}, [ref, debouncedSetSize]);
return size;
};

View file

@ -1,4 +1,4 @@
import { useContext, useEffect } from "react";
import { useContext, useEffect, useMemo } from "react";
import { useSelector } from "react-redux";
import styled from "styled-components";
import { AnimatedEllipsis } from "../..";
@ -40,12 +40,27 @@ function GeneratingIndicator() {
);
}
function ApplyingIndicator() {
return (
<div className="text-xs text-gray-400">
<span>Applying</span>
<AnimatedEllipsis />
</div>
);
}
export function LumpToolbar() {
const dispatch = useAppDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const ttsActive = useAppSelector((state) => state.ui.ttsActive);
const isStreaming = useAppSelector((state) => state.session.isStreaming);
const jetbrains = isJetBrains();
const applyStates = useAppSelector(
(store) => store.session.codeBlockApplyStates.states,
);
const isApplying = useMemo(() => {
return applyStates.find((state) => state.status === "streaming");
}, [applyStates]);
const toolCallState = useSelector(selectCurrentToolCall);
@ -89,6 +104,26 @@ export function LumpToolbar() {
);
}
if (isApplying) {
return (
<Container>
<ApplyingIndicator />
<StopButton
className="text-gray-400"
onClick={() => {
// Note that this will NOT stop generation but once apply is cancelled will show the Generating/cancel option
// Apply is prioritized because it can be more catastrophic
// Intentional to be more WYSIWYG for now
ideMessenger.post("cancelApply", undefined);
}}
>
{/* JetBrains overrides cmd+backspace, so we have to use another shortcut */}
{jetbrains ? getAltKeyLabel() : getMetaKeyLabel()} ⌫ Cancel
</StopButton>
</Container>
);
}
if (isStreaming) {
return (
<Container>

View file

@ -44,16 +44,17 @@ import {
setDialogMessage,
setShowDialog,
} from "../../redux/slices/uiSlice";
import { streamResponseThunk } from "../../redux/thunks";
import { cancelStream } from "../../redux/thunks/cancelStream";
import { streamEditThunk } from "../../redux/thunks/editMode";
import { loadLastSession } from "../../redux/thunks/session";
import { streamResponseThunk } from "../../redux/thunks";
import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util";
import {
FREE_TRIAL_LIMIT_REQUESTS,
incrementFreeTrialCount,
} from "../../util/freeTrial";
import AcceptRejectDiffButtons from "../../components/AcceptRejectDiffButtons";
import CodeToEditCard from "../../components/mainInput/CodeToEditCard";
import EditModeDetails from "../../components/mainInput/EditModeDetails";
import { getLocalStorage, setLocalStorage } from "../../util/localStorage";
@ -61,7 +62,6 @@ import { EmptyChatBody } from "./EmptyChatBody";
import { ExploreDialogWatcher } from "./ExploreDialogWatcher";
import { ToolCallDiv } from "./ToolCallDiv";
import { useAutoScroll } from "./useAutoScroll";
import AcceptRejectDiffButtons from "../../components/AcceptRejectDiffButtons";
const StepsDiv = styled.div`
position: relative;
@ -113,6 +113,7 @@ export function Chat() {
const [stepsOpen] = useState<(boolean | undefined)[]>([]);
const mainTextInputRef = useRef<HTMLInputElement>(null);
const stepsDivRef = useRef<HTMLDivElement>(null);
const tabsRef = useRef<HTMLDivElement>(null);
const history = useAppSelector((state) => state.session.history);
const showChatScrollbar = useAppSelector(
(state) => state.config.config.ui?.showChatScrollbar,
@ -143,6 +144,7 @@ export function Chat() {
!e.shiftKey
) {
dispatch(cancelStream());
ideMessenger.post("cancelApply", undefined); // just always cancel, if not in applying won't matter
}
};
window.addEventListener("keydown", listener);
@ -152,7 +154,11 @@ export function Chat() {
};
}, [isStreaming, jetbrains]);
const { widget, highlights } = useFindWidget(stepsDivRef);
const { widget, highlights } = useFindWidget(
stepsDivRef,
tabsRef,
isStreaming,
);
const currentToolCallApplyState = useAppSelector(
selectCurrentToolCallApplyState,
@ -286,13 +292,12 @@ export function Chat() {
return (
<>
{!!showSessionTabs && mode !== "edit" && <TabBar ref={tabsRef} />}
{widget}
{!!showSessionTabs && mode !== "edit" && <TabBar />}
<StepsDiv
ref={stepsDivRef}
className={`mt-3 overflow-y-scroll pt-[8px] ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${history.length > 0 ? "flex-1" : ""}`}
className={`overflow-y-scroll pt-[8px] ${showScrollbar ? "thin-scrollbar" : "no-scrollbar"} ${history.length > 0 ? "flex-1" : ""}`}
>
{highlights}
{history.map((item, index: number) => (

View file

@ -1,12 +1,15 @@
import {
ArrowTopRightOnSquareIcon,
Cog8ToothIcon,
ClipboardIcon,
Cog6ToothIcon,
KeyIcon,
} from "@heroicons/react/24/outline";
import { DISCORD_LINK, GITHUB_LINK } from "core/util/constants";
import { useContext, useMemo } from "react";
import { Button, SecondaryButton } from "../../components";
import { GhostButton, SecondaryButton } from "../../components";
import { DiscordIcon } from "../../components/svg/DiscordIcon";
import { GithubIcon } from "../../components/svg/GithubIcon";
import ToggleDiv from "../../components/ToggleDiv";
import { useAuth } from "../../context/Auth";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { selectSelectedProfile } from "../../redux/";
@ -48,11 +51,15 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => {
);
const handleRefreshProfiles = () => {
refreshProfiles();
void refreshProfiles();
dispatch(setShowDialog(false));
dispatch(setDialogMessage(undefined));
};
const copyErrorToClipboard = () => {
void navigator.clipboard.writeText(parsedError);
};
// Collect model information to display useful error info
let modelTitle = "Chat model";
let providerName = "the model provider";
@ -99,30 +106,29 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => {
}
const checkKeysButton = apiKeyUrl ? (
<Button
className="cursor-pointer hover:underline"
<GhostButton
className="flex items-center"
onClick={() => {
ideMessenger.post("openUrl", apiKeyUrl!);
}}
>
Check keys/usage
</Button>
<KeyIcon className="mr-1.5 h-3.5 w-3.5" />
<span>View key</span>
</GhostButton>
) : null;
const configButton = (
<SecondaryButton
className="flex flex-row items-center gap-1.5 hover:underline hover:opacity-70"
<GhostButton
className="flex items-center"
onClick={() => {
ideMessenger.post("config/openProfile", {
profileId: undefined,
});
}}
>
<div>
<Cog8ToothIcon className="h-4 w-4" />
</div>
<span>Open Assistant configuration</span>
</SecondaryButton>
<Cog6ToothIcon className="mr-1.5 h-3.5 w-3.5" />
<span>View config</span>
</GhostButton>
);
if (
@ -131,7 +137,20 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => {
return <ModelsAddOnLimitDialog />;
}
let errorContent: React.ReactNode = <></>;
let errorContent = (
<div className="mb-3 mt-1">
<div className="m-0 p-0">
<p className="m-0 mb-2 p-0">
There was an error handling the response from{" "}
{selectedModel?.title || "the model"}.
</p>
<p className="m-0 p-0">
Please try to submit your message again, and if the error persists,
let us know by reporting the issue using the buttons below.
</p>
</div>
</div>
);
// Display components for specific errors
if (statusCode === 429) {
@ -141,7 +160,7 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => {
{`This might mean your ${modelTitle} usage has been rate limited
by ${providerName}.`}
</span>
<div className="flex flex-row flex-wrap gap-2">
<div className="flex flex-row flex-wrap justify-start gap-3 py-4">
{checkKeysButton}
{configButton}
</div>
@ -230,51 +249,71 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => {
);
}
console.log({ message });
return (
<div className={`flex flex-col gap-1 px-3 pb-2 pt-3`}>
<p className="m-0 p-0 text-lg text-red-500">
{statusCode ? `Error (status code ${statusCode})` : "Error"}
</p>
<div className="flex flex-col gap-4 px-3 pb-3 pt-3">
{/* Concise error title */}
<h3 className="text-error m-0 p-0 text-lg font-medium">
Error handling model response
</h3>
{message ? (
<div className="mt-2 flex flex-col gap-0 rounded-sm">
<code className="max-h-20 overflow-y-auto p-2 font-mono">
{parsedError}
</code>
<div
className="flex cursor-pointer flex-row items-center justify-end px-1 py-1 text-gray-500 hover:underline"
onClick={() => {
ideMessenger.post("toggleDevTools", undefined);
}}
>
<span className="px-2">View Logs</span>
<ArrowTopRightOnSquareIcon className="h-4 w-4" />
</div>
{errorContent}
{/* Expandable technical details using ToggleDiv */}
{message && (
<div className="mb-2">
<ToggleDiv title="View error output" testId="error-output-toggle">
<div className="flex flex-col gap-0 rounded-sm">
<code className="text-editor-foreground block max-h-48 overflow-y-auto p-3 font-mono text-xs">
{parsedError}
</code>
<div className="flex flex-row items-center justify-end gap-2 p-2">
<GhostButton
onClick={copyErrorToClipboard}
className="flex items-center"
>
<ClipboardIcon className="mr-1.5 h-3.5 w-3.5" />
<span>Copy output</span>
</GhostButton>
<GhostButton
onClick={() => {
ideMessenger.post("toggleDevTools", undefined);
}}
className="flex items-center"
>
<ArrowTopRightOnSquareIcon className="mr-1.5 h-4 w-4" />
<span className="text-xs">View Logs</span>
</GhostButton>
</div>
</div>
</ToggleDiv>
</div>
) : null}
<div className="mt-3">{errorContent}</div>
)}
<div className="mt-2 flex flex-col gap-1.5">
<span>Report this error:</span>
<div className="flex flex-row flex-wrap items-center gap-2">
<SecondaryButton
className="flex flex-row items-center gap-2 hover:opacity-70"
<div>
<span className="text-base font-medium">Report this error</span>
<div className="mt-2 flex flex-row flex-wrap items-center gap-2">
<GhostButton
className="flex flex-row items-center gap-2 rounded px-3 py-1.5"
onClick={() => {
ideMessenger.post("openUrl", GITHUB_LINK);
}}
>
<GithubIcon className="h-5 w-5" />
<span className="xs:flex hidden">Github</span>
</SecondaryButton>
<SecondaryButton
className="flex flex-row items-center gap-2 hover:opacity-70"
</GhostButton>
<GhostButton
className="flex flex-row items-center gap-2 rounded px-3 py-1.5"
onClick={() => {
ideMessenger.post("openUrl", DISCORD_LINK);
}}
>
<DiscordIcon className="h-5 w-5" />
<span className="xs:flex hidden">Discord</span>
</SecondaryButton>
</GhostButton>
</div>
</div>
</div>

View file

@ -13,10 +13,7 @@ const AdvancedPage = () => {
className={`${isDarkMode ? "bg-gray-800 text-white" : "bg-white text-black"} min-h-screen p-4`}
>
<header className="mb-4 flex items-center justify-between border-b-2 pb-4">
I apologize, but there seems to be a misunderstanding. The user's
request doesn't appear to be related to rewriting the code section you
provided. The request mentions editing a readme.md file, which is not
part of the React component code you've shown.
{" "}
<button
className="rounded bg-blue-500 px-4 py-2 text-white"
onClick={toggleDarkMode}

View file

@ -1,12 +1,12 @@
{
"name": "@continuedev/config-yaml",
"version": "1.0.87",
"version": "1.0.88",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@continuedev/config-yaml",
"version": "1.0.87",
"version": "1.0.88",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",

View file

@ -1,6 +1,6 @@
{
"name": "@continuedev/config-yaml",
"version": "1.0.87",
"version": "1.0.88",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",

View file

@ -160,6 +160,7 @@ export const continuePropertiesSchema = z.object({
apiKeyLocation: z.string().optional(),
apiBase: z.string().optional(),
orgScopeId: z.string().nullable(),
env: z.record(z.string(), z.any()).optional(),
});
export type ContinueProperties = z.infer<typeof continuePropertiesSchema>;

View file

@ -9,13 +9,16 @@ export const contextSchema = z.object({
params: z.any().optional(),
});
// TODO: This should be a discriminated union by type
const mcpServerSchema = z.object({
name: z.string(),
command: z.string(),
command: z.string().optional(),
type: z.enum(["sse", "stdio"]).optional(),
url: z.string().optional(),
faviconUrl: z.string().optional(),
args: z.array(z.string()).optional(),
env: z.record(z.string()).optional(),
connectionTimeout: z.number().gt(0).optional()
connectionTimeout: z.number().gt(0).optional(),
});
export type MCPServer = z.infer<typeof mcpServerSchema>;
@ -39,6 +42,7 @@ export type DocsConfig = z.infer<typeof docSchema>;
const ruleObjectSchema = z.object({
name: z.string(),
rule: z.string(),
description: z.string().optional(),
globs: z.union([z.string(), z.array(z.string())]).optional(),
});
const ruleSchema = z.union([z.string(), ruleObjectSchema]);

View file

@ -117,6 +117,7 @@ const baseModelFields = {
model: z.string(),
apiKey: z.string().optional(),
apiBase: z.string().optional(),
maxStopWords: z.number().optional(),
roles: modelRolesSchema.array().optional(),
capabilities: modelCapabilitySchema.array().optional(),
defaultCompletionOptions: completionOptionsSchema.optional(),

1
packages/fetch/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
coverage/

14
packages/fetch/jest.globals.d.ts vendored Normal file
View file

@ -0,0 +1,14 @@
// This file declares the Jest globals for TypeScript
import '@jest/globals';
declare global {
const describe: typeof import('@jest/globals').describe;
const expect: typeof import('@jest/globals').expect;
const it: typeof import('@jest/globals').it;
const test: typeof import('@jest/globals').test;
const beforeAll: typeof import('@jest/globals').beforeAll;
const afterAll: typeof import('@jest/globals').afterAll;
const beforeEach: typeof import('@jest/globals').beforeEach;
const afterEach: typeof import('@jest/globals').afterEach;
const jest: typeof import('@jest/globals').jest;
}

View file

@ -1,12 +1,12 @@
{
"name": "@continuedev/fetch",
"version": "1.0.6",
"version": "1.0.9",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@continuedev/fetch",
"version": "1.0.6",
"version": "1.0.9",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.5",

View file

@ -1,6 +1,6 @@
{
"name": "@continuedev/fetch",
"version": "1.0.9",
"version": "1.0.10",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",

View file

@ -1,6 +1,66 @@
// 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";
import { Readable } from "stream";
import { parseDataLine, streamSse } from "./stream.js";
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/);
});
});
describe("parseDataLine", () => {
test("parseDataLine should parse valid JSON data with 'data: ' prefix", () => {

View file

@ -2,7 +2,7 @@ export async function* toAsyncIterable(
nodeReadable: NodeJS.ReadableStream,
): AsyncGenerator<Uint8Array> {
for await (const chunk of nodeReadable) {
// @ts-expect-error
// @ts-ignore
yield chunk as Uint8Array;
}
}
@ -13,6 +13,7 @@ export async function* streamResponse(
if (response.status === 499) {
return; // In case of client-side cancellation, just return
}
if (response.status !== 200) {
throw new Error(await response.text());
}

View file

@ -19,5 +19,5 @@
"declaration": true
// "sourceMap": true
},
"include": ["src/**/*"]
"include": ["src/**/*", "jest.globals.d.ts"]
}

View file

@ -64,7 +64,7 @@ They are concerned with:
- [x] Vllm
- [ ] Vertex AI
- [x] Voyage AI
- [ ] WatsonX
- [x] WatsonX
- [x] xAI
- [x] Fireworks
- [x] Moonshot

View file

@ -1,18 +1,18 @@
{
"name": "@continuedev/openai-adapters",
"version": "1.0.21",
"version": "1.0.22",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@continuedev/openai-adapters",
"version": "1.0.21",
"version": "1.0.22",
"license": "Apache-2.0",
"dependencies": {
"@azure/openai": "^1.0.0-beta.12",
"@continuedev/config-types": "^1.0.5",
"@continuedev/config-yaml": "^1.0.51",
"@continuedev/fetch": "^1.0.3",
"@continuedev/fetch": "^1.0.10",
"dotenv": "^16.5.0",
"json-schema": "^0.4.0",
"node-fetch": "^3.3.2",
@ -716,9 +716,9 @@
}
},
"node_modules/@continuedev/fetch": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.3.tgz",
"integrity": "sha512-cGNCUEVnDfC+3O/n1PV+oYhS5yZRLR1Q7Njg929kVbA8kRHe5a3VdKINfFzWdKprOU4wipsXSliciZHCpbJJ9g==",
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/@continuedev/fetch/-/fetch-1.0.10.tgz",
"integrity": "sha512-RBUXtm/VDz+9Itgw+CxrHXwVXoHCAedGzPOgA7gS5HZ9lObaeCJgEfzmfbln1ocFsfqSFmn5X5wSE7DHgfxpVA==",
"dependencies": {
"@continuedev/config-types": "^1.0.5",
"follow-redirects": "^1.15.6",

View file

@ -1,6 +1,6 @@
{
"name": "@continuedev/openai-adapters",
"version": "1.0.21",
"version": "1.0.26",
"description": "",
"main": "dist/index.js",
"types": "dist/index.d.ts",
@ -15,7 +15,7 @@
"@azure/openai": "^1.0.0-beta.12",
"@continuedev/config-types": "^1.0.5",
"@continuedev/config-yaml": "^1.0.51",
"@continuedev/fetch": "^1.0.3",
"@continuedev/fetch": "^1.0.10",
"dotenv": "^16.5.0",
"json-schema": "^0.4.0",
"node-fetch": "^3.3.2",

View file

@ -12,6 +12,7 @@ import {
import { ChatCompletionCreateParams } from "openai/src/resources/index.js";
import { AnthropicConfig } from "../types.js";
import { chatChunk, chatChunkFromDelta, customFetch } from "../util.js";
import { EMPTY_CHAT_COMPLETION } from "../util/emptyChatCompletion.js";
import {
BaseLlmApi,
CreateRerankResponse,
@ -157,6 +158,10 @@ export class AnthropicApi implements BaseLlmApi {
},
);
if (response.status === 499) {
return EMPTY_CHAT_COMPLETION;
}
const completion = (await response.json()) as any;
return {
id: completion.id,

View file

@ -15,6 +15,7 @@ import {
} from "openai/resources/index";
import { CohereConfig } from "../types.js";
import { chatCompletion, customFetch, embedding } from "../util.js";
import { EMPTY_CHAT_COMPLETION } from "../util/emptyChatCompletion.js";
import {
BaseLlmApi,
CreateRerankResponse,
@ -77,6 +78,10 @@ export class CohereApi implements BaseLlmApi {
},
);
if (resp.status === 499) {
return EMPTY_CHAT_COMPLETION;
}
const data = (await resp.json()) as any;
const { input_tokens, output_tokens } = data.meta.tokens;
return chatCompletion({

View file

@ -105,6 +105,10 @@ export class RelaceApi implements BaseLlmApi {
signal,
});
if (response.status === 499) {
return; // Aborted by user
}
const result = (await response.json()) as any;
const mergedCode = result.mergedCode;

View file

@ -0,0 +1,314 @@
import { streamSse } from "@continuedev/fetch";
import { OpenAI } from "openai/index";
import {
ChatCompletion,
ChatCompletionChunk,
ChatCompletionCreateParamsNonStreaming,
ChatCompletionCreateParamsStreaming,
Completion,
CompletionCreateParamsNonStreaming,
CompletionCreateParamsStreaming,
} from "openai/resources/index";
import { ChatCompletionCreateParams } from "openai/src/resources/index.js";
import { WatsonXConfig } from "../types.js";
import { chatCompletion, customFetch } from "../util.js";
import {
BaseLlmApi,
CreateRerankResponse,
FimCreateParamsStreaming,
RerankCreateParams,
} from "./base.js";
export class WatsonXApi implements BaseLlmApi {
apiBase: string;
apiVersion: string = "2023-05-29";
projectId?: string;
deploymentId?: string;
constructor(protected config: WatsonXConfig) {
this.apiBase = config.apiBase ?? "https://us-south.ml.cloud.ibm.com";
if (!this.apiBase.endsWith("/")) {
this.apiBase += "/";
}
this.apiVersion = config.env.apiVersion ?? this.apiVersion;
this.projectId = config.env.projectId;
this.deploymentId = config.env.deploymentId;
}
private async getHeaders(): Promise<Record<string, string>> {
const bearer = await this.getBearerToken();
return {
"Content-Type": "application/json",
Authorization: `Bearer ${bearer.token}`,
};
}
async getBearerToken(): Promise<{ token: string; expiration: number }> {
if (this.apiBase?.includes("cloud.ibm.com")) {
// watsonx SaaS
const wxToken = (await (
await customFetch(this.config.requestOptions)(
`https://iam.cloud.ibm.com/identity/token?apikey=${this.config.apiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`,
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json",
},
},
)
).json()) as any;
return {
token: wxToken["access_token"],
expiration: wxToken["expiration"],
};
} else {
// watsonx Software
if (!this.config.apiKey?.includes(":")) {
// Using ZenApiKey auth
return {
token: this.config.apiKey ?? "",
expiration: -1,
};
} else {
// Using username/password auth
const userPass = this.config.apiKey?.split(":");
const wxToken = (await (
await customFetch(this.config.requestOptions)(
`${this.apiBase}/icp4d-api/v1/authorize`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({
username: userPass[0],
password: userPass[1],
}),
},
)
).json()) as any;
const wxTokenExpiry = (await (
await customFetch(this.config.requestOptions)(
`${this.apiBase}/usermgmt/v1/user/tokenExpiry`,
{
method: "GET",
headers: {
Accept: "application/json",
Authorization: `Bearer ${wxToken["token"]}`,
},
},
)
).json()) as any;
return {
token: wxToken["token"],
expiration: wxTokenExpiry["exp"],
};
}
}
}
private getEndpoint(endpoint: string): string {
return `${this.apiBase}ml/v1/${this.deploymentId ? `deployments/${this.deploymentId}/` : ""}text/${endpoint}_stream?version=${this.apiVersion}`;
}
private _convertBody(oaiBody: ChatCompletionCreateParams) {
const stopSequences = oaiBody.stop
? Array.isArray(oaiBody.stop)
? oaiBody.stop.filter((s) => s.trim() !== "")
: [oaiBody.stop]
: undefined;
const payload: any = {
messages: oaiBody.messages,
max_tokens: oaiBody.max_tokens ?? 1024,
stop: stopSequences,
frequency_penalty: oaiBody.frequency_penalty,
presence_penalty: oaiBody.presence_penalty,
};
if (!this.deploymentId) {
payload.model_id = oaiBody.model;
payload.project_id = this.projectId;
}
if (oaiBody.temperature !== undefined) {
payload.temperature = oaiBody.temperature;
}
if (oaiBody.top_p !== undefined) {
payload.top_p = oaiBody.top_p;
}
if (oaiBody.tools) {
payload.tools = oaiBody.tools;
if (oaiBody.tool_choice) {
payload.tool_choice = oaiBody.tool_choice;
} else {
payload.tool_choice_option = "auto";
}
}
return payload;
}
async chatCompletionNonStream(
body: ChatCompletionCreateParamsNonStreaming,
signal: AbortSignal,
): Promise<ChatCompletion> {
const generator = this.chatCompletionStream(
{
...body,
stream: true,
},
signal,
);
let content = "";
for await (const chunk of generator) {
content += chunk.choices[0].delta.content ?? "";
}
return chatCompletion({
content,
model: body.model,
});
}
async *chatCompletionStream(
body: ChatCompletionCreateParamsStreaming,
signal: AbortSignal,
): AsyncGenerator<ChatCompletionChunk, any, unknown> {
const url = this.getEndpoint("chat");
const headers = await this.getHeaders();
const stringifiedBody = JSON.stringify(this._convertBody(body));
const response = await customFetch(this.config.requestOptions)(url, {
method: "POST",
headers,
body: stringifiedBody,
signal,
});
if (!response.ok || !response.body) {
throw new Error(
`Failed to stream chat completion: ${await response.text()}`,
);
}
for await (const value of streamSse(response as any)) {
if (!value.choices?.[0]) {
continue;
}
yield value;
}
}
async completionNonStream(
body: CompletionCreateParamsNonStreaming,
signal: AbortSignal,
): Promise<Completion> {
throw new Error("Method not implemented.");
}
async *completionStream(
body: CompletionCreateParamsStreaming,
signal: AbortSignal,
): AsyncGenerator<Completion, any, unknown> {
const params = {
decoding_method: body.temperature ? "sample" : "greedy",
max_new_tokens: body.max_tokens ?? 1024,
min_new_tokens: 1,
stop_sequences: body.stop
? Array.isArray(body.stop)
? body.stop
: [body.stop]
: [],
include_stop_sequence: false,
repetition_penalty: body.frequency_penalty || 1,
temperature: body.temperature,
top_p: body.top_p,
top_k: 100,
};
const payload: any = {
input: body.prompt,
parameters: params,
};
if (!this.deploymentId) {
payload.model_id = body.model;
payload.project_id = this.projectId;
}
const url = this.getEndpoint("generation");
const response = await customFetch(this.config.requestOptions)(url, {
method: "POST",
headers: await this.getHeaders(),
body: JSON.stringify(payload),
signal,
});
if (!response.ok || !response.body) {
throw new Error(`Failed to stream completion: ${await response.text()}`);
}
let generatedText = "";
for await (const value of streamSse(response as any)) {
const lines = value.toString().split("\n");
let generatedChunk = "";
lines.forEach((line: string) => {
if (line.startsWith("data:")) {
const dataStr = line.replace(/^data:\s+/, "");
try {
const data = JSON.parse(dataStr);
data.results.forEach((result: any) => {
generatedChunk += result.generated_text || "";
});
} catch (e) {
// parsing error is expected with streaming response
}
}
});
if (generatedChunk) {
generatedText += generatedChunk;
yield {
id: `watsonx-${Date.now()}`,
object: "text_completion",
created: Date.now(),
model: body.model,
choices: [
{
text: generatedChunk,
index: 0,
logprobs: null,
finish_reason: "stop",
},
],
};
}
}
}
async *fimStream(
body: FimCreateParamsStreaming,
signal: AbortSignal,
): AsyncGenerator<ChatCompletionChunk, any, unknown> {
throw new Error("Method not implemented.");
}
async embed(
body: OpenAI.Embeddings.EmbeddingCreateParams,
): Promise<OpenAI.Embeddings.CreateEmbeddingResponse> {
throw new Error("Method not implemented.");
}
async rerank(body: RerankCreateParams): Promise<CreateRerankResponse> {
throw new Error("Method not implemented.");
}
async list(): Promise<OpenAI.Models.Model[]> {
throw new Error("Method not implemented.");
}
}

View file

@ -11,6 +11,7 @@ import { MockApi } from "./apis/Mock.js";
import { MoonshotApi } from "./apis/Moonshot.js";
import { OpenAIApi } from "./apis/OpenAI.js";
import { RelaceApi } from "./apis/Relace.js";
import { WatsonXApi } from "./apis/WatsonX.js";
import { BaseLlmApi } from "./apis/base.js";
import { LLMConfig, OpenAIConfigSchema } from "./types.js";
@ -48,6 +49,8 @@ export function constructLlmApi(config: LLMConfig): BaseLlmApi | undefined {
return new RelaceApi(config);
case "inception":
return new InceptionApi(config);
case "watsonx":
return new WatsonXApi(config);
case "x-ai":
return openAICompatible("https://api.x.ai/v1/", config);
case "voyage":
@ -75,7 +78,10 @@ export function constructLlmApi(config: LLMConfig): BaseLlmApi | undefined {
case "nvidia":
return openAICompatible("https://integrate.api.nvidia.com/v1/", config);
case "ovhcloud":
return openAICompatible("https://oai.endpoints.kepler.ai.cloud.ovh.net/v1/", config);
return openAICompatible(
"https://oai.endpoints.kepler.ai.cloud.ovh.net/v1/",
config,
);
case "scaleway":
return openAICompatible("https://api.scaleway.ai/v1/", config);
case "fireworks":
@ -111,10 +117,9 @@ export {
type Completion,
type CompletionCreateParams,
type CompletionCreateParamsNonStreaming,
type CompletionCreateParamsStreaming
type CompletionCreateParamsStreaming,
} from "openai/resources/index";
// export
export type { BaseLlmApi } from "./apis/base.js";
export type { LLMConfig } from "./types.js";

View file

@ -10,6 +10,7 @@ function testConfig(config: ModelConfig) {
provider: config.provider as any,
apiKey: config.apiKey,
apiBase: config.apiBase,
env: config.env,
});
if (false) {

View file

@ -99,6 +99,17 @@ export const AnthropicConfigSchema = OpenAIConfigSchema.extend({
});
export type AnthropicConfig = z.infer<typeof AnthropicConfigSchema>;
export const WatsonXConfigSchema = BasePlusConfig.extend({
provider: z.literal("watsonx"),
apiKey: z.string(),
env: z.object({
apiVersion: z.string().optional(),
projectId: z.string().optional(),
deploymentId: z.string().optional(),
}),
});
export type WatsonXConfig = z.infer<typeof WatsonXConfigSchema>;
export const JinaConfigSchema = OpenAIConfigSchema.extend({
provider: z.literal("jina"),
});
@ -118,6 +129,7 @@ export const LLMConfigSchema = z.discriminatedUnion("provider", [
AzureConfigSchema,
GeminiConfigSchema,
AnthropicConfigSchema,
WatsonXConfigSchema,
JinaConfigSchema,
MockConfigSchema,
InceptionConfigSchema,

View file

@ -0,0 +1,21 @@
import { ChatCompletion } from "openai/resources/index";
export const EMPTY_CHAT_COMPLETION: ChatCompletion = {
choices: [
{
finish_reason: "stop",
index: 0,
logprobs: null,
message: {
content: null,
role: "assistant",
refusal: null,
},
},
],
usage: undefined,
created: Date.now(),
id: "",
model: "UNSPECIFIED",
object: "chat.completion",
};