Merge branch 'main' into watsonx-vi

This commit is contained in:
Nate 2025-05-29 10:05:58 -07:00
commit 67b5165229
40 changed files with 651 additions and 180 deletions

View file

@ -0,0 +1,13 @@
name: bigger-picture-description-rules
version: 0.0.1
schema: v1
rules:
- name: bigger-picture-description-rules
rule: >-
When a user asks how a certain part of the code works:
1. Describe what the code does in isolation.
2. If the code interacts with other parts of the codebase, describe how the code is imported and used in other parts of the codebase.
3. When describing each use-case, include the parent function for clarity.

View file

@ -0,0 +1,11 @@
---
globs: core/llm/llms/**/*.{ts,test.ts}
description: Tailor recommendations for LLM code based on which specific LLM is being used.
---
# LLM Model Specificity
- Refer to the file name and names of big classes to determine which LLM is being used in a file.
- Ground all observations and recommendations with knowledge of that LLM.
- Consider items such as context length, architecture, speed, and such.
- Pay attention to the parent classes in these files.

1
.gitignore vendored
View file

@ -144,6 +144,7 @@ Icon?
.continuerc.json
.aider*
*.notes.md
notes.md
*.notes.md

View file

@ -51,7 +51,6 @@ import { LLMReranker } from "../llm/llms/llm";
import TransformersJsEmbeddingsProvider from "../llm/llms/TransformersJsEmbeddingsProvider";
import { slashCommandFromPromptFileV1 } from "../promptFiles/v1/slashCommandFromPromptFile";
import { getAllPromptFiles } from "../promptFiles/v2/getPromptFiles";
import { allTools } from "../tools";
import { copyOf } from "../util";
import { GlobalContext } from "../util/GlobalContext";
import mergeJson from "../util/merge";
@ -67,6 +66,7 @@ import {
} from "../util/paths";
import { localPathToUri } from "../util/pathToUri";
import { baseToolDefinitions } from "../tools";
import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
import {
getModelByRole,
@ -529,7 +529,7 @@ async function intermediateToFinalConfig({
const continueConfig: ContinueConfig = {
...config,
contextProviders,
tools: [...allTools],
tools: [...baseToolDefinitions],
mcpServerStatuses: [],
slashCommands: config.slashCommands ?? [],
modelsByRole: {

View file

@ -25,6 +25,7 @@ import { ControlPlaneClient } from "../../control-plane/client.js";
import { getControlPlaneEnv } from "../../control-plane/env.js";
import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js";
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy";
import { getConfigDependentToolDefinitions } from "../../tools";
import { encodeMCPToolUri } from "../../tools/callTool";
import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths";
import { localPathOrUriToPath } from "../../util/pathToUri";
@ -176,12 +177,21 @@ export default async function doLoadConfig(options: {
);
newConfig.slashCommands.push(...serverSlashCommands);
const submenuItems = server.resources.map((resource) => ({
title: resource.name,
description: resource.description ?? resource.name,
id: resource.uri,
icon: server.faviconUrl,
}));
const submenuItems = server.resources
.map((resource) => ({
title: resource.name,
description: resource.description ?? resource.name,
id: resource.uri,
icon: server.faviconUrl,
}))
.concat(
server.resourceTemplates.map((template) => ({
title: template.name,
description: template.description ?? template.name,
id: template.uriTemplate,
icon: server.faviconUrl,
})),
);
if (submenuItems.length > 0) {
const serverContextProvider = new MCPContextProvider({
submenuItems,
@ -193,6 +203,12 @@ export default async function doLoadConfig(options: {
}
}
newConfig.tools.push(
...getConfigDependentToolDefinitions({
rules: newConfig.rules,
}),
);
// Detect duplicate tool names
const counts: Record<string, number> = {};
newConfig.tools.forEach((tool) => {
@ -202,6 +218,7 @@ export default async function doLoadConfig(options: {
counts[tool.function.name] = 1;
}
});
Object.entries(counts).forEach(([toolName, count]) => {
if (count > 1) {
errors!.push({
@ -211,6 +228,26 @@ export default async function doLoadConfig(options: {
}
});
const ruleCounts: Record<string, number> = {};
newConfig.rules.forEach((rule) => {
if (rule.name) {
if (ruleCounts[rule.name]) {
ruleCounts[rule.name] = ruleCounts[rule.name] + 1;
} else {
ruleCounts[rule.name] = 1;
}
}
});
Object.entries(ruleCounts).forEach(([ruleName, count]) => {
if (count > 1) {
errors!.push({
fatal: false,
message: `Duplicate (${count}) rules named "${ruleName}" detected. This may cause unexpected behavior`,
});
}
});
newConfig.allowAnonymousTelemetry =
newConfig.allowAnonymousTelemetry && (await ide.isTelemetryEnabled());

View file

@ -36,11 +36,11 @@ import FreeTrial from "../../llm/llms/FreeTrial";
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
import { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandFromPromptFile";
import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles";
import { allTools } from "../../tools";
import { GlobalContext } from "../../util/GlobalContext";
import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
import { getControlPlaneEnvSync } from "../../control-plane/env";
import { baseToolDefinitions } from "../../tools";
import { getCleanUriPath } from "../../util/uri";
import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
import { LocalPlatformClient } from "./LocalPlatformClient";
@ -193,7 +193,7 @@ async function configYamlToContinueConfig(options: {
const continueConfig: ContinueConfig = {
slashCommands: [],
tools: [...allTools],
tools: [...baseToolDefinitions],
mcpServerStatuses: [],
contextProviders: [],
modelsByRole: {

View file

@ -111,6 +111,7 @@ describe("MCPConnection", () => {
errors: [],
prompts: [],
resources: [],
resourceTemplates: [],
tools: [],
status: "not-connected",
});

View file

@ -3,14 +3,15 @@ import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js";
import {
MCPConnectionStatus,
MCPOptions,
MCPPrompt,
MCPResource,
MCPResourceTemplate,
MCPServerStatus,
MCPTool,
} from "../..";
@ -37,6 +38,7 @@ class MCPConnection {
public prompts: MCPPrompt[] = [];
public tools: MCPTool[] = [];
public resources: MCPResource[] = [];
public resourceTemplates: MCPResourceTemplate[] = [];
private transport: Transport;
private connectionPromise: Promise<unknown> | null = null;
private stdioOutput: { stdout: string; stderr: string } = {
@ -72,6 +74,7 @@ class MCPConnection {
errors: this.errors,
prompts: this.prompts,
resources: this.resources,
resourceTemplates: this.resourceTemplates,
tools: this.tools,
status: this.status,
};
@ -95,6 +98,7 @@ class MCPConnection {
this.tools = [];
this.prompts = [];
this.resources = [];
this.resourceTemplates = [];
this.errors = [];
this.stdioOutput = { stdout: "", stderr: "" };
@ -169,6 +173,23 @@ class MCPConnection {
}
this.errors.push(errorMessage);
}
// Resource templates
try {
const { resourceTemplates } =
await this.client.listResourceTemplates(
{},
{ signal: timeoutController.signal },
);
this.resourceTemplates = resourceTemplates;
} catch (e) {
let errorMessage = `Error loading resource templates for MCP Server ${this.options.name}`;
if (e instanceof Error) {
errorMessage += `: ${e.message}`;
}
this.errors.push(errorMessage);
}
}
// Tools <—> Tools
@ -337,9 +358,12 @@ class MCPConnection {
requestInit: { headers: options.transport.requestOptions?.headers },
});
case "streamable-http":
return new StreamableHTTPClientTransport(new URL(options.transport.url), {
requestInit: { headers: options.transport.requestOptions?.headers },
});
return new StreamableHTTPClientTransport(
new URL(options.transport.url),
{
requestInit: { headers: options.transport.requestOptions?.headers },
},
);
default:
throw new Error(
`Unsupported transport type: ${(options.transport as any).type}`,

View file

@ -20,6 +20,7 @@ class MCPContextProvider extends BaseContextProvider {
displayTitle: "MCP",
description: "Model Context Protocol",
type: "submenu",
renderInlineAs: "",
};
override get description(): ContextProviderDescription {
return {
@ -27,6 +28,7 @@ class MCPContextProvider extends BaseContextProvider {
displayTitle: this.options["serverName"]
? `${this.options["serverName"]} resources`
: "MCP",
renderInlineAs: "",
description: "Model Context Protocol",
type: "submenu",
};
@ -47,6 +49,18 @@ class MCPContextProvider extends BaseContextProvider {
super(options);
}
/**
* Continue experimentally supports resource templates (https://modelcontextprotocol.io/docs/concepts/resources#resource-templates)
* by allowing specifically just the "query" variable in the template, which we will update with the full input of the user in the input box
*/
private insertInputToUriTemplate(uri: string, query: string): string {
const TEMPLATE_VAR = "query";
if (uri.includes(`{${TEMPLATE_VAR}}`)) {
return uri.replace(`{${TEMPLATE_VAR}}`, encodeURIComponent(query));
}
return uri;
}
async getContextItems(
query: string,
extras: ContextProviderExtras,
@ -58,7 +72,9 @@ class MCPContextProvider extends BaseContextProvider {
throw new Error(`No MCP connection found for ${mcpId}`);
}
const { contents } = await connection.client.readResource({ uri });
const { contents } = await connection.client.readResource({
uri: this.insertInputToUriTemplate(uri, extras.fullInput),
});
return await Promise.all(
contents.map(async (resource) => {

View file

@ -13,14 +13,10 @@ export interface OnPremSessionInfo {
export type ControlPlaneSessionInfo = HubSessionInfo | OnPremSessionInfo;
export function isHubSession(
export function isOnPremSession(
sessionInfo: ControlPlaneSessionInfo | undefined,
): sessionInfo is HubSessionInfo {
return (
sessionInfo !== undefined &&
(sessionInfo.AUTH_TYPE === AuthType.WorkOsProd ||
sessionInfo.AUTH_TYPE === AuthType.WorkOsStaging)
);
): sessionInfo is OnPremSessionInfo {
return sessionInfo !== undefined && sessionInfo.AUTH_TYPE === AuthType.OnPrem;
}
export enum AuthType {

View file

@ -12,7 +12,7 @@ import fetch, { RequestInit, Response } from "node-fetch";
import { OrganizationDescription } from "../config/ProfileLifecycleManager.js";
import { IdeSettings, ModelDescription } from "../index.js";
import { ControlPlaneSessionInfo, isHubSession } from "./AuthTypes.js";
import { ControlPlaneSessionInfo, isOnPremSession } from "./AuthTypes.js";
import { getControlPlaneEnv } from "./env.js";
export interface ControlPlaneWorkspace {
@ -63,17 +63,16 @@ export class ControlPlaneClient {
async getAccessToken(): Promise<string | undefined> {
const sessionInfo = await this.sessionInfoPromise;
return isHubSession(sessionInfo) ? sessionInfo.accessToken : undefined;
return isOnPremSession(sessionInfo) ? undefined : sessionInfo?.accessToken;
}
private async request(path: string, init: RequestInit): Promise<Response> {
const sessionInfo = await this.sessionInfoPromise;
const hubSession = isHubSession(sessionInfo);
const accessToken = hubSession ? sessionInfo.accessToken : undefined;
const onPremSession = isOnPremSession(sessionInfo);
const accessToken = await this.getAccessToken();
// Bearer token not necessary for on-prem auth type
if (!accessToken && hubSession) {
if (!accessToken && !onPremSession) {
throw new Error("No access token");
}

View file

@ -723,6 +723,7 @@ export class Core {
};
return await callTool(tool, toolCall.function.arguments, {
config,
ide: this.ide,
llm: config.selectedModelByRole.chat,
fetch: (url, init) =>

19
core/index.d.ts vendored
View file

@ -975,6 +975,7 @@ export interface ToolExtras {
toolCallId: string;
contextItems: ContextItem[];
}) => void;
config: ContinueConfig;
}
export interface Tool {
@ -1004,6 +1005,12 @@ interface ToolChoice {
};
}
export interface ConfigDependentToolParams {
rules: RuleWithSource[];
}
export type GetTool = (params: ConfigDependentToolParams) => Tool;
export interface BaseCompletionOptions {
temperature?: number;
topP?: number;
@ -1141,7 +1148,7 @@ export interface StreamableHTTPOptions {
requestOptions?: RequestOptions;
}
export type TransportOptions =
export type TransportOptions =
| StdioOptions
| WebSocketOptions
| SSEOptions
@ -1174,6 +1181,7 @@ export interface MCPPrompt {
// Leaving here to ideate on
// export type ContinueConfigSource = "local-yaml" | "local-json" | "hub-assistant" | "hub"
// https://modelcontextprotocol.io/docs/concepts/resources#direct-resources
export interface MCPResource {
name: string;
uri: string;
@ -1181,6 +1189,14 @@ export interface MCPResource {
mimeType?: string;
}
// https://modelcontextprotocol.io/docs/concepts/resources#resource-templates
export interface MCPResourceTemplate {
uriTemplate: string;
name: string;
description?: string;
mimeType?: string;
}
export interface MCPTool {
name: string;
description?: string;
@ -1197,6 +1213,7 @@ export interface MCPServerStatus extends MCPOptions {
prompts: MCPPrompt[];
tools: MCPTool[];
resources: MCPResource[];
resourceTemplates: MCPResourceTemplate[];
}
export interface ContinueUIConfig {

View file

@ -11,8 +11,7 @@ test("tagToString returns full tag string when under length limit", () => {
expect(tagToString(tag)).toBe("/normal/path/to/repo::main::12345");
});
test("tagToString truncates beginning of directory when path is too long", () => {
// Create a very long directory path that exceeds MAX_DIR_LENGTH (200)
test("tagToString truncates beginning of directory when path is too long and adds hash for uniqueness", () => {
const longPrefix = "/very/long/path/that/will/be/truncated/";
const importantSuffix = "/user/important-project/src/feature";
const longPath = longPrefix + "x".repeat(200) + importantSuffix;
@ -25,18 +24,14 @@ test("tagToString truncates beginning of directory when path is too long", () =>
const result = tagToString(tag);
// The result should keep the important suffix part
expect(result).toContain(importantSuffix);
// The result should NOT contain the beginning of the path
expect(result).not.toContain(longPrefix);
// The result should include the branch and artifactId
expect(result).toContain("::feature-branch::67890");
// The result should be within the MAX_TABLE_NAME_LENGTH limit (240)
expect(result.length).toBeLessThanOrEqual(240);
expect(result).toMatch(/^[a-f0-9]{8}_/);
expect(result).toContain(importantSuffix);
});
test("tagToString preserves branch and artifactId exactly, even when truncating", () => {
const longPath = "/a".repeat(300); // Much longer than MAX_DIR_LENGTH
const longPath = "/a".repeat(300);
const tag: IndexTag = {
directory: longPath,
branch: "release-v2.0",
@ -45,14 +40,56 @@ test("tagToString preserves branch and artifactId exactly, even when truncating"
const result = tagToString(tag);
// Should contain the exact branch and artifactId
expect(result).toContain("::release-v2.0::build-123");
// Should contain the end of the path
expect(result).toContain("/a/a/a");
// Should not contain the full original path (it should be truncated)
expect(result.length).toBeLessThan(
longPath.length + "::release-v2.0::build-123".length,
);
// The result should be within the MAX_TABLE_NAME_LENGTH limit
expect(result).toMatch(/^[a-f0-9]{8}_/);
expect(result.length).toBeLessThanOrEqual(240);
});
test("tagToString ensures uniqueness for different long paths that would otherwise collide", () => {
const basePath = "/very/long/base/path/that/exceeds/limits/";
const commonSuffix = "/same/ending/path";
const tag1: IndexTag = {
directory: basePath + "different1" + "x".repeat(100) + commonSuffix,
branch: "main",
artifactId: "12345",
};
const tag2: IndexTag = {
directory: basePath + "different2" + "y".repeat(100) + commonSuffix,
branch: "main",
artifactId: "12345",
};
const fullString1 = `${tag1.directory}::${tag1.branch}::${tag1.artifactId}`;
const fullString2 = `${tag2.directory}::${tag2.branch}::${tag2.artifactId}`;
const result1 = tagToString(tag1);
const result2 = tagToString(tag2);
expect(result1).not.toBe(result2);
expect(result1.length).toBeLessThanOrEqual(240);
expect(result2.length).toBeLessThanOrEqual(240);
if (fullString1.length > 240) {
expect(result1).toMatch(/^[a-f0-9]{8}_/);
expect(result2).toMatch(/^[a-f0-9]{8}_/);
} else {
expect(result1).toBe(fullString1);
expect(result2).toBe(fullString2);
}
});
test("tagToString produces consistent results for the same input", () => {
const tag: IndexTag = {
directory:
"/some/very/long/path/that/exceeds/the/maximum/length/limit/for/directory/names/in/the/system",
branch: "develop",
artifactId: "test-123",
};
const result1 = tagToString(tag);
const result2 = tagToString(tag);
expect(result1).toBe(result2);
});

View file

@ -1,3 +1,4 @@
import crypto from "crypto";
import { IndexTag } from "..";
// Maximum length for table names to stay under OS filename limits
@ -18,8 +19,8 @@ const MAX_DIR_LENGTH = 200;
*
* To handle long paths:
* 1. First tries the full string - most backwards compatible
* 2. If too long, truncates directory from the beginning to maintain uniqueness
* (since final parts of paths are more unique than prefixes)
* 2. If too long, truncates directory from the beginning and adds a hash prefix
* to ensure uniqueness while preserving the more readable end parts
* 3. Finally ensures entire string stays under MAX_TABLE_NAME_LENGTH for OS compatibility
*
* @param tag The tag containing directory, branch, and artifactId
@ -32,14 +33,22 @@ export function tagToString(tag: IndexTag): string {
return result;
}
// Create a hash of the full directory path to ensure uniqueness
const dirHash = crypto
.createHash("md5")
.update(tag.directory)
.digest("hex")
.slice(0, 8);
// Calculate how much space we have for the directory after accounting for hash, separators, branch, and artifactId
const nonDirLength = `${dirHash}_::${tag.branch}::${tag.artifactId}`.length;
const maxDirForTruncated = MAX_TABLE_NAME_LENGTH - nonDirLength;
// Truncate from the beginning of directory path to preserve the more unique end parts
const dir =
tag.directory.length > MAX_DIR_LENGTH
? tag.directory.slice(tag.directory.length - MAX_DIR_LENGTH)
const truncatedDir =
tag.directory.length > maxDirForTruncated
? tag.directory.slice(tag.directory.length - maxDirForTruncated)
: tag.directory;
return `${dir}::${tag.branch}::${tag.artifactId}`.slice(
0,
MAX_TABLE_NAME_LENGTH,
);
return `${dirHash}_${truncatedDir}::${tag.branch}::${tag.artifactId}`;
}

View file

@ -10,6 +10,7 @@ export enum BuiltInToolNames {
ViewDiff = "builtin_view_diff",
LSTool = "builtin_ls",
CreateRuleBlock = "builtin_create_rule_block",
RequestRule = "builtin_request_rule",
// excluded from allTools for now
ViewRepoMap = "builtin_view_repo_map",
@ -18,4 +19,4 @@ export enum BuiltInToolNames {
export const BUILT_IN_GROUP_NAME = "Built-In";
export const CLIENT_TOOLS = [BuiltInToolNames.EditExistingFile];
export const CLIENT_TOOLS_IMPLS = [BuiltInToolNames.EditExistingFile];

View file

@ -10,6 +10,7 @@ import { grepSearchImpl } from "./implementations/grepSearch";
import { lsToolImpl } from "./implementations/lsTool";
import { readCurrentlyOpenFileImpl } from "./implementations/readCurrentlyOpenFile";
import { readFileImpl } from "./implementations/readFile";
import { requestRuleImpl } from "./implementations/requestRule";
import { runTerminalCommandImpl } from "./implementations/runTerminalCommand";
import { searchWebImpl } from "./implementations/searchWeb";
import { viewDiffImpl } from "./implementations/viewDiff";
@ -157,6 +158,8 @@ async function callBuiltInTool(
return await readCurrentlyOpenFileImpl(args, extras);
case BuiltInToolNames.CreateRuleBlock:
return await createRuleBlockImpl(args, extras);
case BuiltInToolNames.RequestRule:
return await requestRuleImpl(args, extras);
default:
throw new Error(`Tool "${functionName}" not found`);
}

View file

@ -6,7 +6,7 @@ export const globSearchTool: Tool = {
displayTitle: "Glob File Search",
wouldLikeTo: 'find file matches for "{{{ pattern }}}"',
isCurrently: 'finding file matches for "{{{ pattern }}}"',
hasAlready: 'retreived file matches for "{{{ pattern }}}"',
hasAlready: 'retrieved file matches for "{{{ pattern }}}"',
readonly: true,
isInstant: true,
group: BUILT_IN_GROUP_NAME,

View file

@ -0,0 +1,237 @@
import { RuleWithSource } from "../..";
import { getRequestRuleDescription } from "./requestRule";
describe("getRequestRuleDescription", () => {
it("should return no rules message when no agent-requested rules exist", () => {
const rules: RuleWithSource[] = [
{
name: "Always Apply Rule",
description: "This rule always applies",
source: "default-chat",
rule: "Always use semicolons",
alwaysApply: true,
ruleFile: "/path/to/rule1.md",
},
{
name: "Rule with Globs",
description: "This rule has globs",
source: "rules-block",
rule: "Use TypeScript",
globs: "**/*.ts",
ruleFile: "/path/to/rule2.md",
},
];
const result = getRequestRuleDescription(rules);
expect(result).toBe(
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\nNo rules available.",
);
});
it("should return formatted rules when agent-requested rules exist", () => {
const rules: RuleWithSource[] = [
{
name: "Agent Rule 1",
description: "First agent-requested rule",
source: "rules-block",
rule: "Use consistent formatting",
alwaysApply: false,
ruleFile: "/path/to/agent-rule1.md",
},
{
name: "Agent Rule 2",
description: "Second agent-requested rule",
source: "default-agent",
rule: "Follow naming conventions",
alwaysApply: false,
ruleFile: "/path/to/agent-rule2.md",
},
// These should be filtered out
{
name: "Always Apply Rule",
description: "This rule always applies",
source: "default-chat",
rule: "Always use semicolons",
alwaysApply: true,
ruleFile: "/path/to/rule1.md",
},
{
name: "Rule with Globs",
description: "This rule has globs",
source: "rules-block",
rule: "Use TypeScript",
globs: "**/*.ts",
ruleFile: "/path/to/rule2.md",
},
];
const result = getRequestRuleDescription(rules);
const expected =
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" +
"Agent Rule 1: First agent-requested rule\n" +
"Agent Rule 2: Second agent-requested rule";
expect(result).toBe(expected);
});
it("should handle rules with missing description", () => {
const rules: RuleWithSource[] = [
{
name: "Rule Without Description",
source: "rules-block",
rule: "Some rule content",
alwaysApply: false,
ruleFile: "/path/to/no-desc-rule.md",
},
];
const result = getRequestRuleDescription(rules);
const expected =
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" +
"Rule Without Description: undefined";
expect(result).toBe(expected);
});
it("should handle rules with missing name", () => {
const rules: RuleWithSource[] = [
{
description: "Rule without name",
source: "rules-block",
rule: "Some rule content",
alwaysApply: false,
ruleFile: "/path/to/no-name-rule.md",
},
];
const result = getRequestRuleDescription(rules);
const expected =
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" +
"undefined: Rule without name";
expect(result).toBe(expected);
});
it("should handle rules with missing ruleFile", () => {
const rules: RuleWithSource[] = [
{
name: "Rule Without File",
description: "Rule without file path",
source: "rules-block",
rule: "Some rule content",
alwaysApply: false,
},
];
const result = getRequestRuleDescription(rules);
const expected =
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" +
"Rule Without File: Rule without file path";
expect(result).toBe(expected);
});
it("should filter out rules with alwaysApply undefined (truthy)", () => {
const rules: RuleWithSource[] = [
{
name: "Rule with undefined alwaysApply",
description: "This should be filtered out",
source: "rules-block",
rule: "Some rule",
ruleFile: "/path/to/rule.md",
// alwaysApply is undefined, which is truthy in the filter condition
},
{
name: "Valid Agent Rule",
description: "This should be included",
source: "rules-block",
rule: "Some rule",
alwaysApply: false,
ruleFile: "/path/to/valid-rule.md",
},
];
const result = getRequestRuleDescription(rules);
const expected =
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" +
"Valid Agent Rule: This should be included";
expect(result).toBe(expected);
});
it("should filter out rules with any globs defined", () => {
const rules: RuleWithSource[] = [
{
name: "Rule with string globs",
description: "This should be filtered out",
source: "rules-block",
rule: "Some rule",
alwaysApply: false,
globs: "**/*.ts",
ruleFile: "/path/to/rule1.md",
},
{
name: "Rule with array globs",
description: "This should also be filtered out",
source: "rules-block",
rule: "Some rule",
alwaysApply: false,
globs: ["**/*.ts", "**/*.js"],
ruleFile: "/path/to/rule2.md",
},
{
name: "Valid Agent Rule",
description: "This should be included",
source: "rules-block",
rule: "Some rule",
alwaysApply: false,
ruleFile: "/path/to/valid-rule.md",
},
];
const result = getRequestRuleDescription(rules);
const expected =
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" +
"Valid Agent Rule: This should be included";
expect(result).toBe(expected);
});
it("should handle empty rules array", () => {
const rules: RuleWithSource[] = [];
const result = getRequestRuleDescription(rules);
expect(result).toBe(
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\nNo rules available.",
);
});
it("should handle single agent-requested rule", () => {
const rules: RuleWithSource[] = [
{
name: "Single Rule",
description: "The only agent-requested rule",
source: "rules-block",
rule: "Follow this guideline",
alwaysApply: false,
ruleFile: "/path/to/single-rule.md",
},
];
const result = getRequestRuleDescription(rules);
const expected =
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n" +
"Single Rule: The only agent-requested rule";
expect(result).toBe(expected);
});
});

View file

@ -0,0 +1,52 @@
import { ConfigDependentToolParams, GetTool } from "../..";
import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn";
export interface RequestRuleArgs {
name: string;
}
export function getRequestRuleDescription(
rules: ConfigDependentToolParams["rules"],
): string {
// Must be explicitly false and no globs
const agentRequestedRules = rules.filter(
(rule) => rule.alwaysApply === false && !rule.globs,
);
const prefix =
"Use this tool to select additional rules, specifically based on their descriptions. Available rules:\n";
const body = agentRequestedRules
.map((rule) => `${rule.name}: ${rule.description}`)
.join("\n");
if (body.length === 0) {
return prefix + "No rules available.";
}
return prefix + body;
}
export const requestRuleTool: GetTool = ({ rules }) => ({
type: "function",
displayTitle: "Request Rules",
wouldLikeTo: "request rule {{{ name }}}",
isCurrently: "reading rule {{{ name }}}",
hasAlready: "read rule {{{ name }}}",
group: BUILT_IN_GROUP_NAME,
readonly: false,
function: {
name: BuiltInToolNames.RequestRule,
description: getRequestRuleDescription(rules),
parameters: {
type: "object",
required: ["name"],
properties: {
name: {
type: "string",
description: "Name of the rule",
},
},
},
},
});

View file

@ -0,0 +1,28 @@
import { ToolImpl } from ".";
import { parseMarkdownRule } from "../../config/markdown/parseMarkdownRule";
export const requestRuleImpl: ToolImpl = async (args, extras) => {
// Find the rule by name in the config
const rule = extras.config.rules.find((r) => r.name === args.name);
if (!rule || !rule.ruleFile) {
throw new Error(
`Rule with name "${args.name}" not found or has no file path`,
);
}
const fileContent = await extras.ide.readFile(rule.ruleFile);
const { markdown, frontmatter } = parseMarkdownRule(fileContent);
return [
{
name: frontmatter.name ?? "",
description: frontmatter.description ?? "",
content: markdown,
uri: {
type: "file",
value: rule.ruleFile,
},
},
];
};

View file

@ -1,3 +1,4 @@
import { ConfigDependentToolParams, Tool } from "..";
import { createNewFileTool } from "./definitions/createNewFile";
import { createRuleBlock } from "./definitions/createRuleBlock";
import { editFileTool } from "./definitions/editFile";
@ -6,11 +7,12 @@ import { grepSearchTool } from "./definitions/grepSearch";
import { lsTool } from "./definitions/lsTool";
import { readCurrentlyOpenFileTool } from "./definitions/readCurrentlyOpenFile";
import { readFileTool } from "./definitions/readFile";
import { requestRuleTool } from "./definitions/requestRule";
import { runTerminalCommandTool } from "./definitions/runTerminalCommand";
import { searchWebTool } from "./definitions/searchWeb";
import { viewDiffTool } from "./definitions/viewDiff";
export const allTools = [
export const baseToolDefinitions = [
readFileTool,
editFileTool,
createNewFileTool,
@ -26,3 +28,7 @@ export const allTools = [
// viewSubdirectoryTool,
// viewRepoMapTool,
];
export const getConfigDependentToolDefinitions = (
params: ConfigDependentToolParams,
): Tool[] => [requestRuleTool(params)];

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.19
pluginVersion=1.0.21
# 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

@ -132,18 +132,18 @@ class GetTheme {
val inputPlaceholder = namedColor("TextField.inactiveForeground")
val listHoverBackground = namedColor("List.hoverBackground") ?: slightChange(background)
val actionHoverBackground = namedColor("ActionButton.hoverBackground") ?: namedColor("Button.darcula.hoverBackground")
val listHoverForeground = namedColor("List.hoverForeground") ?: slightChange(foreground)
val tableOddRow = namedColor("Table.hoverBackground") ?: namedColor("Table.stripeColor")
val listSelectionForeground = namedColor("List.selectionForeground")
val tableOddRow = namedColor("Table.hoverBackground") ?: namedColor("Table.stripeColor")
val description = namedColor("Label.disabledForeground") ?: namedColor("Label.infoForeground")
val description = namedColor("Label.infoForeground") ?: namedColor("Label.disabledForeground") ?: foreground
val mutedDescription = namedColor("Component.infoForeground")
?: namedColor("ContextHelp.foreground")
?: namedColor("TextField.placeholderForeground")
?: namedColor("Label.disabledForeground")
?: namedColor("ToolTip.foreground")
?: description
val link = namedColor("Link.activeForeground")
@ -201,8 +201,8 @@ class GetTheme {
"find-match" to findMatchBackground,
"find-match-selected" to findMatchSelectedBackground,
"list-hover" to listHoverBackground,
"list-active" to actionHoverBackground,
"list-active-foreground" to listSelectionForeground
"list-active" to listHoverBackground,
"list-active-foreground" to listHoverForeground
).mapValues { toHex(it.value) }
return theme
} catch (error: Error) {

View file

@ -504,10 +504,16 @@ class IdeProtocolClient(
val editor = EditorUtils.getEditor(project)
val rif = editor?.getHighlightedRIF() ?: return
val serializedRif = com.github.continuedev.continueintellijextension.RangeInFileWithContents(
filepath = rif.filepath,
range = rif.range,
contents = rif.contents
)
continuePluginService.sendToWebview(
"highlightedCode",
HighlightedCodePayload(
rangeInFileWithContents = rif,
rangeInFileWithContents = serializedRif,
shouldRun = edit
)
)

View file

@ -232,7 +232,7 @@ data class ApplyState(
)
data class HighlightedCodePayload(
val rangeInFileWithContents: RangeInFileWithContents,
val rangeInFileWithContents: com.github.continuedev.continueintellijextension.RangeInFileWithContents,
val prompt: String? = null,
val shouldRun: Boolean? = null
)

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "1.1.39",
"version": "1.1.40",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "1.1.39",
"version": "1.1.40",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",
@ -110,7 +110,7 @@
"@continuedev/fetch": "^1.0.10",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.25",
"@modelcontextprotocol/sdk": "^1.5.0",
"@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
"@typescript-eslint/eslint-plugin": "^7.8.0",

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "1.1.40",
"version": "1.1.41",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"

View file

@ -72,7 +72,7 @@ export function ModeSelect() {
<div className="relative">
<ListboxButton
data-testid="mode-select-button"
className="xs:px-2 text-description-muted bg-table-oddRow gap-1 rounded-full border-none px-1.5 py-0.5 transition-colors duration-200 hover:brightness-110"
className="xs:px-2 text-description gap-1 rounded-full border-none px-1.5 py-0.5 transition-colors duration-200 hover:brightness-110"
>
<ModeIcon mode={mode} />
<span className="hidden sm:block">

View file

@ -113,11 +113,15 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) {
data-tooltip-id={resourcesTooltipId}
>
<CircleStackIcon className="h-3 w-3" />
<span className="text-xs">{server.resources.length}</span>
<span className="text-xs">
{server.resources.length + server.resourceTemplates.length}
</span>
<ToolTip id={resourcesTooltipId} className="flex flex-col gap-0.5">
{server.resources.map((resource, idx) => (
<code key={idx}>{resource.name}</code>
))}
{[...server.resources, ...server.resourceTemplates].map(
(resource, idx) => (
<code key={idx}>{resource.name}</code>
),
)}
{server.resources.length === 0 && (
<span className="text-lightgray">No resources</span>
)}

View file

@ -72,7 +72,7 @@ const ListboxOption = React.forwardRef<HTMLLIElement, ListboxOptionProps>(
ref={ref}
{...props}
className={cn(
"text-vsc-foreground flex select-none flex-row items-center justify-between px-2 py-1",
"text-foreground flex select-none flex-row items-center justify-between px-2 py-1",
props.disabled
? "opacity-50"
: "background-transparent hover:bg-list-active hover:text-list-active-foreground cursor-pointer opacity-100",

View file

@ -1,6 +1,6 @@
import { UserCircleIcon } from "@heroicons/react/24/solid";
import { isHubSession } from "core/control-plane/AuthTypes";
import { isOnPremSession } from "core/control-plane/AuthTypes";
import { SecondaryButton } from "../../components";
import {
Popover,
@ -29,7 +29,7 @@ export function AccountButton() {
}
// No login button for on-prem deployments
if (!isHubSession(session)) {
if (isOnPremSession(session)) {
return null;
}

View file

@ -333,17 +333,16 @@ export function Chat() {
"assistant" &&
item.message.toolCalls &&
item.toolCallState ? (
<div>
<div className="">
{item.message.toolCalls?.map((toolCall, i) => {
return (
<div key={i}>
<ToolCallDiv
toolCallState={item.toolCallState!}
toolCall={toolCall}
output={history[index + 1]?.contextItems}
historyIndex={index}
/>
</div>
<ToolCallDiv
key={i}
toolCallState={item.toolCallState!}
toolCall={toolCall}
output={history[index + 1]?.contextItems}
historyIndex={index}
/>
);
})}
</div>

View file

@ -1,8 +1,8 @@
import { ChevronDownIcon, ChevronRightIcon } from "@heroicons/react/24/outline";
import { ChevronRightIcon } from "@heroicons/react/24/outline";
import { ContextItemWithId, Tool, ToolCallState } from "core";
import { ComponentType, useMemo, useState } from "react";
import { ContextItemsPeekItem } from "../../../components/mainInput/belowMainInput/ContextItemsPeek";
import { ArgsItems } from "./ToolCallArgs";
import { ArgsItems, ArgsToggleIcon } from "./ToolCallArgs";
import { ToolCallStatusMessage } from "./ToolCallStatusMessage";
interface SimpleToolCallUIProps {
@ -32,49 +32,35 @@ export function SimpleToolCallUI({
}, [toolCallState.parsedArgs]);
return (
<div className="flex flex-1 flex-col px-2 pt-2 hover:brightness-125">
<div className="flex flex-row justify-between">
<div className="flex flex-col pl-5 pr-2 pt-4">
<div className="flex min-w-0 flex-row items-center justify-between gap-2">
<div
className="flex cursor-pointer items-center justify-start text-xs text-gray-300"
className="text-description flex min-w-0 cursor-pointer flex-row items-center justify-between gap-1.5 text-xs transition-colors duration-200 ease-in-out hover:brightness-125"
onClick={() => setOpen((prev) => !prev)}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
data-testid="context-items-peek"
>
<div className="relative mr-1 h-4 w-4">
<div className="flex h-4 w-4 flex-shrink-0 flex-col items-center justify-center">
{Icon && !isHovered && !open ? (
<Icon className={`absolute h-4 w-4 text-gray-400`} />
<Icon className={`text-description h-4 w-4`} />
) : (
<>
<ChevronRightIcon
className={`absolute h-4 w-4 text-gray-400 transition-all duration-200 ease-in-out ${
open ? "rotate-90 opacity-0" : "rotate-0 opacity-100"
}`}
/>
<ChevronDownIcon
className={`absolute h-4 w-4 text-gray-400 transition-all duration-200 ease-in-out ${
open ? "rotate-0 opacity-100" : "-rotate-90 opacity-0"
}`}
/>
</>
<ChevronRightIcon
className={`text-description h-4 w-4 transition-transform duration-200 ease-in-out ${
open ? "rotate-90" : "rotate-0"
}`}
/>
)}
</div>
<span
className="ml-1 text-xs text-gray-400 transition-colors duration-200"
data-testid="tool-call-title"
>
<ToolCallStatusMessage tool={tool} toolCallState={toolCallState} />
</span>
<ToolCallStatusMessage tool={tool} toolCallState={toolCallState} />
</div>
{/* <div>
{args.length > 0 ? (
<ArgsToggleIcon
isShowing={showingArgs}
setIsShowing={setShowingArgs}
toolCallId={toolCallState.toolCallId}
/>
) : null}
</div> */}
{args.length > 0 ? (
<ArgsToggleIcon
isShowing={showingArgs}
setIsShowing={setShowingArgs}
toolCallId={toolCallState.toolCallId}
/>
) : null}
</div>
<ArgsItems args={args} isShowing={showingArgs} />
<div
@ -87,7 +73,7 @@ export function SimpleToolCallUI({
<ContextItemsPeekItem key={idx} contextItem={contextItem} />
))
) : (
<div className="pl-2 text-xs italic text-gray-400">
<div className="text-description pl-5 text-xs italic">
No tool call output
</div>
)}

View file

@ -24,22 +24,20 @@ export function ToolCallDisplay({
return (
<>
<div className="relative flex flex-col justify-center p-4 pb-0">
<div className="flex flex-col justify-center p-4 pb-0">
<div className="mb-4 flex flex-col">
<div className="flex flex-row items-center justify-between gap-3">
<div className="flex flex-row gap-2">
<div className="flex flex-row items-center justify-between gap-1.5">
<div className="flex min-w-0 flex-row items-center gap-2">
<div className="mt-[1px] h-4 w-4 flex-shrink-0 font-semibold">
{icon}
</div>
{tool?.faviconUrl && (
<img src={tool.faviconUrl} className="h-4 w-4 rounded-sm" />
)}
<div className="flex" data-testid="tool-call-status-message">
<ToolCallStatusMessage
tool={tool}
toolCallState={toolCallState}
/>
</div>
<ToolCallStatusMessage
tool={tool}
toolCallState={toolCallState}
/>
</div>
{!!args.length ? (
<ArgsToggleIcon

View file

@ -25,10 +25,9 @@ export const ArgsToggleIcon = ({
e.stopPropagation();
setIsShowing(!isShowing);
}}
className={`cursor-pointer select-none rounded-sm px-1 py-0.5 hover:bg-gray-400/40 hover:opacity-80 ${isShowing ? "bg-gray-400/40" : "bg-transparent"}`}
className={`hover:description-muted/30 cursor-pointer select-none rounded px-1 py-0.5 hover:opacity-80 ${isShowing ? "bg-description-muted/30" : "bg-transparent"}`}
>
<CodeBracketIcon className="h-3 w-3 flex-shrink-0" />
{/* {`{}`} */}
<CodeBracketIcon className="h-2.5 w-2.5 flex-shrink-0 opacity-60" />
</div>
<ToolTip id={argsTooltipId}>
{isShowing ? "Hide args" : "Show args"}
@ -52,11 +51,13 @@ export const ArgsItems = ({ args, isShowing }: ArgsItemsProps) => {
}
return (
<div className="ml-7 mt-1">
<div className="ml-5 mr-2 mt-1 flex flex-col text-xs">
{args.map(([key, value]) => (
<div key={key} className="flex flex-row items-center gap-2 py-0.5">
<span className="text-lightgray">{key}:</span>
<code className="line-clamp-1">{value.toString()}</code>
<code className="line-clamp-1 break-all">
{JSON.stringify(value)}
</code>
</div>
))}
</div>

View file

@ -1,7 +1,5 @@
import { Tool, ToolCallState } from "core";
import Mustache from "mustache";
import { ReactNode } from "react";
import { getFontSize } from "../../../util";
import { useFontSize } from "../../../components/ui/font";
interface ToolCallStatusMessageProps {
@ -16,35 +14,26 @@ export function ToolCallStatusMessage({
const fontSize = useFontSize();
if (!tool) return "Agent tool use";
const defaultToolDescription = (
<>
<code>{tool.displayTitle ?? tool.function.name}</code> <span>tool</span>
</>
);
const toolName = tool.displayTitle ?? tool.function.name;
const defaultToolDescription = `${toolName} tool`;
const futureMessage = tool.wouldLikeTo ? (
Mustache.render(tool.wouldLikeTo, toolCallState.parsedArgs)
) : (
<>
<span>use the</span> {defaultToolDescription}
</>
);
const futureMessage: string = tool.wouldLikeTo
? Mustache.render(tool.wouldLikeTo, toolCallState.parsedArgs)
: `use the ${defaultToolDescription}`;
// TODO go back and replace arg string values and tool names with <code> tags
// to make them more readable
let intro = "";
let message: ReactNode = "";
let message = "";
if (
toolCallState.status === "done" ||
(tool.isInstant && toolCallState.status === "calling")
) {
intro = "";
message = tool.hasAlready ? (
Mustache.render(tool.hasAlready, toolCallState.parsedArgs)
) : (
<>
<span>used the</span> {defaultToolDescription}
</>
);
message = tool.hasAlready
? Mustache.render(tool.hasAlready, toolCallState.parsedArgs)
: `used the ${defaultToolDescription}`;
} else if (toolCallState.status === "generating") {
intro = "is generating output to";
message = futureMessage;
@ -53,13 +42,9 @@ export function ToolCallStatusMessage({
message = futureMessage;
} else if (toolCallState.status === "calling") {
intro = "is";
message = tool.isCurrently ? (
Mustache.render(tool.isCurrently, toolCallState.parsedArgs)
) : (
<>
<span>calling the</span> {defaultToolDescription}
</>
);
message = tool.isCurrently
? Mustache.render(tool.isCurrently, toolCallState.parsedArgs)
: `calling the ${defaultToolDescription}`;
} else if (
toolCallState.status === "canceled" ||
toolCallState.status === "errored"
@ -68,8 +53,12 @@ export function ToolCallStatusMessage({
message = futureMessage;
}
return (
<div className="block" style={{ fontSize }}>
<span>Continue</span> {intro} {message}
<div
className="text-description line-clamp-4 min-w-0 break-words"
style={{ fontSize }}
data-testid="tool-call-title"
>
{`Continue ${intro} ${message}`}
</div>
);
}

View file

@ -80,16 +80,14 @@ export function ToolCallDiv(props: ToolCallDivProps) {
if (icon) {
return (
<div className="ml-4 mt-2 flex">
<SimpleToolCallUI
tool={tool}
toolCallState={props.toolCallState}
icon={
props.toolCallState.status === "generated" ? ArrowRightIcon : icon
}
contextItems={props.output ?? []}
/>
</div>
<SimpleToolCallUI
tool={tool}
toolCallState={props.toolCallState}
icon={
props.toolCallState.status === "generated" ? ArrowRightIcon : icon
}
contextItems={props.output ?? []}
/>
);
}

View file

@ -56,6 +56,7 @@ export const uiSlice = createSlice({
[BuiltInToolNames.ViewDiff]: "allowedWithoutPermission",
[BuiltInToolNames.LSTool]: "allowedWithoutPermission",
[BuiltInToolNames.CreateRuleBlock]: "allowedWithPermission",
[BuiltInToolNames.RequestRule]: "disabled",
},
toolGroupSettings: {
[BUILT_IN_GROUP_NAME]: "include",

View file

@ -1,6 +1,6 @@
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import { ContextItem } from "core";
import { CLIENT_TOOLS } from "core/tools/builtIn";
import { CLIENT_TOOLS_IMPLS } from "core/tools/builtIn";
import { callClientTool } from "../../util/clientTools/callClientTool";
import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall";
import { selectSelectedChatModel } from "../slices/configSlice";
@ -51,7 +51,7 @@ export const callCurrentTool = createAsyncThunk<void, undefined, ThunkApiType>(
// Errors that occur outside specifically calling the tool
// Should not be caught here - should be handled as normal stream errors
if (
CLIENT_TOOLS.find(
CLIENT_TOOLS_IMPLS.find(
(toolName) => toolName === toolCallState.toolCall.function.name,
)
) {