Merge branch 'main' into tomasz/rule-colocation

This commit is contained in:
Tomasz Stefaniak 2025-06-11 15:20:08 -07:00
commit 35ee97438f
34 changed files with 895 additions and 219 deletions

View file

@ -0,0 +1,157 @@
import {
createMarkdownWithFrontmatter,
createRuleFilePath,
createRuleMarkdown,
sanitizeRuleName,
} from "./createMarkdownRule";
import { parseMarkdownRule } from "./parseMarkdownRule";
describe("sanitizeRuleName", () => {
it("should sanitize rule names for filenames", () => {
expect(sanitizeRuleName("My Test Rule")).toBe("my-test-rule");
expect(sanitizeRuleName("Rule with @#$% chars")).toBe("rule-with-chars");
expect(sanitizeRuleName("Multiple spaces")).toBe("multiple-spaces");
expect(sanitizeRuleName("UPPERCASE-rule")).toBe("uppercase-rule");
expect(sanitizeRuleName("already-sanitized")).toBe("already-sanitized");
});
it("should handle empty and edge case inputs", () => {
expect(sanitizeRuleName("")).toBe("");
expect(sanitizeRuleName(" ")).toBe("");
expect(sanitizeRuleName("123")).toBe("123");
expect(sanitizeRuleName("rule-with-numbers-123")).toBe(
"rule-with-numbers-123",
);
});
});
describe("createRuleFilePath", () => {
it("should create correct rule file path", () => {
const result = createRuleFilePath("/workspace", "My Test Rule");
expect(result).toBe("/workspace/.continue/rules/my-test-rule.md");
});
it("should handle special characters in rule name", () => {
const result = createRuleFilePath("/home/user", "Rule with @#$% chars");
expect(result).toBe("/home/user/.continue/rules/rule-with-chars.md");
});
it("should handle edge case rule names", () => {
const result = createRuleFilePath("/test", " Multiple Spaces ");
expect(result).toBe("/test/.continue/rules/multiple-spaces.md");
});
});
describe("createMarkdownWithFrontmatter", () => {
it("should create properly formatted markdown with frontmatter", () => {
const frontmatter = {
name: "Test Rule",
description: "A test rule",
globs: "*.ts",
};
const markdown = "# Test Rule\n\nThis is a test rule.";
const result = createMarkdownWithFrontmatter(frontmatter, markdown);
// The exact quote style doesn't matter as long as it parses correctly
expect(result).toContain("name: Test Rule");
expect(result).toContain("description: A test rule");
expect(result).toContain("globs:");
expect(result).toContain("*.ts");
expect(result).toContain("---\n\n# Test Rule\n\nThis is a test rule.");
});
it("should handle empty frontmatter", () => {
const frontmatter = {};
const markdown = "# Simple Rule\n\nJust markdown content.";
const result = createMarkdownWithFrontmatter(frontmatter, markdown);
const expected = `---
{}
---
# Simple Rule
Just markdown content.`;
expect(result).toBe(expected);
});
it("should create content that can be parsed back correctly", () => {
const originalFrontmatter = {
name: "Roundtrip Test",
description: "Testing roundtrip parsing",
globs: ["*.js", "*.ts"],
alwaysApply: true,
};
const originalMarkdown =
"# Roundtrip Test\n\nThis should parse back correctly.";
const created = createMarkdownWithFrontmatter(
originalFrontmatter,
originalMarkdown,
);
const parsed = parseMarkdownRule(created);
expect(parsed.frontmatter).toEqual(originalFrontmatter);
expect(parsed.markdown).toBe(originalMarkdown);
});
});
describe("createRuleMarkdown", () => {
it("should create rule markdown with all options", () => {
const result = createRuleMarkdown("Test Rule", "This is the rule content", {
description: "Test description",
globs: ["*.ts", "*.js"],
alwaysApply: true,
});
const parsed = parseMarkdownRule(result);
expect(parsed.frontmatter.description).toBe("Test description");
expect(parsed.frontmatter.globs).toEqual(["*.ts", "*.js"]);
expect(parsed.frontmatter.alwaysApply).toBe(true);
expect(parsed.markdown).toBe("# Test Rule\n\nThis is the rule content");
});
it("should create rule markdown with minimal options", () => {
const result = createRuleMarkdown("Simple Rule", "Simple content");
const parsed = parseMarkdownRule(result);
expect(parsed.frontmatter.description).toBeUndefined();
expect(parsed.frontmatter.globs).toBeUndefined();
expect(parsed.frontmatter.alwaysApply).toBeUndefined();
expect(parsed.markdown).toBe("# Simple Rule\n\nSimple content");
});
it("should handle string globs", () => {
const result = createRuleMarkdown("String Glob Rule", "Content", {
globs: "*.py",
});
const parsed = parseMarkdownRule(result);
expect(parsed.frontmatter.globs).toBe("*.py");
});
it("should trim description and globs", () => {
const result = createRuleMarkdown("Trim Test", "Content", {
description: " spaced description ",
globs: " *.ts ",
});
const parsed = parseMarkdownRule(result);
expect(parsed.frontmatter.description).toBe("spaced description");
expect(parsed.frontmatter.globs).toBe("*.ts");
});
it("should handle alwaysApply false explicitly", () => {
const result = createRuleMarkdown("Always Apply False", "Content", {
alwaysApply: false,
});
const parsed = parseMarkdownRule(result);
expect(parsed.frontmatter.alwaysApply).toBe(false);
});
});

View file

@ -0,0 +1,75 @@
import * as YAML from "yaml";
import { joinPathsToUri } from "../../util/uri";
import { RuleFrontmatter } from "./parseMarkdownRule";
export const RULE_FILE_EXTENSION = "md";
/**
* Sanitizes a rule name for use in filenames (removes special chars, replaces spaces with dashes)
*/
export function sanitizeRuleName(name: string): string {
return name
.toLowerCase()
.replace(/[^a-z0-9\s-]/g, "")
.replace(/\s+/g, "-")
.replace(/^-+|-+$/g, ""); // Remove leading/trailing dashes
}
/**
* Creates the file path for a rule in the workspace .continue/rules directory
*/
export function createRuleFilePath(
workspaceDir: string,
ruleName: string,
): string {
const safeRuleName = sanitizeRuleName(ruleName);
return joinPathsToUri(
workspaceDir,
".continue",
"rules",
`${safeRuleName}.${RULE_FILE_EXTENSION}`,
);
}
/**
* Creates markdown content with YAML frontmatter in the format expected by parseMarkdownRule
*/
export function createMarkdownWithFrontmatter(
frontmatter: RuleFrontmatter,
markdown: string,
): string {
const frontmatterStr = YAML.stringify(frontmatter).trim();
return `---\n${frontmatterStr}\n---\n\n${markdown}`;
}
/**
* Creates a rule markdown file content from rule components
*/
export function createRuleMarkdown(
name: string,
ruleContent: string,
options: {
description?: string;
globs?: string | string[];
alwaysApply?: boolean;
} = {},
): string {
const frontmatter: RuleFrontmatter = {};
if (options.globs) {
frontmatter.globs =
typeof options.globs === "string" ? options.globs.trim() : options.globs;
}
if (options.description) {
frontmatter.description = options.description.trim();
}
if (options.alwaysApply !== undefined) {
frontmatter.alwaysApply = options.alwaysApply;
}
const markdownBody = `# ${name}\n\n${ruleContent}`;
return createMarkdownWithFrontmatter(frontmatter, markdownBody);
}

