Merge branch 'main' into no-results-instruction

This commit is contained in:
Nate 2025-07-03 19:08:13 -07:00
commit 6fa241a3e4
196 changed files with 5591 additions and 2037 deletions

View file

@ -0,0 +1,5 @@
---
globs: "gui/**/*.tsx"
---
You should try to use the `rem` CSS unit whenever possible for scalability instead of `px`.

View file

@ -0,0 +1,5 @@
---
alwaysApply: false
---
Convert all of the styled components in this file into tailwind CSS. If a variable is used that is not already in @theme.ts and @tailwind.config.cjs, then you should figure out where it comes from and try adding that so it can be used. Wherever a function is called to interpolate a value, you can just use inline `styles={{ ... }}`. For ternaries, you could use @cn.ts.

View file

@ -1,6 +0,0 @@
---
name: Never use useEffect
regex: "useEffect"
---
TELL THE USER IN ALL CAPS THAT YOU REFUSE TO TAKE ANY FURTHER ACTION UNTIL THE `useEffect` IS REMOVED FROM THE CODE. IT IS A BAD PRACTICE AND SHOULD NEVER BE NECESSARY. YOU CAN SUGGEST A FIX TO REMOVE THE `useEffect` AND REPLACE IT WITH SOMETHING ELSE, BUT YOU SHOULD REFUSE TO DO ANY OTHER TASKS BEFORE THAT IS DONE.

View file

@ -26,5 +26,6 @@ jobs:
path-to-signatures: "signatures/version1/cla.json"
path-to-document: "https://github.com/continuedev/continue/blob/main/docs/docs/CLA.md"
branch: cla-signatures
allowlist: dependabot[bot]
# Bots and CLAs signed outside of GitHub
allowlist: dependabot[bot],fbricon,panyamkeerthana,Jazzcort,owtaylor,halfline
signed-commit-message: "CLA signed in $pullRequestNo"

View file

@ -167,20 +167,8 @@ jobs:
path: gui/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }}
- uses: actions/cache@v4
id: config-yaml-cache
with:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- name: Build and check config-yaml
run: |
cd ../../packages/config-yaml
npm i
npx tsc --noEmit
# Tests are currently failing, commenting out for now
# npm test
npm run build
- name: Build packages (Unix)
run: ./scripts/build-packages.sh
# npm install core
- name: Install core node_modules

1
.vscode/launch.json vendored
View file

@ -19,6 +19,7 @@
"pauseForSourceMap": false,
"outFiles": ["${workspaceFolder}/extensions/vscode/out/extension.js"],
"preLaunchTask": "vscode-extension:build",
"postDebugTask": "Terminate All Tasks",
"env": {
// "CONTROL_PLANE_ENV": "local",
"CONTINUE_GLOBAL_DIR": "${workspaceFolder}/extensions/.continue-debug"

13
.vscode/tasks.json vendored
View file

@ -223,6 +223,19 @@
],
"type": "shell",
"problemMatcher": []
},
{
"label": "Terminate All Tasks",
"command": "${input:terminate}",
"type": "shell"
}
],
"inputs": [
{
"id": "terminate",
"type": "command",
"command": "workbench.action.tasks.terminate",
"args": "terminateAll"
}
]
}

View file

@ -144,6 +144,7 @@
"myers-diff": "^2.1.0",
"onnxruntime-common": "1.14.0",
"onnxruntime-web": "1.14.0",
"shiki": "^3.6.0",
"ts-jest": "^29.1.1",
"typescript": "^5.6.3",
"vitest": "^3.1.4"

View file

@ -132,6 +132,14 @@ export function postprocessCompletion({
completion = "\n" + completion;
}
if (
(llm.model.includes("gemini") || llm.model.includes("gemma")) &&
completion.endsWith("<|file_separator|>")
) {
// "<|file_separator|>" is 18 characters long
completion = completion.slice(0, -18);
}
// If prefix ends with space and so does completion, then remove the space from completion
if (prefix.endsWith(" ") && completion.startsWith(" ")) {

View file

@ -1,6 +1,7 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, test } from "vitest";
import { testConfigHandler } from "../test/fixtures";
import { TEST_DIR } from "../test/testDir";
import { getConfigTsPath } from "../util/paths";
@ -24,7 +25,7 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => {
);
});
test.skip("should add a system message from config.ts", async () => {
test("should add a system message from config.ts", async () => {
const configTs = `export function modifyConfig(config: Config): Config {
config.systemMessage = "SYSTEM";
return config;
@ -39,7 +40,7 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => {
expect(config.systemMessage).toBe("SYSTEM");
});
test.skip("should acknowledge override from .continuerc.json", async () => {
test("should acknowledge override from .continuerc.json", async () => {
fs.writeFileSync(
path.join(TEST_DIR, ".continuerc.json"),
JSON.stringify({ systemMessage: "SYSTEM2" }),

View file

@ -62,7 +62,7 @@ import {
} from "../util/paths";
import { localPathToUri } from "../util/pathToUri";
import { baseToolDefinitions } from "../tools";
import { getToolsForIde } from "../tools";
import { resolveRelativePathInDir } from "../util/ideUtils";
import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
import {
@ -525,7 +525,7 @@ async function intermediateToFinalConfig({
const continueConfig: ContinueConfig = {
...config,
contextProviders,
tools: [...baseToolDefinitions],
tools: await getToolsForIde(ide),
mcpServerStatuses: [],
slashCommands: [],
modelsByRole: {

View file

@ -1,3 +1,4 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { walkDirCache } from "../indexing/walkDir";
import { testIde } from "../test/fixtures";
import { addToTestDir, setUpTestDir, tearDownTestDir } from "../test/testDir";

View file

@ -33,7 +33,7 @@ export async function loadCodebaseRules(ide: IDE): Promise<{
const content = await ide.readFile(filePath);
const rule = markdownToRule(content, { uriType: "file", filePath });
rules.push({ ...rule, source: "rules-block" });
rules.push({ ...rule, source: "rules-block", ruleFile: filePath });
} catch (e) {
errors.push({
fatal: false,

View file

@ -33,7 +33,7 @@ export async function loadMarkdownRules(ide: IDE): Promise<{
uriType: "file",
filePath: file.path,
});
rules.push({ ...rule, source: "rules-block" });
rules.push({ ...rule, source: "rules-block", ruleFile: file.path });
} catch (e) {
errors.push({
fatal: false,

View file

@ -22,6 +22,7 @@ export const sharedConfigSchema = z
logEditingData: z.boolean(),
optInNextEditFeature: z.boolean(),
enableExperimentalTools: z.boolean(),
codebaseToolCallingOnly: z.boolean(),
// `ui` in `ContinueConfig`
showSessionTabs: z.boolean(),
@ -187,6 +188,10 @@ export function modifyAnyConfigWithSharedConfig<
configCopy.experimental.optInNextEditFeature =
sharedConfig.optInNextEditFeature;
}
if (sharedConfig.codebaseToolCallingOnly !== undefined) {
configCopy.experimental.codebaseToolCallingOnly =
sharedConfig.codebaseToolCallingOnly;
}
return configCopy;
}

View file

@ -1,344 +0,0 @@
import { jest } from "@jest/globals";
import { BrowserSerializedContinueConfig } from "..";
// Create the mock before importing anything else
const mockDecodeSecretLocation = jest.fn();
// Mock the module
jest.unstable_mockModule("@continuedev/config-yaml", () => ({
SecretType: {
User: "user",
Organization: "organization",
FreeTrial: "free_trial",
},
decodeSecretLocation: mockDecodeSecretLocation,
}));
// Import after mocking
const { usesFreeTrialApiKey } = await import("./usesFreeTrialApiKey");
const { SecretType } = await import("@continuedev/config-yaml");
beforeEach(() => {
mockDecodeSecretLocation.mockReset();
});
test("usesFreeTrialApiKey should return false when config is null", () => {
const result = usesFreeTrialApiKey(null);
expect(result).toBe(false);
});
test("usesFreeTrialApiKey should return false when config is undefined", () => {
const result = usesFreeTrialApiKey(undefined as any);
expect(result).toBe(false);
});
test("usesFreeTrialApiKey should return false when no models have apiKeyLocation", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
underlyingProviderName: "test",
},
{
title: "Model 2",
provider: "test",
model: "test-model-2",
underlyingProviderName: "test",
},
],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
});
test("usesFreeTrialApiKey should return false when models have apiKeyLocation but none are free trial", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "user:testuser/api-key",
underlyingProviderName: "test",
},
],
edit: [
{
title: "Model 2",
provider: "test",
model: "test-model-2",
apiKeyLocation: "organization:testorg/api-key",
underlyingProviderName: "test",
},
],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation
.mockReturnValueOnce({
secretType: SecretType.User,
userSlug: "testuser",
secretName: "api-key",
})
.mockReturnValueOnce({
secretType: SecretType.Organization,
orgSlug: "testorg",
secretName: "api-key",
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
});
test("usesFreeTrialApiKey should return true when at least one model uses free trial API key", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "user:testuser/api-key",
underlyingProviderName: "test",
},
{
title: "Free Trial Model",
provider: "test",
model: "free-trial-model",
apiKeyLocation: "free_trial:owner/package/api-key",
underlyingProviderName: "test",
},
],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation
.mockReturnValueOnce({
secretType: SecretType.User,
userSlug: "testuser",
secretName: "api-key",
})
.mockReturnValueOnce({
secretType: SecretType.FreeTrial,
blockSlug: { ownerSlug: "owner", packageSlug: "package" },
secretName: "api-key",
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(true);
expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
});
test("usesFreeTrialApiKey should return true when free trial model is in a different role", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "user:testuser/api-key",
underlyingProviderName: "test",
},
],
edit: [
{
title: "Free Trial Edit Model",
provider: "test",
model: "free-trial-edit-model",
apiKeyLocation: "free_trial:owner/package/api-key",
underlyingProviderName: "test",
},
],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation
.mockReturnValueOnce({
secretType: SecretType.User,
userSlug: "testuser",
secretName: "api-key",
})
.mockReturnValueOnce({
secretType: SecretType.FreeTrial,
blockSlug: { ownerSlug: "owner", packageSlug: "package" },
secretName: "api-key",
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(true);
});
test("usesFreeTrialApiKey should return false and log error when decodeSecretLocation throws", () => {
const consoleSpy = jest.spyOn(console, "error").mockImplementation(() => {});
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "invalid-secret-location",
underlyingProviderName: "test",
},
],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation.mockImplementation(() => {
throw new Error("Invalid secret location format");
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
expect(consoleSpy).toHaveBeenCalledWith(
"Error checking for free trial API key:",
expect.any(Error),
);
consoleSpy.mockRestore();
});
test("usesFreeTrialApiKey should handle empty modelsByRole object", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
expect(mockDecodeSecretLocation).not.toHaveBeenCalled();
});

View file

@ -0,0 +1,348 @@
import { beforeEach, describe, expect, test, vi } from "vitest";
import { BrowserSerializedContinueConfig } from "..";
// Create the mock before importing anything else
const mockDecodeSecretLocation = vi.fn();
// Mock the module
vi.mock("@continuedev/config-yaml", () => ({
SecretType: {
User: "user",
Organization: "organization",
FreeTrial: "free_trial",
},
decodeSecretLocation: mockDecodeSecretLocation,
}));
describe("usesFreeTrialApiKey", () => {
let usesFreeTrialApiKey: typeof import("./usesFreeTrialApiKey").usesFreeTrialApiKey;
let SecretType: typeof import("@continuedev/config-yaml").SecretType;
beforeEach(async () => {
mockDecodeSecretLocation.mockReset();
usesFreeTrialApiKey = (await import("./usesFreeTrialApiKey"))
.usesFreeTrialApiKey;
SecretType = (await import("@continuedev/config-yaml")).SecretType;
});
test("usesFreeTrialApiKey should return false when config is null", () => {
const result = usesFreeTrialApiKey(null);
expect(result).toBe(false);
});
test("usesFreeTrialApiKey should return false when config is undefined", () => {
const result = usesFreeTrialApiKey(undefined as any);
expect(result).toBe(false);
});
test("usesFreeTrialApiKey should return false when no models have apiKeyLocation", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
underlyingProviderName: "test",
},
{
title: "Model 2",
provider: "test",
model: "test-model-2",
underlyingProviderName: "test",
},
],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
});
test("usesFreeTrialApiKey should return false when models have apiKeyLocation but none are free trial", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "user:testuser/api-key",
underlyingProviderName: "test",
},
],
edit: [
{
title: "Model 2",
provider: "test",
model: "test-model-2",
apiKeyLocation: "organization:testorg/api-key",
underlyingProviderName: "test",
},
],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation
.mockReturnValueOnce({
secretType: SecretType.User,
userSlug: "testuser",
secretName: "api-key",
})
.mockReturnValueOnce({
secretType: SecretType.Organization,
orgSlug: "testorg",
secretName: "api-key",
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
});
test("usesFreeTrialApiKey should return true when at least one model uses free trial API key", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "user:testuser/api-key",
underlyingProviderName: "test",
},
{
title: "Free Trial Model",
provider: "test",
model: "free-trial-model",
apiKeyLocation: "free_trial:owner/package/api-key",
underlyingProviderName: "test",
},
],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation
.mockReturnValueOnce({
secretType: SecretType.User,
userSlug: "testuser",
secretName: "api-key",
})
.mockReturnValueOnce({
secretType: SecretType.FreeTrial,
blockSlug: { ownerSlug: "owner", packageSlug: "package" },
secretName: "api-key",
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(true);
expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
});
test("usesFreeTrialApiKey should return true when free trial model is in a different role", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "user:testuser/api-key",
underlyingProviderName: "test",
},
],
edit: [
{
title: "Free Trial Edit Model",
provider: "test",
model: "free-trial-edit-model",
apiKeyLocation: "free_trial:owner/package/api-key",
underlyingProviderName: "test",
},
],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation
.mockReturnValueOnce({
secretType: SecretType.User,
userSlug: "testuser",
secretName: "api-key",
})
.mockReturnValueOnce({
secretType: SecretType.FreeTrial,
blockSlug: { ownerSlug: "owner", packageSlug: "package" },
secretName: "api-key",
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(true);
});
test("usesFreeTrialApiKey should return false and log error when decodeSecretLocation throws", () => {
const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "invalid-secret-location",
underlyingProviderName: "test",
},
],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation.mockImplementation(() => {
throw new Error("Invalid secret location format");
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
expect(consoleSpy).toHaveBeenCalledWith(
"Error checking for free trial API key:",
expect.any(Error),
);
consoleSpy.mockRestore();
});
test("usesFreeTrialApiKey should handle empty modelsByRole object", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
expect(mockDecodeSecretLocation).not.toHaveBeenCalled();
});
});

View file

@ -10,7 +10,7 @@ import {
JSONModelDescription,
PromptTemplate,
} from "../";
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/constructMessages";
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../llm/defaultSystemMessages";
import { GlobalContext } from "../util/GlobalContext";
import { editConfigFile } from "../util/paths";

View file

@ -1,3 +1,4 @@
import { describe, expect, it } from "vitest";
import { PromptTemplate } from "..";
import { serializePromptTemplates } from "./util";

View file

@ -1,5 +1,5 @@
import { BlockType, RULE_FILE_EXTENSION } from "@continuedev/config-yaml";
import { describe, expect, test } from "@jest/globals";
import { describe, expect, test } from "vitest";
import { findAvailableFilename, getFileContent } from "./workspaceBlocks";
describe("getFileContent", () => {

View file

@ -1,10 +1,10 @@
import { jest } from "@jest/globals";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { beforeEach, describe, expect, it, vi } from "vitest";
import MCPConnection from "./MCPConnection";
describe("MCPConnection", () => {
beforeEach(() => {
jest.restoreAllMocks();
vi.restoreAllMocks();
});
describe("constructor", () => {
@ -131,10 +131,10 @@ describe("MCPConnection", () => {
it("should connect successfully", async () => {
const conn = new MCPConnection(options);
const mockConnect = jest
const mockConnect = vi
.spyOn(Client.prototype, "connect")
.mockResolvedValue(undefined);
const mockGetServerCapabilities = jest
const mockGetServerCapabilities = vi
.spyOn(Client.prototype, "getServerCapabilities")
.mockReturnValue({
resources: {},
@ -142,12 +142,12 @@ describe("MCPConnection", () => {
prompts: {},
});
const mockListResources = jest
const mockListResources = vi
.spyOn(Client.prototype, "listResources")
.mockResolvedValue({
resources: [{ name: "test-resource", uri: "test-uri" }],
});
const mockListTools = jest
const mockListTools = vi
.spyOn(Client.prototype, "listTools")
.mockResolvedValue({
tools: [
@ -159,7 +159,7 @@ describe("MCPConnection", () => {
},
],
});
const mockListPrompts = jest
const mockListPrompts = vi
.spyOn(Client.prototype, "listPrompts")
.mockResolvedValue({ prompts: [{ name: "test-prompt" }] });
@ -175,7 +175,7 @@ describe("MCPConnection", () => {
it("should handle custom connection timeout", async () => {
const conn = new MCPConnection({ ...options, timeout: 1500 });
const mockConnect = jest
const mockConnect = vi
.spyOn(Client.prototype, "connect")
.mockImplementation(
() => new Promise((resolve) => setTimeout(resolve, 1000)),
@ -190,7 +190,7 @@ describe("MCPConnection", () => {
it("should handle connection timeout", async () => {
const conn = new MCPConnection({ ...options, timeout: 1 });
const mockConnect = jest
const mockConnect = vi
.spyOn(Client.prototype, "connect")
.mockImplementation(
() => new Promise((resolve) => setTimeout(resolve, 100)),
@ -208,7 +208,7 @@ describe("MCPConnection", () => {
const conn = new MCPConnection(options);
conn.status = "connected";
const mockConnect = jest.spyOn(Client.prototype, "connect");
const mockConnect = vi.spyOn(Client.prototype, "connect");
const abortController = new AbortController();
await conn.connectClient(false, abortController.signal);
@ -219,7 +219,7 @@ describe("MCPConnection", () => {
it("should handle transport errors", async () => {
const conn = new MCPConnection(options);
const mockConnect = jest
const mockConnect = vi
.spyOn(Client.prototype, "connect")
.mockRejectedValue(new Error("spawn test-cmd ENOENT"));
@ -233,7 +233,7 @@ describe("MCPConnection", () => {
it.skip("should include stderr output in error message when stdio command fails", async () => {
// Clear any existing mocks to ensure we get real behavior
jest.restoreAllMocks();
vi.restoreAllMocks();
// Use a command that will definitely fail and produce stderr output
const failingOptions = {

View file

@ -1,3 +1,4 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { MCPOptions } from "../..";
import MCPConnection from "./MCPConnection";
import { MCPManagerSingleton } from "./MCPManagerSingleton";
@ -18,8 +19,8 @@ class TestMCPConnection extends MCPConnection {
} as any;
this.abortController = new AbortController();
this.connectClient = jest.fn().mockResolvedValue(undefined);
this.getStatus = jest
this.connectClient = vi.fn().mockResolvedValue(undefined);
this.getStatus = vi
.fn()
.mockReturnValue({ status: "connected", errors: [] });
}
@ -54,13 +55,12 @@ describe("MCPManagerSingleton", () => {
id: string,
options: MCPOptions,
): MCPConnection {
if (!this.connections.has(id)) {
const connection = new TestMCPConnection(options);
this.connections.set(id, connection);
return connection;
} else {
if (this.connections.has(id)) {
return this.connections.get(id)!;
}
const connection = new TestMCPConnection(options);
this.connections.set(id, connection);
return connection;
};
});
@ -103,7 +103,7 @@ describe("MCPManagerSingleton", () => {
"test-id",
testOptions,
) as TestMCPConnection;
const closeSpy = jest.spyOn(connection.client, "close");
const closeSpy = vi.spyOn(connection.client, "close");
await manager.removeConnection("test-id");
@ -133,8 +133,8 @@ describe("MCPManagerSingleton", () => {
"test-id",
testOptions,
) as TestMCPConnection;
const abortSpy = jest.spyOn(connection.abortController, "abort");
const closeSpy = jest.spyOn(connection.client, "close");
const abortSpy = vi.spyOn(connection.abortController, "abort");
const closeSpy = vi.spyOn(connection.client, "close");
// Remove it by setting empty server list
manager.setConnections([], false);
@ -192,7 +192,7 @@ describe("MCPManagerSingleton", () => {
});
it("should call onConnectionsRefreshed if defined", async () => {
const mockCallback = jest.fn();
const mockCallback = vi.fn();
manager.onConnectionsRefreshed = mockCallback;
manager.createConnection("test-id", testOptions);
@ -209,7 +209,7 @@ describe("MCPManagerSingleton", () => {
testOptions,
) as TestMCPConnection;
const mockStatus = { status: "connected", errors: [] };
connection.getStatus = jest.fn().mockReturnValue(mockStatus);
connection.getStatus = vi.fn().mockReturnValue(mockStatus);
const statuses = manager.getStatuses();
expect(statuses).toHaveLength(1);

View file

@ -1,5 +1,6 @@
import fetch from "node-fetch";
import { afterAll, describe, expect, test } from "vitest";
import { contextProviderClassFromName } from ".";
import {
ContextProviderExtras,
@ -8,7 +9,7 @@ import {
} from "../..";
import { ConfigHandler } from "../../config/ConfigHandler";
import { LLMLogger } from "../../llm/logger";
import { TEST_DIR } from "../../test/testDir";
import { setUpTestDir, tearDownTestDir, TEST_DIR } from "../../test/testDir";
import FileSystemIde from "../../util/filesystem";
const CONTEXT_PROVIDERS_TO_TEST: ContextProviderWithParams[] = [
@ -25,6 +26,7 @@ const CONTEXT_PROVIDERS_TO_TEST: ContextProviderWithParams[] = [
async function getContextProviderExtras(
fullInput: string,
): Promise<ContextProviderExtras> {
setUpTestDir();
const ide = new FileSystemIde(TEST_DIR);
const ideSettingsPromise = ide.getIdeSettings();
const llmLogger = new LLMLogger();
@ -53,6 +55,10 @@ async function getContextProviderExtras(
}
describe.skip("Should successfully run all context providers", () => {
afterAll(() => {
tearDownTestDir();
});
const extrasPromise = getContextProviderExtras("Test");
CONTEXT_PROVIDERS_TO_TEST.forEach((provider) => {

View file

@ -1,5 +1,6 @@
import { BaseContextProvider } from "../";
import { ContextProviderName } from "../../";
import { Telemetry } from "../../util/posthog";
import ClipboardContextProvider from "./ClipboardContextProvider";
import CodebaseContextProvider from "./CodebaseContextProvider";
@ -75,5 +76,12 @@ export const Providers: (typeof BaseContextProvider)[] = [
export function contextProviderClassFromName(
name: ContextProviderName,
): typeof BaseContextProvider | undefined {
return Providers.find((cls) => cls.description.title === name);
const provider = Providers.find((cls) => cls.description.title === name);
void Telemetry.capture("context_provider_load", {
providerName: name,
found: !!provider, // also capture those which user expected to be present
});
return provider;
}

View file

@ -1,14 +1,40 @@
// @ts-ignore
import nlp from "wink-nlp-utils";
import { BranchAndDir, Chunk, ContinueConfig, IDE, ILLM } from "../../../";
import {
BranchAndDir,
Chunk,
ContextItem,
ContinueConfig,
IDE,
ILLM,
Tool,
ToolExtras,
} from "../../../";
import { openedFilesLruCache } from "../../../autocomplete/util/openedFilesLruCache";
import { chunkDocument } from "../../../indexing/chunk/chunk";
import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCodebaseIndex";
import { LanceDbIndex } from "../../../indexing/LanceDbIndex";
import { BuiltInToolNames } from "../../../tools/builtIn";
import { callBuiltInTool } from "../../../tools/callTool";
import { globSearchTool } from "../../../tools/definitions/globSearch";
import { grepSearchTool } from "../../../tools/definitions/grepSearch";
import { lsTool } from "../../../tools/definitions/lsTool";
import { readFileTool } from "../../../tools/definitions/readFile";
import { viewRepoMapTool } from "../../../tools/definitions/viewRepoMap";
import { viewSubdirectoryTool } from "../../../tools/definitions/viewSubdirectory";
const DEFAULT_CHUNK_SIZE = 384;
const AVAILABLE_TOOLS: Tool[] = [
globSearchTool,
grepSearchTool,
lsTool,
readFileTool,
viewRepoMapTool,
viewSubdirectoryTool,
];
export interface RetrievalPipelineOptions {
llm: ILLM;
config: ContinueConfig;
@ -155,4 +181,105 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
run(args: RetrievalPipelineRunArguments): Promise<Chunk[]> {
throw new Error("Not implemented");
}
protected async retrieveWithTools(input: string): Promise<Chunk[]> {
const toolSelectionPrompt = `Given the following user input: "${input}"
Available tools:
${AVAILABLE_TOOLS.map((tool) => {
const requiredParams = tool.function.parameters?.required || [];
const properties = tool.function.parameters?.properties || {};
const paramDescriptions = requiredParams
.map(
(param: any) => `${param}: ${properties[param]?.description || "string"}`,
)
.join(", ");
return `- ${tool.function.name}: ${tool.function.description}
Required arguments: ${paramDescriptions || "none"}`;
}).join("\n")}
Determine which tools should be used to answer this query. You should feel free to use multiple tools when they would be helpful for comprehensive results. Respond ONLY a JSON object containing the following and nothing else:
{
"tools": [
{
"name": "<tool_name>",
"args": { "<required_parameter_name>": "<required_parameter_value>" }
}
]
}`;
// Get LLM response for tool selection
const toolSelectionResponse = await this.options.llm.chat(
[{ role: "user", content: toolSelectionPrompt }],
new AbortController().signal,
);
let toolCalls: { name: string; args: any }[] = [];
try {
const responseContent =
typeof toolSelectionResponse.content === "string"
? toolSelectionResponse.content
: toolSelectionResponse.content
.map((part) => (part.type === "text" ? part.text : ""))
.join("");
const parsed = JSON.parse(responseContent);
toolCalls = parsed.tools || [];
console.log("retrieveWithTools", toolCalls);
} catch (e) {
console.log("Failed to parse tool selection response", e);
return [];
}
// Execute tools and collect results
const allContextItems: ContextItem[] = [];
const toolExtras: ToolExtras = {
ide: this.options.ide,
llm: this.options.llm,
fetch: fetch,
tool: grepSearchTool,
config: this.options.config,
};
for (const toolCall of toolCalls) {
const tool = AVAILABLE_TOOLS.find(
(t) => t.function.name === toolCall.name,
)!;
const args = toolCall.args;
if (toolCall.name === BuiltInToolNames.GrepSearch) {
args.splitByFile = true;
}
toolExtras.tool = tool;
const contextItems = await callBuiltInTool(
toolCall.name,
args,
toolExtras,
);
allContextItems.push(...contextItems);
}
const chunks: Chunk[] = [];
// Transform ContextItem[] to Chunk[]
for (let i = 0; i < allContextItems.length; i++) {
const contextItem = allContextItems[i];
const filepath = contextItem.uri?.value || contextItem.name || "unknown";
const cleanedFilepath = filepath.replace(/^file:\/\/\//, "");
chunks.push({
content: contextItem.content,
startLine: -1,
endLine: -1,
digest: `file:///${cleanedFilepath}`,
filepath: `file:///${cleanedFilepath}`,
index: i,
});
}
console.log("retrieveWithTools chunks", chunks);
return chunks;
}
}