View file

@ -0,0 +1,3 @@
export * from "./createMarkdownRule";
export * from "./loadMarkdownRules";
export * from "./parseMarkdownRule";

View file

@ -14,12 +14,14 @@ import {
IDE,
IdeSettings,
ILLMLogger,
RuleWithSource,
SerializedContinueConfig,
Tool,
} from "../../";
import { constructMcpSlashCommand } from "../../commands/slash/mcp";
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
import MCPContextProvider from "../../context/providers/MCPContextProvider";
import RulesContextProvider from "../../context/providers/RulesContextProvider";
import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { getControlPlaneEnv } from "../../control-plane/env.js";
@ -40,6 +42,24 @@ import { migrateJsonSharedConfig } from "../migrateSharedConfig";
import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
import { loadContinueConfigFromYaml } from "../yaml/loadYaml";
async function loadRules(ide: IDE) {
const rules: RuleWithSource[] = [];
const errors = [];
// Add rules from .continuerules files
const { rules: yamlRules, errors: continueRulesErrors } =
await getWorkspaceContinueRuleDotFiles(ide);
rules.unshift(...yamlRules);
errors.push(...continueRulesErrors);
// Add rules from markdown files in .continue/rules
const { rules: markdownRules, errors: markdownRulesErrors } =
await loadMarkdownRules(ide);
rules.unshift(...markdownRules);
errors.push(...markdownRulesErrors);
return { rules, errors };
}
export default async function doLoadConfig(options: {
ide: IDE;
ideSettingsPromise: Promise<IdeSettings>;
@ -126,17 +146,11 @@ export default async function doLoadConfig(options: {
// Remove ability have undefined errors, just have an array
errors = [...(errors ?? [])];
// Add rules from .continuerules files
const { rules, errors: continueRulesErrors } =
await getWorkspaceContinueRuleDotFiles(ide);
// Load rules and always include the RulesContextProvider
const { rules, errors: rulesErrors } = await loadRules(ide);
errors.push(...rulesErrors);
newConfig.rules.unshift(...rules);
errors.push(...continueRulesErrors);
// Add rules from markdown files in .continue/rules
const { rules: markdownRules, errors: markdownRulesErrors } =
await loadMarkdownRules(ide);
newConfig.rules.unshift(...markdownRules);
errors.push(...markdownRulesErrors);
newConfig.contextProviders.push(new RulesContextProvider({}));
// Add rules from colocated rules.md files in the codebase
const { rules: codebaseRules, errors: codebaseRulesErrors } =

View file

@ -0,0 +1,170 @@
import { BlockType } from "@continuedev/config-yaml";
import { describe, expect, test } from "@jest/globals";
import { RULE_FILE_EXTENSION } from "../markdown";
import { findAvailableFilename, getFileContent } from "./workspaceBlocks";
describe("getFileContent", () => {
test("returns markdown content for rules block type", () => {
const result = getFileContent("rules");
expect(result).toContain("# New Rule");
expect(result).toContain("Your rule content");
expect(result).toContain("A description of your rule");
});
test("returns YAML content for non-rules block types", () => {
const result = getFileContent("models");
expect(result).toContain("name: New model");
expect(result).toContain("version: 0.0.1");
expect(result).toContain("schema: v1");
expect(result).toContain("models:");
expect(result).toContain("provider: anthropic");
});
test("generates correct YAML for different block types", () => {
const contextResult = getFileContent("context");
expect(contextResult).toContain("name: New context");
expect(contextResult).toContain("context:");
expect(contextResult).toContain("provider: file");
const docsResult = getFileContent("docs");
expect(docsResult).toContain("name: New doc");
expect(docsResult).toContain("docs:");
expect(docsResult).toContain("startUrl: https://docs.continue.dev");
const promptsResult = getFileContent("prompts");
expect(promptsResult).toContain("name: New prompt");
expect(promptsResult).toContain("prompts:");
expect(promptsResult).toContain("thorough suite of unit tests");
const mcpResult = getFileContent("mcpServers");
expect(mcpResult).toContain("name: New MCP server");
expect(mcpResult).toContain("mcpServers:");
expect(mcpResult).toContain("command: npx");
});
});
describe("findAvailableFilename", () => {
test("returns base filename when it doesn't exist", async () => {
const mockFileExists = async (uri: string) => false;
const result = await findAvailableFilename(
"/workspace/.continue/models",
"models",
mockFileExists,
);
expect(result).toBe("/workspace/.continue/models/new-model.yaml");
});
test("returns filename with counter when base exists", async () => {
const mockFileExists = async (uri: string) => {
return uri === "/workspace/.continue/models/new-model.yaml";
};
const result = await findAvailableFilename(
"/workspace/.continue/models",
"models",
mockFileExists,
);
expect(result).toBe("/workspace/.continue/models/new-model-1.yaml");
});
test("increments counter until available filename is found", async () => {
const existingFiles = new Set([
"/workspace/.continue/context/new-context.yaml",
"/workspace/.continue/context/new-context-1.yaml",
"/workspace/.continue/context/new-context-2.yaml",
]);
const mockFileExists = async (uri: string) => {
return existingFiles.has(uri);
};
const result = await findAvailableFilename(
"/workspace/.continue/context",
"context",
mockFileExists,
);
expect(result).toBe("/workspace/.continue/context/new-context-3.yaml");
});
test("handles different block types correctly with proper extensions", async () => {
const mockFileExists = async (uri: string) => false;
const testCases: Array<{ blockType: BlockType; expected: string }> = [
{ blockType: "models", expected: "/test/new-model.yaml" },
{ blockType: "context", expected: "/test/new-context.yaml" },
{ blockType: "rules", expected: `/test/new-rule.${RULE_FILE_EXTENSION}` },
{ blockType: "docs", expected: "/test/new-doc.yaml" },
{ blockType: "prompts", expected: "/test/new-prompt.yaml" },
{ blockType: "mcpServers", expected: "/test/new-mcp-server.yaml" },
];
for (const { blockType, expected } of testCases) {
const result = await findAvailableFilename(
"/test",
blockType,
mockFileExists,
);
expect(result).toBe(expected);
}
});
test("respects custom extension parameter", async () => {
const mockFileExists = async (uri: string) => false;
const result = await findAvailableFilename(
"/test",
"models",
mockFileExists,
"json",
);
expect(result).toBe("/test/new-model.json");
});
test("handles rules markdown files with counter", async () => {
const existingFiles = new Set([
`/workspace/.continue/rules/new-rule.${RULE_FILE_EXTENSION}`,
`/workspace/.continue/rules/new-rule-1.${RULE_FILE_EXTENSION}`,
]);
const mockFileExists = async (uri: string) => {
return existingFiles.has(uri);
};
const result = await findAvailableFilename(
"/workspace/.continue/rules",
"rules",
mockFileExists,
);
expect(result).toBe(
`/workspace/.continue/rules/new-rule-2.${RULE_FILE_EXTENSION}`,
);
});
test("handles large counter values", async () => {
const existingFiles = new Set(
Array.from({ length: 100 }, (_, i) =>
i === 0
? "/workspace/.continue/prompts/new-prompt.yaml"
: `/workspace/.continue/prompts/new-prompt-${i}.yaml`,
),
);
const mockFileExists = async (uri: string) => {
return existingFiles.has(uri);
};
const result = await findAvailableFilename(
"/workspace/.continue/prompts",
"prompts",
mockFileExists,
);
expect(result).toBe("/workspace/.continue/prompts/new-prompt-100.yaml");
});
});

View file

@ -2,10 +2,24 @@ import { BlockType, ConfigYaml } from "@continuedev/config-yaml";
import * as YAML from "yaml";
import { IDE } from "../..";
import { joinPathsToUri } from "../../util/uri";
import { RULE_FILE_EXTENSION, createRuleMarkdown } from "../markdown";
const BLOCK_TYPE_CONFIG: Record<
BlockType,
{ singular: string; filename: string }
> = {
context: { singular: "context", filename: "context" },
models: { singular: "model", filename: "model" },
rules: { singular: "rule", filename: "rule" },
docs: { singular: "doc", filename: "doc" },
prompts: { singular: "prompt", filename: "prompt" },
mcpServers: { singular: "MCP server", filename: "mcp-server" },
data: { singular: "data", filename: "data" },
};
function getContentsForNewBlock(blockType: BlockType): ConfigYaml {
const configYaml: ConfigYaml = {
name: `New ${blockType.slice(0, -1)}`,
name: `New ${BLOCK_TYPE_CONFIG[blockType]?.singular}`,
version: "0.0.1",
schema: "v1",
};
@ -64,6 +78,43 @@ function getContentsForNewBlock(blockType: BlockType): ConfigYaml {
return configYaml;
}
function getFileExtension(blockType: BlockType): string {
return blockType === "rules" ? RULE_FILE_EXTENSION : "yaml";
}
export function getFileContent(blockType: BlockType): string {
if (blockType === "rules") {
return createRuleMarkdown("New Rule", "Your rule content", {
description: "A description of your rule",
});
} else {
return YAML.stringify(getContentsForNewBlock(blockType));
}
}
export async function findAvailableFilename(
baseDirUri: string,
blockType: BlockType,
fileExists: (uri: string) => Promise<boolean>,
extension?: string,
): Promise<string> {
const baseFilename = `new-${BLOCK_TYPE_CONFIG[blockType]?.filename}`;
const fileExtension = extension ?? getFileExtension(blockType);
let counter = 0;
let fileUri: string;
do {
const suffix = counter === 0 ? "" : `-${counter}`;
fileUri = joinPathsToUri(
baseDirUri,
`${baseFilename}${suffix}.${fileExtension}`,
);
counter++;
} while (await fileExists(fileUri));
return fileUri;
}
export async function createNewWorkspaceBlockFile(
ide: IDE,
blockType: BlockType,
@ -77,21 +128,14 @@ export async function createNewWorkspaceBlockFile(
const baseDirUri = joinPathsToUri(workspaceDirs[0], `.continue/${blockType}`);
// Find the first available filename
let counter = 0;
let fileUri: string;
do {
const suffix = counter === 0 ? "" : `-${counter}`;
fileUri = joinPathsToUri(
baseDirUri,
`new-${blockType.slice(0, -1)}${suffix}.yaml`,
);
counter++;
} while (await ide.fileExists(fileUri));
await ide.writeFile(
fileUri,
YAML.stringify(getContentsForNewBlock(blockType)),
const fileUri = await findAvailableFilename(
baseDirUri,
blockType,
ide.fileExists.bind(ide),
);
const fileContent = getFileContent(blockType);
await ide.writeFile(fileUri, fileContent);
await ide.openFile(fileUri);
}

View file

@ -0,0 +1,91 @@
import { BaseContextProvider } from "..";
import {
ContextItem,
ContextItemUri,
ContextProviderDescription,
ContextProviderExtras,
ContextSubmenuItem,
LoadSubmenuItemsArgs,
RuleWithSource,
} from "../..";
import { getControlPlaneEnv } from "../../control-plane/env";
class RulesContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "rules",
displayTitle: "Rules",
description: "Mention rules files",
type: "submenu",
renderInlineAs: "",
};
// This is only used within this class. Worst case if there are exact duplicates is that one always calls the other, but this is an extreme edge case
// Can eventually pull in more metadata, but this is experimental
private getIdFromRule(rule: RuleWithSource): string {
return rule.ruleFile ?? rule.slug ?? rule.name ?? rule.rule;
}
private getNameFromRule(rule: RuleWithSource): string {
return rule.name ?? rule.slug ?? rule.ruleFile ?? rule.source;
}
private getDescriptionFromRule(rule: RuleWithSource): string {
return rule.description ?? rule.name ?? "";
}
private getUriFromRule(
rule: RuleWithSource,
appUrl: string,
): ContextItemUri | undefined {
if (rule.ruleFile) {
return {
type: "file",
value: rule.ruleFile,
};
}
if (rule.slug) {
let url = `${appUrl}${rule.slug}`;
return {
type: "url",
value: url,
};
}
return undefined;
}
async getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
const rule = extras.config.rules.find(
(rule) => this.getIdFromRule(rule) === query,
);
if (!rule) {
return [];
}
const env = await getControlPlaneEnv(extras.ide.getIdeSettings());
return [
{
name: this.getNameFromRule(rule),
content: rule.rule,
description: this.getDescriptionFromRule(rule),
uri: this.getUriFromRule(rule, env.APP_URL),
},
];
}
async loadSubmenuItems(
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
return args.config.rules.map((rule) => ({
id: this.getIdFromRule(rule),
description: this.getDescriptionFromRule(rule),
title: this.getNameFromRule(rule),
}));
}
}
export default RulesContextProvider;

View file

@ -25,6 +25,7 @@ import OSContextProvider from "./OSContextProvider";
import PostgresContextProvider from "./PostgresContextProvider";
import ProblemsContextProvider from "./ProblemsContextProvider";
import RepoMapContextProvider from "./RepoMapContextProvider";
import RulesContextProvider from "./RulesContextProvider";
import SearchContextProvider from "./SearchContextProvider";
import TerminalContextProvider from "./TerminalContextProvider";
import URLContextProvider from "./URLContextProvider";
@ -66,6 +67,7 @@ export const Providers: (typeof BaseContextProvider)[] = [
MCPContextProvider,
GitCommitContextProvider,
ClipboardContextProvider,
RulesContextProvider,
];
export function contextProviderClassFromName(

View file

@ -730,6 +730,7 @@ export class Core {
tool,
toolCallId: toolCall.id,
onPartialOutput,
codeBaseIndexer: this.codeBaseIndexer,
});
});

2
core/index.d.ts vendored
View file

@ -4,6 +4,7 @@ import {
PromptTemplates,
} from "@continuedev/config-yaml";
import Parser from "web-tree-sitter";
import { CodebaseIndexer } from "./indexing/CodebaseIndexer";
import { LLMConfigurationStatuses } from "./llm/constants";
declare global {
@ -972,6 +973,7 @@ export interface ToolExtras {
contextItems: ContextItem[];
}) => void;
config: ContinueConfig;
codeBaseIndexer?: CodebaseIndexer;
}
export interface Tool {

View file

@ -278,7 +278,7 @@ describe("CodebaseIndexer", () => {
expect.anything(),
);
expect(mockMessenger.send).toHaveBeenCalledWith("refreshSubmenuItems", {
providers: "dependsOnIndexing",
providers: "all",
});
});

View file

@ -1,7 +1,6 @@
import * as fs from "fs/promises";
import { ConfigHandler } from "../config/ConfigHandler.js";
import { IContinueServerClient } from "../continueServer/interface.js";
import { IDE, IndexingProgressUpdate, IndexTag } from "../index.js";
import type { FromCoreProtocol, ToCoreProtocol } from "../protocol";
import type { IMessenger } from "../protocol/messenger";
@ -549,10 +548,10 @@ export class CodebaseIndexer {
// New methods using messenger directly
private async updateProgress(update: IndexingProgressUpdate) {
private updateProgress(update: IndexingProgressUpdate) {
this.codebaseIndexingState = update;
if (this.messenger) {
await this.messenger.request("indexProgress", update);
void this.messenger.request("indexProgress", update);
}
}
@ -582,7 +581,7 @@ export class CodebaseIndexer {
paths,
this.indexingCancellationController.signal,
)) {
await this.updateProgress(update);
this.updateProgress(update);
if (update.status === "failed") {
await this.sendIndexingErrorTelemetry(update);
@ -596,7 +595,7 @@ export class CodebaseIndexer {
// Directly refresh submenu items
if (this.messenger) {
this.messenger.send("refreshSubmenuItems", {
providers: "dependsOnIndexing",
providers: "all",
});
}
this.indexingCancellationController = undefined;
@ -613,7 +612,7 @@ export class CodebaseIndexer {
this.indexingCancellationController = new AbortController();
try {
for await (const update of this.refreshFiles(files)) {
await this.updateProgress(update);
this.updateProgress(update);
if (update.status === "failed") {
await this.sendIndexingErrorTelemetry(update);
@ -626,7 +625,9 @@ export class CodebaseIndexer {
// Directly refresh submenu items
if (this.messenger) {
this.messenger.send("refreshSubmenuItems", { providers: "all" });
this.messenger.send("refreshSubmenuItems", {
providers: "all",
});
}
this.indexingCancellationController = undefined;
}
@ -634,7 +635,7 @@ export class CodebaseIndexer {
public async handleIndexingError(e: any) {
if (e instanceof LLMError && this.messenger) {
// Need to report this specific error to the IDE for special handling
await this.messenger.request("reportError", e);
void this.messenger.request("reportError", e);
}
// broadcast indexing error
@ -644,7 +645,7 @@ export class CodebaseIndexer {
desc: e.message,
};
await this.updateProgress(updateToSend);
this.updateProgress(updateToSend);
void this.sendIndexingErrorTelemetry(updateToSend);
}

View file

@ -13,10 +13,10 @@ class Scaleway extends OpenAI {
private static MODEL_IDS: { [name: string]: string } = {
"llama3.1-8b": "llama-3.1-8b-instruct",
"llama3.1-70b": "llama-3.1-70b-instruct",
"mistral-nemo": "mistral-nemo-instruct-2407",
"llama3.3-70b": "llama-3.3-70b-instruct",
"mistral-small3.1": "mistral-small-3.1-24b-instruct-2503",
"deepseek-r1-distill-llama-70b": "deepseek-r1-distill-llama-70b",
"qwen2.5-coder-32b": "qwen2.5-coder-32b-instruct",
pixtral: "pixtral-12b-2409",
};
protected _convertModelName(model: string) {

View file

@ -34,6 +34,10 @@ class ContinueProxy extends OpenAI {
constructor(options: LLMOptions) {
super(options);
this.configEnv = options.env;
// This it set to `undefined` to handle the case where we are proxying requests to Azure. We pass the correct env vars
// needed to do this in `extraBodyProperties` below, but if we don't set `apiType` to `undefined`, we end up proxying to
// `/openai/deployments/` which is invalid since that URL construction happens on the proxy.
this.apiType = undefined;
this.actualApiBase = options.apiBase;
this.apiKeyLocation = options.apiKeyLocation;
this.orgScopeId = options.orgScopeId;

View file

@ -37,11 +37,6 @@ export const createRuleBlock: Tool = {
description:
"Optional file patterns to which this rule applies (e.g. ['**/*.{ts,tsx}'] or ['src/**/*.ts', 'tests/**/*.ts'])",
},
alwaysApply: {
type: "boolean",
description:
"Whether this rule should always be applied regardless of file pattern matching",
},
},
},
},

View file

@ -17,6 +17,10 @@ export const createNewFileImpl: ToolImpl = async (args, extras) => {
}
await extras.ide.writeFile(resolvedFileUri, args.contents);
await extras.ide.openFile(resolvedFileUri);
await extras.ide.saveFile(resolvedFileUri);
if (extras.codeBaseIndexer) {
void extras.codeBaseIndexer?.refreshCodebaseIndexFiles([resolvedFileUri]);
}
return [
{
name: getUriPathBasename(resolvedFileUri),

View file

@ -1,114 +1,124 @@
import { parseMarkdownRule } from "../../config/markdown/parseMarkdownRule";
import { jest } from "@jest/globals";
import { parseMarkdownRule } from "../../config/markdown";
import { createRuleBlockImpl } from "./createRuleBlock";
// Mock the extras parameter with necessary functions
const mockIde = {
getWorkspaceDirs: jest.fn().mockResolvedValue(["/"]),
writeFile: jest.fn().mockResolvedValue(undefined),
openFile: jest.fn().mockResolvedValue(undefined),
getWorkspaceDirs: jest.fn<() => Promise<string[]>>().mockResolvedValue(["/"]),
writeFile: jest
.fn<(path: string, content: string) => Promise<void>>()
.mockResolvedValue(undefined),
openFile: jest
.fn<(path: string) => Promise<void>>()
.mockResolvedValue(undefined),
};
const mockExtras = {
ide: mockIde,
};
describe("createRuleBlockImpl", () => {
beforeEach(() => {
jest.clearAllMocks();
beforeEach(() => {
jest.clearAllMocks();
});
test("createRuleBlockImpl should create a rule with glob pattern", async () => {
const args = {
name: "TypeScript Rule",
rule: "Use interfaces for object shapes",
description: "Always use interfaces",
alwaysApply: true,
globs: "**/*.{ts,tsx}",
};
await createRuleBlockImpl(args, mockExtras as any);
const fileContent = mockIde.writeFile.mock.calls[0][1] as string;
const { frontmatter, markdown } = parseMarkdownRule(fileContent);
expect(frontmatter).toEqual({
description: "Always use interfaces",
globs: "**/*.{ts,tsx}",
});
it("should create a rule with glob pattern", async () => {
const args = {
name: "TypeScript Rule",
rule: "Use interfaces for object shapes",
globs: "**/*.{ts,tsx}",
};
expect(markdown).toContain("# TypeScript Rule");
expect(markdown).toContain("Use interfaces for object shapes");
});
await createRuleBlockImpl(args, mockExtras as any);
test("createRuleBlockImpl should create a filename based on sanitized rule name using shared path function", async () => {
const args = {
name: "Special Ch@racters & Spaces",
rule: "Handle special characters",
description: "Test rule",
alwaysApply: false,
};
const fileContent = mockIde.writeFile.mock.calls[0][1];
await createRuleBlockImpl(args, mockExtras as any);
const { frontmatter, markdown } = parseMarkdownRule(fileContent);
const fileUri = mockIde.writeFile.mock.calls[0][0];
expect(fileUri).toBe("/.continue/rules/special-chracters-spaces.md");
});
expect(frontmatter).toEqual({
globs: "**/*.{ts,tsx}",
});
test("createRuleBlockImpl 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",
alwaysApply: true,
};
expect(markdown).toContain("# TypeScript Rule");
expect(markdown).toContain("Use interfaces for object shapes");
await createRuleBlockImpl(args, mockExtras as any);
const fileContent = mockIde.writeFile.mock.calls[0][1] as string;
const { frontmatter, markdown } = parseMarkdownRule(fileContent);
expect(frontmatter).toEqual({
description: "This is a detailed explanation of the rule",
});
it("should create a filename based on sanitized rule name", async () => {
const args = {
name: "Special Ch@racters & Spaces",
rule: "Handle special characters",
};
expect(markdown).toContain("# Description Test");
expect(markdown).toContain("This is the rule content");
});
await createRuleBlockImpl(args, mockExtras as any);
test("createRuleBlockImpl 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",
alwaysApply: false,
globs: "**/*.js",
};
const fileUri = mockIde.writeFile.mock.calls[0][0];
expect(fileUri).toContain("special-chracters-spaces.md");
await createRuleBlockImpl(args, mockExtras as any);
const fileContent = mockIde.writeFile.mock.calls[0][1] as string;
const { frontmatter, markdown } = parseMarkdownRule(fileContent);
expect(frontmatter).toEqual({
description: "This rule enforces our team standards",
globs: "**/*.js",
});
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",
};
expect(markdown).toContain("# Complete Rule");
expect(markdown).toContain("Follow this standard");
});
await createRuleBlockImpl(args, mockExtras as any);
test("createRuleBlockImpl should create a rule with alwaysApply set to false", async () => {
const args = {
name: "Conditional Rule",
rule: "This rule should not always be applied",
description: "Optional rule",
alwaysApply: false,
};
const fileContent = mockIde.writeFile.mock.calls[0][1];
await createRuleBlockImpl(args, mockExtras as any);
const { frontmatter, markdown } = parseMarkdownRule(fileContent);
const fileContent = mockIde.writeFile.mock.calls[0][1] as string;
expect(frontmatter).toEqual({
description: "This is a detailed explanation of the rule",
});
const { frontmatter } = parseMarkdownRule(fileContent);
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");
});
it("should create a rule with alwaysApply set to false", async () => {
const args = {
name: "Conditional Rule",
rule: "This rule should not always be applied",
alwaysApply: false,
};
await createRuleBlockImpl(args, mockExtras as any);
const fileContent = mockIde.writeFile.mock.calls[0][1];
const { frontmatter } = parseMarkdownRule(fileContent);
expect(frontmatter).toEqual({
alwaysApply: false,
});
expect(frontmatter).toEqual({
description: "Optional rule",
});
});

View file

@ -1,8 +1,6 @@
import * as YAML from "yaml";
import { ToolImpl } from ".";
import { RuleWithSource } from "../..";
import { RuleFrontmatter } from "../../config/markdown/parseMarkdownRule";
import { joinPathsToUri, pathToUriPathSegment } from "../../util/uri";
import { createRuleFilePath, createRuleMarkdown } from "../../config/markdown";
export type CreateRuleBlockArgs = Pick<
Required<RuleWithSource>,
@ -14,49 +12,16 @@ export const createRuleBlockImpl: ToolImpl = async (
args: CreateRuleBlockArgs,
extras,
) => {
// Use the pathToUriPathSegment utility for sanitizing the name
const safeRuleName = pathToUriPathSegment(args.name)
.toLowerCase()
.replace(/[^a-z0-9-]/g, "") // Further sanitize to remove any remaining special chars
.replace(/-+/g, "-") // Replace multiple dashes with a single dash
.replace(/^-|-$/g, ""); // Remove leading/trailing dashes
const fileContent = createRuleMarkdown(args.name, args.rule, {
description: args.description,
globs: args.globs,
});
const fileExtension = "md";
const frontmatter: RuleFrontmatter = {};
if (args.globs) {
frontmatter.globs =
typeof args.globs === "string" ? args.globs.trim() : args.globs;
}
if (args.description) {
frontmatter.description = args.description.trim();
}
if (args.alwaysApply !== undefined) {
frontmatter.alwaysApply = args.alwaysApply;
}
const frontmatterYaml = YAML.stringify(frontmatter).trim();
let fileContent = `---
${frontmatterYaml}
---
# ${args.name}
${args.rule}
`;
const [localContinueDir] = await extras.ide.getWorkspaceDirs();
const rulesDirUri = joinPathsToUri(
localContinueDir,
".continue",
"rules",
`${safeRuleName}.${fileExtension}`,
);
const ruleFilePath = createRuleFilePath(localContinueDir, args.name);
await extras.ide.writeFile(rulesDirUri, fileContent);
await extras.ide.openFile(rulesDirUri);
await extras.ide.writeFile(ruleFilePath, fileContent);
await extras.ide.openFile(ruleFilePath);
return [
{
@ -64,7 +29,7 @@ ${args.rule}
description: args.description || "",
uri: {
type: "file",
value: rulesDirUri,
value: ruleFilePath,
},
content: `Rule created successfully`,
},

View file

@ -10,15 +10,15 @@ Amazon Bedrock is a fully managed service on AWS that provides access to foundat
## Chat model
We recommend configuring **Claude 3.5 Sonnet** as your chat model.
We recommend configuring **Claude 3.7 Sonnet** as your chat model.
<Tabs groupId="config-example">
<TabItem value="yaml" label="YAML">
```yaml title="config.yaml"
models:
- name: Claude 3.5 Sonnet
- name: Claude 3.7 Sonnet
provider: bedrock
model: anthropic.claude-3-5-sonnet-20240620-v1:0
model: us.anthropic.claude-3-7-sonnet-20250219-v1:0
env:
region: us-east-1
profile: bedrock
@ -31,9 +31,9 @@ We recommend configuring **Claude 3.5 Sonnet** as your chat model.
{
"models": [
{
"title": "Claude 3.5 Sonnet",
"title": "Claude 3.7 Sonnet",
"provider": "bedrock",
"model": "anthropic.claude-3-5-sonnet-20240620-v1:0",
"model": "us.anthropic.claude-3-7-sonnet-20250219-v1:0",
"region": "us-east-1",
"profile": "bedrock"
}
@ -147,6 +147,36 @@ We recommend configuring `cohere.rerank-v3-5:0` as your reranking model, you may
</TabItem>
</Tabs>
## Prompt caching
Bedrock allows Claude models to cache tool payloads, system messages, and chat
messages between requests. Enable this behavior by adding
`promptCaching: true` under `defaultCompletionOptions` in your model
configuration.
Prompt caching is generally available for:
- Claude 3.7 Sonnet
- Claude 3.5 Haiku
- Amazon Nova Micro
- Amazon Nova Lite
- Amazon Nova Pro
Customers who were granted access to Claude 3.5 Sonnet v2 during the prompt
caching preview will retain that access, but it cannot be enabled for new users
on that model.
```yaml title="config.yaml"
models:
- name: Claude 3.7 Sonnet
provider: bedrock
model: us.anthropic.claude-3-7-sonnet-20250219-v1:0
defaultCompletionOptions:
promptCaching: true
```
Prompt caching is not supported in JSON configuration files, so use the YAML syntax above to enable it.
## Authentication
Authentication will be through temporary or long-term credentials in

View file

@ -5,15 +5,15 @@ slug: ../bedrock
## 聊天模型
我们推荐配置 **Claude 3.5 Sonnet** 作为你的聊天模型。
我们推荐配置 **Claude 3.7 Sonnet** 作为你的聊天模型。
```json title="config.json"
{
"models": [
{
"title": "Claude 3.5 Sonnet",
"title": "Claude 3.7 Sonnet",
"provider": "bedrock",
"model": "anthropic.claude-3-5-sonnet-20240620-v1:0",
"model": "us.anthropic.claude-3-7-sonnet-20250219-v1:0",
"region": "us-east-1",
"profile": "bedrock"
}
@ -48,6 +48,32 @@ Bedrock 当前没有任何重排序模型。
[点击这里](../../model-roles/reranking.md) 查看重排序模型提供者列表。
## 提示词缓存
Bedrock 支持 Claude 模型的提示词缓存。 在 `defaultCompletionOptions`
中设置 `promptCaching: true` 即可缓存工具调用、系统消息和聊天消息。
提示词缓存目前适用于以下模型:
- Claude 3.7 Sonnet
- Claude 3.5 Haiku
- Amazon Nova Micro
- Amazon Nova Lite
- Amazon Nova Pro
在预览期间获准使用 Claude 3.5 Sonnet v2 的用户仍可继续使用提示词缓存,但该模型不会再向新的用户开放此功能。
```yaml title="config.yaml"
models:
- name: Claude 3.7 Sonnet
provider: bedrock
model: us.anthropic.claude-3-7-sonnet-20250219-v1:0
defaultCompletionOptions:
promptCaching: true
```
提示词缓存不支持 JSON 配置文件,只能在 YAML 中启用。
## 认证
认证可以通过 `~/.aws/credentials` 配置属性中临时的或长期的证书,(例如 "bedrock") 。

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "1.1.46",
"version": "1.1.47",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -18,7 +18,7 @@
"homepage": "https://continue.dev",
"qna": "https://github.com/continuedev/continue/issues/new/choose",
"license": "Apache-2.0",
"displayName": "Continue",
"displayName": "Continue - open-source AI code assistant",
"pricing": "Free",
"description": "The leading open-source AI code assistant",
"publisher": "Continue",

View file

@ -51,8 +51,7 @@ export default function AcceptRejectAllButtons({
>
<div className="flex flex-row items-center gap-1">
<XMarkIcon className="text-error h-4 w-4" />
<span>Reject</span>
<span className="xs:inline-block hidden">All</span>
<span className="hidden sm:inline">Reject</span>
</div>
</button>
<ToolTip id="reject-shortcut" />
@ -66,8 +65,7 @@ export default function AcceptRejectAllButtons({
>
<div className="flex flex-row items-center gap-1">
<CheckIcon className="text-success h-4 w-4" />
<span>Accept</span>
<span className="xs:inline-block hidden">All</span>
<span className="hidden sm:inline">Accept</span>
</div>
</button>
<ToolTip id="accept-shortcut" />

View file

@ -31,8 +31,8 @@ export function ApplyActions(props: ApplyActionsProps) {
);
case "done":
return (
<div className="flex select-none items-center rounded bg-zinc-700 px-1.5 sm:gap-1">
<span className="max-xs:hidden text-lightgray text-center text-xs">
<div className="flex select-none items-center rounded bg-zinc-700 sm:gap-1 md:px-1.5">
<span className="text-lightgray text-center text-xs max-md:hidden">
{`${props.applyState?.numDiffs === 1 ? "1 diff" : `${props.applyState?.numDiffs} diffs`}`}
</span>
@ -42,7 +42,7 @@ export function ApplyActions(props: ApplyActionsProps) {
onClick={onClickReject}
tooltipContent={`Reject all (${getMetaKeyLabel()}⇧⌫)`}
>
<XMarkIcon className="h-3.5 w-3.5 text-red-600 hover:brightness-125" />
<XMarkIcon className="text-error h-3.5 w-3.5 hover:brightness-125" />
</ToolbarButtonWithTooltip>
<ToolbarButtonWithTooltip
@ -50,7 +50,7 @@ export function ApplyActions(props: ApplyActionsProps) {
onClick={props.onClickAccept}
tooltipContent={`Accept all (${getMetaKeyLabel()}⇧⏎)`}
>
<CheckIcon className="h-3.5 w-3.5 text-green-600 hover:brightness-125" />
<CheckIcon className="text-success h-3.5 w-3.5 hover:brightness-125" />
</ToolbarButtonWithTooltip>
</div>
</div>

View file

@ -291,7 +291,7 @@ export function StepContainerPreToolbar({
return (
<TopDiv>
<ToolbarDiv isExpanded={isExpanded} className="find-widget-skip gap-3">
<div className="flex max-w-72 flex-row items-center">
<div className="max-w-[50% flex flex-row items-center">
<ChevronDownIcon
onClick={() => setIsExpanded(!isExpanded)}
className={`text-lightgray h-3.5 w-3.5 flex-shrink-0 cursor-pointer hover:brightness-125 ${

View file

@ -292,6 +292,26 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => {
},
description: "Create a new .prompt file",
});
} else if (subMenuTitle === "Mention rules files") {
items.push({
title: "Add new rule",
type: "action",
action: () => {
void ideMessenger.request("config/addLocalWorkspaceBlock", {
blockType: "rules",
});
const { tr } = props.editor.view.state;
const text = tr.doc.textBetween(0, tr.selection.from);
const start = text.lastIndexOf("@");
if (start !== -1) {
props.editor.view.dispatch(
tr.delete(start, tr.selection.from).scrollIntoView(),
);
}
props.onClose(); // Escape the mention list after creating a new rule
},
description: "Creates a rule file",
});
}
setLoadingSubmenuItem(items.find((item) => item.id === "loading"));
setAllItems(items.filter((item) => item.id !== "loading"));

View file

@ -28,9 +28,9 @@ export function PendingApplyStatesToolbar({
{Object.entries(applyStatesByFilepath).map(([filepath, states]) => (
<div key={filepath} className="flex justify-between gap-3">
{filepath && (
<span className="bg-badge flex items-center gap-1 rounded px-0.5">
<span className="bg-badge flex min-w-0 max-w-[75%] items-center gap-1 truncate rounded pr-1 text-xs">
<FileIcon filename={filepath} height="18px" width="18px" />
{getUriPathBasename(filepath)}
<span className="truncate">{getUriPathBasename(filepath)}</span>
</span>
)}
<AcceptRejectDiffButtons

View file

@ -7,13 +7,11 @@ import { useContext } from "react";
import { GhostButton } from "../../..";
import { useAuth } from "../../../../context/Auth";
import { IdeMessengerContext } from "../../../../context/IdeMessenger";
import { useAppDispatch } from "../../../../redux/hooks";
import { fontSize } from "../../../../util";
export function ExploreBlocksButton(props: { blockType: string }) {
const { selectedProfile } = useAuth();
const ideMessenger = useContext(IdeMessengerContext);
const dispatch = useAppDispatch();
const isLocal = selectedProfile?.profileType === "local";
@ -26,21 +24,11 @@ export function ExploreBlocksButton(props: { blockType: string }) {
const handleClick = () => {
if (isLocal) {
ideMessenger.request("config/addLocalWorkspaceBlock", {
void ideMessenger.request("config/addLocalWorkspaceBlock", {
blockType: props.blockType as BlockType,
});
// switch (props.blockType) {
// case "docs":
// dispatch(setShowDialog(true));
// dispatch(setDialogMessage(<AddDocsDialog />));
// break;
// default:
// ideMessenger.request("config/openProfile", {
// profileId: selectedProfile.id,
// });
// }
} else {
ideMessenger.request("controlPlane/openUrl", {
void ideMessenger.request("controlPlane/openUrl", {
path: `new?type=block&blockType=${props.blockType}`,
orgSlug: undefined,
});

View file

@ -34,7 +34,7 @@ const RuleCard: React.FC<RuleCardProps> = ({ rule }) => {
const handleOpen = async () => {
if (rule.slug) {
ideMessenger.request("controlPlane/openUrl", {
void ideMessenger.request("controlPlane/openUrl", {
path: `${rule.slug}/new-version`,
orgSlug: undefined,
});

View file

@ -14,6 +14,7 @@ import {
GlobeAltIcon,
MagnifyingGlassIcon,
PaperClipIcon,
PencilIcon,
PlusIcon,
SparklesIcon,
TrashIcon,
@ -42,6 +43,7 @@ export const NAMED_ICONS: { [key: string]: any } = {
debugger: BugAntIcon,
os: CpuChipIcon,
tree: Bars3BottomLeftIcon,
rules: PencilIcon,
"prompt-files": DocumentTextIcon,
"repo-map": FolderIcon,
"/clear": TrashIcon,

View file

@ -1,4 +1,5 @@
import {
ArrowPathIcon,
ArrowTopRightOnSquareIcon,
ClipboardIcon,
Cog6ToothIcon,
@ -7,6 +8,7 @@ import {
import { DISCORD_LINK, GITHUB_LINK } from "core/util/constants";
import { useContext, useMemo } from "react";
import { GhostButton, SecondaryButton } from "../../components";
import { useMainEditor } from "../../components/mainInput/TipTapEditor";
import { DiscordIcon } from "../../components/svg/DiscordIcon";
import { GithubIcon } from "../../components/svg/GithubIcon";
import ToggleDiv from "../../components/ToggleDiv";
@ -16,6 +18,7 @@ import { selectSelectedProfile } from "../../redux/";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { selectSelectedChatModel } from "../../redux/slices/configSlice";
import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice";
import { streamResponseThunk } from "../../redux/thunks";
import { isLocalProfile } from "../../util";
import { providers } from "../AddNewModel/configs/providers";
import { ModelsAddOnLimitDialog } from "./ModelsAddOnLimitDialog";
@ -44,6 +47,7 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => {
const selectedModel = useAppSelector(selectSelectedChatModel);
const selectedProfile = useAppSelector(selectSelectedProfile);
const { session, refreshProfiles } = useAuth();
const { mainEditor } = useMainEditor();
const parsedError = useMemo<string>(
() => parseErrorMessage((error as any)?.message || ""),
@ -60,6 +64,8 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => {
void navigator.clipboard.writeText(parsedError);
};
const history = useAppSelector((store) => store.session.history);
// Collect model information to display useful error info
let modelTitle = "Chat model";
let providerName = "the model provider";
@ -131,6 +137,48 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => {
</GhostButton>
);
const resubmitButton = (
<GhostButton
className="flex items-center"
onClick={() => {
let index = -1;
for (let i = history.length - 1; i >= 0; i--) {
if (
history[i].message.role === "user" ||
history[i].message.role === "tool"
) {
index = i;
break;
}
}
if (!mainEditor) {
console.error("Main editor not found, cannot resubmit message.");
return;
}
const editorState =
index === -1 ? mainEditor.getJSON() : history[index].editorState;
void dispatch(
streamResponseThunk({
editorState,
modifiers: {
noContext: true,
useCodebase: false,
},
index: index === -1 ? 0 : index,
}),
);
dispatch(setShowDialog(false));
dispatch(setDialogMessage(undefined));
}}
>
<ArrowPathIcon className="mr-1.5 h-3.5 w-3.5" />
<span>Resubmit last message</span>
</GhostButton>
);
if (
parsedError === "You have exceeded the chat limit for the Models Add-On."
) {
@ -138,7 +186,7 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => {
}
let errorContent = (
<div className="mb-3 mt-1">
<div className="mb-1 mt-3">
<div className="m-0 p-0">
<p className="m-0 mb-2 p-0">
There was an error handling the response from{" "}
@ -148,6 +196,7 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => {
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 className="mt-3">{resubmitButton}</div>
</div>
</div>
);
@ -233,7 +282,7 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => {
if (
message &&
(message.toLowerCase().includes("overloaded") ||
message.toLowerCase().includes("malformed"))
message.toLowerCase().includes("malformed json"))
) {
errorContent = (
<div className="flex flex-col gap-2">

View file

@ -17,4 +17,5 @@ export default {
__dirname: path.dirname(fileURLToPath(import.meta.url)),
__filename: path.resolve(fileURLToPath(import.meta.url)),
},
modulePathIgnorePatterns: ["<rootDir>/dist"],
};

View file

@ -24,6 +24,7 @@ export async function* streamResponse(
// Get the major version of Node.js
const nodeMajorVersion = parseInt(process.versions.node.split(".")[0], 10);
let chunks = 0;
try {
if (nodeMajorVersion >= 20) {
@ -33,6 +34,7 @@ export async function* streamResponse(
new TextDecoderStream("utf-8"),
)) {
yield chunk;
chunks++;
}
} else {
// Fallback for Node versions below 20
@ -41,11 +43,30 @@ export async function* streamResponse(
const nodeStream = response.body as unknown as NodeJS.ReadableStream;
for await (const chunk of toAsyncIterable(nodeStream)) {
yield decoder.decode(chunk, { stream: true });
chunks++;
}
}
} catch (e) {
if (e instanceof Error && e.name.startsWith("AbortError")) {
return; // In case of client-side cancellation, just return
if (e instanceof Error) {
if (e.name.startsWith("AbortError")) {
return; // In case of client-side cancellation, just return
}
if (e.message.toLowerCase().includes("premature close")) {
// Premature close can happen for various reasons, including:
// - Malformed chunks of data received from the server
// - The server closed the connection before sending the complete response
// - Long delays from the server during streaming
// - 'Keep alive' header being used in combination with an http agent and a set, low number of maxSockets
if (chunks === 0) {
throw new Error(
"Stream was closed before any data was received. Try again. (Premature Close)",
);
} else {
throw new Error(
"The response was cancelled mid-stream. Try again. (Premature Close).",
);
}
}
}
throw e;
}

View file

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

View file

@ -19,9 +19,6 @@ export class AzureApi extends OpenAIApi {
this.openai = new OpenAI({
apiKey: azureConfig.apiKey,
baseURL: this._getAzureBaseURL(azureConfig),
defaultQuery: azureConfig.env?.apiVersion
? { "api-version": azureConfig.env.apiVersion }
: {},
fetch: customFetch(azureConfig.requestOptions),
});
}
@ -42,11 +39,17 @@ export class AzureApi extends OpenAIApi {
if (this._isAzureOpenAI(config.env?.apiType)) {
if (!config.env?.deployment) {
throw new Error(
"Azure deployment is required if `apiType` is `azure-openai` or `azure`",
"`env.deployment` is a required configuration property for Azure OpenAI",
);
}
return `${baseURL}/openai/deployments/${config.env.deployment}`;
if (!config.env?.apiVersion) {
throw new Error(
"`env.apiVersion` is a required configuration property for Azure OpenAI",
);
}
return `${baseURL}/openai/deployments/${config.env.deployment}?api-version=${config.env.apiVersion}`;
}
return baseURL;