View file

@ -64,12 +64,22 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
console.error("Error retrieving repo map chunks:", error);
}
retrievalResults.push(
...recentlyEditedFilesChunks,
...ftsChunks,
...embeddingsChunks,
...repoMapChunks,
);
if (this.options.config.experimental?.codebaseToolCallingOnly) {
let toolBasedChunks: Chunk[] = [];
try {
toolBasedChunks = await this.retrieveWithTools(input);
} catch (error) {
console.error("Error retrieving tool based chunks:", error);
}
retrievalResults.push(...toolBasedChunks);
} else {
retrievalResults.push(
...recentlyEditedFilesChunks,
...ftsChunks,
...embeddingsChunks,
...repoMapChunks,
);
}
if (filterDirectory) {
// Backup if the individual retrieval methods don't listen

View file

@ -58,12 +58,22 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
console.error("Error retrieving repo map chunks:", error);
}
retrievalResults.push(
...recentlyEditedFilesChunks,
...ftsChunks,
...embeddingsChunks,
...repoMapChunks,
);
if (config.experimental?.codebaseToolCallingOnly) {
let toolBasedChunks: Chunk[] = [];
try {
toolBasedChunks = await this.retrieveWithTools(input);
} catch (error) {
console.error("Error retrieving tool based chunks:", error);
}
retrievalResults.push(...toolBasedChunks);
} else {
retrievalResults.push(
...recentlyEditedFilesChunks,
...ftsChunks,
...embeddingsChunks,
...repoMapChunks,
);
}
if (filterDirectory) {
// Backup if the individual retrieval methods don't listen
@ -107,7 +117,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
chunks.forEach((chunk, idx) => chunkIndexMap.set(chunk, idx));
results.sort(
(a, b) => scores[chunkIndexMap.get(a)!] - scores[chunkIndexMap.get(b)!],
(a, b) => scores[chunkIndexMap.get(b)!] - scores[chunkIndexMap.get(a)!],
);
results = results.slice(-this.options.nFinal);
return results;

View file

@ -113,7 +113,11 @@ export async function retrieveContextItemsFromEmbeddings(
}
return {
name: `${baseName} (${r.startLine + 1}-${r.endLine + 1})`,
// Don't show line numbers for tool calls where startLine = -1
name:
r.startLine === -1
? baseName
: `${baseName} (${r.startLine + 1}-${r.endLine + 1})`,
description: last2Parts,
content: `\`\`\`${relativePathOrBasename}\n${r.content}\n\`\`\``,
uri: {

View file

@ -1,6 +1,6 @@
// Generated by Continue
import { describe, expect, it } from "vitest";
import { Chunk } from "../../index";
import { deduplicateChunks } from "./util";
describe("deduplicateChunks", () => {

View file

@ -38,6 +38,7 @@ import { TTS } from "./util/tts";
import {
CompleteOnboardingPayload,
ContextItemId,
ContextItemWithId,
IdeSettings,
ModelDescription,
@ -45,7 +46,6 @@ import {
RangeInFile,
ToolCall,
type ContextItem,
type ContextItemId,
type IDE,
} from ".";
@ -558,7 +558,6 @@ export class Core {
: undefined,
input: data.input,
language: data.language,
onlyOneInsertion: false,
overridePrompt: undefined,
abortController,
});
@ -723,8 +722,8 @@ export class Core {
const EDIT_AGGREGATION_OPTIONS = {
deltaT: 1.0,
deltaL: 5,
maxEdits: 250,
maxDuration: 100.0,
maxEdits: 500,
maxDuration: 120.0,
contextSize: 5,
};
@ -872,7 +871,7 @@ export class Core {
this.messenger.send("toolCallPartialOutput", params);
};
return await callTool(tool, toolCall, {
const result = await callTool(tool, toolCall, {
config,
ide: this.ide,
llm: config.selectedModelByRole.chat,
@ -883,6 +882,8 @@ export class Core {
onPartialOutput,
codeBaseIndexer: this.codeBaseIndexer,
});
return result;
}
private async isItemTooBig(item: ContextItemWithId) {
@ -1101,10 +1102,9 @@ export class Core {
}
try {
const id: ContextItemId = {
providerTitle: provider.description.title,
itemId: uuidv4(),
};
void Telemetry.capture("context_provider_get_context_items", {
name: provider.description.title,
});
const items = await provider.getContextItems(query, {
config,
@ -1127,10 +1127,14 @@ export class Core {
true,
);
return items.map((item) => ({
...item,
id,
}));
return items.map((item) => {
const id: ContextItemId = {
providerTitle: provider.description.title,
itemId: uuidv4(),
};
return { ...item, id };
});
} catch (e) {
let knownError = false;

View file

@ -66,7 +66,6 @@ export async function* streamDiffLines({
abortController,
input,
language,
onlyOneInsertion,
overridePrompt,
rulesToInclude,
}: {
@ -77,7 +76,6 @@ export async function* streamDiffLines({
abortController: AbortController;
input: string;
language: string | undefined;
onlyOneInsertion: boolean;
overridePrompt: ChatMessage[] | undefined;
rulesToInclude: RuleWithSource[] | undefined;
}): AsyncGenerator<DiffLine> {
@ -112,7 +110,7 @@ export async function* streamDiffLines({
// If any rules are present this will result in using chat instead of legacy completion
const systemMessage = rulesToInclude
? getSystemMessageWithRules({
rules: rulesToInclude,
availableRules: rulesToInclude,
userMessage:
typeof prompt === "string"
? ({
@ -125,7 +123,7 @@ export async function* streamDiffLines({
) as UserChatMessage | ToolResultChatMessage | undefined),
baseSystemMessage: undefined,
contextItems: [],
})
}).systemMessage
: undefined;
if (systemMessage) {
@ -182,13 +180,7 @@ export async function* streamDiffLines({
diffLines = addIndentation(diffLines, indentation);
}
let seenGreen = false;
for await (const diffLine of diffLines) {
yield diffLine;
if (diffLine.type === "new") {
seenGreen = true;
} else if (onlyOneInsertion && seenGreen && diffLine.type === "same") {
break;
}
}
}

8
core/index.d.ts vendored
View file

@ -57,6 +57,7 @@ export interface IndexingProgressUpdate {
| "disabled"
| "cancelled";
debugInfo?: string;
warnings?: string[];
}
// This is more or less a V2 of IndexingProgressUpdate for docs etc.
@ -444,6 +445,7 @@ interface ToolCallState {
status: ToolStatus;
parsedArgs: any;
output?: ContextItem[];
tool?: Tool;
}
interface Reasoning {
@ -1421,6 +1423,12 @@ export interface ExperimentalConfig {
* If enabled, will enable next edit in place of autocomplete
*/
optInNextEditFeature?: boolean;
/**
* If enabled, @codebase will only use tool calling
* instead of embeddings, FTS, recently edited files, etc.
*/
codebaseToolCallingOnly?: boolean;
}
export interface AnalyticsConfig {

View file

@ -35,7 +35,8 @@ type SnippetChunk = ChunkWithoutID & { title: string; signature: string };
export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
relativeExpectedTime: number = 1;
artifactId = "codeSnippets";
static artifactId = "codeSnippets";
artifactId: string = CodeSnippetsCodebaseIndex.artifactId;
constructor(private readonly ide: IDE) {}
@ -220,7 +221,6 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
// Compute
for (let i = 0; i < results.compute.length; i++) {
const compute = results.compute[i];
let snippets: SnippetChunk[] = [];
try {
snippets = await this.getSnippetsInFile(

View file

@ -48,6 +48,16 @@ export class CodebaseIndexer {
private codebaseIndexingState: IndexingProgressUpdate;
private readonly pauseToken: PauseToken;
private getUserFriendlyIndexName(artifactId: string): string {
if (artifactId === FullTextSearchCodebaseIndex.artifactId)
return "Full text search";
if (artifactId === CodeSnippetsCodebaseIndex.artifactId)
return "Code snippets";
if (artifactId === ChunkCodebaseIndex.artifactId) return "Chunking";
if (artifactId.startsWith("vectordb")) return "Embedding";
return artifactId; // fallback to original
}
// Note that we exclude certain Sqlite errors that we do not want to clear the indexes on,
// e.g. a `SQLITE_BUSY` error.
errorsRegexesToClearIndexesOn = [
@ -314,6 +324,7 @@ export class CodebaseIndexer {
status: "loading",
};
const beginTime = Date.now();
let collectedWarnings: string[] = [];
for (const directory of dirs) {
const dirBasename = getUriPathBasename(directory);
@ -344,45 +355,52 @@ export class CodebaseIndexer {
const repoName = await this.ide.getRepoName(directory);
let nextLogThreshold = 0;
try {
for await (const updateDesc of this.indexFiles(
directory,
directoryFiles,
branch,
repoName,
)) {
// Handle pausing in this loop because it's the only one really taking time
if (abortSignal.aborted) {
yield {
progress: 0,
desc: "Indexing cancelled",
status: "cancelled",
};
return;
}
if (this.pauseToken.paused) {
yield* this.yieldUpdateAndPause();
}
yield updateDesc;
if (updateDesc.progress >= nextLogThreshold) {
// log progress every 2.5%
nextLogThreshold += 0.025;
this.logProgress(
beginTime,
Math.floor(directoryFiles.length * updateDesc.progress),
updateDesc.progress,
);
}
for await (const updateDesc of this.indexFiles(
directory,
directoryFiles,
branch,
repoName,
)) {
// Handle pausing in this loop because it's the only one really taking time
if (abortSignal.aborted) {
yield {
progress: 0,
desc: "Indexing cancelled",
status: "cancelled",
};
return;
}
if (this.pauseToken.paused) {
yield* this.yieldUpdateAndPause();
}
// Collect warnings from indexFiles
if (updateDesc.warnings && updateDesc.warnings.length > 0) {
collectedWarnings = [...updateDesc.warnings];
}
yield updateDesc;
if (updateDesc.progress >= nextLogThreshold) {
// log progress every 2.5%
nextLogThreshold += 0.025;
this.logProgress(
beginTime,
Math.floor(directoryFiles.length * updateDesc.progress),
updateDesc.progress,
);
}
} catch (err) {
yield this.handleErrorAndGetProgressUpdate(err);
return;
}
}
// Final completion message with preserved warnings
yield {
progress: 1,
desc: "Indexing Complete",
desc:
collectedWarnings.length > 0
? `Indexing completed with ${collectedWarnings.length} warning(s)`
: "Indexing Complete",
status: "done",
warnings: collectedWarnings.length > 0 ? collectedWarnings : undefined,
};
this.logProgress(beginTime, 0, 1);
}
@ -490,6 +508,8 @@ export class CodebaseIndexer {
const indexesToBuild = await this.getIndexesToBuild();
let completedIndexCount = 0;
let progress = 0;
const warnings: string[] = [];
for (const codebaseIndex of indexesToBuild) {
const tag: IndexTag = {
directory,
@ -500,45 +520,101 @@ export class CodebaseIndexer {
progress: progress,
desc: `Planning changes for ${codebaseIndex.artifactId} index...`,
status: "indexing",
warnings: warnings.length > 0 ? [...warnings] : undefined,
};
const [results, lastUpdated, markComplete] =
await getComputeDeleteAddRemove(
tag,
{ ...stats },
(filepath) => this.ide.readFile(filepath),
repoName,
);
const totalOps = this.totalIndexOps(results);
let completedOps = 0;
// Don't update if nothing to update. Some of the indices might do unnecessary setup work
if (totalOps > 0) {
for (const subResult of this.batchRefreshIndexResults(results)) {
for await (const { desc } of codebaseIndex.update(
try {
const [results, lastUpdated, markComplete] =
await getComputeDeleteAddRemove(
tag,
subResult,
markComplete,
{ ...stats },
(filepath) => this.ide.readFile(filepath),
repoName,
)) {
yield {
progress,
desc,
status: "indexing",
};
}
completedOps +=
subResult.compute.length +
subResult.del.length +
subResult.addTag.length +
subResult.removeTag.length;
progress =
(completedIndexCount + completedOps / totalOps) *
(1 / indexesToBuild.length);
}
}
);
const totalOps = this.totalIndexOps(results);
let completedOps = 0;
await markComplete(lastUpdated, IndexResultType.UpdateLastUpdated);
completedIndexCount += 1;
// Don't update if nothing to update. Some of the indices might do unnecessary setup work
if (totalOps > 0) {
for (const subResult of this.batchRefreshIndexResults(results)) {
try {
for await (const { desc } of codebaseIndex.update(
tag,
subResult,
markComplete,
repoName,
)) {
yield {
progress,
desc,
status: "indexing",
warnings: warnings.length > 0 ? [...warnings] : undefined,
};
}
completedOps +=
subResult.compute.length +
subResult.del.length +
subResult.addTag.length +
subResult.removeTag.length;
progress =
(completedIndexCount + completedOps / totalOps) *
(1 / indexesToBuild.length);
} catch (err) {
// Collect non-fatal errors as warnings and continue
const warningMsg =
err instanceof Error ? err.message : String(err);
const friendlyName = this.getUserFriendlyIndexName(
codebaseIndex.artifactId,
);
warnings.push(`${friendlyName}: ${warningMsg}`);
console.warn(`${friendlyName}: ${warningMsg}`, err);
// Complete this batch and continue with next
completedOps +=
subResult.compute.length +
subResult.del.length +
subResult.addTag.length +
subResult.removeTag.length;
progress =
(completedIndexCount + completedOps / totalOps) *
(1 / indexesToBuild.length);
}
}
}
await markComplete(lastUpdated, IndexResultType.UpdateLastUpdated);
completedIndexCount += 1;
} catch (err) {
// Handle errors during planning phase
const cause = getRootCause(err as Error);
if (cause instanceof LLMError) {
// LLM errors are critical, re-throw them
throw cause;
}
// Collect planning errors as warnings and continue to next index
const errorMsg = err instanceof Error ? err.message : String(err);
const friendlyName = this.getUserFriendlyIndexName(
codebaseIndex.artifactId,
);
warnings.push(`${friendlyName}: ${errorMsg}`);
console.warn(
`Warning during ${codebaseIndex.artifactId} planning:`,
err,
);
completedIndexCount += 1;
progress = completedIndexCount * (1 / indexesToBuild.length);
}
}
// Final update with any collected warnings
if (warnings.length > 0) {
yield {
progress: 1,
desc: `Indexing completed with ${warnings.length} warning(s)`,
status: "done",
warnings: [...warnings],
};
}
}

View file

@ -55,7 +55,6 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
for (let i = 0; i < results.compute.length; i++) {
const item = results.compute[i];
// Insert chunks
const chunks = await db.all(
"SELECT * FROM chunks WHERE path = ? AND cacheKey = ?",
@ -68,7 +67,7 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
[item.path, chunk.content],
);
await db.run(
`INSERT INTO fts_metadata (id, path, cacheKey, chunkId)
`INSERT INTO fts_metadata (id, path, cacheKey, chunkId)
VALUES (?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
path = excluded.path,

View file

@ -20,10 +20,10 @@ The indexing process does the following:
All indexes must be returned by `getIndexesToBuild` in [`CodebaseIndexer.ts`](./CodebaseIndexer.ts) if they are to be used.
`CodeSnippetsCodebaseIndex`: uses tree-sitter queries to get a list of functions, classes, and other top-level code objects in each file
`CodeSnippetsIndex`: uses tree-sitter queries to get a list of functions, classes, and other top-level code objects in each file
`FullTextSearchCodebaseIndex`: creates a full-text search index using SQLite FTS5
`ChunkCodebaseIndex`: chunks files recursively by code structure, for use in other embeddings providers like `LanceDbCodebaseIndex`
`LanceDbCodebaseIndex`: calculates embeddings for each chunk and adds them to the LanceDB vector database, with metadata going into SQLite. Note that for each branch, a unique table is created in LanceDB.
`ChunkCodebaseIndex`: chunks files recursively by code structure, for use in other embeddings providers like `LanceDbIndex`
`LanceDbIndex`: calculates embeddings for each chunk and adds them to the LanceDB vector database, with metadata going into SQLite. Note that for each branch, a unique table is created in LanceDB.
## Known problems

View file

@ -981,17 +981,11 @@ export default class DocsService {
// Otherwise sync the index based on config changes
const oldConfigDocs = oldConfig?.docs || [];
const newConfigDocs = newConfig.docs || [];
const newConfigStartUrls = newConfigDocs.map((doc) => doc.startUrl);
// NOTE since listMetadata filters by embeddings provider id embedding model changes are accounted for here
const currentlyIndexedDocs = await this.listMetadata();
const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl);
// Anything found in sqlite but not in new config should be deleted
const deletedDocs = currentlyIndexedDocs.filter(
(doc) => !newConfigStartUrls.includes(doc.startUrl),
);
// Anything found in old config, new config, AND sqlite that doesn't match should be reindexed
// TODO if only favicon and title change, only update, don't embed
// Otherwise anything found in new config that isn't in sqlite should be added/indexed
@ -1038,10 +1032,6 @@ export default class DocsService {
...changedDocs.map((doc) => this.indexAndAdd(doc, true)),
...addedDocs.map((doc) => this.indexAndAdd(doc)),
]);
for (const doc of deletedDocs) {
await this.deleteIndexes(doc.startUrl);
}
} catch (e) {
console.error("Error syncing docs index on config update", e);
} finally {

View file

@ -187,7 +187,8 @@ function autodetectTemplateType(model: string): TemplateType | undefined {
lower.includes("gemini") ||
lower.includes("grok") ||
lower.includes("moonshot") ||
lower.includes("mercury")
lower.includes("mercury") ||
/^o\d/.test(lower)
) {
return undefined;
}

View file

@ -0,0 +1,190 @@
import { expect, test } from "vitest";
import { autodetectTemplateType } from "./autodetect";
test("autodetectTemplateType returns 'codellama-70b' for CodeLlama 70B models", () => {
expect(autodetectTemplateType("codellama-70b")).toBe("codellama-70b");
expect(autodetectTemplateType("CodeLlama-70B")).toBe("codellama-70b");
expect(autodetectTemplateType("codellama-70b-instruct")).toBe(
"codellama-70b",
);
expect(autodetectTemplateType("CodeLlama-70B-Python")).toBe("codellama-70b");
});
test("autodetectTemplateType returns undefined for models that don't need templates", () => {
expect(autodetectTemplateType("gpt-4")).toBe(undefined);
expect(autodetectTemplateType("gpt-3.5-turbo")).toBe(undefined);
expect(autodetectTemplateType("GPT-4")).toBe(undefined);
expect(autodetectTemplateType("command-r")).toBe(undefined);
expect(autodetectTemplateType("aya-23")).toBe(undefined);
expect(autodetectTemplateType("chat-bison")).toBe(undefined);
expect(autodetectTemplateType("pplx-70b")).toBe(undefined);
expect(autodetectTemplateType("gemini-pro")).toBe(undefined);
expect(autodetectTemplateType("grok-beta")).toBe(undefined);
expect(autodetectTemplateType("moonshot-v1")).toBe(undefined);
expect(autodetectTemplateType("mercury-chat")).toBe(undefined);
expect(autodetectTemplateType("mercury-chat")).toBe(undefined);
expect(autodetectTemplateType("o3-mini")).toBe(undefined);
expect(autodetectTemplateType("o4")).toBe(undefined);
expect(autodetectTemplateType("claude-sonnet-4-20250514")).toBe("none");
expect(autodetectTemplateType("claude-3-7-sonnet-latest")).toBe("none");
});
test("autodetectTemplateType returns 'llama3' for Llama 3 models", () => {
expect(autodetectTemplateType("llama3")).toBe("llama3");
expect(autodetectTemplateType("llama-3")).toBe("llama3");
expect(autodetectTemplateType("Llama3-8B")).toBe("llama3");
expect(autodetectTemplateType("llama-3:70b")).toBe("llama3");
});
test("autodetectTemplateType returns 'llava' for LLaVA models", () => {
expect(autodetectTemplateType("llava")).toBe("llava");
expect(autodetectTemplateType("LLaVA")).toBe("llava");
expect(autodetectTemplateType("llava-1.5")).toBe("llava");
expect(autodetectTemplateType("llava-v1.6")).toBe("llava");
});
test("autodetectTemplateType returns 'zephyr' for TinyLlama models", () => {
expect(autodetectTemplateType("tinyllama")).toBe("zephyr");
expect(autodetectTemplateType("TinyLlama")).toBe("zephyr");
expect(autodetectTemplateType("tinyllama-1.1b")).toBe("zephyr");
});
test("autodetectTemplateType returns 'xwin-coder' for XWin models", () => {
expect(autodetectTemplateType("xwin")).toBe("xwin-coder");
expect(autodetectTemplateType("XWin")).toBe("xwin-coder");
expect(autodetectTemplateType("xwin-coder")).toBe("xwin-coder");
});
test("autodetectTemplateType returns 'chatml' for Dolphin models", () => {
expect(autodetectTemplateType("dolphin")).toBe("chatml");
expect(autodetectTemplateType("Dolphin")).toBe("chatml");
expect(autodetectTemplateType("dolphin-2.1")).toBe("chatml");
});
test("autodetectTemplateType returns 'gemma' for Gemma models", () => {
expect(autodetectTemplateType("gemma")).toBe("gemma");
expect(autodetectTemplateType("Gemma")).toBe("gemma");
expect(autodetectTemplateType("gemma-7b")).toBe("gemma");
});
test("autodetectTemplateType returns 'phi2' for Phi-2 models", () => {
expect(autodetectTemplateType("phi2")).toBe("phi2");
expect(autodetectTemplateType("Phi2")).toBe("phi2");
expect(autodetectTemplateType("microsoft-phi2")).toBe("phi2");
});
test("autodetectTemplateType returns 'phind' for Phind models", () => {
expect(autodetectTemplateType("phind")).toBe("phind");
expect(autodetectTemplateType("Phind")).toBe("phind");
expect(autodetectTemplateType("phind-codellama")).toBe("phind");
});
test("autodetectTemplateType returns 'llama2' for general Llama models", () => {
expect(autodetectTemplateType("llama")).toBe("llama2");
expect(autodetectTemplateType("Llama")).toBe("llama2");
expect(autodetectTemplateType("llama2")).toBe("llama2");
expect(autodetectTemplateType("llama-2")).toBe("llama2");
expect(autodetectTemplateType("codellama")).toBe("llama2");
});
test("autodetectTemplateType returns 'zephyr' for Zephyr models", () => {
expect(autodetectTemplateType("zephyr")).toBe("zephyr");
expect(autodetectTemplateType("Zephyr")).toBe("zephyr");
expect(autodetectTemplateType("zephyr-7b")).toBe("zephyr");
});
test("autodetectTemplateType returns 'none' for Claude models", () => {
expect(autodetectTemplateType("claude")).toBe("none");
expect(autodetectTemplateType("Claude")).toBe("none");
expect(autodetectTemplateType("claude-3")).toBe("none");
expect(autodetectTemplateType("claude-3-opus")).toBe("none");
});
test("autodetectTemplateType returns 'none' for Codestral models", () => {
expect(autodetectTemplateType("codestral")).toBe("none");
expect(autodetectTemplateType("Codestral")).toBe("none");
expect(autodetectTemplateType("codestral-22b")).toBe("none");
});
test("autodetectTemplateType returns 'alpaca' for Alpaca and Wizard models", () => {
expect(autodetectTemplateType("alpaca")).toBe("alpaca");
expect(autodetectTemplateType("Alpaca")).toBe("alpaca");
expect(autodetectTemplateType("wizard")).toBe("alpaca");
expect(autodetectTemplateType("Wizard")).toBe("alpaca");
expect(autodetectTemplateType("wizardlm")).toBe("alpaca");
});
test("autodetectTemplateType returns 'llama2' for Mistral and Mixtral models", () => {
expect(autodetectTemplateType("mistral")).toBe("llama2");
expect(autodetectTemplateType("Mistral")).toBe("llama2");
expect(autodetectTemplateType("mixtral")).toBe("llama2");
expect(autodetectTemplateType("Mixtral")).toBe("llama2");
expect(autodetectTemplateType("mistral-7b")).toBe("llama2");
});
test("autodetectTemplateType returns 'deepseek' for DeepSeek models", () => {
expect(autodetectTemplateType("deepseek")).toBe("deepseek");
expect(autodetectTemplateType("DeepSeek")).toBe("deepseek");
expect(autodetectTemplateType("deepseek-coder")).toBe("deepseek");
});
test("autodetectTemplateType returns 'openchat' for Ninja and OpenChat models", () => {
expect(autodetectTemplateType("ninja")).toBe("openchat");
expect(autodetectTemplateType("Ninja")).toBe("openchat");
expect(autodetectTemplateType("openchat")).toBe("openchat");
expect(autodetectTemplateType("OpenChat")).toBe("openchat");
});
test("autodetectTemplateType returns 'neural-chat' for Neural Chat models", () => {
expect(autodetectTemplateType("neural-chat")).toBe("neural-chat");
expect(autodetectTemplateType("Neural-Chat")).toBe("neural-chat");
expect(autodetectTemplateType("intel-neural-chat")).toBe("neural-chat");
});
test("autodetectTemplateType returns 'granite' for Granite models", () => {
expect(autodetectTemplateType("granite")).toBe("granite");
expect(autodetectTemplateType("granite2:8b")).toBe("granite");
expect(autodetectTemplateType("Granite")).toBe("granite");
expect(autodetectTemplateType("granite-code")).toBe("granite");
});
test("autodetectTemplateType returns chatml for other models", () => {
expect(autodetectTemplateType("unknown-model")).toBe("chatml");
expect(autodetectTemplateType("random-ai")).toBe("chatml");
expect(autodetectTemplateType("")).toBe("chatml");
});
test("autodetectTemplateType handles case sensitivity correctly", () => {
expect(autodetectTemplateType("LLAMA3")).toBe("llama3");
expect(autodetectTemplateType("gpt-4")).toBe(undefined);
expect(autodetectTemplateType("GPT-4")).toBe(undefined);
expect(autodetectTemplateType("CLAUDE")).toBe("none");
});
test("autodetectTemplateType follows correct precedence order", () => {
// CodeLlama 70B should be detected before general llama
expect(autodetectTemplateType("codellama-70b")).toBe("codellama-70b");
// Llama3 should be detected before general llama
expect(autodetectTemplateType("llama3")).toBe("llama3");
// General llama should be detected after specific cases
expect(autodetectTemplateType("llama2")).toBe("llama2");
// TinyLlama should be detected as zephyr, not llama
expect(autodetectTemplateType("tinyllama")).toBe("zephyr");
});
test("autodetectTemplateType handles edge cases with special characters", () => {
expect(autodetectTemplateType("llama-3-8b-instruct")).toBe("llama3");
expect(autodetectTemplateType("gpt-4-turbo-preview")).toBe(undefined);
expect(autodetectTemplateType("claude-3-opus-20240229")).toBe("none");
expect(autodetectTemplateType("mistral-7b-instruct-v0.1")).toBe("llama2");
});
test("autodetectTemplateType handles models with mixed keywords", () => {
// Should match the first applicable pattern
expect(autodetectTemplateType("llama3-chat")).toBe("llama3"); // llama3 comes before general patterns
expect(autodetectTemplateType("gpt-llama")).toBe(undefined); // gpt comes first, returns undefined
expect(autodetectTemplateType("claude-llama")).toBe("llama2"); // llama comes first, returns llama2
});

View file

@ -1,187 +0,0 @@
import {
ChatHistoryItem,
ChatMessage,
ContextItemWithId,
RuleWithSource,
TextMessagePart,
ToolResultChatMessage,
UserChatMessage,
} from "../";
import { findLast } from "../util/findLast";
import { normalizeToMessageParts } from "../util/messageContent";
import { isUserOrToolMsg } from "./messages";
import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules";
import { RulePolicies } from "./rules/types";
export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL =
"https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts";
export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL =
"https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts";
export const CODEBLOCK_FORMATTING_INSTRUCTIONS = `\
Always include the language and file name in the info string when you write code blocks.
If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py'
`;
export const EDIT_CODE_INSTRUCTIONS = `\
When addressing code modification requests, present a concise code snippet that
emphasizes only the necessary changes and uses abbreviated placeholders for
unmodified sections. For example:
\`\`\`language /path/to/file
// ... existing code ...
{{ modified code here }}
// ... existing code ...
{{ another modification }}
// ... rest of code ...
\`\`\`
In existing files, you should always restate the function or class that the snippet belongs to:
\`\`\`language /path/to/file
// ... existing code ...
function exampleFunction() {
// ... existing code ...
{{ modified code here }}
// ... rest of function ...
}
// ... rest of code ...
\`\`\`
Since users have access to their complete file, they prefer reading only the
relevant modifications. It's perfectly acceptable to omit unmodified portions
at the beginning, middle, or end of files using these "lazy" comments. Only
provide the complete file when explicitly requested. Include a concise explanation
of changes unless the user specifically asks for code only.
`;
export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
<important_rules>
You are in chat mode.
If the user asks to make changes to files offer that they can use the Apply Button on the code block, or switch to Agent Mode to make the suggested updates automatically.
If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details.
${CODEBLOCK_FORMATTING_INSTRUCTIONS}
${EDIT_CODE_INSTRUCTIONS}
</important_rules>`;
export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\
<important_rules>
You are in agent mode.
${CODEBLOCK_FORMATTING_INSTRUCTIONS}
</important_rules>`;
/**
* Helper function to get the context items for a user message
*/
function getUserContextItems(
userMsg: UserChatMessage | ToolResultChatMessage | undefined,
history: ChatHistoryItem[],
): ContextItemWithId[] {
if (!userMsg) return [];
// Find the history item that contains the userMsg
const historyItem = history.find((item) => {
// Check if the message ID matches
if ("id" in userMsg && "id" in item.message) {
return (item.message as any).id === (userMsg as any).id;
}
// Fallback to content comparison
return (
item.message.content === userMsg.content &&
item.message.role === userMsg.role
);
});
return historyItem?.contextItems || [];
}
export function constructMessages(
messageMode: string,
history: ChatHistoryItem[],
baseChatOrAgentSystemMessage: string | undefined,
rules: RuleWithSource[],
rulePolicies?: RulePolicies,
): ChatMessage[] {
const filteredHistory = history.filter(
(item) => item.message.role !== "system",
);
const msgs: ChatMessage[] = [];
for (let i = 0; i < filteredHistory.length; i++) {
const historyItem = filteredHistory[i];
if (messageMode === "chat") {
const toolMessage: ToolResultChatMessage =
historyItem.message as ToolResultChatMessage;
if (historyItem.toolCallState?.toolCallId || toolMessage.toolCallId) {
// remove all tool calls from the history
continue;
}
}
if (historyItem.message.role === "user") {
// Gather context items for user messages
let content = normalizeToMessageParts(historyItem.message);
const ctxItems = historyItem.contextItems
.map((ctxItem) => {
return {
type: "text",
text: `${ctxItem.content}\n`,
} as TextMessagePart;
})
.filter((part) => !!part.text.trim());
content = [...ctxItems, ...content];
msgs.push({
...historyItem.message,
content,
});
} else {
msgs.push(historyItem.message);
}
}
const lastUserMsg = findLast(msgs, isUserOrToolMsg) as
| UserChatMessage
| ToolResultChatMessage
| undefined;
// Get context items for the last user message
const lastUserContextItems = getUserContextItems(
lastUserMsg,
filteredHistory,
);
const systemMessage = getSystemMessageWithRules({
baseSystemMessage: baseChatOrAgentSystemMessage,
rules,
userMessage: lastUserMsg,
contextItems: lastUserContextItems,
rulePolicies,
});
if (systemMessage.trim()) {
msgs.unshift({
role: "system",
content: systemMessage,
});
}
// Remove the "id" from all of the messages
return msgs.map((msg) => {
const { id, ...rest } = msg as any;
return rest;
});
}

View file

@ -0,0 +1,68 @@
export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL =
"https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts";
export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL =
"https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts";
export const CODEBLOCK_FORMATTING_INSTRUCTIONS = `\
Always include the language and file name in the info string when you write code blocks.
If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py'
`;
export const EDIT_CODE_INSTRUCTIONS = `\
When addressing code modification requests, present a concise code snippet that
emphasizes only the necessary changes and uses abbreviated placeholders for
unmodified sections. For example:
\`\`\`language /path/to/file
// ... existing code ...
{{ modified code here }}
// ... existing code ...
{{ another modification }}
// ... rest of code ...
\`\`\`
In existing files, you should always restate the function or class that the snippet belongs to:
\`\`\`language /path/to/file
// ... existing code ...
function exampleFunction() {
// ... existing code ...
{{ modified code here }}
// ... rest of function ...
}
// ... rest of code ...
\`\`\`
Since users have access to their complete file, they prefer reading only the
relevant modifications. It's perfectly acceptable to omit unmodified portions
at the beginning, middle, or end of files using these "lazy" comments. Only
provide the complete file when explicitly requested. Include a concise explanation
of changes unless the user specifically asks for code only.
`;
export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
<important_rules>
You are in chat mode.
If the user asks to make changes to files offer that they can use the Apply Button on the code block, or switch to Agent Mode to make the suggested updates automatically.
If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details.
${CODEBLOCK_FORMATTING_INSTRUCTIONS}
${EDIT_CODE_INSTRUCTIONS}
</important_rules>`;
export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\
<important_rules>
You are in agent mode.
${CODEBLOCK_FORMATTING_INSTRUCTIONS}
</important_rules>`;

View file

@ -384,6 +384,50 @@ export abstract class BaseLLM implements ILLM {
}
}
private async parseError(resp: any): Promise<Error> {
let text = await resp.text();
if (resp.status === 404 && !resp.url.includes("/v1")) {
const parsedError = JSON.parse(text);
const errorMessageRaw = parsedError?.error ?? parsedError?.message;
const error =
typeof errorMessageRaw === "string"
? errorMessageRaw.replace(/"/g, "'")
: undefined;
let model = error?.match(/model '(.*)' not found/)?.[1];
if (model && resp.url.match("127.0.0.1:11434")) {
text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`;
return new LLMError(text, this); // No need to add HTTP status details
} else if (text.includes("/api/chat")) {
text =
"The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue.";
} else {
text =
"This may mean that you forgot to add '/v1' to the end of your 'apiBase' in config.json.";
}
} else if (resp.status === 404 && resp.url.includes("api.openai.com")) {
text =
"You may need to add pre-paid credits before using the OpenAI API.";
} else if (
resp.status === 401 &&
(resp.url.includes("api.mistral.ai") ||
resp.url.includes("codestral.mistral.ai"))
) {
if (resp.url.includes("codestral.mistral.ai")) {
return new Error(
"You are using a Mistral API key, which is not compatible with the Codestral API. Please either obtain a Codestral API key, or use the Mistral API by setting 'apiBase' to 'https://api.mistral.ai/v1' in config.json.",
);
} else {
return new Error(
"You are using a Codestral API key, which is not compatible with the Mistral API. Please either obtain a Mistral API key, or use the the Codestral API by setting 'apiBase' to 'https://codestral.mistral.ai/v1' in config.json.",
);
}
}
return new Error(
`HTTP ${resp.status} ${resp.statusText} from ${resp.url}\n\n${text}`,
);
}
fetch(url: RequestInfo | URL, init?: RequestInit): Promise<Response> {
// Custom Node.js fetch
const customFetch = async (input: URL | RequestInfo, init: any) => {
@ -399,44 +443,9 @@ export abstract class BaseLLM implements ILLM {
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, "'");
let model = error?.match(/model '(.*)' not found/)?.[1];
if (model && resp.url.match("127.0.0.1:11434")) {
text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`;
throw new LLMError(text, this); // No need to add HTTP status details
} else if (text.includes("/api/chat")) {
text =
"The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue.";
} else {
text =
"This may mean that you forgot to add '/v1' to the end of your 'apiBase' in config.json.";
}
} else if (
resp.status === 404 &&
resp.url.includes("api.openai.com")
) {
text =
"You may need to add pre-paid credits before using the OpenAI API.";
} else if (
resp.status === 401 &&
(resp.url.includes("api.mistral.ai") ||
resp.url.includes("codestral.mistral.ai"))
) {
if (resp.url.includes("codestral.mistral.ai")) {
throw new Error(
"You are using a Mistral API key, which is not compatible with the Codestral API. Please either obtain a Codestral API key, or use the Mistral API by setting 'apiBase' to 'https://api.mistral.ai/v1' in config.json.",
);
} else {
throw new Error(
"You are using a Codestral API key, which is not compatible with the Mistral API. Please either obtain a Mistral API key, or use the the Codestral API by setting 'apiBase' to 'https://codestral.mistral.ai/v1' in config.json.",
);
}
}
throw new Error(
`HTTP ${resp.status} ${resp.statusText} from ${resp.url}\n\n${text}`,
);
const error = await this.parseError(resp);
throw error;
}
return resp;

View file

@ -1,12 +1,10 @@
import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime";
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
import Bedrock from "./Bedrock.js";
import {
ChatMessage,
Chunk,
CompletionOptions,
UserChatMessage,
} from "../../index.js";
import Bedrock from "./Bedrock.js";
// Mock AWS SDK
jest.mock("@aws-sdk/client-bedrock-runtime", () => ({
@ -317,96 +315,266 @@ describe("Bedrock", () => {
});
});
it("should convert text messages correctly", () => {
const message: ChatMessage = {
role: "user",
content: "Hello",
} as UserChatMessage;
const converted = bedrock["_convertMessage"](message);
expect(converted).toEqual({
role: "user",
content: [{ text: "Hello" }],
});
it("should convert simple user and assistant messages correctly", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "Hello" } as UserChatMessage,
{ role: "assistant", content: "Hi there" },
];
const availableTools = new Set<string>();
const converted = bedrock["_convertMessages"](messages, availableTools);
expect(converted).toEqual([
{ role: "user", content: [{ text: "Hello" }] },
{ role: "assistant", content: [{ text: "Hi there" }] },
]);
});
it("should convert tool responses correctly", () => {
const message: ChatMessage = {
role: "tool",
content: "Tool result",
toolCallId: "tool-1",
};
const converted = bedrock["_convertMessage"](message);
expect(converted).toEqual({
role: "user",
content: [
{
toolResult: {
toolUseId: "tool-1",
content: [{ text: "Tool result" }],
},
},
],
});
});
it("should convert tool calls correctly", () => {
const message: ChatMessage = {
role: "assistant",
content: "",
toolCalls: [
{
id: "tool-1",
type: "function" as const,
function: {
name: "test_tool",
arguments: '{"arg":"value"}',
},
},
],
};
const converted = bedrock["_convertMessage"](message);
expect(converted).toEqual({
role: "assistant",
content: [
{
toolUse: {
toolUseId: "tool-1",
name: "test_tool",
input: { arg: "value" },
},
},
],
});
});
it("should handle multimodal content correctly", () => {
const message: ChatMessage = {
role: "user",
content: [
{ type: "text", text: "Look at this image:" },
{
type: "imageUrl",
imageUrl: {
url: "data:image/jpeg;base64,/9j/4AAQSkZJRg==",
},
},
],
} as UserChatMessage;
const converted = bedrock["_convertMessage"](message);
expect(converted).toEqual({
role: "user",
content: [
{ text: "Look at this image:" },
{
image: {
format: "jpeg",
source: {
bytes: Buffer.from("/9j/4AAQSkZJRg==", "base64"),
it("should handle tool responses correctly", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "Use a tool" } as UserChatMessage,
{
role: "assistant",
content: "",
toolCalls: [
{
id: "tool-1",
type: "function",
function: {
name: "test_tool",
arguments: '{"arg":"value"}',
},
},
},
],
],
},
{
role: "tool",
content: "Tool result",
toolCallId: "tool-1",
},
];
const availableTools = new Set(["test_tool"]);
const converted = bedrock["_convertMessages"](messages, availableTools);
expect(converted).toEqual([
{ role: "user", content: [{ text: "Use a tool" }] },
{
role: "assistant",
content: [
{
toolUse: {
toolUseId: "tool-1",
name: "test_tool",
input: { arg: "value" },
},
},
],
},
{
role: "user",
content: [
{
toolResult: {
toolUseId: "tool-1",
content: [{ text: "Tool result" }],
},
},
],
},
]);
});
it("should handle tool calls with unavailable tools as text", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "Use a tool" } as UserChatMessage,
{
role: "assistant",
content: "",
toolCalls: [
{
id: "tool-1",
type: "function",
function: {
name: "unavailable_tool",
arguments: '{"arg":"value"}',
},
},
],
},
];
// Empty set means no tools are available
const availableTools = new Set<string>();
const converted = bedrock["_convertMessages"](messages, availableTools);
expect(converted).toEqual([
{ role: "user", content: [{ text: "Use a tool" }] },
{
role: "assistant",
content: [
{
text: expect.stringContaining("Assistant tool call:"),
},
],
},
]);
});
it("should handle thinking messages correctly", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "Think about this" } as UserChatMessage,
{ role: "thinking", content: "I am thinking about the solution" },
{ role: "assistant", content: "Here's my answer" },
];
const availableTools = new Set<string>();
const converted = bedrock["_convertMessages"](messages, availableTools);
expect(converted).toEqual([
{ role: "user", content: [{ text: "Think about this" }] },
{
role: "assistant",
content: [
{
reasoningContent: {
reasoningText: {
text: "I am thinking about the solution",
signature: undefined,
},
},
},
{ text: "Here's my answer" },
],
},
]);
});
it("should handle redacted thinking messages", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "Think about this" } as UserChatMessage,
{
role: "thinking",
content: "",
redactedThinking: "redacted-content-bytes",
},
{ role: "assistant", content: "Here's my answer" },
];
const availableTools = new Set<string>();
const converted = bedrock["_convertMessages"](messages, availableTools);
expect(converted).toEqual([
{ role: "user", content: [{ text: "Think about this" }] },
{
role: "assistant",
content: [
{
reasoningContent: {
redactedContent: expect.any(Uint8Array),
},
},
{ text: "Here's my answer" },
],
},
]);
// Check that the Uint8Array contains the expected bytes
const redactedContent =
converted[1].content?.[0].reasoningContent?.redactedContent;
expect(redactedContent).toBeInstanceOf(Uint8Array);
expect(Buffer.from(redactedContent!).toString()).toBe(
"redacted-content-bytes",
);
});
it("should convert multimodal content correctly", () => {
const messages: ChatMessage[] = [
{
role: "user",
content: [
{ type: "text", text: "Look at this image:" },
{
type: "imageUrl",
imageUrl: {
url: "data:image/jpeg;base64,/9j/4AAQSkZJRg==",
},
},
],
} as UserChatMessage,
];
const availableTools = new Set<string>();
const converted = bedrock["_convertMessages"](messages, availableTools);
expect(converted).toEqual([
{
role: "user",
content: [
{ text: "Look at this image:" },
{
image: {
format: "jpeg",
source: {
bytes: expect.any(Uint8Array),
},
},
},
],
},
]);
// Check that the image bytes were processed correctly
const imageBytes = converted[0].content?.[1].image?.source?.bytes;
expect(imageBytes).toBeInstanceOf(Uint8Array);
expect(Buffer.from(imageBytes!).toString("base64")).toBe(
"/9j/4AAQSkZJRg==",
);
});
it("should add cache points for prompt caching when needed", () => {
// Create a test instance with caching behavior enabled
const bedrockWithCaching = new TestBedrock({
apiKey: "test-key",
model: "anthropic.claude-3-sonnet-20240229-v1:0",
region: "us-east-1",
});
// Set caching behavior
bedrockWithCaching.cacheBehavior = {
cacheConversation: true,
cacheSystemMessage: true,
};
const messages: ChatMessage[] = [
{ role: "system", content: "You are a helpful assistant" },
{ role: "user", content: "First message" } as UserChatMessage,
{ role: "assistant", content: "First response" },
{ role: "user", content: "Second message" } as UserChatMessage,
];
const availableTools = new Set<string>();
const converted = bedrockWithCaching["_convertMessages"](
messages,
availableTools,
);
// The last two user messages should have cache points
// But we're not testing the system message here since it's handled separately
expect(converted.length).toBe(3);
expect(converted[0].role).toBe("user");
expect(converted[0].content?.some((block) => block.cachePoint)).toBe(
true,
);
expect(converted[1].role).toBe("assistant");
expect(converted[2].role).toBe("user");
expect(converted[2].content?.some((block) => block.cachePoint)).toBe(
true,
);
// Verify that text content includes a cache ID suffix
const userMessageText = converted[0].content?.[0].text;
expect(userMessageText).toMatch(/First message.+/);
});
});
});

View file

@ -1,8 +1,10 @@
import {
BedrockRuntimeClient,
ContentBlock,
ConversationRole,
ConverseStreamCommand,
ConverseStreamCommandOutput,
ImageFormat,
InvokeModelCommand,
Message,
ToolConfiguration,
@ -14,6 +16,7 @@ import {
Chunk,
CompletionOptions,
LLMOptions,
MessageContent,
} from "../../index.js";
import { safeParseToolCallArgs } from "../../tools/parseArgs.js";
import { renderChatMessage, stripImages } from "../../util/messageContent.js";
@ -289,8 +292,8 @@ class Bedrock extends BaseLLM {
const systemMessage = stripImages(
messages.find((m) => m.role === "system")?.content ?? "",
);
const convertedMessages = this._convertMessages(messages);
// Prompt and system message caching settings
const shouldCacheSystemMessage =
(!!systemMessage && this.cacheBehavior?.cacheSystemMessage) ||
this.completionOptions.promptCaching;
@ -298,9 +301,7 @@ class Bedrock extends BaseLLM {
shouldCacheSystemMessage ||
this.cacheBehavior?.cacheConversation ||
this.completionOptions.promptCaching;
const shouldCacheToolsConfig = this.completionOptions.promptCaching;
// Add header for prompt caching
if (enablePromptCaching) {
this.requestOptions.headers = {
...this.requestOptions.headers,
@ -308,30 +309,37 @@ class Bedrock extends BaseLLM {
};
}
// First get tools
const supportsTools =
(this.capabilities?.tools ||
PROVIDER_TOOL_SUPPORT.bedrock?.(options.model)) ??
false;
let toolConfig =
supportsTools && options.tools
? ({
tools: options.tools.map((tool) => ({
toolSpec: {
name: tool.function.name,
description: tool.function.description,
inputSchema: {
json: tool.function.parameters,
},
},
})),
} as ToolConfiguration)
: undefined;
if (toolConfig?.tools && shouldCacheToolsConfig) {
toolConfig.tools.push({ cachePoint: { type: "default" } });
let toolConfig: undefined | ToolConfiguration = undefined;
const availableTools = new Set<string>();
if (supportsTools && options.tools && options.tools.length > 0) {
toolConfig = {
tools: options.tools.map((tool) => ({
toolSpec: {
name: tool.function.name,
description: tool.function.description,
inputSchema: {
json: tool.function.parameters,
},
},
})),
} as ToolConfiguration;
const shouldCacheToolsConfig = this.completionOptions.promptCaching;
if (shouldCacheToolsConfig) {
toolConfig.tools!.push({ cachePoint: { type: "default" } });
}
options.tools.forEach((tool) => {
availableTools.add(tool.function.name);
});
}
const convertedMessages = this._convertMessages(messages, availableTools);
return {
modelId: options.model,
system: systemMessage
@ -368,167 +376,236 @@ class Bedrock extends BaseLLM {
};
}
private _convertMessage(
message: ChatMessage,
addCaching: boolean = false,
): Message | null {
// Handle system messages explicitly
if (message.role === "system") {
return null;
}
/*
Converts the messages to the format expected by the Bedrock API.
*/
private _convertMessages(
messages: ChatMessage[],
availableTools: Set<string>,
): Message[] {
let currentRole: "user" | "assistant" = "user";
let currentBlocks: ContentBlock[] = [];
const cachePoint = addCaching
? { cachePoint: { type: "default" } }
: undefined;
// Tool response handling
if (message.role === "tool") {
return {
role: "user",
content: [
{
toolResult: {
toolUseId: message.toolCallId,
content: [
{
text: message.content || "",
},
],
},
},
],
};
}
// Tool calls handling
if (message.role === "assistant" && message.toolCalls) {
return {
role: "assistant",
content: message.toolCalls.map((toolCall) => ({
toolUse: {
toolUseId: toolCall.id,
name: toolCall.function?.name,
input: safeParseToolCallArgs(toolCall),
},
})),
};
}
if (message.role === "thinking") {
if (message.redactedThinking) {
const content: ContentBlock.ReasoningContentMember = {
reasoningContent: {
redactedContent: new Uint8Array(
Buffer.from(message.redactedThinking),
),
},
};
return {
role: "assistant",
content: [content],
};
} else {
const content: ContentBlock.ReasoningContentMember = {
reasoningContent: {
reasoningText: {
text: (message.content as string) || "",
signature: message.signature,
},
},
};
return {
role: "assistant",
content: [content],
};
const converted: Message[] = [];
const pushCurrentMessage = () => {
if (currentBlocks.length === 0 && converted.length > 1) {
throw new Error(
`Bedrock: no content in ${currentRole} message before conversational turn change`,
);
}
}
// Standard text message
if (typeof message.content === "string") {
if (addCaching) {
message.content += getSecureID();
if (currentBlocks.length > 0) {
converted.push({
role: currentRole,
content: currentBlocks,
});
}
const content: any[] = [{ text: message.content }];
if (addCaching) {
content.push({ cachePoint: { type: "default" } });
}
return {
role: message.role,
content,
};
}
currentBlocks = [];
};
// Improved multimodal content handling
if (Array.isArray(message.content)) {
const content: any[] = [];
const nonSystemMessages = messages.filter((m) => m.role !== "system");
const hasAddedToolCallIds = new Set<string>();
// Process all parts first
message.content.forEach((part) => {
if (part.type === "text") {
if (addCaching) {
part.text += getSecureID();
for (let idx = 0; idx < nonSystemMessages.length; idx++) {
const message = nonSystemMessages[idx];
if (message.role === "user" || message.role === "tool") {
// Detect conversational turn change
if (currentRole !== ConversationRole.USER) {
pushCurrentMessage();
currentRole = ConversationRole.USER;
}
// USER messages:
// Non-empty user message content is converted to "text" and "image" blocks
// If ANY user message part is cached, we add a single cache point block when we push the message
if (message.role === "user") {
const trimmedContent =
typeof message.content === "string"
? message.content.trim()
: message.content;
if (trimmedContent) {
currentBlocks.push(
...this._convertMessageContentToBlocks(trimmedContent),
);
}
content.push({ text: part.text });
}
// TOOL messages:
// Tool messages are represented by "toolResult" blocks
// toolResult blocks must follow valid toolUse blocks (which also verifies that the tool name is present in toolConfig)
// If it doesn't, we convert it to a text block
else if (message.role === "tool") {
const trimmedContent = message.content.trim() || "No tool output";
if (hasAddedToolCallIds.has(message.toolCallId)) {
currentBlocks.push({
toolResult: {
toolUseId: message.toolCallId,
content: [
{
text: trimmedContent,
},
],
},
});
} else {
currentBlocks.push({
text: `Tool call output for Tool Call ID ${message.toolCallId}:\n\n${trimmedContent}`,
});
}
}
} else if (message.role === "assistant" || message.role === "thinking") {
// Detect conversational turn change
if (currentRole !== ConversationRole.ASSISTANT) {
pushCurrentMessage();
currentRole = ConversationRole.ASSISTANT;
}
// ASSISTANT messages:
// Non-empty assistant message content is converted to "text" and "image" blocks
if (message.role === "assistant") {
const trimmedContent =
typeof message.content === "string"
? message.content.trim()
: message.content;
if (trimmedContent) {
currentBlocks.push(
...this._convertMessageContentToBlocks(trimmedContent),
);
}
// TOOL CALLS:
// Tool calls are represented by "toolUse" blocks
// Each tool call must have an id and a function name
// The function name must match one of the available tools
// Otherwise, we will convert it to a text block (e.g. Chat mode will pass no tools)
if (message.toolCalls) {
for (const toolCall of message.toolCalls) {
if (toolCall.id && toolCall.function?.name) {
if (availableTools.has(toolCall.function.name)) {
currentBlocks.push({
toolUse: {
toolUseId: toolCall.id,
name: toolCall.function.name,
input: safeParseToolCallArgs(toolCall),
},
});
hasAddedToolCallIds.add(toolCall.id);
} else {
const toolCallText = `Assistant tool call:\nTool name: ${toolCall.function.name}\nTool Call ID: ${toolCall.id}\nArguments: ${toolCall.function?.arguments ?? "{}"}`;
currentBlocks.push({
text: toolCallText,
});
}
} else {
console.warn(
`Bedrock: tool call missing id or name, skipping tool call: ${JSON.stringify(toolCall)}`,
);
continue;
}
}
}
} else if (message.role === "thinking") {
// THINKING:
// Thinking messages are represented by "reasoningContent" blocks which can have redacted content or reasoning content
if (message.redactedThinking) {
const block: ContentBlock.ReasoningContentMember = {
reasoningContent: {
redactedContent: new Uint8Array(
Buffer.from(message.redactedThinking),
),
},
};
currentBlocks.push(block);
} else {
const block: ContentBlock.ReasoningContentMember = {
reasoningContent: {
reasoningText: {
text: (message.content as string) || "",
signature: message.signature,
},
},
};
currentBlocks.push(block);
}
}
}
}
if (currentBlocks.length > 0) {
pushCurrentMessage();
}
// If caching is enabled, we add cache_control parameter to the last two user messages
// The second-to-last because it retrieves potentially already cached contents,
// The last one because we want it cached for later retrieval.
// See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html
if (this.cacheBehavior?.cacheConversation) {
this._addCachingToLastTwoUserMessages(converted);
}
return converted;
}
private _addCachingToLastTwoUserMessages(converted: Message[]) {
let numCached = 0;
for (let i = converted.length - 1; i >= 0; i--) {
const message = converted[i];
if (message.role === "user") {
message.content?.forEach((block) => {
if (block.text) {
block.text += getSecureID();
}
});
message.content?.push({ cachePoint: { type: "default" } });
numCached++;
}
if (numCached === 2) {
break;
}
}
}
// Converts Continue message content (string/parts) to Bedrock ContentBlock format.
// Unsupported/problematic image formats are skipped with a warning.
private _convertMessageContentToBlocks(
content: MessageContent,
): ContentBlock[] {
const blocks: ContentBlock[] = [];
if (typeof content === "string") {
blocks.push({ text: content });
} else {
for (const part of content) {
if (part.type === "text") {
blocks.push({ text: part.text });
} else if (part.type === "imageUrl" && part.imageUrl) {
try {
const [mimeType, base64Data] = part.imageUrl.url.split(",");
const format = mimeType.split("/")[1]?.split(";")[0] || "jpeg";
content.push({
image: {
format,
source: {
bytes: Buffer.from(base64Data, "base64"),
if (
format === ImageFormat.JPEG ||
format === ImageFormat.PNG ||
format === ImageFormat.WEBP ||
format === ImageFormat.GIF
) {
blocks.push({
image: {
format,
source: {
bytes: Uint8Array.from(Buffer.from(base64Data, "base64")),
},
},
},
});
});
} else {
console.warn(
`Bedrock: skipping unsupported image part format: ${format}`,
part,
);
}
} catch (error) {
console.warn(`Failed to process image: ${error}`);
console.warn("Bedrock: failed to process image part", error, part);
}
}
});
// Add cache point as a separate block at the end if needed
if (addCaching && content.length > 0) {
content.push({ cachePoint: { type: "default" } });
}
return {
role: message.role,
content,
} as Message;
}
return null;
}
private _convertMessages(messages: ChatMessage[]): any[] {
const filteredmessages = messages.filter(
(m) => m.role !== "system" && !!m.content,
);
const lastTwoUserMsgIndices = filteredmessages
.map((msg, index) => (msg.role === "user" ? index : -1))
.filter((index) => index !== -1)
.slice(-2);
const converted = filteredmessages
.map((message, filteredMsgIdx) => {
// Add cache_control parameter to the last two user messages
// The second-to-last because it retrieves potentially already cached contents,
// The last one because we want it cached for later retrieval.
// See: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html
const addCaching =
this.cacheBehavior?.cacheConversation &&
lastTwoUserMsgIndices.includes(filteredMsgIdx);
try {
return this._convertMessage(message, addCaching);
} catch (error) {
console.error(`Failed to convert message: ${error}`);
return null;
}
})
.filter(Boolean);
return converted;
return blocks;
}
private async _getCredentials() {

View file

@ -0,0 +1,57 @@
import { streamSse } from "@continuedev/fetch";
import { CompletionOptions, LLMOptions } from "../../index.js";
import { osModelsEditPrompt } from "../templates/edit.js";
import OpenAI from "./OpenAI.js";
class LlamaStack extends OpenAI {
static providerName = "llamastack";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "http://localhost:8321/v1/openai/v1/",
model: "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8",
promptTemplates: {
edit: osModelsEditPrompt,
},
useLegacyCompletionsEndpoint: false,
};
maxStopWords: number | undefined = 16;
supportsFim(): boolean {
return true;
}
async *_streamFim(
prefix: string,
suffix: string,
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
const endpoint = new URL("completions", this.apiBase);
const resp = await this.fetch(endpoint, {
method: "POST",
body: JSON.stringify({
model: options.model,
prompt: prefix,
suffix,
max_tokens: options.maxTokens,
temperature: options.temperature,
top_p: options.topP,
frequency_penalty: options.frequencyPenalty,
presence_penalty: options.presencePenalty,
stop: options.stop,
stream: true,
}),
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
signal,
});
for await (const chunk of streamSse(resp)) {
yield chunk.choices[0].text;
}
}
}
export default LlamaStack;

View file

@ -8,7 +8,7 @@ import {
LLMOptions,
} from "../..";
import { renderTemplatedString } from "../../util/handlebars/renderTemplatedString";
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../constructMessages";
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../defaultSystemMessages";
import { BaseLLM } from "../index";
import Anthropic from "./Anthropic";
import Asksage from "./Asksage";
@ -33,6 +33,7 @@ import Inception from "./Inception";
import Kindo from "./Kindo";
import LlamaCpp from "./LlamaCpp";
import Llamafile from "./Llamafile";
import LlamaStack from "./LlamaStack";
import LMStudio from "./LMStudio";
import Mistral from "./Mistral";
import MockLLM from "./Mock";
@ -62,7 +63,6 @@ import Vllm from "./Vllm";
import Voyage from "./Voyage";
import WatsonX from "./WatsonX";
import xAI from "./xAI";
export const LLMClasses = [
Anthropic,
Cohere,
@ -116,6 +116,7 @@ export const LLMClasses = [
Relace,
Inception,
Voyage,
LlamaStack,
];
export async function llmFromDescription(

View file

@ -327,27 +327,36 @@ export const getApplicableRules = (
export const getSystemMessageWithRules = ({
baseSystemMessage,
userMessage,
rules,
availableRules,
contextItems,
rulePolicies = {},
}: {
baseSystemMessage?: string;
userMessage: UserChatMessage | ToolResultChatMessage | undefined;
rules: RuleWithSource[];
availableRules: RuleWithSource[];
contextItems: ContextItemWithId[];
rulePolicies?: RulePolicies;
}) => {
const applicableRules = getApplicableRules(
}): {
systemMessage: string;
appliedRules: RuleWithSource[];
} => {
const appliedRules = getApplicableRules(
userMessage,
rules,
availableRules,
contextItems,
rulePolicies,
);
let systemMessage = baseSystemMessage ?? "";
for (const rule of applicableRules) {
systemMessage += `\n\n${rule.rule}`;
for (const rule of appliedRules) {
if (systemMessage) {
systemMessage += "\n\n";
}
systemMessage += rule.rule;
}
return systemMessage;
return {
systemMessage,
appliedRules,
};
};

View file

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

View file

@ -22,6 +22,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
"gpt-4",
"o3",
"gemini",
"claude-opus-4",
].some((part) => model.toLowerCase().startsWith(part));
},
anthropic: (model) => {
@ -32,6 +33,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
"claude-3-7",
"claude-3.7",
"claude-sonnet-4",
"claude-opus-4",
].some((part) => model.toLowerCase().startsWith(part))
) {
return true;
@ -86,15 +88,14 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
);
},
bedrock: (model) => {
// 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",
"claude-3-5-sonnet",
"claude-3.5-sonnet",
"claude-3-7-sonnet",
"claude-3.7-sonnet",
"claude-sonnet-4",
"claude-opus-4",
].some((part) => model.toLowerCase().includes(part))
) {
return true;
@ -179,7 +180,9 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
return false;
},
deepseek: (model) => {
if (model !== "deepseek-reasoner") {
// https://api-docs.deepseek.com/quick_start/pricing
// https://api-docs.deepseek.com/guides/function_calling
if (model === "deepseek-reasoner" || model === "deepseek-chat") {
return true;
}

View file

@ -0,0 +1,30 @@
import QuickLRU from "quick-lru";
export interface prevEdit {
unidiff: string;
fileUri: string;
workspaceUri: string;
timestamp: number;
}
const maxPrevEdits = 5;
export const prevEditLruCache = new QuickLRU<string, prevEdit>({
maxSize: maxPrevEdits,
});
export const setPrevEdit = (edit: prevEdit): void => {
const uniqueSuffix = Math.random().toString(36).substring(2, 8);
const key = `${edit.fileUri}:${edit.timestamp}:${uniqueSuffix}`;
prevEditLruCache.set(key, edit);
};
export const getPrevEditsDescending = (): prevEdit[] => {
const edits: prevEdit[] = [];
for (const [_, edit] of prevEditLruCache.entriesDescending()) {
if (edits.length >= maxPrevEdits) {
break;
}
edits.push(edit);
}
return edits;
};

View file

@ -5,6 +5,13 @@ import { ConfigHandler } from "../../config/ConfigHandler";
import { DataLogger } from "../../data/log";
import { RecentlyEditedRange } from "../types";
import { getAutocompleteContext } from "./autocompleteContextFetching";
import { createDiff, DiffFormatType } from "./diffFormatting";
import {
getPrevEditsDescending,
prevEdit,
prevEditLruCache,
setPrevEdit,
} from "./prevEditLruCache";
const randomNumberBetween = (min: number, max: number) => {
min = Math.ceil(min); // Ensure min is an integer
@ -27,6 +34,11 @@ interface ProcessNextEditDataParams {
modelNameOrInstance?: string | undefined;
}
interface filenameAndDiff {
filename: string;
diff: string;
}
export const processNextEditData = async ({
filePath,
beforeContent,
@ -48,7 +60,6 @@ export const processNextEditData = async ({
// undefined;
const modelName = "Codestral";
const maxPromptTokens = randomNumberBetween(500, 12000);
const autocompleteContext = await getAutocompleteContext(
@ -68,16 +79,64 @@ export const processNextEditData = async ({
// createDiff(beforeContent, afterContent, filePath, DiffFormatType.Unified),
// );
void DataLogger.getInstance().logDevData({
name: "nextEdit",
data: {
fileURI: filePath,
workspaceDirURI: workspaceDir,
let filenamesAndDiffs: filenameAndDiff[] = [];
const timestamp = Date.now();
let prevEdits: prevEdit[] = getPrevEditsDescending(); // edits from most to least recent
if (prevEdits.length > 0) {
// if last edit was 10+ minutes ago or the workspace changed, forget previous edits
if (
timestamp - prevEdits[0].timestamp >= 1000 * 60 * 10 ||
workspaceDir !== prevEdits[0].workspaceUri
) {
prevEditLruCache.clear();
prevEdits = [];
}
// extract filenames and diffs for logging
filenamesAndDiffs = prevEdits.map(
(edit) =>
({
// filename relative to workspace dir
filename: edit.fileUri
.replace(edit.workspaceUri, "")
.replace(/^[/\\]/, ""),
// diff without the first 4 lines (the file header)
diff: edit.unidiff.split("\n").slice(4).join("\n"),
}) as filenameAndDiff,
);
}
if (filenamesAndDiffs.length > 0) {
// if there are previous edits, log
void DataLogger.getInstance().logDevData({
name: "nextEditWithHistory",
data: {
previousEdits: filenamesAndDiffs,
fileURI: filePath,
workspaceDirURI: workspaceDir,
beforeContent,
afterContent,
beforeCursorPos: cursorPosBeforeEdit,
afterCursorPos: cursorPosAfterPrevEdit,
context: autocompleteContext,
},
});
}
// add current edit to history
const thisEdit: prevEdit = {
unidiff: createDiff(
beforeContent,
afterContent,
beforeCursorPos: cursorPosBeforeEdit,
afterCursorPos: cursorPosAfterPrevEdit,
context: autocompleteContext,
},
});
filePath,
DiffFormatType.Unified,
),
fileUri: filePath,
workspaceUri: workspaceDir,
timestamp: timestamp,
};
setPrevEdit(thisEdit);
};

View file

@ -112,3 +112,83 @@ export function getRenderableDiffWithGutterAnnotations(
},
};
}
/**
* Check if the diff is indeed a FIM.
* @param oldEditRange Original string content.
* @param newEditRange New string content.
* @param cursorPosition The position of the cursor in the old string.
* @returns boolean indicating if the change is purely additive (FIM)
* @returns string of FIM text content.
*/
export function checkFim(
oldEditRange: string,
newEditRange: string,
cursorPosition: { line: number; character: number },
):
| {
isFim: true;
fimText: string;
}
| {
isFim: false;
fimText: null;
} {
// Find the common prefix.
let prefixLength = 0;
while (
prefixLength < oldEditRange.length &&
prefixLength < newEditRange.length &&
oldEditRange[prefixLength] === newEditRange[prefixLength]
) {
prefixLength++;
}
// Find the common suffix
let oldSuffixPos = oldEditRange.length - 1;
let newSuffixPos = newEditRange.length - 1;
while (
oldSuffixPos >= prefixLength &&
newSuffixPos >= prefixLength &&
oldEditRange[oldSuffixPos] === newEditRange[newSuffixPos]
) {
oldSuffixPos--;
newSuffixPos--;
}
// The old text is purely preserved if:
// 1. The prefix ends before or at the cursor.
// 2. The suffix starts after or at the cursor.
// 3. There's no gap between prefix and suffix in the old text.
const suffixStartInOld = oldSuffixPos + 1;
const suffixStartInNew = newSuffixPos + 1;
// Convert cursor position to an offset in the string.
// For simplicity, we need to calculate the cursor's position in the string.
// This requires knowledge of line endings in the oldEditRange.
const lines = oldEditRange.substring(0, prefixLength).split("\n");
const cursorOffset =
lines.length > 1
? lines.slice(0, -1).reduce((sum, line) => sum + line.length + 1, 0) +
cursorPosition.character
: cursorPosition.character;
// Check if the cursor is positioned between the prefix and suffix.
const cursorBetweenPrefixAndSuffix =
prefixLength <= cursorOffset && cursorOffset <= suffixStartInOld;
// Check if the old text is completely preserved (no deletion).
const noTextDeleted = suffixStartInOld - prefixLength <= 0;
const isFim = cursorBetweenPrefixAndSuffix && noTextDeleted;
if (isFim) {
// Extract the content between prefix and suffix in the new string.
const fimText = newEditRange.substring(prefixLength, suffixStartInNew);
return { isFim, fimText };
} else {
return { isFim, fimText: null };
}
}

View file

@ -0,0 +1,92 @@
import { describe, expect, it } from "vitest";
import { checkFim } from "./diff";
describe("checkFim", () => {
const testCases = [
{
name: "simple insertion at cursor",
oldEditRange: ["function test() {", " ", "}"].join("\n"),
newEditRange: ["function test() {", " console.log('hello');", "}"].join(
"\n",
),
cursorPosition: { line: 1, character: 2 },
expected: {
isFim: true,
fimText: "console.log('hello');",
},
},
{
name: "not a FIM because insertion starts before { and new suffix is different from {}",
oldEditRange: ["function test() {}"].join("\n"),
newEditRange: ["function test() {console.log('test');}"].join("\n"),
cursorPosition: { line: 0, character: 16 },
expected: {
isFim: false,
fimText: null,
},
},
{
name: "insertion with cursor at beginning",
oldEditRange: ["function test() {}"].join("\n"),
newEditRange: ["function test() {console.log('test');}"].join("\n"),
cursorPosition: { line: 0, character: 17 },
expected: {
isFim: true,
fimText: "console.log('test');",
},
},
{
name: "not a FIM because text was deleted",
oldEditRange: ["function test() {", " return 42;", "}"].join("\n"),
newEditRange: ["function test() {", " console.log('hello');", "}"].join(
"\n",
),
cursorPosition: { line: 1, character: 2 },
expected: {
isFim: false,
fimText: null,
},
},
{
name: "not a FIM because text was changed before cursor",
oldEditRange: ["let x = 1;"].join("\n"),
newEditRange: ["const x = 1; // initialized x"].join("\n"),
cursorPosition: { line: 0, character: 8 },
expected: {
isFim: false,
fimText: null,
},
},
{
name: "multi-line insertion at cursor",
oldEditRange: [
"function process() {",
" ",
" return result;",
"}",
].join("\n"),
newEditRange: [
"function process() {",
" const data = fetchData();",
" const result = processData(data);",
" return result;",
"}",
].join("\n"),
cursorPosition: { line: 1, character: 2 },
expected: {
isFim: true,
fimText:
"const data = fetchData();\n const result = processData(data);",
},
},
];
testCases.forEach(
({ name, oldEditRange, newEditRange, cursorPosition, expected }) => {
it(name, () => {
const result = checkFim(oldEditRange, newEditRange, cursorPosition);
expect(result).toEqual(expected);
});
},
);
});

View file

@ -39,7 +39,7 @@ type NextEditModelName = "mercury-coder-nextedit" | "this field is not used";
const NEXT_EDIT_MODEL_TEMPLATES: Record<NextEditModelName, NextEditTemplate> = {
"mercury-coder-nextedit": {
template:
"### User Edits:\n\n{{{userEdits}}}\n\n### User Excerpts:\n\n\`\`\`{{{languageShorthand}}}\n{{{userExcerpts}}}\`\`\`",
"### User Edits:\n\n{{{userEdits}}}\n\n### User Excerpts:\n\n```{{{languageShorthand}}}\n{{{userExcerpts}}}```",
},
"this field is not used": {
template: "NEXT_EDIT",
@ -49,7 +49,7 @@ const NEXT_EDIT_MODEL_TEMPLATES: Record<NextEditModelName, NextEditTemplate> = {
function templateRendererOfModel(
modelName: NextEditModelName,
): TemplateRenderer {
const template = NEXT_EDIT_MODEL_TEMPLATES[modelName];
let template = NEXT_EDIT_MODEL_TEMPLATES[modelName];
if (!template) {
throw new Error(`Model ${modelName} is not supported for next edit.`);
}
@ -65,7 +65,7 @@ export function renderPrompt(
helper: HelperVars,
userEdits: string,
): UserPrompt {
const modelName = helper.modelName as NextEditModelName;
let modelName = helper.modelName as NextEditModelName;
if (modelName === "this field is not used") {
return {
@ -76,7 +76,18 @@ export function renderPrompt(
// Validate that the modelName is actually a supported model.
if (!Object.keys(NEXT_EDIT_MODEL_TEMPLATES).includes(modelName)) {
throw new Error(`${helper.modelName} is not yet supported for next edit.`);
// Check if modelName includes any known model name as substring.
const matchingModel = Object.keys(NEXT_EDIT_MODEL_TEMPLATES).find((key) =>
modelName.includes(key),
);
if (matchingModel) {
modelName = matchingModel as NextEditModelName;
} else {
throw new Error(
`${helper.modelName} is not yet supported for next edit.`,
);
}
}
const renderer = templateRendererOfModel(modelName);

View file

@ -1,9 +1,86 @@
import { DEFAULT_PROMPTS_FOLDER_V1, DEFAULT_PROMPTS_FOLDER_V2 } from ".";
import { DEFAULT_PROMPTS_FOLDER_V1 } from ".";
import { IDE } from "..";
import { walkDir } from "../indexing/walkDir";
import { readAllGlobalPromptFiles } from "../util/paths";
import { joinPathsToUri } from "../util/uri";
// The hardcoded init prompt content
const INIT_PROMPT_CONTENT = `name: Init
description: Initialize Codebase
---
You are an expert development assistant. Your task is to create a comprehensive CONTINUE.md project guide for the user's codebase to help them and their team better understand and work with the project.
## Step 1: Check Required Tools
First, verify that you have access to the necessary tools:
- builtin_file_glob_search: To discover project files
- builtin_read_file: To analyze file contents
- builtin_ls: To explore directory structure
- builtin_create_new_file: To generate the CONTINUE.md file
If any of these tools are unavailable, inform the user that they need to activate them and enable "Agent Mode" in Continue before proceeding.
## Step 2: Project Analysis
Analyze the project structure and key files to understand:
- The programming languages and frameworks used
- The overall architecture and organization
- Key components and their responsibilities
- Important configuration files
- Build/deployment system
## Step 3: Generate CONTINUE.md
Create a comprehensive CONTINUE.md file in the .continue/rules/ directory with the following sections:
1. **Project Overview**
- Brief description of the project's purpose
- Key technologies used
- High-level architecture
2. **Getting Started**
- Prerequisites (required software, dependencies)
- Installation instructions
- Basic usage examples
- Running tests
3. **Project Structure**
- Overview of main directories and their purpose
- Key files and their roles
- Important configuration files
4. **Development Workflow**
- Coding standards or conventions
- Testing approach
- Build and deployment process
- Contribution guidelines
5. **Key Concepts**
- Domain-specific terminology
- Core abstractions
- Design patterns used
6. **Common Tasks**
- Step-by-step guides for frequent development tasks
- Examples of common operations
7. **Troubleshooting**
- Common issues and their solutions
- Debugging tips
8. **References**
- Links to relevant documentation
- Important resources
Make sure your analysis is thorough but concise. Focus on information that would be most helpful to developers working on the project. If certain information isn't available from the codebase, make reasonable assumptions but mark these sections as needing verification.
## Step 4: Finalize
After creating the .continue/rules/CONTINUE.md file, provide a summary of what you've created and remind the user to:
1. Review and edit the file as needed
2. Commit it to their repository to share with their team
3. Explain that Continue will automatically load this file into context when working with the project
Also inform the user that they can create additional rules.md files in subdirectories for more specific documentation related to those components.`;
export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts";
export async function getPromptFilesFromDir(
ide: IDE,
dir: string,
@ -57,8 +134,17 @@ export async function getAllPromptFiles(
// Also read from ~/.continue/.prompts
promptFiles.push(...readAllGlobalPromptFiles());
// Add hardcoded init prompt
promptFiles.push({
path: "builtin:/init.prompt",
content: INIT_PROMPT_CONTENT,
});
return await Promise.all(
promptFiles.map(async (file) => {
if (file.path.startsWith("builtin:")) {
return file;
}
const content = await ide.readFile(file.path);
return { path: file.path, content };
}),

View file

@ -77,4 +77,5 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
updateApplyState: [ApplyState, void];
exitEditMode: [undefined, void];
focusEdit: [undefined, void];
generateRule: [undefined, void];
};

View file

@ -1,22 +1,23 @@
export enum BuiltInToolNames {
ReadFile = "builtin_read_file",
EditExistingFile = "builtin_edit_existing_file",
SearchAndReplaceInFile = "builtin_search_and_replace_in_file",
ReadCurrentlyOpenFile = "builtin_read_currently_open_file",
CreateNewFile = "builtin_create_new_file",
RunTerminalCommand = "builtin_run_terminal_command",
GrepSearch = "builtin_grep_search",
FileGlobSearch = "builtin_file_glob_search",
SearchWeb = "builtin_search_web",
ViewDiff = "builtin_view_diff",
LSTool = "builtin_ls",
CreateRuleBlock = "builtin_create_rule_block",
RequestRule = "builtin_request_rule",
FetchUrlContent = "builtin_fetch_url_content",
ReadFile = "read_file",
EditExistingFile = "edit_existing_file",
SearchAndReplaceInFile = "search_and_replace_in_file",
ReadCurrentlyOpenFile = "read_currently_open_file",
CreateNewFile = "create_new_file",
RunTerminalCommand = "run_terminal_command",
GrepSearch = "grep_search",
FileGlobSearch = "file_glob_search",
SearchWeb = "search_web",
ViewDiff = "view_diff",
LSTool = "ls",
CreateRuleBlock = "create_rule_block",
RequestRule = "request_rule",
FetchUrlContent = "fetch_url_content",
CodebaseTool = "codebase",
// excluded from allTools for now
ViewRepoMap = "builtin_view_repo_map",
ViewSubdirectory = "builtin_view_subdirectory",
ViewRepoMap = "view_repo_map",
ViewSubdirectory = "view_subdirectory",
}
export const BUILT_IN_GROUP_NAME = "Built-In";

View file

@ -3,6 +3,7 @@ import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton";
import { canParseUrl } from "../util/url";
import { BuiltInToolNames } from "./builtIn";
import { codebaseToolImpl } from "./implementations/codebaseTool";
import { createNewFileImpl } from "./implementations/createNewFile";
import { createRuleBlockImpl } from "./implementations/createRuleBlock";
import { fetchUrlContentImpl } from "./implementations/fetchUrlContent";
@ -15,6 +16,8 @@ import { requestRuleImpl } from "./implementations/requestRule";
import { runTerminalCommandImpl } from "./implementations/runTerminalCommand";
import { searchWebImpl } from "./implementations/searchWeb";
import { viewDiffImpl } from "./implementations/viewDiff";
import { viewRepoMapImpl } from "./implementations/viewRepoMap";
import { viewSubdirectoryImpl } from "./implementations/viewSubdirectory";
import { safeParseToolCallArgs } from "./parseArgs";
async function callHttpTool(
@ -134,7 +137,7 @@ async function callToolFromUri(
}
}
async function callBuiltInTool(
export async function callBuiltInTool(
functionName: string,
args: any,
extras: ToolExtras,
@ -164,6 +167,12 @@ async function callBuiltInTool(
return await createRuleBlockImpl(args, extras);
case BuiltInToolNames.RequestRule:
return await requestRuleImpl(args, extras);
case BuiltInToolNames.CodebaseTool:
return await codebaseToolImpl(args, extras);
case BuiltInToolNames.ViewRepoMap:
return await viewRepoMapImpl(args, extras);
case BuiltInToolNames.ViewSubdirectory:
return await viewSubdirectoryImpl(args, extras);
default:
throw new Error(`Tool "${functionName}" not found`);
}

View file

@ -0,0 +1,29 @@
import { Tool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export const codebaseTool: Tool = {
type: "function",
displayTitle: "Codebase Search",
wouldLikeTo: "search the codebase for: {{{ query }}}",
isCurrently: "searching the codebase for: {{{ query }}}",
hasAlready: "searched the codebase for: {{{ query }}}",
readonly: true,
isInstant: false,
group: BUILT_IN_GROUP_NAME,
function: {
name: BuiltInToolNames.CodebaseTool,
description:
"Use this tool to semantically search through the codebase and retrieve relevant code snippets based on a natural language query. This helps find relevant code context for understanding or working with the codebase.",
parameters: {
type: "object",
required: ["query"],
properties: {
query: {
type: "string",
description:
"Natural language description of what you're looking for in the codebase (e.g., 'authentication logic', 'database connection setup', 'error handling')",
},
},
},
},
};

View file

@ -13,7 +13,7 @@ export const createRuleBlock: Tool = {
function: {
name: BuiltInToolNames.CreateRuleBlock,
description:
'Creates a "rule" that can be referenced in future conversations. This should be used whenever you want to establish code standards / preferences that should be applied consistently, or when you want to avoid making a mistake again. To modify existing rules, use the edit tool instead.',
'Creates a "rule" that can be referenced in future conversations. This should be used whenever you want to establish code standards / preferences that should be applied consistently, or when you want to avoid making a mistake again. To modify existing rules, use the edit tool instead.\n\nRule Types:\n- Always: Include only "rule" (always included in model context)\n- Auto Attached: Include "rule", "globs", and/or "regex" (included when files match patterns)\n- Agent Requested: Include "rule" and "description" (AI decides when to apply based on description)\n- Manual: Include only "rule" (only included when explicitly mentioned using @ruleName)',
parameters: {
type: "object",
required: ["name", "rule", "description"],
@ -30,7 +30,8 @@ export const createRuleBlock: Tool = {
},
description: {
type: "string",
description: "Short description of the rule",
description:
"Description of when this rule should be applied. Required for Agent Requested rules (AI decides when to apply). Optional for other types.",
},
globs: {
type: "string",
@ -42,6 +43,11 @@ export const createRuleBlock: Tool = {
description:
"Optional regex patterns to match against file content. Rule applies only to files whose content matches the pattern (e.g. 'useEffect' for React hooks or '\\bclass\\b' for class definitions)",
},
alwaysApply: {
type: "boolean",
description:
"Whether this rule should always be applied. Set to false for Agent Requested and Manual rules. Omit or set to true for Always and Auto Attached rules.",
},
},
},
},

View file

@ -1,5 +1,5 @@
import { Tool } from "../..";
import { EDIT_CODE_INSTRUCTIONS } from "../../llm/constructMessages";
import { EDIT_CODE_INSTRUCTIONS } from "../../llm/defaultSystemMessages";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export interface EditToolArgs {

View file

@ -13,7 +13,7 @@ export const globSearchTool: Tool = {
function: {
name: BuiltInToolNames.FileGlobSearch,
description:
"Search for files in the project. Output may be truncated; use targeted patterns",
"Search for files recursively in the project using glob patterns. Supports ** for recursive directory search. Output may be truncated; use targeted patterns",
parameters: {
type: "object",
required: ["pattern"],

View file

@ -0,0 +1,61 @@
import { ToolImpl } from ".";
import { RangeInFile } from "../..";
import { retrieveContextItemsFromEmbeddings } from "../../context/retrieval/retrieval";
export const codebaseToolImpl: ToolImpl = async (args, extras) => {
if (!args.query || args.query.trim() === "") {
return [
{
name: "Error",
description: "Codebase search error",
content: "Query parameter is required and cannot be empty.",
},
];
}
try {
const contextExtras = {
config: extras.config,
fullInput: args.query,
embeddingsProvider: extras.config.selectedModelByRole.embed,
reranker: extras.config.selectedModelByRole.rerank,
llm: extras.llm,
ide: extras.ide,
selectedCode: [] as RangeInFile[],
fetch: extras.fetch,
};
// Use the existing retrieval function to get context items
const results = await retrieveContextItemsFromEmbeddings(
contextExtras,
undefined,
undefined,
);
// If no results found, return helpful message
if (results.length === 0) {
return [
{
name: "No Results",
description: "Codebase search",
content: `No relevant code found for query: "${args.query}". This could mean:
- The codebase hasn't been indexed yet
- No code matches the search criteria
- Embeddings provider is not configured
Try re-indexing the codebase or using a more specific query.`,
},
];
}
return results;
} catch (error) {
return [
{
name: "Error",
description: "Codebase search error",
content: `Failed to search codebase: ${error instanceof Error ? error.message : String(error)}`,
},
];
}
};

View file

@ -36,6 +36,7 @@ test("createRuleBlockImpl should create a rule with glob pattern", async () => {
const { frontmatter, markdown } = parseMarkdownRule(fileContent);
expect(frontmatter).toEqual({
alwaysApply: true,
description: "Always use interfaces",
globs: "**/*.{ts,tsx}",
});
@ -72,6 +73,7 @@ test("createRuleBlockImpl should create a rule with description pattern", async
const { frontmatter, markdown } = parseMarkdownRule(fileContent);
expect(frontmatter).toEqual({
alwaysApply: true,
description: "This is a detailed explanation of the rule",
});
@ -94,6 +96,7 @@ test("createRuleBlockImpl should include both globs and description in frontmatt
const { frontmatter, markdown } = parseMarkdownRule(fileContent);
expect(frontmatter).toEqual({
alwaysApply: false,
description: "This rule enforces our team standards",
globs: "**/*.js",
});
@ -116,6 +119,7 @@ test("createRuleBlockImpl should create a rule with alwaysApply set to false", a
const { frontmatter } = parseMarkdownRule(fileContent);
expect(frontmatter).toEqual({
alwaysApply: false,
description: "Optional rule",
});
});

View file

@ -5,29 +5,18 @@ import { createRuleFilePath } from "../../config/markdown/utils";
export type CreateRuleBlockArgs = Pick<
Required<RuleWithSource>,
"rule" | "description" | "alwaysApply" | "name"
"rule" | "name"
> &
Pick<RuleWithSource, "globs" | "regex">;
Pick<RuleWithSource, "globs" | "regex" | "description" | "alwaysApply">;
export const createRuleBlockImpl: ToolImpl = async (
args: CreateRuleBlockArgs,
{ name, rule, ...otherArgs }: CreateRuleBlockArgs,
extras,
) => {
// Create options object with the fields that createRuleMarkdown expects
const options: any = {
description: args.description,
globs: args.globs,
};
// Add regex if provided
if (args.regex) {
options.regex = args.regex;
}
const fileContent = createRuleMarkdown(args.name, args.rule, options);
const fileContent = createRuleMarkdown(name, rule, otherArgs);
const [localContinueDir] = await extras.ide.getWorkspaceDirs();
const ruleFilePath = createRuleFilePath(localContinueDir, args.name);
const ruleFilePath = createRuleFilePath(localContinueDir, name);
await extras.ide.writeFile(ruleFilePath, fileContent);
await extras.ide.openFile(ruleFilePath);
@ -35,7 +24,7 @@ export const createRuleBlockImpl: ToolImpl = async (
return [
{
name: "New Rule Block",
description: args.description || "",
description: otherArgs.description || "",
uri: {
type: "file",
value: ruleFilePath,

View file

@ -5,6 +5,41 @@ import { formatGrepSearchResults } from "../../util/grepSearch";
const DEFAULT_GREP_SEARCH_RESULTS_LIMIT = 100;
const DEFAULT_GREP_SEARCH_CHAR_LIMIT = 5000; // ~1000 tokens, will keep truncation simply for now
function splitGrepResultsByFile(content: string): ContextItem[] {
const matches = [...content.matchAll(/^\.\/([^\n]+)$/gm)];
if (matches.length === 0) {
return [];
}
const contextItems: ContextItem[] = [];
for (let i = 0; i < matches.length; i++) {
const match = matches[i];
const filepath = match[1];
const startIndex = match.index!;
const endIndex =
i < matches.length - 1 ? matches[i + 1].index! : content.length;
// Extract grepped content for this file
const fileContent = content
.substring(startIndex, endIndex)
.replace(/^\.\/[^\n]+\n/, "") // remove the line with file path
.trim();
if (fileContent) {
contextItems.push({
name: `Search results in ${filepath}`,
description: `Grep search results from ${filepath}`,
content: fileContent,
uri: { type: "file", value: filepath },
});
}
}
return contextItems;
}
export const grepSearchImpl: ToolImpl = async (args, extras) => {
const results = await extras.ide.getSearchResults(
args.query,
@ -26,13 +61,21 @@ export const grepSearchImpl: ToolImpl = async (args, extras) => {
);
}
const contextItems: ContextItem[] = [
{
name: "Search results",
description: "Results from grep search",
content: formatted,
},
];
let contextItems: ContextItem[] = [];
const splitByFile: boolean = args.splitByFile || false;
if (splitByFile) {
contextItems = splitGrepResultsByFile(formatted);
} else {
contextItems = [
{
name: "Search results",
description: "Results from grep search",
content: formatted,
},
];
}
if (truncationReasons.length > 0) {
contextItems.push({
name: "Search truncation warning",

View file

@ -1,28 +1,41 @@
import { getUriDescription } from "../../util/uri";
import { ToolImpl } from ".";
import { throwIfFileExceedsHalfOfContext } from "./readFileLimit";
export const readCurrentlyOpenFileImpl: ToolImpl = async (args, extras) => {
const result = await extras.ide.getCurrentFile();
if (!result) {
return [];
}
if (result) {
await throwIfFileExceedsHalfOfContext(
result.path,
result.contents,
extras.config.selectedModelByRole.chat,
);
const { relativePathOrBasename, last2Parts, baseName } = getUriDescription(
result.path,
await extras.ide.getWorkspaceDirs(),
);
const { relativePathOrBasename, last2Parts, baseName } = getUriDescription(
result.path,
await extras.ide.getWorkspaceDirs(),
);
return [
{
name: `Current file: ${baseName}`,
description: last2Parts,
content: `\`\`\`${relativePathOrBasename}\n${result.contents}\n\`\`\``,
uri: {
type: "file",
value: result.path,
return [
{
name: `Current file: ${baseName}`,
description: last2Parts,
content: `\`\`\`${relativePathOrBasename}\n${result.contents}\n\`\`\``,
uri: {
type: "file",
value: result.path,
},
},
},
];
];
} else {
return [
{
name: `No Current File`,
description: "",
content: "There are no files currently open.",
},
];
}
};

View file

@ -2,6 +2,7 @@ import { resolveRelativePathInDir } from "../../util/ideUtils";
import { getUriPathBasename } from "../../util/uri";
import { ToolImpl } from ".";
import { throwIfFileExceedsHalfOfContext } from "./readFileLimit";
export const readFileImpl: ToolImpl = async (args, extras) => {
const firstUriMatch = await resolveRelativePathInDir(
@ -12,6 +13,13 @@ export const readFileImpl: ToolImpl = async (args, extras) => {
throw new Error(`Could not find file ${args.filepath}`);
}
const content = await extras.ide.readFile(firstUriMatch);
await throwIfFileExceedsHalfOfContext(
args.filepath,
content,
extras.config.selectedModelByRole.chat,
);
return [
{
name: getUriPathBasename(args.filepath),

View file

@ -0,0 +1,18 @@
import { ILLM } from "../..";
import { countTokensAsync } from "../../llm/countTokens";
export async function throwIfFileExceedsHalfOfContext(
filepath: string,
content: string,
model: ILLM | null,
) {
if (model) {
const tokens = await countTokensAsync(content, model.title);
const tokenLimit = model.contextLength / 2;
if (tokens > tokenLimit) {
throw new Error(
`File ${filepath} is too large (${tokens} tokens vs ${tokenLimit} token limit). Try another approach`,
);
}
}
}

View file

@ -1,4 +1,5 @@
import { ConfigDependentToolParams, IDE, Tool } from "..";
import { codebaseTool } from "./definitions/codebaseTool";
import { createNewFileTool } from "./definitions/createNewFile";
import { createRuleBlock } from "./definitions/createRuleBlock";
import { editFileTool } from "./definitions/editFile";
@ -16,10 +17,12 @@ import { viewDiffTool } from "./definitions/viewDiff";
import { viewRepoMapTool } from "./definitions/viewRepoMap";
import { viewSubdirectoryTool } from "./definitions/viewSubdirectory";
// missing support for remote os calls: https://github.com/microsoft/vscode/issues/252269
export const localOnlyToolDefinitions = [grepSearchTool];
// I'm writing these as functions because we've messed up 3 TIMES by pushing to const, causing duplicate tool definitions on subsequent config loads.
export const baseToolDefinitions = [
// missing support for remote os calls: https://github.com/microsoft/vscode/issues/252269
const getLocalOnlyToolDefinitions = () => [grepSearchTool];
const getBaseToolDefinitions = () => [
readFileTool,
createNewFileTool,
runTerminalCommandTool,
@ -37,11 +40,16 @@ export const getConfigDependentToolDefinitions = (
): Tool[] => [
requestRuleTool(params),
...(params.enableExperimentalTools
? [searchAndReplaceInFileTool, viewRepoMapTool, viewSubdirectoryTool]
? [
searchAndReplaceInFileTool,
viewRepoMapTool,
viewSubdirectoryTool,
codebaseTool,
]
: [editFileTool]),
];
export const getToolsForIde = async (ide: IDE) =>
export const getToolsForIde = async (ide: IDE): Promise<Tool[]> =>
(await ide.isWorkspaceRemote())
? baseToolDefinitions
: [...baseToolDefinitions, ...localOnlyToolDefinitions];
? getBaseToolDefinitions()
: [...getBaseToolDefinitions(), ...getLocalOnlyToolDefinitions()];

View file

@ -1,6 +1,6 @@
export function findLastIndex(
arr: any[],
criterion: (item: any) => boolean,
export function findLastIndex<T = any>(
arr: T[],
criterion: (item: T) => boolean,
): number {
let lastIndex = -1;

View file

@ -28,14 +28,12 @@ In [Chat mode](../chat/how-to-use-it.md), tools are **not** included in the requ
Continue includes several built-in tools which provide the model access to IDE functionality:
- **Read file** (`builtin_read_file`): read the contents of a file within the project
- **Read currently open file** (`builtin_read_currently_open_file`): read the contents of the currently open file
- **Create new file** (`builtin_create_new_file`): Create a new file within the project, with path and contents specified by the model
- **Exact search** (`builtin_exact_search`): perform a `ripgrep` search within the project
- **Glob search** (`builtin_file_glob_search`): perform a glob search on files in the project. Currently limits to 100 output and warns the Agent if limit reached.
- **Run terminal command** (`builtin_run_terminal_command`): run a terminal command from the workspace root
- **Search web** (`builtin_search_web`): Perform a web search to get top results
- **View diff** (`builtin_view_diff`): View the current working git diff
- **View repo map** (`builtin_view_repo_map`): request a copy of the repository map—same as the [Repo Map Context Provider](../customize/context-providers.mdx#repository-map)
- **View subdirectory** (`builtin_view_subdirectory`): request a copy of a repo map for a specific directory within the project
- **Create Rule Block** (`builtin_create_rule_block`): creates a new rule block in `.continue/rules` based on the contents of the conversation
- **Read file** (`read_file`): read the contents of a file within the project
- **Read currently open file** (`read_currently_open_file`): read the contents of the currently open file
- **Create new file** (`create_new_file`): Create a new file within the project, with path and contents specified by the model
- **Exact search** (`exact_search`): perform a `ripgrep` search within the project
- **Glob search** (`file_glob_search`): perform a glob search on files in the project. Currently limits to 100 output and warns the Agent if limit reached.
- **Run terminal command** (`run_terminal_command`): run a terminal command from the workspace root
- **Search web** (`search_web`): Perform a web search to get top results
- **View diff** (`view_diff`): View the current working git diff
- **Create Rule Block** (`create_rule_block`): creates a new rule block in `.continue/rules` based on the contents of the conversation

View file

@ -48,7 +48,7 @@ Rules can be added locally using the "Add Rules" button while viewing the Local
![add local rules button](/img/add-local-rules.png)
:::info Automatically create local rule blocks
When in Agent mode, you can prompt the agent to create a rule for you using the `builtin_create_rule_block` tool if enabled.
When in Agent mode, you can prompt the agent to create a rule for you using the `create_rule_block` tool if enabled.
For example, you can say "Create a rule for this", and a rule will be created for you in `.continue/rules` based on your conversation.
:::

View file

@ -0,0 +1,113 @@
import TabItem from "@theme/TabItem";
import Tabs from "@theme/Tabs";
# Llama Stack
[Llama Stack](https://llama-stack.readthedocs.io/en/latest/index.html) is an open-source library that standardizes the core building blocks that simplify AI application development. It codifies best practices across the Llama ecosystem. More specifically, it provides
- **Unified API layer** for Inference, RAG, Agents, Tools, Safety, Evals, and Telemetry.
- **Plugin architecture** to support the rich ecosystem of different API implementations in various environments, including local development, on-premises, cloud, and mobile.
- **Prepackaged verified distributions** which offer a one-stop solution for developers to get started quickly and reliably in any environment.
- **Multiple developer interfaces** like CLI and SDKs for Python, Typescript, iOS, and Android.
- **Standalone applications** as examples for how to build production-grade AI applications with Llama Stack.
To try Llama Stack locally, run:
```shell
curl -LsSf https://github.com/meta-llama/llama-stack/raw/main/install.sh | bash
```
Learn more about how to get started with llama stack in this [guide](https://llama-stack.readthedocs.io/en/latest/getting_started/index.html)
## Chat model
We recommend configuring **Llama 4 Maverick** as your chat model.
<Tabs groupId="config-example">
<TabItem value="yaml" label="YAML">
```yaml title="config.yaml"
models:
- name: Llama4 Maverick
provider: llamastack
model: meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8
apiBase: http://<llama stack endpoint>/v1/openai/v1/
```
</TabItem>
<TabItem value="json" label="JSON">
```json title="config.json"
{
"models": [
{
"title": "Llama4 Maverick",
"provider": "llamastack",
"model": "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8",
"apiBase": "http://<llama stack endpoint>/v1/openai/v1/"
}
]
}
```
</TabItem>
</Tabs>
## Autocomplete model
We recommend configuring **CodeLlama 7B** as your autocomplete model.
<Tabs groupId="config-example">
<TabItem value="yaml" label="YAML">
```yaml title="config.yaml"
models:
- name: CodeLlama 7B
provider: llamastack
model: codellama:7b
apiBase: http://<llama stack endpoint>/v1/openai/v1/
roles:
- autocomplete
```
</TabItem>
<TabItem value="json" label="JSON">
```json title="config.json"
{
"tabAutocompleteModel": {
"title": "CodeLlama 7B",
"provider": "llamastack",
"model": "codellama:7b",
"apiBase": "http://<llama stack endpoint>/v1/openai/v1/"
}
}
```
</TabItem>
</Tabs>
## Embeddings model
By default, Llama Stack uses **all-MiniLM-L6-v2** as the embeddings model.
<Tabs groupId="config-example">
<TabItem value="yaml" label="YAML">
```yaml title="config.yaml"
models:
- name: all-MiniLM-L6-v2
provider: llamastack
model: all-MiniLM-L6-v2
apiBase: http://<llama stack endpoint>/v1/openai/v1/
roles:
- embed
```
</TabItem>
<TabItem value="json" label="JSON">
```json title="config.json"
{
"embeddingsProvider": {
"provider": "llamastack",
"model": "all-MiniLM-L6-v2",
"apiBase": "http://<llama stack endpoint>/v1/openai/v1/"
}
}
```
</TabItem>
</Tabs>
## Reranking model
Llama Stack currently did not support Reranking API yet.

View file

@ -9,6 +9,7 @@ This file is for contribution guidelines specific to the JetBrains extension. Se
- [Environment Setup](#environment-setup)
- [IDE Installation](#ide-installation)
- [IDE configuration](#ide-configuration)
- [Recommended plugins](#recommended-plugins)
- [Node.js Requirements](#nodejs-requirements)
- [Install all dependencies](#install-all-dependencies)
- [Misc](#misc)
@ -50,7 +51,13 @@ notes below).
### IDE configuration
- Enable code formatting on save: `Settings | Tools | Actions on Save | Reformat code`
- We recommend installing the [Thread Access Info](https://plugins.jetbrains.com/plugin/16815-thread-access-info) plugin
#### Recommended plugins
- [Thread Access Info](https://plugins.jetbrains.com/plugin/16815-thread-access-info) - adds an extra debug panel
showing possible thread access violation (according to Intellij Platform SDK guidelines)
- [File Expander](https://plugins.jetbrains.com/plugin/11940-file-expander) - allows you to easily preview archives as
directories (like `build/distributions/continue-*.zip`)
### Node.js Requirements

View file

@ -46,7 +46,7 @@ dependencies {
testImplementation("org.junit.jupiter:junit-jupiter-api:5.10.0")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.9.2")
testImplementation("com.squareup.okhttp3:logging-interceptor:4.12.0")
implementation("com.automation-remarks:video-recorder-junit5:2.0")
testImplementation("com.automation-remarks:video-recorder-junit5:2.0")
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3")
@ -192,11 +192,8 @@ tasks {
}
runIde {
// Open the `manual-testing-sandbox` directory and the specific file on start
args = listOf(
"${rootProject.projectDir.parentFile.parentFile}/manual-testing-sandbox",
"${rootProject.projectDir.parentFile.parentFile}/manual-testing-sandbox/test.kt"
).map { file(it).absolutePath }
val dir = "${rootProject.projectDir.parentFile.parentFile.absolutePath}/manual-testing-sandbox"
args = listOf(dir, "$dir/test.kt")
}
test {

View file

@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension
pluginName=continue-intellij-extension
pluginRepositoryUrl=https://github.com/continuedev/continue
# SemVer format -> https://semver.org
pluginVersion=1.0.26
pluginVersion=1.0.27
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
pluginSinceBuild=223
# IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension

View file

@ -0,0 +1,10 @@
package com.github.continuedev.continueintellijextension
import com.intellij.openapi.util.IconLoader
object Icons {
@JvmField
val Continue = IconLoader.getIcon("/icons/continue.svg", javaClass)
@JvmField
val Close = IconLoader.getIcon("/icons/close.svg", javaClass)
}

View file

@ -1,26 +0,0 @@
package com.github.continuedev.continueintellijextension
import com.intellij.DynamicBundle
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
@NonNls
private const val BUNDLE = "messages.MyBundle"
object MyBundle : DynamicBundle(BUNDLE) {
@JvmStatic
fun message(
@PropertyKey(resourceBundle = BUNDLE) key: String,
vararg params: Any
) =
getMessage(key, *params)
@Suppress("unused")
@JvmStatic
fun messagePointer(
@PropertyKey(resourceBundle = BUNDLE) key: String,
vararg params: Any
) =
getLazyMessage(key, *params)
}

View file

@ -5,7 +5,7 @@ import com.github.continuedev.continueintellijextension.services.ContinueExtensi
import com.intellij.openapi.actionSystem.ActionPromoter
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.service
import org.jetbrains.annotations.NotNull
class ContinueActionPromote : ActionPromoter {
@ -13,7 +13,7 @@ class ContinueActionPromote : ActionPromoter {
override fun promote(@NotNull actions: List<AnAction>, @NotNull context: DataContext): List<AnAction>? {
// For autocomplete actions
if (actions.any { it is AcceptAutocompleteAction }) {
val settings = ServiceManager.getService(ContinueExtensionSettings::class.java)
val settings = service<ContinueExtensionSettings>()
if (settings.continueState.showIDECompletionSideBySide) {
return actions.filterIsInstance<AcceptAutocompleteAction>()
}

View file

@ -1,7 +1,7 @@
package com.github.continuedev.continueintellijextension.actions
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.ToolWindowManager
@ -28,12 +28,5 @@ fun focusContinueInput(project: Project?) {
continuePluginService.ideProtocolClient?.sendHighlightedCode()
}
fun getPluginService(project: Project?): ContinuePluginService? {
if (project == null) {
return null
}
return ServiceManager.getService(
project,
ContinuePluginService::class.java
)
}
fun getPluginService(project: Project?): ContinuePluginService? =
project?.service<ContinuePluginService>()

View file

@ -1,9 +1,7 @@
package com.github.continuedev.continueintellijextension.activities
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import com.intellij.openapi.project.Project
/**
* The service is a parent disposable that represents the entire plugin lifecycle
@ -18,15 +16,4 @@ class ContinuePluginDisposable : Disposable {
override fun dispose() {
}
companion object {
fun getInstance(): ContinuePluginDisposable {
return ApplicationManager.getApplication().getService(ContinuePluginDisposable::class.java)
}
fun getInstance(project: Project): ContinuePluginDisposable {
return project.getService(ContinuePluginDisposable::class.java)
}
}
}

View file

@ -14,7 +14,6 @@ import com.github.continuedev.continueintellijextension.utils.toUriOrNull
import com.intellij.openapi.actionSystem.KeyboardShortcut
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.keymap.KeymapManager
@ -122,14 +121,10 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
private fun initializePlugin(project: Project) {
val coroutineScope = CoroutineScope(Dispatchers.IO)
val continuePluginService = ServiceManager.getService(
project,
ContinuePluginService::class.java
)
val continuePluginService = project.service<ContinuePluginService>()
coroutineScope.launch {
val settings =
ServiceManager.getService(ContinueExtensionSettings::class.java)
val settings = service<ContinueExtensionSettings>()
if (!settings.continueState.shownWelcomeDialog) {
settings.continueState.shownWelcomeDialog = true
// Open tutorial file
@ -270,7 +265,7 @@ class ContinuePluginStartupActivity : StartupActivity, DumbAware {
EditorFactory.getInstance().eventMulticaster.addSelectionListener(
listener,
ContinuePluginDisposable.getInstance(project)
project.service<ContinuePluginDisposable>()
)
val coreMessengerManager = CoreMessengerManager(project, ideProtocolClient, coroutineScope)

View file

@ -7,7 +7,6 @@ import com.github.continuedev.continueintellijextension.utils.uuid
import com.intellij.injected.editor.VirtualFileWindow
import com.intellij.openapi.application.*
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.InlayProperties
@ -64,8 +63,7 @@ class AutocompleteService(private val project: Project) {
var lastChangeWasPartialAccept = false
fun triggerCompletion(editor: Editor) {
val settings =
ServiceManager.getService(ContinueExtensionSettings::class.java)
val settings = service<ContinueExtensionSettings>()
if (!settings.continueState.enableTabAutocomplete) {
return
}
@ -183,7 +181,7 @@ class AutocompleteService(private val project: Project) {
}
if (isInjectedFile(editor)) return
// Skip rendering completions if the code completion dropdown is already visible and the IDE completion side-by-side setting is disabled
if (shouldSkipRender(ServiceManager.getService(ContinueExtensionSettings::class.java))) {
if (shouldSkipRender()) {
return
}
@ -230,9 +228,10 @@ class AutocompleteService(private val project: Project) {
}
}
private fun shouldSkipRender(settings: ContinueExtensionSettings) =
!settings.continueState.showIDECompletionSideBySide && !autocompleteLookupListener.isLookupEmpty()
private fun shouldSkipRender(): Boolean {
val settings = service<ContinueExtensionSettings>()
return !settings.continueState.showIDECompletionSideBySide && !autocompleteLookupListener.isLookupEmpty()
}
private fun splitKeepingDelimiters(input: String, delimiterPattern: String = "\\s+"): List<String> {
val initialSplit = input.split("(?<=$delimiterPattern)|(?=$delimiterPattern)".toRegex())

View file

@ -1,5 +1,6 @@
package com.github.continuedev.continueintellijextension.autocomplete
import com.github.continuedev.continueintellijextension.Icons
import com.github.continuedev.continueintellijextension.activities.ContinuePluginDisposable
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.intellij.openapi.Disposable
@ -26,7 +27,7 @@ class AutocompleteSpinnerWidget(project: Project) : EditorBasedWidget(project),
private val animatedIcon = AnimatedIcon.Default()
init {
Disposer.register(ContinuePluginDisposable.getInstance(project), this)
Disposer.register(project.service<ContinuePluginDisposable>(), this)
updateIcon()
}
@ -50,7 +51,7 @@ class AutocompleteSpinnerWidget(project: Project) : EditorBasedWidget(project),
}
override fun getIcon(): Icon = if (isLoading) animatedIcon else
IconLoader.getIcon("/icons/continue.svg", javaClass)
Icons.Continue
fun setLoading(loading: Boolean) {
isLoading = loading

View file

@ -41,11 +41,12 @@ class MessageTypes {
"getTerminalContents",
"showToast",
"openUrl",
"isWorkspaceRemote",
// These only come from the GUI for now but should be here to prevent confusion
"toggleDevTools",
"showTutorial",
// These are jetbrains only and only come from the GUI for now
// But again including for consistency
"copyText",

View file

@ -10,6 +10,7 @@ import com.github.continuedev.continueintellijextension.editor.EditorUtils
import com.github.continuedev.continueintellijextension.protocol.ApplyToFileParams
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import kotlinx.coroutines.suspendCancellableCoroutine
@ -201,7 +202,7 @@ class ApplyToFileHandler(
if (EditorUtils.editorFileExist(params.filepath)) EditorUtils.getOrOpenEditor(project, params.filepath)
else EditorUtils.getEditorByCreateFile(project, params.filepath)
val diffStreamService = project.getService(DiffStreamService::class.java)
val diffStreamService = project.service<DiffStreamService>()
val handler = ApplyToFileHandler(
project, continuePluginService, ide, params, editorUtils, diffStreamService

View file

@ -43,7 +43,9 @@ class CoreMessenger(
val message =
gson.toJson(mapOf("messageId" to id, "messageType" to messageType, "data" to data))
responseListeners[id] = onResponse
write(message)
coroutineScope.launch(Dispatchers.IO) {
write(message)
}
}
private fun handleMessage(json: String) {

View file

@ -9,7 +9,7 @@ import com.intellij.diff.contents.DiffContent
import com.intellij.diff.requests.SimpleDiffRequest
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.service
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
@ -18,7 +18,6 @@ import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.LocalFileSystem
import java.awt.Toolkit
import java.io.File
import java.net.URI
import java.nio.file.Paths
import javax.swing.Action
import javax.swing.JComponent
@ -89,11 +88,7 @@ class DiffManager(private val project: Project) : DumbAware {
FileDocumentManager.getInstance().saveDocument(document)
// Notify server of acceptance
val continuePluginService = ServiceManager.getService(
project,
ContinuePluginService::class.java
)
continuePluginService.ideProtocolClient?.sendAcceptRejectDiff(true, diffInfo.stepIndex)
project.service<ContinuePluginService>().ideProtocolClient?.sendAcceptRejectDiff(true, diffInfo.stepIndex)
// Clean up state
cleanUpFile(file)
@ -102,10 +97,7 @@ class DiffManager(private val project: Project) : DumbAware {
fun rejectDiff(file2: String?) {
val file = (file2 ?: lastFile2) ?: return
val diffInfo = diffInfoMap[file] ?: return
val continuePluginService = ServiceManager.getService(
project,
ContinuePluginService::class.java
)
val continuePluginService = project.service<ContinuePluginService>()
continuePluginService.ideProtocolClient?.deleteAtIndex(diffInfo.stepIndex)
continuePluginService.ideProtocolClient?.sendAcceptRejectDiff(false, diffInfo.stepIndex)
continuePluginService.coreMessenger?.request("cancelApply", null, null) {}

View file

@ -166,6 +166,9 @@ class GetTheme {
val findMatchSelectedBackground = namedColor("SearchMatch.selectedBackground") ?:
editorScheme.getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES)?.backgroundColor
// Use editor background with slight tint for code blocks
val textCodeBlockBackground = slightChange(editorBackground, 3) ?: editorBackground
// These should match the keys in GUI's theme.ts
val theme = mapOf(
"background" to background,
@ -197,6 +200,7 @@ class GetTheme {
"warning" to warningColor,
"error" to errorColor,
"link" to link,
"textCodeBlockBackground" to textCodeBlockBackground,
"accent" to accentColor,
"find-match" to findMatchBackground,
"find-match-selected" to findMatchSelectedBackground,

View file

@ -6,6 +6,7 @@ import com.github.continuedev.continueintellijextension.activities.showTutorial
import com.github.continuedev.continueintellijextension.auth.ContinueAuthService
import com.github.continuedev.continueintellijextension.editor.DiffStreamService
import com.github.continuedev.continueintellijextension.editor.EditorUtils
import com.github.continuedev.continueintellijextension.error.ContinueErrorService
import com.github.continuedev.continueintellijextension.protocol.*
import com.github.continuedev.continueintellijextension.services.*
import com.github.continuedev.continueintellijextension.utils.*
@ -46,7 +47,7 @@ class IdeProtocolClient(
init {
// Setup config.json / config.ts save listeners
VirtualFileManager.getInstance().addAsyncFileListener(
AsyncFileSaveListener(continuePluginService), ContinuePluginDisposable.getInstance(project)
AsyncFileSaveListener(continuePluginService), project.service<ContinuePluginDisposable>()
)
}
@ -67,8 +68,7 @@ class IdeProtocolClient(
}
"jetbrains/isOSREnabled" -> {
val isOSREnabled =
ServiceManager.getService(ContinueExtensionSettings::class.java).continueState.enableOSR
val isOSREnabled = service<ContinueExtensionSettings>().continueState.enableOSR
respond(isOSREnabled)
}
@ -202,6 +202,11 @@ class IdeProtocolClient(
respond(contents)
}
"isWorkspaceRemote" -> {
val isRemote = ide.isWorkspaceRemote()
respond(isRemote)
}
"saveFile" -> {
val params = Gson().fromJson(
dataElement.toString(),
@ -463,8 +468,10 @@ class IdeProtocolClient(
println("Unknown message type: $messageType")
}
}
} catch (error: Exception) {
ide.showToast(ToastType.ERROR, " Error handling message of type $messageType: $error")
} catch (exception: Exception) {
val exceptionMessage = "Error handling message of type $messageType: $exception"
service<ContinueErrorService>().report(exception, exceptionMessage)
ide.showToast(ToastType.ERROR, exceptionMessage)
}
}
}
@ -473,7 +480,7 @@ class IdeProtocolClient(
val editor = EditorUtils.getEditor(project)
val rif = editor?.getHighlightedRIF() ?: return
val serializedRif = com.github.continuedev.continueintellijextension.RangeInFileWithContents(
val serializedRif = com.github.continuedev.continueintellijextension.RangeInFileWithContents(
filepath = rif.filepath,
range = rif.range,
contents = rif.contents

View file

@ -1,9 +1,9 @@
package com.github.continuedev.continueintellijextension.`continue`
import com.github.continuedev.continueintellijextension.*
import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath
import com.github.continuedev.continueintellijextension.constants.ContinueConstants
import com.github.continuedev.continueintellijextension.`continue`.GitService
import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath
import com.github.continuedev.continueintellijextension.error.ContinueErrorService
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.utils.*
@ -11,7 +11,6 @@ import com.intellij.codeInsight.daemon.impl.HighlightInfo
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.util.ExecUtil
import com.intellij.ide.BrowserUtil
import com.intellij.ide.plugins.PluginManager
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.notification.NotificationAction
@ -19,6 +18,7 @@ import com.intellij.notification.NotificationGroupManager
import com.intellij.notification.NotificationType
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.EDT
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.impl.DocumentMarkupModel
import com.intellij.openapi.extensions.PluginId
@ -38,9 +38,7 @@ import java.io.BufferedReader
import java.io.File
import java.io.FileInputStream
import java.io.InputStreamReader
import java.net.URI
import java.nio.charset.Charset
import java.nio.file.Paths
class IntelliJIDE(
private val project: Project,
@ -297,23 +295,26 @@ class IntelliJIDE(
continuePluginService.diffManager?.showDiff(filepath, newContents, stepIndex)
}
override suspend fun getOpenFiles(): List<String> {
val fileEditorManager = FileEditorManager.getInstance(project)
return fileEditorManager.openFiles.mapNotNull { it.toUriOrNull() }.toList()
}
override suspend fun getCurrentFile(): Map<String, Any>? {
val fileEditorManager = FileEditorManager.getInstance(project)
val editor = fileEditorManager.selectedTextEditor
val virtualFile = editor?.document?.let { FileDocumentManager.getInstance().getFile(it) }
return virtualFile?.toUriOrNull()?.let {
mapOf(
"path" to it,
"contents" to editor.document.text,
"isUntitled" to false
)
override suspend fun getOpenFiles(): List<String> =
withContext(Dispatchers.EDT) {
FileEditorManager.getInstance(project).openFiles
.mapNotNull { it.toUriOrNull() }
.toList()
}
override suspend fun getCurrentFile(): Map<String, Any>? =
withContext(Dispatchers.EDT) {
val fileEditorManager = FileEditorManager.getInstance(project)
val document = fileEditorManager.selectedTextEditor?.document
val virtualFile = document?.let { FileDocumentManager.getInstance().getFile(it) }
virtualFile?.toUriOrNull()?.let {
mapOf(
"path" to it,
"contents" to document.text,
"isUntitled" to false
)
}
}
}
override suspend fun getPinnedFiles(): List<String> {
// Returning open files for now as per existing code
@ -344,11 +345,10 @@ class IntelliJIDE(
command.setWorkDirectory(project.basePath)
val results = ExecUtil.execAndGetOutput(command).stdout
return results.split("\n")
} catch (e: Exception) {
showToast(
ToastType.ERROR,
"Error executing ripgrep: ${e.message}"
)
} catch (exception: Exception) {
val message = "Error executing ripgrep: ${exception.message}"
service<ContinueErrorService>().report(exception, message)
showToast(ToastType.ERROR, message)
return emptyList()
}
} else {
@ -386,11 +386,10 @@ class IntelliJIDE(
command.setWorkDirectory(project.basePath)
return ExecUtil.execAndGetOutput(command).stdout
} catch (e: Exception) {
showToast(
ToastType.ERROR,
"Error executing ripgrep: ${e.message}"
)
} catch (exception: Exception) {
val message = "Error executing ripgrep: ${exception.message}"
service<ContinueErrorService>().report(exception, message)
showToast(ToastType.ERROR, message)
return "Error: Unable to execute ripgrep command."
}
} else {
@ -530,10 +529,9 @@ class IntelliJIDE(
}
val deferred = CompletableDeferred<String?>()
val icon = IconLoader.getIcon("/icons/continue.svg", javaClass)
val notification = NotificationGroupManager.getInstance().getNotificationGroup("Continue")
.createNotification(message, notificationType).setIcon(icon)
.createNotification(message, notificationType).setIcon(Icons.Continue)
val buttonTexts = otherParams.filterIsInstance<String>().toTypedArray()
buttonTexts.forEach { buttonText ->

View file

@ -7,7 +7,7 @@ import com.github.continuedev.continueintellijextension.services.ContinuePluginS
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.command.undo.UndoManager
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.markup.HighlighterLayer
import com.intellij.openapi.editor.markup.RangeHighlighter
@ -42,7 +42,6 @@ class DiffStreamHandler(
private var isRunning: Boolean = false
private var hasAcceptedOrRejectedBlock: Boolean = false
private val unfinishedHighlighters: MutableList<RangeHighlighter> = mutableListOf()
private val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java)
private val virtualFile = FileDocumentManager.getInstance().getFile(editor.document)
@ -62,10 +61,10 @@ class DiffStreamHandler(
numDiffs = diffBlocks.size,
filepath = virtualFile?.url,
fileContent = "not implemented",
toolCallId = toolCallId?.toString()
toolCallId = toolCallId
)
continuePluginService.sendToWebview("updateApplyState", payload)
project.service<ContinuePluginService>().sendToWebview("updateApplyState", payload)
}
fun acceptAll() {
@ -102,7 +101,7 @@ class DiffStreamHandler(
isRunning = true
sendUpdate(ApplyStateStatus.STREAMING)
continuePluginService.coreMessenger?.request(
project.service<ContinuePluginService>().coreMessenger?.request(
"streamDiffLines",
StreamDiffLinesPayload(
input = input,

View file

@ -1,5 +1,6 @@
package com.github.continuedev.continueintellijextension.editor
import com.github.continuedev.continueintellijextension.Icons
import com.github.continuedev.continueintellijextension.`continue`.GetTheme
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
@ -357,8 +358,7 @@ class CustomPanel(
}
private fun createCloseButton(): JComponent {
val closeIcon = IconLoader.getIcon("/icons/close.svg", javaClass)
return JLabel(closeIcon).apply {
return JLabel(Icons.Close).apply {
background = Color(0, 0, 0, 0)
border = JBUI.Borders.empty(2, 6, 2, 0)
toolTipText = "`esc` to cancel"

View file

@ -0,0 +1,50 @@
package com.github.continuedev.continueintellijextension.error
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.components.Service
import com.intellij.openapi.diagnostic.Attachment
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.PluginId
import com.intellij.ui.jcef.JBCefApp
import io.sentry.Hint
import io.sentry.Sentry
import io.sentry.SentryEvent
import io.sentry.protocol.Message
private typealias SentryAttachment = io.sentry.Attachment
@Service
class ContinueErrorService {
private val log = Logger.getInstance(ContinueErrorService::class.java)
init {
Sentry.init { config ->
config.dsn = SENTRY_DSN
config.isSendDefaultPii = false
config.setTag("ide_version", ApplicationInfo.getInstance().build.asString())
config.setTag("jcef_supported", JBCefApp.isSupported().toString())
config.setTag("plugin_version", PluginManagerCore.getPlugin(PluginId.getId(PLUGIN_ID))?.version)
}
}
fun report(
throwable: Throwable,
message: String? = null,
attachments: List<Attachment>? = null
) {
val sentryEvent = SentryEvent()
sentryEvent.throwable = throwable
sentryEvent.message = Message().apply { this.message = message }
val hint = Hint.withAttachments(attachments?.map { SentryAttachment(it.bytes, it.path) })
Sentry.captureEvent(sentryEvent, hint)
log.warn("Problem sent to Sentry: $message", throwable)
}
private companion object {
private const val PLUGIN_ID = "com.github.continuedev.continueintellijextension"
private const val SENTRY_DSN =
"https://fe99934dcdc537d84209893a3f96a196@o4505462064283648.ingest.us.sentry.io/4508184596054016"
}
}

View file

@ -1,29 +1,16 @@
package com.github.continuedev.continueintellijextension.error
import com.intellij.diagnostic.IdeaReportingEvent
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.ErrorReportSubmitter
import com.intellij.openapi.diagnostic.IdeaLoggingEvent
import com.intellij.openapi.diagnostic.SubmittedReportInfo
import com.intellij.openapi.diagnostic.SubmittedReportInfo.SubmissionStatus
import com.intellij.ui.jcef.JBCefApp
import com.intellij.util.Consumer
import io.sentry.Sentry
import io.sentry.SentryEvent
import io.sentry.protocol.Message
import java.awt.Component
class ContinueErrorSubmitter : ErrorReportSubmitter() {
init {
Sentry.init { config ->
config.dsn = SENTRY_DSN
config.isSendDefaultPii = false
config.setTag("ide_version", ApplicationInfo.getInstance().build.asString())
config.setTag("jcef_supported", JBCefApp.isSupported().toString())
}
}
override fun getReportActionText() =
"Report to Continue"
@ -34,12 +21,13 @@ class ContinueErrorSubmitter : ErrorReportSubmitter() {
consumer: Consumer<in SubmittedReportInfo>
): Boolean {
try {
val event = events.filterIsInstance<IdeaReportingEvent>().firstOrNull() ?: return false
val sentryEvent = SentryEvent()
sentryEvent.throwable = event.data.throwable
sentryEvent.message = Message().apply { message = additionalInfo }
sentryEvent.setTag("plugin_version", event.plugin?.version)
Sentry.captureEvent(sentryEvent)
val event = events.filterIsInstance<IdeaReportingEvent>()
.firstOrNull() ?: return false
service<ContinueErrorService>().report(
throwable = event.data.throwable,
message = additionalInfo ?: event.data.message,
attachments = event.data.allAttachments
)
} catch (_: Exception) {
consumer.consume(SubmittedReportInfo(SubmissionStatus.FAILED))
return false
@ -48,8 +36,4 @@ class ContinueErrorSubmitter : ErrorReportSubmitter() {
return true
}
private companion object {
private const val SENTRY_DSN = "https://fe99934dcdc537d84209893a3f96a196@o4505462064283648.ingest.us.sentry.io/4508184596054016"
}
}

View file

@ -111,7 +111,7 @@ open class ContinueExtensionSettings : PersistentStateComponent<ContinueExtensio
companion object {
val instance: ContinueExtensionSettings
get() = ServiceManager.getService(ContinueExtensionSettings::class.java)
get() = service<ContinueExtensionSettings>()
}

View file

@ -9,30 +9,21 @@ import com.github.continuedev.continueintellijextension.utils.uuid
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.ui.jcef.*
import com.intellij.ui.jcef.JBCefClient.Properties
import com.intellij.util.application
import org.cef.CefApp
import org.cef.browser.CefBrowser
import org.cef.handler.CefLoadHandlerAdapter
class ContinueBrowser(val project: Project, url: String) {
private fun registerAppSchemeHandler() {
CefApp.getInstance().registerSchemeHandlerFactory(
"http",
"continue",
CustomSchemeHandlerFactory()
)
}
val browser: JBCefBrowser
val continuePluginService: ContinuePluginService = project.getService(ContinuePluginService::class.java)
init {
val isOSREnabled = application.getService(ContinueExtensionSettings::class.java).continueState.enableOSR
val isOSREnabled = service<ContinueExtensionSettings>().continueState.enableOSR
this.browser = JBCefBrowser.createBuilder().setOffScreenRendering(isOSREnabled).build().apply {
// To avoid using System.setProperty to affect other plugins,
@ -43,7 +34,7 @@ class ContinueBrowser(val project: Project, url: String) {
}
registerAppSchemeHandler()
Disposer.register(ContinuePluginDisposable.getInstance(project), browser)
Disposer.register(project.service<ContinuePluginDisposable>(), browser)
// Listen for events sent from browser
val myJSQueryOpenInBrowser = JBCefJSQuery.create((browser as JBCefBrowserBase?)!!)
@ -60,7 +51,7 @@ class ContinueBrowser(val project: Project, url: String) {
}
if (PASS_THROUGH_TO_CORE.contains(messageType)) {
continuePluginService.coreMessenger?.request(messageType, data, messageId, respond)
project.service<ContinuePluginService>().coreMessenger?.request(messageType, data, messageId, respond)
return@addHandler null
}
@ -75,7 +66,7 @@ class ContinueBrowser(val project: Project, url: String) {
}
if (msg != null) {
continuePluginService.ideProtocolClient?.handleMessage(msg, respondToWebview)
project.service<ContinuePluginService>().ideProtocolClient?.handleMessage(msg, respondToWebview)
}
null
@ -99,7 +90,7 @@ class ContinueBrowser(val project: Project, url: String) {
// Load the url only after the protocolClient is initialized,
// otherwise some messages will be lost, which are some configurations when the page is loaded.
// Moreover, we should add LoadHandler before loading the url.
continuePluginService.onProtocolClientInitialized {
project.service<ContinuePluginService>().onProtocolClientInitialized {
browser.loadURL(url)
}
@ -138,6 +129,14 @@ class ContinueBrowser(val project: Project, url: String) {
}
}
private fun registerAppSchemeHandler() {
CefApp.getInstance().registerSchemeHandlerFactory(
"http",
"continue",
CustomSchemeHandlerFactory()
)
}
private fun buildJavaScript(jsonData: String): String {
return """window.postMessage($jsonData, "*");"""
}

View file

@ -3,13 +3,13 @@ package com.github.continuedev.continueintellijextension.toolWindow
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.service
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowFactory
import com.intellij.ui.content.ContentFactory
import javax.swing.*
import javax.swing.JComponent
const val JS_QUERY_POOL_SIZE = "200"
@ -52,9 +52,7 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
val url = System.getenv("GUI_URL")?.toString() ?: defaultGUIUrl
val browser = ContinueBrowser(project, url)
val continuePluginService =
ServiceManager.getService(project, ContinuePluginService::class.java)
continuePluginService.continuePluginWindow = this
project.service<ContinuePluginService>().continuePluginWindow = this
browser
}

Some files were not shown because too many files have changed in this diff Show more