Merge pull request #6264 from continuedev/dallin/prompt-tools

Support tools for prompts
This commit is contained in:
Nate Sesti 2025-06-27 21:48:05 -07:00 • committed by GitHub
commit ece5026e2a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
69 changed files with 1920 additions and 1303 deletions

View file

@ -1,88 +0,0 @@
import { CustomCommand, SlashCommand, SlashCommandDescription } from "../";
import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString";
import { replaceSlashCommandWithPromptInChatHistory } from "../promptFiles/v1/updateChatHistory";
import { renderPromptFileV2 } from "../promptFiles/v2/renderPromptFile";
import { renderChatMessage } from "../util/messageContent";
import SlashCommands from "./slash";
export function slashFromCustomCommand(
customCommand: CustomCommand,
): SlashCommand {
const commandName = customCommand.name.startsWith("/")
? customCommand.name.substring(1)
: customCommand.name;
return {
name: commandName,
description: customCommand.description ?? "",
prompt: customCommand.prompt,
run: async function* ({
input,
llm,
history,
ide,
completionOptions,
config,
selectedCode,
fetch,
abortController,
}) {
// Render prompt template
let renderedPrompt: string;
if (customCommand.prompt.includes("{{{ input }}}")) {
renderedPrompt = await renderTemplatedString(
customCommand.prompt,
ide.readFile.bind(ide),
{ input },
);
} else {
const renderedPromptFile = await renderPromptFileV2(
customCommand.prompt,
{
config,
llm,
ide,
selectedCode,
fetch,
fullInput: input,
embeddingsProvider: config.modelsByRole.embed[0],
reranker: config.modelsByRole.rerank[0],
},
);
renderedPrompt = renderedPromptFile[1];
}
// Replaces slash command messages with the rendered prompt
// which INCLUDES the input
const messages = replaceSlashCommandWithPromptInChatHistory(
history,
commandName,
renderedPrompt,
undefined,
);
for await (const chunk of llm.streamChat(
messages,
abortController.signal,
completionOptions,
)) {
yield renderChatMessage(chunk);
}
},
};
}
export function slashCommandFromDescription(
desc: SlashCommandDescription,
): SlashCommand | undefined {
const cmd = SlashCommands.find((cmd) => cmd.name === desc.name);
if (!cmd) {
return undefined;
}
return {
...cmd,
params: desc.params,
description: desc.description ?? cmd.description,
};
}

View file

@ -1,6 +1,6 @@
import { streamLines } from "../../diff/util.js";
import { SlashCommand } from "../../index.js";
import { removeQuotesAndEscapes } from "../../util/index.js";
import { streamLines } from "../../../diff/util.js";
import { SlashCommand } from "../../../index.js";
import { removeQuotesAndEscapes } from "../../../util/index.js";
function commandIsPotentiallyDangerous(command: string) {
return (

View file

@ -1,5 +1,5 @@
import { SlashCommand } from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { SlashCommand } from "../../../index.js";
import { renderChatMessage } from "../../../util/messageContent.js";
const CommitMessageCommand: SlashCommand = {
name: "commit",

View file

@ -1,6 +1,6 @@
import { ChatMessage, SlashCommand } from "../../index.js";
import { removeQuotesAndEscapes } from "../../util/index.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { ChatMessage, SlashCommand } from "../../../index.js";
import { removeQuotesAndEscapes } from "../../../util/index.js";
import { renderChatMessage } from "../../../util/messageContent.js";
const PROMPT = (
input: string,

View file

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

View file

@ -0,0 +1,37 @@
import {
SlashCommand,
SlashCommandDescription,
SlashCommandWithSource,
} from "../../..";
import GenerateTerminalCommand from "./cmd";
import CommitMessageCommand from "./commit";
import DraftIssueCommand from "./draftIssue";
import HttpSlashCommand from "./http";
import OnboardSlashCommand from "./onboard";
import ReviewMessageCommand from "./review";
import ShareSlashCommand from "./share";
const LegacyBuiltInSlashCommands: SlashCommand[] = [
DraftIssueCommand,
ShareSlashCommand,
GenerateTerminalCommand,
HttpSlashCommand,
CommitMessageCommand,
ReviewMessageCommand,
OnboardSlashCommand,
];
export function getLegacyBuiltInSlashCommandFromDescription(
desc: SlashCommandDescription,
): SlashCommandWithSource | undefined {
const cmd = LegacyBuiltInSlashCommands.find((cmd) => cmd.name === desc.name);
if (!cmd) {
return undefined;
}
return {
...cmd,
params: desc.params,
description: desc.description ?? cmd.description,
source: "built-in-legacy",
};
}

View file

@ -1,17 +1,17 @@
import ignore from "ignore";
import type { FileType, IDE, SlashCommand } from "../..";
import type { FileType, IDE, SlashCommand } from "../../..";
import {
DEFAULT_IGNORE,
getGlobalContinueIgArray,
gitIgArrayFromFile,
} from "../../indexing/ignore";
import { renderChatMessage } from "../../util/messageContent";
} from "../../../indexing/ignore";
import { renderChatMessage } from "../../../util/messageContent";
import {
findUriInDirs,
getUriPathBasename,
joinPathsToUri,
} from "../../util/uri";
} from "../../../util/uri";
const LANGUAGE_DEP_MGMT_FILENAMES = [
"package.json", // JavaScript (Node.js)

View file

@ -1,5 +1,5 @@
import { ChatMessage, SlashCommand } from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { ChatMessage, SlashCommand } from "../../../index.js";
import { renderChatMessage } from "../../../util/messageContent.js";
const prompt = `
Review the following code, focusing on Readability, Maintainability, Code Smells, Speed, and Memory Performance. Provide feedback with these guidelines:

View file

@ -3,10 +3,10 @@ import { homedir } from "node:os";
import { fileURLToPath, pathToFileURL } from "node:url";
import path from "path";
import { languageForFilepath } from "../../autocomplete/constants/AutocompleteLanguageInfo.js";
import { SlashCommand } from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { getContinueGlobalPath } from "../../util/paths.js";
import { languageForFilepath } from "../../../autocomplete/constants/AutocompleteLanguageInfo.js";
import { SlashCommand } from "../../../index.js";
import { renderChatMessage } from "../../../util/messageContent.js";
import { getContinueGlobalPath } from "../../../util/paths.js";
// If useful elsewhere, helper funcs should move to core/util/index.ts or similar
function getOffsetDatetime(date: Date): Date {

View file

@ -0,0 +1,15 @@
import { CustomCommand, SlashCommandWithSource } from "../..";
export function convertCustomCommandToSlashCommand(
customCommand: CustomCommand,
): SlashCommandWithSource {
const commandName = customCommand.name.startsWith("/")
? customCommand.name.substring(1)
: customCommand.name;
return {
name: commandName,
description: customCommand.description ?? "",
prompt: customCommand.prompt,
source: "json-custom-command",
};
}

View file

@ -1,17 +0,0 @@
import GenerateTerminalCommand from "./cmd";
import CommitMessageCommand from "./commit";
import DraftIssueCommand from "./draftIssue";
import HttpSlashCommand from "./http";
import OnboardSlashCommand from "./onboard";
import ReviewMessageCommand from "./review";
import ShareSlashCommand from "./share";
export default [
DraftIssueCommand,
ShareSlashCommand,
GenerateTerminalCommand,
HttpSlashCommand,
CommitMessageCommand,
ReviewMessageCommand,
OnboardSlashCommand,
];

View file

@ -1,70 +0,0 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { PromptMessage } from "@modelcontextprotocol/sdk/types.js";
import { ChatMessage, SlashCommand } from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
export function constructMcpSlashCommand(
client: Client,
name: string,
description?: string,
args?: string[],
): SlashCommand {
return {
name,
description: description ?? "MCP Prompt",
params: {},
run: async function* (context) {
const argsObject: { [key: string]: string } = {};
const userInput = context.input.split(" ").slice(1).join(" ");
if (args) {
args.forEach((arg, i) => {
argsObject[arg] = ""; // userInput
});
}
const result = await client.getPrompt({ name, arguments: argsObject });
const mcpMessages: PromptMessage[] = result.messages;
const messages: ChatMessage[] = mcpMessages.map((msg) => {
if (msg.content.type !== "text") {
throw new Error(
"Continue currently only supports text prompts through MCP",
);
}
return {
content: msg.content.text,
role: msg.role,
};
});
if (messages.length === 0) {
yield "The MCP prompt returned no messages";
return;
}
if (userInput) {
const lastMessage = messages.at(-1);
if (!lastMessage || lastMessage.role !== "user") {
messages.push({
role: "user",
content: userInput,
});
} else {
let newContent = renderChatMessage(lastMessage);
if (newContent) {
newContent += "\n\n";
}
newContent += userInput;
lastMessage.content = newContent;
}
}
for await (const chunk of context.llm.streamChat(
messages,
context.abortController.signal,
context.completionOptions,
)) {
yield renderChatMessage(chunk);
}
},
};
}

View file

@ -0,0 +1,34 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { SlashCommandWithSource } from "../../index.js";
export function constructMcpSlashCommand(
client: Client,
name: string,
description?: string,
args?: string[],
): SlashCommandWithSource {
return {
name,
description: description ?? "MCP Prompt",
source: "mcp-prompt",
params: {},
};
}
export function stringifyMcpPrompt(
prompt: Awaited<ReturnType<typeof Client.prototype.getPrompt>>,
): string {
const { messages } = prompt;
let stringified = "";
for (const message of messages) {
if (message.content.type === "text") {
stringified += `<${message.content.role}/>\n${message.content.text}\n<${message.content.role}/>`;
} else {
console.warn(
`MCP Prompt conversion warning: ${message.content.type} content is not yet supported, message skipped`,
);
}
}
return stringified;
}

View file

@ -0,0 +1,13 @@
import { Prompt } from "@continuedev/config-yaml";
import { SlashCommandWithSource } from "../..";
export function convertPromptBlockToSlashCommand(
prompt: Prompt,
): SlashCommandWithSource {
return {
name: prompt.name,
description: prompt.description ?? "",
prompt: prompt.prompt,
source: "yaml-prompt-block",
};
}

View file

@ -0,0 +1,21 @@
import { SlashCommandWithSource } from "../..";
import { parsePromptFile } from "../../promptFiles/parsePromptFile";
export function slashCommandFromPromptFile(
path: string,
content: string,
): SlashCommandWithSource | null {
const { name, description, systemMessage, prompt, version } = parsePromptFile(
path,
content,
);
return {
name,
description,
prompt,
source: version === 1 ? "prompt-file-v1" : "prompt-file-v2",
promptFile: path,
overrideSystemMessage: systemMessage,
};
}

View file

@ -16,7 +16,7 @@ export function rifWithContentsToContextItem(
return {
content: rif.contents,
name: `${basename} ${rangeStr}`,
description: `${relativePathOrBasename} ${rangeStr}`, // This is passed to the LLM - do not pass full URI
description: `${relativePathOrBasename} ${rangeStr}`,
id: {
providerTitle: "code",
itemId: uuidv4(),

View file

@ -30,12 +30,11 @@ import {
ModelDescription,
RerankerDescription,
SerializedContinueConfig,
SlashCommand,
SlashCommandWithSource,
} from "..";
import {
slashCommandFromDescription,
slashFromCustomCommand,
} from "../commands/index";
import { getLegacyBuiltInSlashCommandFromDescription } from "../commands/slash/built-in-legacy";
import { convertCustomCommandToSlashCommand } from "../commands/slash/customSlashCommand";
import { slashCommandFromPromptFile } from "../commands/slash/promptFileSlashCommand";
import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton";
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider";
import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider";
@ -48,8 +47,7 @@ import { LLMClasses, llmFromDescription } from "../llm/llms";
import CustomLLMClass from "../llm/llms/CustomLLM";
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 { getAllPromptFiles } from "../promptFiles/getPromptFiles";
import { copyOf } from "../util";
import { GlobalContext } from "../util/GlobalContext";
import mergeJson from "../util/merge";
@ -66,6 +64,7 @@ import {
import { localPathToUri } from "../util/pathToUri";
import { baseToolDefinitions } from "../tools";
import { resolveRelativePathInDir } from "../util/ideUtils";
import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
import {
getModelByRole,
@ -174,15 +173,15 @@ async function serializedToIntermediateConfig(
ide: IDE,
): Promise<Config> {
// DEPRECATED - load custom slash commands
const slashCommands: SlashCommand[] = [];
const slashCommands: SlashCommandWithSource[] = [];
for (const command of initial.slashCommands || []) {
const newCommand = slashCommandFromDescription(command);
const newCommand = getLegacyBuiltInSlashCommandFromDescription(command);
if (newCommand) {
slashCommands.push(newCommand);
}
}
for (const command of initial.customCommands || []) {
slashCommands.push(slashFromCustomCommand(command));
slashCommands.push(convertCustomCommandToSlashCommand(command));
}
// DEPRECATED - load slash commands from v1 prompt files
@ -194,7 +193,7 @@ async function serializedToIntermediateConfig(
);
for (const file of promptFiles) {
const slashCommand = slashCommandFromPromptFileV1(file.path, file.content);
const slashCommand = slashCommandFromPromptFile(file.path, file.content);
if (slashCommand) {
slashCommands.push(slashCommand);
}
@ -254,7 +253,10 @@ async function intermediateToFinalConfig({
loadPromptFiles?: boolean;
}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
const errors: ConfigValidationError[] = [];
const workspaceDirs = await ide.getWorkspaceDirs();
const getUriFromPath = (path: string) => {
return resolveRelativePathInDir(path, ide, workspaceDirs);
};
// Auto-detect models
let models: BaseLLM[] = [];
await Promise.all(
@ -263,6 +265,7 @@ async function intermediateToFinalConfig({
const llm = await llmFromDescription(
desc,
ide.readFile.bind(ide),
getUriFromPath,
uniqueId,
ideSettings,
llmLogger,
@ -284,6 +287,7 @@ async function intermediateToFinalConfig({
title: modelName,
},
ide.readFile.bind(ide),
getUriFromPath,
uniqueId,
ideSettings,
llmLogger,
@ -360,6 +364,7 @@ async function intermediateToFinalConfig({
const llm = await llmFromDescription(
desc,
ide.readFile.bind(ide),
getUriFromPath,
uniqueId,
ideSettings,
llmLogger,
@ -529,7 +534,7 @@ async function intermediateToFinalConfig({
contextProviders,
tools: [...baseToolDefinitions],
mcpServerStatuses: [],
slashCommands: config.slashCommands ?? [],
slashCommands: [],
modelsByRole: {
chat: models,
edit: models,
@ -551,6 +556,17 @@ async function intermediateToFinalConfig({
rules: [],
};
for (const cmd of config.slashCommands ?? []) {
if ("source" in cmd) {
continueConfig.slashCommands.push(cmd);
} else {
continueConfig.slashCommands.push({
...cmd,
source: "config-ts-slash-command",
});
}
}
if (config.systemMessage) {
continueConfig.rules.unshift({
rule: config.systemMessage,
@ -651,9 +667,10 @@ async function finalToBrowserConfig(
return {
allowAnonymousTelemetry: final.allowAnonymousTelemetry,
completionOptions: final.completionOptions,
slashCommands: final.slashCommands?.map(
({ run, ...slashCommandDescription }) => slashCommandDescription,
),
slashCommands: final.slashCommands?.map(({ run, ...rest }) => ({
...rest,
isLegacy: !!run,
})),
contextProviders: final.contextProviders?.map((c) => c.description),
disableIndexing: final.disableIndexing,
disableSessionTitles: final.disableSessionTitles,
@ -975,7 +992,6 @@ async function loadContinueConfigFromJson(
export {
finalToBrowserConfig,
intermediateToFinalConfig,
loadContinueConfigFromJson,
type BrowserSerializedContinueConfig,
};

View file

@ -16,9 +16,9 @@ import {
ILLMLogger,
RuleWithSource,
SerializedContinueConfig,
SlashCommandDescWithSource,
Tool,
} from "../../";
import { constructMcpSlashCommand } from "../../commands/slash/mcp";
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
import MCPContextProvider from "../../context/providers/MCPContextProvider";
import RulesContextProvider from "../../context/providers/RulesContextProvider";
@ -190,14 +190,15 @@ export default async function doLoadConfig(options: {
}));
newConfig.tools.push(...serverTools);
const serverSlashCommands = server.prompts.map((prompt) =>
constructMcpSlashCommand(
server.client,
prompt.name,
prompt.description,
prompt.arguments?.map((a: any) => a.name),
),
);
const serverSlashCommands: SlashCommandDescWithSource[] =
server.prompts.map((prompt) => ({
name: prompt.name,
description: prompt.description ?? "MCP Prompt",
source: "mcp-prompt",
isLegacy: false,
mcpServerName: server.name, // Used in client to retrieve prompt
mcpArgs: prompt.arguments,
}));
newConfig.slashCommands.push(...serverSlashCommands);
const submenuItems = server.resources

View file

@ -25,7 +25,6 @@ import {
ILLMLogger,
RuleWithSource,
} from "../..";
import { slashFromCustomCommand } from "../../commands";
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
import CodebaseContextProvider from "../../context/providers/CodebaseContextProvider";
import DocsContextProvider from "../../context/providers/DocsContextProvider";
@ -33,11 +32,12 @@ import FileContextProvider from "../../context/providers/FileContextProvider";
import { contextProviderClassFromName } from "../../context/providers/index";
import { ControlPlaneClient } from "../../control-plane/client";
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
import { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandFromPromptFile";
import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles";
import { getAllPromptFiles } from "../../promptFiles/getPromptFiles";
import { GlobalContext } from "../../util/GlobalContext";
import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand";
import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand";
import { getControlPlaneEnvSync } from "../../control-plane/env";
import { getToolsForIde } from "../../tools";
import { getCleanUriPath } from "../../util/uri";
@ -263,7 +263,7 @@ async function configYamlToContinueConfig(options: {
promptFiles.forEach((file) => {
try {
const slashCommand = slashCommandFromPromptFileV1(
const slashCommand = slashCommandFromPromptFile(
file.path,
file.content,
);
@ -286,7 +286,7 @@ async function configYamlToContinueConfig(options: {
config.prompts?.forEach((prompt) => {
try {
const slashCommand = slashFromCustomCommand(prompt);
const slashCommand = convertPromptBlockToSlashCommand(prompt);
continueConfig.slashCommands?.push(slashCommand);
} catch (e) {
localErrors.push({

View file

@ -161,4 +161,21 @@ export class MCPManagerSingleton {
client: connection.client,
}));
}
async getPrompt(
serverName: string,
promptName: string,
args: Record<string, string> = {},
) {
const connection = this.connections.get(serverName);
if (!connection) {
throw new Error(
`Error getting prompt: MCP Connection ${serverName} not found`,
);
}
return await connection.client.getPrompt({
name: promptName,
arguments: args,
});
}
}

View file

@ -21,7 +21,9 @@ class TerminalContextProvider extends BaseContextProvider {
return [
{
description: "The contents of the terminal",
content: `Current terminal contents:\n\n${content}`,
content: `Current terminal contents:\n\n${
content || "The terminal is empty."
}`,
name: "Terminal",
},
];

View file

@ -21,7 +21,7 @@ import { CodebaseIndexer } from "./indexing/CodebaseIndexer";
import DocsService from "./indexing/docs/DocsService";
import { countTokens } from "./llm/countTokens";
import Ollama from "./llm/llms/Ollama";
import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile";
import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile";
import { callTool } from "./tools/callTool";
import { ChatDescriber } from "./util/chatDescriber";
import { clipboardCache } from "./util/clipboardCache";
@ -50,6 +50,7 @@ import {
import { BLOCK_TYPES, ConfigYaml } from "@continuedev/config-yaml";
import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache";
import { stringifyMcpPrompt } from "./commands/slash/mcpSlashCommand";
import { isLocalDefinitionFile } from "./config/loadLocalAssistants";
import {
setupLocalConfig,
@ -381,6 +382,19 @@ export class Core {
on("mcp/reloadServer", async (msg) => {
await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
});
on("mcp/getPrompt", async (msg) => {
const { serverName, promptName, args } = msg.data;
const prompt = await MCPManagerSingleton.getInstance().getPrompt(
serverName,
promptName,
args,
);
const stringifiedPrompt = stringifyMcpPrompt(prompt);
return {
prompt: stringifiedPrompt,
description: prompt.description,
};
});
// Context providers
on("context/addDocs", async (msg) => {
void this.docsService.indexAndAdd(msg.data);

53
core/index.d.ts vendored
View file

@ -838,15 +838,44 @@ export interface ContinueSDK {
abortController: AbortController;
}
export interface SlashCommand {
/* Be careful changing SlashCommand or SlashCommandDescription, config.ts can break */
export interface SlashCommandDescription {
name: string;
description: string;
prompt?: string;
params?: { [key: string]: any };
promptFile?: string;
}
export interface SlashCommand extends SlashCommandDescription {
run: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>;
}
export interface SlashCommandWithSource extends SlashCommandDescription {
run?: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>; // Optional - only needed for legacy
source: SlashCommandSource;
promptFile?: string;
overrideSystemMessage?: string;
}
export type SlashCommandSource =
| "built-in-legacy"
| "built-in"
| "json-custom-command"
| "config-ts-slash-command"
| "yaml-prompt-block"
| "mcp-prompt"
| "prompt-file-v1"
| "prompt-file-v2"
| "invokable-rule";
export interface SlashCommandDescWithSource extends SlashCommandDescription {
isLegacy: boolean; // Maps to if slashcommand.run exists
source: SlashCommandSource;
promptFile?: string;
mcpServerName?: string;
mcpArgs?: MCPPromptArgs;
}
// Config
export type StepName =
@ -947,8 +976,6 @@ export interface ContextProviderWithParams {
params: { [key: string]: any };
}
export type SlashCommandDescription = Omit<SlashCommand, "run">;
export interface CustomCommand {
name: string;
prompt: string;
@ -1172,14 +1199,16 @@ export type MCPConnectionStatus =
| "error"
| "not-connected";
export type MCPPromptArgs = {
name: string;
description?: string;
required?: boolean;
}[];
export interface MCPPrompt {
name: string;
description?: string;
arguments?: {
name: string;
description?: string;
required?: boolean;
}[];
arguments?: MCPPromptArgs;
}
// Leaving here to ideate on
@ -1444,7 +1473,7 @@ export interface Config {
/** Request options that will be applied to all models and context providers */
requestOptions?: RequestOptions;
/** The list of slash commands that will be available in the sidebar */
slashCommands?: SlashCommand[];
slashCommands?: (SlashCommand | SlashCommandWithSource)[];
/** Each entry in this array will originally be a ContextProviderWithParams, the same object from your config.json, but you may add CustomContextProviders.
* A CustomContextProvider requires you only to define a title and getContextItems function. When you type '@title <query>', Continue will call `getContextItems(query)`.
*/
@ -1481,7 +1510,7 @@ export interface ContinueConfig {
// systemMessage?: string;
completionOptions?: BaseCompletionOptions;
requestOptions?: RequestOptions;
slashCommands: SlashCommand[];
slashCommands: SlashCommandWithSource[];
contextProviders: IContextProvider[];
disableSessionTitles?: boolean;
disableIndexing?: boolean;
@ -1504,7 +1533,7 @@ export interface BrowserSerializedContinueConfig {
// systemMessage?: string;
completionOptions?: BaseCompletionOptions;
requestOptions?: RequestOptions;
slashCommands: SlashCommandDescription[];
slashCommands: SlashCommandDescWithSource[];
contextProviders: ContextProviderDescription[];
disableIndexing?: boolean;
disableSessionTitles?: boolean;

View file

@ -1,3 +1,4 @@
import Handlebars from "handlebars";
import {
BaseCompletionOptions,
IdeSettings,
@ -6,10 +7,9 @@ import {
JSONModelDescription,
LLMOptions,
} from "../..";
import { renderTemplatedString } from "../../promptFiles/v1/renderTemplatedString";
import { renderTemplatedString } from "../../util/handlebars/renderTemplatedString";
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../constructMessages";
import { BaseLLM } from "../index";
import Anthropic from "./Anthropic";
import Asksage from "./Asksage";
import Azure from "./Azure";
@ -121,6 +121,7 @@ export const LLMClasses = [
export async function llmFromDescription(
desc: JSONModelDescription,
readFile: (filepath: string) => Promise<string>,
getUriFromPath: (path: string) => Promise<string | undefined>,
uniqueId: string,
ideSettings: IdeSettings,
llmLogger: ILLMLogger,
@ -142,9 +143,12 @@ export async function llmFromDescription(
baseChatSystemMessage = DEFAULT_CHAT_SYSTEM_MESSAGE;
baseChatSystemMessage += "\n\n";
baseChatSystemMessage += await renderTemplatedString(
Handlebars,
desc.systemMessage,
readFile,
{},
[],
readFile,
getUriFromPath,
);
}

View file

@ -59,6 +59,12 @@ export async function* llmStreamChat(
},
true,
);
if (!slashCommand.run) {
console.error(
`Slash command ${command.name} (${command.source}) has no run function`,
);
throw new Error(`Slash command not found`);
}
const gen = slashCommand.run({
input,

View file

@ -1,6 +1,6 @@
import { IDE } from "../..";
import { GlobalContext } from "../../util/GlobalContext";
import { joinPathsToUri } from "../../util/uri";
import { IDE } from "..";
import { GlobalContext } from "../util/GlobalContext";
import { joinPathsToUri } from "../util/uri";
const FIRST_TIME_DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file
# It is used to define and reuse prompts within Continue

View file

@ -1,10 +1,9 @@
import { IDE } from "../..";
import { walkDir } from "../../indexing/walkDir";
import { readAllGlobalPromptFiles } from "../../util/paths";
import { joinPathsToUri } from "../../util/uri";
import { DEFAULT_PROMPTS_FOLDER_V1 } from "../v1";
import { DEFAULT_PROMPTS_FOLDER_V1, DEFAULT_PROMPTS_FOLDER_V2 } from ".";
import { IDE } from "..";
import { walkDir } from "../indexing/walkDir";
import { readAllGlobalPromptFiles } from "../util/paths";
import { joinPathsToUri } from "../util/uri";
export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts";
export async function getPromptFilesFromDir(
ide: IDE,
dir: string,

19
core/promptFiles/index.ts Normal file
View file

@ -0,0 +1,19 @@
import { ContextProviderName } from "..";
export const DEFAULT_PROMPTS_FOLDER_V1 = ".prompts";
export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts";
export const SUPPORTED_PROMPT_CONTEXT_PROVIDERS: ContextProviderName[] = [
"file",
"clipboard",
"repo-map",
"currentFile",
"os",
"problems",
"codebase",
"tree",
"open",
"debugger",
"terminal",
"diff",
];

View file

@ -1,8 +1,8 @@
import * as YAML from "yaml";
import { getLastNPathParts } from "../../util/uri";
import { getLastNPathParts } from "../util/uri";
export function parsePromptFileV1V2(path: string, content: string) {
export function parsePromptFile(path: string, content: string) {
let [preambleRaw, prompt] = content.split("\n---\n");
if (prompt === undefined) {
prompt = preambleRaw;

View file

@ -1,38 +0,0 @@
import Handlebars from "handlebars";
import { ContextItem, ContinueSDK, IContextProvider } from "../..";
function createContextItem(item: ContextItem, provider: IContextProvider) {
return {
...item,
id: {
itemId: item.description,
providerTitle: provider.description.title,
},
};
}
export function getContextProviderHelpers(
context: ContinueSDK,
): Array<[string, Handlebars.HelperDelegate]> | undefined {
return context.config.contextProviders?.map((provider: IContextProvider) => [
provider.description.title,
async (helperContext: any) => {
const items = await provider.getContextItems(helperContext, {
config: context.config,
embeddingsProvider: context.config.selectedModelByRole.embed,
fetch: context.fetch,
fullInput: context.input,
ide: context.ide,
llm: context.llm,
reranker: context.config.selectedModelByRole.rerank,
selectedCode: context.selectedCode,
});
items.forEach((item) =>
context.addContextItem(createContextItem(item, provider)),
);
return items.map((item) => item.content).join("\n\n");
},
]);
}

View file

@ -1,117 +0,0 @@
import Handlebars from "handlebars";
import { v4 as uuidv4 } from "uuid";
function convertToLetter(num: number): string {
let result = "";
while (num > 0) {
const remainder = (num - 1) % 26;
result = String.fromCharCode(97 + remainder) + result;
num = Math.floor((num - 1) / 26);
}
return result;
}
/**
* We replace filepaths with alphabetic characters to handle
* escaping issues.
*/
const replaceFilepaths = (
value: string,
ctxProviderNames: string[],
): [string, { [key: string]: string }] => {
const ast = Handlebars.parse(value);
const keysToFilepath: { [key: string]: string } = {};
let keyIndex = 1;
for (const i in ast.body) {
const node = ast.body[i] as any;
if (node.type === "MustacheStatement") {
const originalNodeVal = node.path.original;
const isFilepath = !ctxProviderNames.includes(originalNodeVal);
if (isFilepath) {
const letter = convertToLetter(keyIndex);
keysToFilepath[letter] = originalNodeVal;
value = value.replace(
new RegExp(`{{\\s*${originalNodeVal}\\s*}}`),
`{{${letter}}}`,
);
keyIndex++;
}
}
}
return [value, keysToFilepath];
};
export function registerHelpers(
helpers: Array<[string, Handlebars.HelperDelegate]>,
): {
[key: string]: Promise<string>;
} {
const promises: { [key: string]: Promise<string> } = {};
for (const [name, helper] of helpers) {
Handlebars.registerHelper(name, (...args) => {
const id = uuidv4();
promises[id] = helper(...args);
return `__${id}__`;
});
}
return promises;
}
export async function prepareTemplateAndData(
template: string,
readFile: (filepath: string) => Promise<string>,
inputData: Record<string, string>,
ctxProviderNames: string[],
): Promise<[string, any]> {
const [newTemplate, vars] = replaceFilepaths(template, ctxProviderNames);
const data: any = { ...inputData };
for (const [replacedName, originalCtxProviderName] of Object.entries(vars)) {
data[replacedName] =
inputData[originalCtxProviderName] ?? originalCtxProviderName;
// If it's not a context provider, assume it's a filepath.
if (!ctxProviderNames.includes(originalCtxProviderName)) {
const fileContents = await readFile(vars[replacedName]);
if (fileContents) {
data[replacedName] = fileContents;
}
}
}
return [newTemplate, data];
}
export function compileAndRenderTemplate(
template: string,
data: Record<string, string>,
): string {
const templateFn = Handlebars.compile(template);
return templateFn(data);
}
export async function resolveHelperPromises(
renderedString: string,
promises: { [key: string]: Promise<string> },
): Promise<string> {
await Promise.all(Object.values(promises));
for (const id in promises) {
renderedString = renderedString.replace(`__${id}__`, await promises[id]);
}
return renderedString;
}

View file

@ -1 +0,0 @@
export const DEFAULT_PROMPTS_FOLDER_V1 = ".prompts";

View file

@ -1,89 +0,0 @@
import { ContinueSDK, SlashCommand } from "../..";
import { getDiffsFromCache } from "../../autocomplete/snippets/gitDiffCache";
import { renderChatMessage } from "../../util/messageContent";
import { getLastNPathParts } from "../../util/uri";
import { parsePromptFileV1V2 } from "../v2/parsePromptFileV1V2";
import { renderPromptFileV2 } from "../v2/renderPromptFile";
import { getContextProviderHelpers } from "./getContextProviderHelpers";
import { renderTemplatedString } from "./renderTemplatedString";
import { replaceSlashCommandWithPromptInChatHistory } from "./updateChatHistory";
export function extractName(preamble: { name?: string }, path: string): string {
return preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0];
}
async function renderPromptV1(
prompt: string,
context: ContinueSDK,
userInput: string,
) {
const helpers = getContextProviderHelpers(context);
const inputData: Record<string, string> = {
input: userInput,
};
// A few context providers that don't need to be in config.json to work in .prompt files
if (helpers?.find((helper) => helper[0] === "diff")) {
const diffs = await getDiffsFromCache(context.ide);
inputData.diff = diffs.join("\n");
}
if (helpers?.find((helper) => helper[0] === "currentFile")) {
const currentFile = await context.ide.getCurrentFile();
if (currentFile) {
inputData.currentFile = currentFile.path;
}
}
return renderTemplatedString(
prompt,
context.ide.readFile.bind(context.ide),
inputData,
helpers,
);
}
export function slashCommandFromPromptFileV1(
path: string,
content: string,
): SlashCommand | null {
const { name, description, systemMessage, prompt } = parsePromptFileV1V2(
path,
content,
);
return {
name,
description,
prompt,
promptFile: path,
run: async function* (context) {
const [_, renderedPrompt] = await renderPromptFileV2(prompt, {
config: context.config,
fullInput: context.input,
embeddingsProvider: context.config.modelsByRole.embed[0],
reranker: context.config.modelsByRole.rerank[0],
llm: context.llm,
ide: context.ide,
selectedCode: context.selectedCode,
fetch: context.fetch,
});
const messages = replaceSlashCommandWithPromptInChatHistory(
context.history,
name,
renderedPrompt,
systemMessage,
);
for await (const chunk of context.llm.streamChat(
messages,
context.abortController.signal,
context.completionOptions,
)) {
yield renderChatMessage(chunk);
}
},
};
}

View file

@ -1,64 +0,0 @@
import { ChatMessage } from "../..";
export function replaceSlashCommandWithPromptInChatHistory(
history: ChatMessage[],
commandName: string,
renderedPrompt: string,
systemMessageOverride?: string,
): ChatMessage[] {
const messages = [...history];
for (let i = messages.length - 1; i >= 0; i--) {
const { role, content } = messages[i];
if (role !== "user") {
continue;
}
if (Array.isArray(content)) {
if (
content.some(
(part) =>
part.type === "text" && part.text?.startsWith(`/${commandName}`),
)
) {
messages[i] = updateArrayContent(
messages[i],
commandName,
renderedPrompt,
);
break;
}
} else if (
typeof content === "string" &&
content.startsWith(`/${commandName}`)
) {
messages[i] = { ...messages[i], content: renderedPrompt };
break;
}
}
if (systemMessageOverride) {
if (messages[0]?.role === "system") {
messages[0].content = systemMessageOverride;
} else {
messages.unshift({ role: "system", content: systemMessageOverride });
}
}
return messages;
}
function updateArrayContent(
message: any,
commandName: string,
renderedPrompt: string,
) {
return {
...message,
content: message.content.map((part: any) =>
part.text?.startsWith(`/${commandName}`)
? { ...part, text: renderedPrompt }
: part,
),
};
}

View file

@ -1,34 +0,0 @@
import * as YAML from "yaml";
import { getLastNPathParts } from "../../util/uri";
export function extractName(preamble: { name?: string }, path: string): string {
return preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0];
}
export function getPreambleAndBody(content: string): [string, string] {
let [preamble, body] = content.split("\n---\n");
if (body === undefined) {
// This means there is no preamble
body = preamble;
preamble = "";
}
return [preamble, body];
}
export function parsePreamble(
path: string,
content: string,
): { [key: string]: any; name: string; description: string } {
const [preambleRaw, _] = getPreambleAndBody(content);
const preamble = YAML.parse(preambleRaw) ?? {};
const name = extractName(preamble, path);
const description = preamble.description ?? name;
return {
...preamble,
name,
description,
};
}

View file

@ -1,84 +0,0 @@
import { ContextItem, ContextProviderExtras } from "../..";
import { contextProviderClassFromName } from "../../context/providers";
import { getUrlContextItems } from "../../context/providers/URLContextProvider";
import { resolveRelativePathInDir } from "../../util/ideUtils";
import { getUriPathBasename } from "../../util/uri";
import { getPreambleAndBody } from "./parse";
async function resolveAttachment(
name: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
// Context providers
const contextProvider = extras.config.contextProviders?.find(
(provider) => provider.description.title === name,
);
if (contextProvider) {
const items = await contextProvider.getContextItems("", extras);
return items;
} else {
// Just instantiate it here
const providerClass = contextProviderClassFromName(name) as any;
if (providerClass) {
const providerInstance = new providerClass({});
return providerInstance.getContextItems("", extras);
}
}
// Files
const resolvedFileUri = await resolveRelativePathInDir(name, extras.ide);
if (resolvedFileUri) {
let subItems: ContextItem[] = [];
if (name.endsWith(".prompt")) {
// Recurse
const [items, _] = await renderPromptFileV2(
await extras.ide.readFile(resolvedFileUri),
extras,
);
subItems.push(...items);
}
const content = `\`\`\`${name}\n${await extras.ide.readFile(resolvedFileUri)}\n\`\`\``;
return [
...subItems,
{
name: getUriPathBasename(resolvedFileUri),
content,
description: resolvedFileUri,
},
];
}
// URLs
if (name.startsWith("http")) {
const items = getUrlContextItems(name, extras.fetch);
return items;
}
return [];
}
export async function renderPromptFileV2(
rawContent: string,
extras: ContextProviderExtras,
): Promise<[ContextItem[], string]> {
const [_, body] = getPreambleAndBody(rawContent);
const contextItemsPromises: Promise<ContextItem[]>[] = [];
const renderedBody = body.replace(/@([^\s]+)/g, (match, name) => {
contextItemsPromises.push(resolveAttachment(name, extras));
return match;
});
const contextItems = (await Promise.all(contextItemsPromises)).flat();
const renderedPrompt = [
...contextItems.map((item) => item.content),
renderedBody,
extras.fullInput,
]
.join("\n\n")
.trim();
return [contextItems, renderedPrompt];
}

View file

@ -1,175 +0,0 @@
import { ContextProviderExtras, ILLM, RangeInFile } from "../..";
import { testConfigHandler, testIde } from "../../test/fixtures";
import {
addToTestDir,
setUpTestDir,
tearDownTestDir,
} from "../../test/testDir";
import { renderPromptFileV2 } from "./renderPromptFile";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock(
import("../../context/providers/URLContextProvider"),
async (importOriginal) => {
const actual = await importOriginal();
return {
...actual,
getUrlContextItems: vi.fn().mockResolvedValue([
{
description: "https://example.com",
content: "Example Content",
name: "Example site",
uri: {
type: "url",
value: "https://example.com",
},
},
]),
};
},
);
describe("renderPromptFileV2", () => {
let extras: ContextProviderExtras;
const mockGetContextItems = vi.fn().mockResolvedValue([
{
name: "custom",
content: "Custom provider content",
description: "Custom provider",
},
]);
beforeEach(async () => {
const { config } = await testConfigHandler.loadConfig();
// Setup mock extras
extras = {
config: {
...config!,
contextProviders: [
{
description: {
type: "normal",
title: "CustomProvider",
displayTitle: "Custom Provider",
description: "A custom context provider",
},
loadSubmenuItems: vi.fn().mockResolvedValue([]),
getContextItems: mockGetContextItems,
},
],
},
fullInput: "User input",
embeddingsProvider: null,
reranker: null,
llm: {} as ILLM,
ide: testIde,
selectedCode: [] as RangeInFile[],
fetch: vi.fn(),
};
// Clear all mocks
vi.clearAllMocks();
setUpTestDir();
});
afterEach(() => {
tearDownTestDir();
});
it("should render a prompt file with no attachments", async () => {
const rawContent = "Simple prompt with no attachments";
const [contextItems, renderedPrompt] = await renderPromptFileV2(
rawContent,
extras,
);
expect(contextItems).toHaveLength(0);
expect(renderedPrompt).toBe(
"Simple prompt with no attachments\n\nUser input",
);
});
it("should handle URL attachments", async () => {
const rawContent = "Content with URL @https://example.com";
const [contextItems, renderedPrompt] = await renderPromptFileV2(
rawContent,
extras,
);
expect(contextItems).toHaveLength(1);
expect(renderedPrompt).toContain("Example Content");
});
it("should resolve file attachments", async () => {
const rawContent = "Content with file attachment @test.txt";
addToTestDir([["test.txt", "File content"]]);
const [contextItems, renderedPrompt] = await renderPromptFileV2(
rawContent,
extras,
);
expect(contextItems).toHaveLength(1);
expect(renderedPrompt).toContain("```test.txt\nFile content\n```");
expect(renderedPrompt).toContain("Content with file attachment @test.txt");
});
it("should handle nested prompt files", async () => {
const rawContent = "Main prompt with nested @nested.prompt";
addToTestDir([
["nested.prompt", "Nested prompt content with @CustomProvider"],
]);
const [contextItems, renderedPrompt] = await renderPromptFileV2(
rawContent,
extras,
);
expect(renderedPrompt).toContain("Custom provider content");
});
it("should handle custom context providers", async () => {
const rawContent = "Content with custom provider @CustomProvider";
const [contextItems, renderedPrompt] = await renderPromptFileV2(
rawContent,
extras,
);
expect(contextItems).toHaveLength(1);
expect(renderedPrompt).toContain("Custom provider content");
expect(mockGetContextItems).toHaveBeenCalled();
});
it("should handle multiple attachments", async () => {
const rawContent = "Content with @file1.txt and @file2.txt";
addToTestDir([
["file1.txt", "Content 1"],
["file2.txt", "Content 2"],
]);
const [contextItems, renderedPrompt] = await renderPromptFileV2(
rawContent,
extras,
);
expect(contextItems).toHaveLength(2);
expect(renderedPrompt).toContain("```file1.txt\nContent 1\n```");
expect(renderedPrompt).toContain("```file2.txt\nContent 2\n```");
});
it("should handle failed attachment resolutions gracefully", async () => {
const rawContent = "Content with @nonexistent";
const [contextItems, renderedPrompt] = await renderPromptFileV2(
rawContent,
extras,
);
expect(contextItems).toHaveLength(0);
expect(renderedPrompt).toBe("Content with @nonexistent\n\nUser input");
});
});

View file

@ -29,7 +29,7 @@ import {
Session,
SessionMetadata,
SiteIndexingConfig,
SlashCommandDescription,
SlashCommandDescWithSource,
StreamDiffLinesPayload,
ToolCall,
} from "../";
@ -118,6 +118,17 @@ export type ToCoreFromIdeOrWebviewProtocol = {
},
void,
];
"mcp/getPrompt": [
{
serverName: string;
promptName: string;
args?: Record<string, string>;
},
{
prompt: string;
description: string | undefined;
},
];
"context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap];
"context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]];
"autocomplete/complete": [AutocompleteInput, string[]];
@ -141,7 +152,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
completionOptions: LLMFullCompletionOptions;
title: string;
legacySlashCommandData?: {
command: SlashCommandDescription;
command: SlashCommandDescWithSource;
input: string;
contextItems: ContextItemWithId[];
historyIndex: number;

View file

@ -27,6 +27,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"config/updateSharedConfig",
"config/updateSelectedModel",
"mcp/reloadServer",
"mcp/getPrompt",
"context/getContextItems",
"context/getSymbolsForFiles",
"context/loadSubmenuItems",

View file

@ -0,0 +1,111 @@
import { v4 as uuidv4 } from "uuid";
export type HandlebarsType = typeof import("handlebars");
function convertToLetter(num: number): string {
let result = "";
while (num > 0) {
const remainder = (num - 1) % 26;
result = String.fromCharCode(97 + remainder) + result;
num = Math.floor((num - 1) / 26);
}
return result;
}
export function registerHelpers(
handlebars: HandlebarsType,
helpers: Array<[string, Handlebars.HelperDelegate]>,
): {
[key: string]: Promise<string>;
} {
const promises: { [key: string]: Promise<string> } = {};
for (const [name, helper] of helpers) {
handlebars.registerHelper(name, (...args) => {
const id = uuidv4();
promises[id] = helper(...args);
return `__${id}__`;
});
}
return promises;
}
export async function prepareTemplatedFilepaths(
handlebars: HandlebarsType,
template: string,
inputData: Record<string, string>,
ctxProviderNames: string[],
readFile: (filepath: string) => Promise<string>,
getUriFromPath: (path: string) => Promise<string | undefined>,
) {
// First, replace filepaths with letters to avoid escaping issues
const ast = handlebars.parse(template);
const filepathLetters: Map<string, string> = new Map();
const requiredContextProviders: Set<string> = new Set();
let withLetterKeys = template;
let letterIndex = 1;
for (const i in ast.body) {
const node = ast.body[i] as any;
if (node.type === "MustacheStatement") {
const originalNodeVal = node.path.original;
if (originalNodeVal.toLowerCase() === "input") {
continue;
}
const isFilepath = !ctxProviderNames.includes(originalNodeVal);
if (isFilepath) {
const letter = convertToLetter(letterIndex);
filepathLetters.set(letter, originalNodeVal);
withLetterKeys = withLetterKeys.replace(
new RegExp(`{{\\s*${originalNodeVal}\\s*}}`),
`{{${letter}}}`,
);
letterIndex++;
} else {
requiredContextProviders.add(originalNodeVal);
}
}
}
// Then, resolve the filepaths to their actual content and add to template data
// Fallback to simple error string if file read fails
const templateData = { ...inputData };
for (const [letter, filepath] of filepathLetters.entries()) {
try {
const uri = await getUriFromPath(filepath);
if (uri) {
const fileContents = await readFile(uri);
templateData[letter] = fileContents;
} else {
throw new Error(`File not found: ${filepath}`);
}
} catch (e) {
console.error(`Error reading file in prompt file ${filepath}:`, e);
templateData[letter] = `[Error reading file "${filepath}"]`;
}
}
return { withLetterKeys, templateData, requiredContextProviders };
}
export async function resolveHelperPromises(
renderedString: string,
promises: { [key: string]: Promise<string> },
): Promise<string> {
await Promise.all(Object.values(promises));
for (const id in promises) {
renderedString = renderedString.replace(`__${id}__`, await promises[id]);
}
return renderedString;
}

View file

@ -1,30 +1,35 @@
import {
compileAndRenderTemplate,
prepareTemplateAndData,
prepareTemplatedFilepaths,
registerHelpers,
resolveHelperPromises,
type HandlebarsType,
} from "./handlebarUtils";
export async function renderTemplatedString(
handlebars: HandlebarsType,
template: string,
readFile: (filepath: string) => Promise<string>,
inputData: Record<string, string>,
availableHelpers?: Array<[string, Handlebars.HelperDelegate]>,
availableHelpers: Array<[string, Handlebars.HelperDelegate]>,
readFile: (filepath: string) => Promise<string>,
getUriFromPath: (path: string) => Promise<string | undefined>,
): Promise<string> {
const helperPromises = availableHelpers
? registerHelpers(availableHelpers)
? registerHelpers(handlebars, availableHelpers)
: {};
const ctxProviderNames = availableHelpers?.map((h) => h[0]) ?? [];
const [newTemplate, data] = await prepareTemplateAndData(
const { withLetterKeys, templateData } = await prepareTemplatedFilepaths(
handlebars,
template,
readFile,
inputData,
ctxProviderNames,
readFile,
getUriFromPath,
);
let renderedString = compileAndRenderTemplate(newTemplate, data);
const templateFn = handlebars.compile(withLetterKeys);
const renderedString = templateFn(templateData);
return resolveHelperPromises(renderedString, helperPromises);
}

View file

@ -188,6 +188,7 @@ export function getUriDescription(uri: string, dirUriCandidates: string[]) {
dirUriCandidates,
);
const baseName = getUriPathBasename(uri);
const extension = getFileExtensionFromBasename(baseName);
const last2Parts = getLastNUriRelativePathParts(dirUriCandidates, uri, 2);
return {
uri,
@ -195,5 +196,6 @@ export function getUriDescription(uri: string, dirUriCandidates: string[]) {
foundInDir,
last2Parts,
baseName,
extension,
};
}

View file

@ -92,6 +92,7 @@ class MessageTypes {
"config/updateSharedConfig",
"config/updateSelectedModel",
"mcp/reloadServer",
"mcp/getPrompt",
"context/getContextItems",
"context/getSymbolsForFiles",
"context/loadSubmenuItems",

65
gui/package-lock.json generated
View file

@ -31,6 +31,7 @@
"dompurify": "^3.0.6",
"downshift": "^7.6.0",
"escape-carriage": "^1.3.1",
"handlebars": "^4.7.8",
"lodash": "^4.17.21",
"lowlight": "^3.3.0",
"minisearch": "^7.0.2",
@ -6304,6 +6305,36 @@
"integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==",
"dev": true
},
"node_modules/handlebars": {
"version": "4.7.8",
"resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.7.8.tgz",
"integrity": "sha512-vafaFqs8MZkRrSX7sFVUdo3ap/eNiLnb4IakshzvP56X5Nr1iGKAIqdX6tMlm6HcNRIkr6AxO5jFEoJzzpT8aQ==",
"license": "MIT",
"dependencies": {
"minimist": "^1.2.5",
"neo-async": "^2.6.2",
"source-map": "^0.6.1",
"wordwrap": "^1.0.0"
},
"bin": {
"handlebars": "bin/handlebars"
},
"engines": {
"node": ">=0.4.7"
},
"optionalDependencies": {
"uglify-js": "^3.1.4"
}
},
"node_modules/handlebars/node_modules/source-map": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
"integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/has-bigints": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.2.tgz",
@ -8778,6 +8809,15 @@
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/minimist": {
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/minipass": {
"version": "7.1.2",
"resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz",
@ -8850,6 +8890,12 @@
"integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==",
"dev": true
},
"node_modules/neo-async": {
"version": "2.6.2",
"resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz",
"integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==",
"license": "MIT"
},
"node_modules/node-releases": {
"version": "2.0.18",
"resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.18.tgz",
@ -12157,6 +12203,19 @@
"resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-2.1.0.tgz",
"integrity": "sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A=="
},
"node_modules/uglify-js": {
"version": "3.19.3",
"resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.19.3.tgz",
"integrity": "sha512-v3Xu+yuwBXisp6QYTcH4UbH+xYJXqnq2m/LtQVWKWzYc1iehYnLixoQDN9FH6/j9/oybfd6W9Ghwkl8+UMKTKQ==",
"license": "BSD-2-Clause",
"optional": true,
"bin": {
"uglifyjs": "bin/uglifyjs"
},
"engines": {
"node": ">=0.8.0"
}
},
"node_modules/unbox-primitive": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.2.tgz",
@ -13753,6 +13812,12 @@
"node": ">=0.10.0"
}
},
"node_modules/wordwrap": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz",
"integrity": "sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q==",
"license": "MIT"
},
"node_modules/wrap-ansi": {
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz",

View file

@ -40,6 +40,7 @@
"dompurify": "^3.0.6",
"downshift": "^7.6.0",
"escape-carriage": "^1.3.1",
"handlebars": "^4.7.8",
"lodash": "^4.17.21",
"lowlight": "^3.3.0",
"minisearch": "^7.0.2",

View file

@ -1,9 +1,9 @@
import { ChatBubbleLeftIcon } from "@heroicons/react/24/outline";
import { SlashCommandDescription } from "core";
import { SlashCommandDescWithSource } from "core";
interface ConversationStarterCardProps {
command: SlashCommandDescription;
onClick: (command: SlashCommandDescription) => void;
command: SlashCommandDescWithSource;
onClick: (command: SlashCommandDescWithSource) => void;
}
export function ConversationStarterCard({

View file

@ -1,4 +1,4 @@
import { SlashCommandDescription } from "core";
import { SlashCommandDescWithSource } from "core";
import { useState } from "react";
import { useBookmarkedSlashCommands } from "../../hooks/useBookmarkedSlashCommands";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
@ -23,8 +23,12 @@ export function ConversationStarterCards() {
isCommandBookmarked(command.name),
);
function onClick(command: SlashCommandDescription) {
mainEditor?.commands.insertPrompt(command);
function onClick(command: SlashCommandDescWithSource) {
mainEditor?.commands.insertPrompt({
description: command.description,
title: command.name,
content: command.prompt,
});
}
if (bookmarkedSlashCommands.length === 0) {

View file

@ -1,27 +1,35 @@
import { SlashCommandDescription } from "core";
import { SlashCommandDescWithSource } from "core";
import { sortCommandsByBookmarkStatus } from "../utils";
describe("sortCommandsByBookmarkStatus", () => {
const mockCommands: SlashCommandDescription[] = [
const mockCommands: SlashCommandDescWithSource[] = [
{
name: "command1",
description: "First command",
prompt: "This is command 1",
source: "built-in",
isLegacy: false,
},
{
name: "command2",
description: "Second command",
prompt: "This is command 2",
source: "built-in",
isLegacy: false,
},
{
name: "command3",
description: "Third command",
prompt: "This is command 3",
source: "built-in",
isLegacy: false,
},
{
name: "command4",
description: "Fourth command",
prompt: "This is command 4",
source: "built-in",
isLegacy: false,
},
];

View file

@ -1,4 +1,4 @@
import { SlashCommandDescription } from "core";
import { SlashCommandDescWithSource } from "core";
import {} from "core/config/default";
/**
@ -8,9 +8,9 @@ import {} from "core/config/default";
* @returns A new sorted array with bookmarked commands first
*/
export function sortCommandsByBookmarkStatus(
commands: SlashCommandDescription[],
commands: SlashCommandDescWithSource[],
bookmarkedCommands: string[],
): SlashCommandDescription[] {
): SlashCommandDescWithSource[] {
return [...commands].sort((a, b) => {
const aIsBookmarked = bookmarkedCommands.includes(a.name);
const bIsBookmarked = bookmarkedCommands.includes(b.name);

View file

@ -4,7 +4,7 @@ import {
PencilIcon,
} from "@heroicons/react/24/outline";
import { BookmarkIcon as BookmarkSolid } from "@heroicons/react/24/solid";
import { SlashCommandDescription } from "core";
import { SlashCommandDescWithSource } from "core";
import { useContext, useMemo } from "react";
import { useAuth } from "../../../../context/Auth";
import { IdeMessengerContext } from "../../../../context/IdeMessenger";
@ -15,10 +15,12 @@ import { useMainEditor } from "../../TipTapEditor";
import { useLump } from "../LumpContext";
import { ExploreBlocksButton } from "./ExploreBlocksButton";
type PromptWithSlug = SlashCommandDescription & { slug?: string };
interface PromptCommandWithSlug extends SlashCommandDescWithSource {
slug?: string;
}
interface PromptRowProps {
prompt: PromptWithSlug;
prompt: PromptCommandWithSlug;
isBookmarked: boolean;
setIsBookmarked: (isBookmarked: boolean) => void;
onEdit?: () => void;
@ -38,7 +40,11 @@ function PromptRow({
const handlePromptClick = (e: React.MouseEvent) => {
e.stopPropagation();
mainEditor?.commands.insertPrompt(prompt);
mainEditor?.commands.insertPrompt({
title: prompt.name,
description: prompt.description,
content: prompt.prompt,
});
hideLump();
};
@ -102,7 +108,7 @@ export function PromptsSection() {
(state) => state.config.config.slashCommands ?? [],
);
const handleEdit = (prompt: PromptWithSlug) => {
const handleEdit = (prompt: PromptCommandWithSlug) => {
if (prompt.promptFile) {
ideMessenger.post("openFile", {
path: prompt.promptFile,
@ -120,23 +126,24 @@ export function PromptsSection() {
};
const sortedCommands = useMemo(() => {
const promptsWithSlug: PromptWithSlug[] = structuredClone(slashCommands);
const promptsWithSlug: PromptCommandWithSlug[] =
structuredClone(slashCommands);
// get the slugs from rawYaml
if (selectedProfile?.rawYaml) {
const parsed = parseConfigYaml(selectedProfile.rawYaml);
const parsedPrompts = parsed.prompts ?? [];
let index = 0;
for (const prompt of promptsWithSlug) {
for (const commandWithSlug of promptsWithSlug) {
// skip for local prompt files
if (prompt.promptFile) continue;
if (commandWithSlug.promptFile) continue;
const yamlPrompt = parsedPrompts[index];
if (yamlPrompt) {
if ("uses" in yamlPrompt) {
prompt.slug = yamlPrompt.uses;
commandWithSlug.slug = yamlPrompt.uses;
} else {
prompt.slug = `${selectedProfile?.fullSlug.ownerSlug}/${selectedProfile?.fullSlug.packageSlug}`;
commandWithSlug.slug = `${selectedProfile?.fullSlug.ownerSlug}/${selectedProfile?.fullSlug.packageSlug}`;
}
}
index = index + 1;

View file

@ -1,8 +1,9 @@
import { mergeAttributes, Node } from "@tiptap/core";
import { Node as ProseMirrorNode } from "@tiptap/pm/model";
import { ReactNodeViewRenderer } from "@tiptap/react";
import { ContextItemWithId, SlashCommandDescription } from "core";
import { ContextItemWithId } from "core";
import { MAIN_EDITOR_INPUT_ID } from "../../../../../pages/gui/Chat";
import { ComboBoxItem } from "../../../types";
import { PromptBlockPreview } from "./PromptBlockPreview";
export interface PromptBlockOptions {
@ -20,7 +21,9 @@ declare module "@tiptap/core" {
/**
* Insert a prompt block into the editor
*/
insertPrompt: (item: SlashCommandDescription) => ReturnType;
insertPrompt: (
item: Pick<ComboBoxItem, "title" | "content" | "description">,
) => ReturnType;
/**
* Clear all prompt blocks from the editor
@ -76,15 +79,15 @@ export const PromptBlock = Node.create<PromptBlockOptions>({
addCommands() {
return {
insertPrompt:
(prompt: SlashCommandDescription) =>
(item) =>
({ chain }) => {
const item: ContextItemWithId = {
content: prompt.prompt ?? "",
name: prompt.name,
description: prompt.description,
const contextItem: ContextItemWithId = {
content: item.content ?? "",
name: item.title,
description: item.description,
id: {
providerTitle: "prompt",
itemId: prompt.name,
itemId: item.title,
},
};
@ -93,7 +96,7 @@ export const PromptBlock = Node.create<PromptBlockOptions>({
.insertContentAt(0, {
type: this.name,
attrs: {
item,
item: contextItem,
inputId: MAIN_EDITOR_INPUT_ID,
},
})

View file

@ -22,11 +22,7 @@ export const SlashCommand = Node.create<SlashCommandOptions>({
// First delete the slash character and any text after it
editor.chain().focus().deleteRange(range).run();
editor.commands.insertPrompt({
name: props.title,
description: props.description,
prompt: props.content,
});
editor.commands.insertPrompt(props);
},
},
};

View file

@ -0,0 +1,536 @@
import { JSONContent } from "@tiptap/react";
import { ContextItemWithId } from "core";
import { expect, test, vi } from "vitest";
import { processEditorContent } from "./processEditorContent";
describe("processEditorContent", () => {
// Create some reusable test data
const createContextItem = (
content: string,
description: string,
fileUri?: string,
editing?: boolean,
): ContextItemWithId => ({
id: { providerTitle: "test", itemId: "test-id" },
content,
description,
name: "Test Item",
editing,
uri: fileUri ? { type: "file", value: fileUri } : undefined,
});
test("processEditorContent should return empty arrays when content is empty", () => {
// Empty editor state
const emptyEditorState: JSONContent = {
type: "doc",
content: [],
};
const result = processEditorContent(emptyEditorState);
expect(result.parts).toEqual([]);
expect(result.contextRequests).toEqual([]);
expect(result.selectedCode).toEqual([]);
expect(result.slashCommandName).toBeUndefined();
});
test("processEditorContent should process text paragraphs", () => {
const editorState: JSONContent = {
type: "doc",
content: [
{
type: "paragraph",
content: [
{
type: "text",
text: "Hello world",
},
],
},
{
type: "paragraph",
content: [
{
type: "text",
text: "This is another paragraph",
},
],
},
],
};
const result = processEditorContent(editorState);
expect(result.parts).toEqual([
{
type: "text",
text: "Hello world\nThis is another paragraph",
},
]);
expect(result.contextRequests).toEqual([]);
expect(result.selectedCode).toEqual([]);
});
test("processEditorContent should detect slash commands", () => {
const editorState: JSONContent = {
type: "doc",
content: [
{
type: "prompt-block",
attrs: {
item: {
name: "test-command",
},
},
},
{
type: "paragraph",
content: [
{
type: "text",
text: "Some text after the prompt",
},
],
},
],
};
const result = processEditorContent(editorState);
expect(result.slashCommandName).toBe("test-command");
expect(result.parts).toEqual([
{
type: "text",
text: "Some text after the prompt",
},
]);
});
test("processEditorContent should handle mentions and collect context requests", () => {
const editorState: JSONContent = {
type: "doc",
content: [
{
type: "paragraph",
content: [
{
type: "text",
text: "Hello ",
},
{
type: "mention",
attrs: {
id: "fileSearch",
label: "@fileSearch",
itemType: "contextProvider",
},
},
{
type: "text",
text: " and also ",
},
{
type: "mention",
attrs: {
id: "github",
label: "@github",
itemType: "contextProvider",
},
},
],
},
],
};
const result = processEditorContent(editorState);
expect(result.parts).toEqual([
{
type: "text",
text: "Hello @fileSearch and also @github",
},
]);
expect(result.contextRequests).toEqual([
{ provider: "fileSearch" },
{ provider: "github" },
]);
});
test("processEditorContent should handle code blocks", () => {
const codeItem = createContextItem(
"function test() {\n return 'hello';\n}",
"a description",
"file:///example.js",
);
const editorState: JSONContent = {
type: "doc",
content: [
{
type: "paragraph",
content: [
{
type: "text",
text: "Check this code:",
},
],
},
{
type: "code-block",
attrs: {
item: codeItem,
},
},
],
};
const result = processEditorContent(editorState);
expect(result.parts).toEqual([
{
type: "text",
text: "Check this code:\n\n```js example.js\nfunction test() {\n return 'hello';\n}\n```\n",
},
]);
expect(result.selectedCode).toHaveLength(1);
expect(result.selectedCode[0].filepath).toBe("file:///example.js");
});
test("processEditorContent should not include editing code blocks in the text", () => {
const editingCodeItem = createContextItem(
"function test() {\n return 'hello';\n}",
"a description",
"file:///editing.js",
true, // Set editing to true
);
const editorState: JSONContent = {
type: "doc",
content: [
{
type: "paragraph",
content: [
{
type: "text",
text: "Edit this code:",
},
],
},
{
type: "code-block",
attrs: {
item: editingCodeItem,
},
},
],
};
const result = processEditorContent(editorState);
// The code block should not be included in parts because it's marked as editing
expect(result.parts).toEqual([
{
type: "text",
text: "Edit this code:",
},
]);
// But it should still be in selectedCode
expect(result.selectedCode).toHaveLength(1);
expect(result.selectedCode[0].filepath).toBe("file:///editing.js");
});
test("processEditorContent should handle images", () => {
const editorState: JSONContent = {
type: "doc",
content: [
{
type: "paragraph",
content: [
{
type: "text",
text: "Here's an image:",
},
],
},
{
type: "image",
attrs: {
src: "https://example.com/image.png",
},
},
],
};
const result = processEditorContent(editorState);
expect(result.parts).toEqual([
{
type: "text",
text: "Here's an image:",
},
{
type: "imageUrl",
imageUrl: { url: "https://example.com/image.png" },
},
]);
});
test("processEditorContent should handle complex content with multiple elements", () => {
const codeItem = createContextItem(
"const x = 42;",
"a description",
"file:///script.ts",
);
const editorState: JSONContent = {
type: "doc",
content: [
{
type: "prompt-block",
attrs: {
item: {
name: "explain",
},
},
},
{
type: "paragraph",
content: [
{
type: "text",
text: "Please explain this code and also check ",
},
{
type: "mention",
attrs: {
id: "related",
label: "@related",
itemType: "similarFiles",
},
},
],
},
{
type: "code-block",
attrs: {
item: codeItem,
},
},
{
type: "paragraph",
content: [
{
type: "text",
text: "What does this constant do?",
},
],
},
{
type: "image",
attrs: {
src: "https://example.com/diagram.png",
},
},
],
};
const result = processEditorContent(editorState);
expect(result.slashCommandName).toBe("explain");
expect(result.contextRequests).toEqual([{ provider: "similarFiles" }]);
expect(result.selectedCode).toHaveLength(1);
expect(result.selectedCode[0].filepath).toBe("file:///script.ts");
// `\n\n\`\`\`${extension} ${relativePathOrBasename}\n${contextItem.content}\n\`\`\`\n`;
expect(result.parts).toEqual([
{
type: "text",
text: "Please explain this code and also check @related\n\n```ts script.ts\nconst x = 42;\n```\n\nWhat does this constant do?",
},
{
type: "imageUrl",
imageUrl: { url: "https://example.com/diagram.png" },
},
]);
});
test("processEditorContent should merge consecutive text parts", () => {
const editorState: JSONContent = {
type: "doc",
content: [
{
type: "paragraph",
content: [
{
type: "text",
text: "First paragraph",
},
],
},
{
type: "paragraph",
content: [
{
type: "text",
text: "Second paragraph",
},
],
},
{
type: "image",
attrs: {
src: "https://example.com/image.png",
},
},
{
type: "paragraph",
content: [
{
type: "text",
text: "Third paragraph",
},
],
},
],
};
const result = processEditorContent(editorState);
// First two paragraphs should be merged, but the third should be separate
// because there's an image in between
expect(result.parts).toEqual([
{
type: "text",
text: "First paragraph\nSecond paragraph",
},
{
type: "imageUrl",
imageUrl: { url: "https://example.com/image.png" },
},
{
type: "text",
text: "Third paragraph",
},
]);
});
test("processEditorContent should handle unexpected content types gracefully", () => {
// Testing with an unknown node type
const editorState: JSONContent = {
type: "doc",
content: [
{
type: "paragraph",
content: [
{
type: "text",
text: "Normal text",
},
],
},
{
type: "unknown-type", // This type doesn't exist
content: [
{
type: "text",
text: "This should be ignored",
},
],
},
],
};
// Spy on console.warn to verify it's called
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
const result = processEditorContent(editorState);
// Only the normal paragraph should be processed
expect(result.parts).toEqual([
{
type: "text",
text: "Normal text",
},
]);
// Console.warn should be called for the unknown type
expect(warnSpy).toHaveBeenCalledWith(
"Unexpected content type",
"unknown-type",
);
warnSpy.mockRestore();
});
test("processEditorContent should handle missing attrs in code blocks", () => {
// Testing with a code block that has no item attribute
const editorState: JSONContent = {
type: "doc",
content: [
{
type: "code-block",
// Missing attrs property
},
],
};
// Spy on console.warn to verify it's called
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
const result = processEditorContent(editorState);
// No parts should be created
expect(result.parts).toEqual([]);
expect(result.selectedCode).toEqual([]);
// Console.warn should be called for the missing item attribute
expect(warnSpy).toHaveBeenCalledWith("codeBlock has no item attribute");
warnSpy.mockRestore();
});
test("processEditorContent should handle paragraphs with unexpected child types", () => {
// Testing with a paragraph that has an unknown child type
const editorState: JSONContent = {
type: "doc",
content: [
{
type: "paragraph",
content: [
{
type: "text",
text: "Normal text ",
},
{
type: "unknown-child", // This type doesn't exist
text: "This should be ignored",
},
],
},
],
};
// Spy on console.warn to verify it's called
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
const result = processEditorContent(editorState);
// Only the normal text should be processed
expect(result.parts).toEqual([
{
type: "text",
text: "Normal text ",
},
]);
// Console.warn should be called for the unknown child type
expect(warnSpy).toHaveBeenCalledWith(
"Unexpected child type",
"unknown-child",
);
warnSpy.mockRestore();
});
});

View file

@ -0,0 +1,119 @@
import Image from "@tiptap/extension-image";
import { Paragraph } from "@tiptap/extension-paragraph";
import { Text } from "@tiptap/extension-text";
import { JSONContent } from "@tiptap/react";
import {
ContextItemWithId,
MessagePart,
RangeInFile,
TextMessagePart,
} from "core";
import { ctxItemToRifWithContents } from "core/commands/util";
import { getUriDescription } from "core/util/uri";
import { CodeBlock, Mention, PromptBlock } from "../extensions";
import { GetContextRequest } from "./types";
interface MentionAttrs {
label: string;
id: string;
itemType?: string;
query?: string;
}
function resolvePromptBlock(p: JSONContent): string | undefined {
return p.attrs?.item.name;
}
function resolveParagraph(p: JSONContent): [string, GetContextRequest[]] {
const contextRequests: GetContextRequest[] = [];
const text = (p.content || [])
.map((child) => {
switch (child.type) {
case Text.name:
return child.text;
case Mention.name:
const attrs = child.attrs as MentionAttrs;
contextRequests.push({
provider:
attrs.itemType === "contextProvider" ? attrs.id : attrs.itemType!,
});
return child.attrs?.renderInlineAs ?? child.attrs?.label;
default:
console.warn("Unexpected child type", child.type);
return "";
}
})
.join("")
.trimStart();
return [text, contextRequests];
}
export function processEditorContent(editorState: JSONContent) {
const contextRequests: GetContextRequest[] = [];
const selectedCode: RangeInFile[] = [];
let slashCommandName: string | undefined;
const parts: MessagePart[] = [];
for (const p of editorState?.content || []) {
switch (p.type) {
case PromptBlock.name:
slashCommandName = resolvePromptBlock(p);
break;
case Paragraph.name:
const [text, ctxItems] = resolveParagraph(p);
contextRequests.push(...ctxItems);
if (text) {
// Merge with previous text part if possible
if (parts[parts.length - 1]?.type === "text") {
(parts[parts.length - 1] as TextMessagePart).text += "\n" + text;
} else {
parts.push({ type: "text", text });
}
}
break;
case CodeBlock.name:
if (!p.attrs?.item) {
console.warn("codeBlock has no item attribute");
break;
}
const contextItem = p.attrs.item as ContextItemWithId;
const rif = ctxItemToRifWithContents(contextItem, true);
selectedCode.push(rif);
// If editing, only include in selectedCode
if (contextItem.editing) {
break;
}
const { extension, relativePathOrBasename } = getUriDescription(
rif.filepath,
window.workspacePaths ?? [],
);
const codeText = `\n\`\`\`${extension} ${relativePathOrBasename}\n${contextItem.content}\n\`\`\`\n`;
if (parts[parts.length - 1]?.type === "text") {
(parts[parts.length - 1] as TextMessagePart).text += "\n" + codeText;
} else {
parts.push({ type: "text", text: codeText });
}
break;
case Image.name:
parts.push({
type: "imageUrl",
imageUrl: { url: p.attrs?.src },
});
break;
default: {
console.warn("Unexpected content type", p.type);
}
}
}
return { parts, contextRequests, selectedCode, slashCommandName };
}

View file

@ -0,0 +1,32 @@
import { SlashCommandDescWithSource } from "core";
import { IIdeMessenger } from "../../../../context/IdeMessenger";
export async function renderMcpPrompt(
command: SlashCommandDescWithSource,
ideMessenger: IIdeMessenger,
userInput?: string,
) {
// TODO add support for mcp prompt args using command.mcpArgs
const args: { [key: string]: string } = {};
if (command.mcpArgs) {
command.mcpArgs.forEach((arg, i) => {
args[arg.name] = "";
});
}
const response = await ideMessenger.request("mcp/getPrompt", {
serverName: command.mcpServerName!,
promptName: command.name,
args: args,
});
if (response.status === "success") {
let renderedPrompt = response.content.prompt;
if (userInput) {
renderedPrompt += `\n\n${userInput}`;
}
return renderedPrompt;
} else {
throw new Error(
`Failed to get MCP prompt for slash command ${command.name}`,
);
}
}

View file

@ -0,0 +1,128 @@
import { SlashCommandDescWithSource } from "core";
import { beforeEach, describe, it, vi } from "vitest";
import {
MockIdeMessenger,
MockResponseHandler,
} from "../../../../context/MockIdeMessenger";
import { getRenderedV1Prompt } from "./renderPromptv1";
function getTestPromptV1Command(body: string): SlashCommandDescWithSource {
return {
prompt: body,
name: "test-prompt-name",
description: "test-prompt-description",
isLegacy: false,
source: "prompt-file-v1",
};
}
describe("get rendered v1 prompt file", () => {
const ideMessenger = new MockIdeMessenger();
const firstDir = ideMessenger.responses["getWorkspaceDirs"]?.[0] ?? "";
const customGetContextItems: MockResponseHandler<
"context/getContextItems"
> = async ({ name }) => {
if (name === "diff") {
return [
{
id: {
itemId: "id",
providerTitle: "diff",
},
name: "name",
description: "description",
content: "Diff provider content",
},
];
}
return [];
};
beforeEach(async () => {
vi.clearAllMocks();
ideMessenger.resetMocks();
});
it("should render a prompt file with no attachments or templated input", async () => {
const rawContent = "Simple prompt with no attachments";
const command = getTestPromptV1Command(rawContent);
const rendered = await getRenderedV1Prompt(
ideMessenger,
command,
"User input",
[],
);
expect(rendered).toBe("Simple prompt with no attachments\n\nUser input");
});
it("should render a prompt file templated input", async () => {
const rawContent = "{{{ input }}} Simple prompt with no attachments";
const command = getTestPromptV1Command(rawContent);
const rendered = await getRenderedV1Prompt(
ideMessenger,
command,
"User input",
[],
);
expect(rendered).toBe("User input Simple prompt with no attachments");
});
it("Should handle file attachments", async () => {
ideMessenger.responses["readFile"] = "Test file content";
const rawContent = "Content with URL {{{ testFile.txt }}}";
const command = getTestPromptV1Command(rawContent);
const rendered = await getRenderedV1Prompt(
ideMessenger,
command,
"User input",
[],
);
expect(rendered).toBe("Content with URL Test file content\n\nUser input");
});
it("should handle supported providers", async () => {
ideMessenger.responseHandlers["context/getContextItems"] =
customGetContextItems;
const rawContent = "Tell me about {{{ diff }}} please";
const command = getTestPromptV1Command(rawContent);
const rendered = await getRenderedV1Prompt(
ideMessenger,
command,
"User input",
[],
);
expect(rendered).toBe(
"Tell me about Diff provider content please\n\nUser input",
);
});
it("should render file read errors within prompt", async () => {
ideMessenger.responses["fileExists"] = false;
const rawContent = "Content with provider {{{ nonexistent }}}";
const command = getTestPromptV1Command(rawContent);
const rendered = await getRenderedV1Prompt(
ideMessenger,
command,
"User input",
[],
);
expect(rendered).toBe(
`Content with provider [Error reading file "nonexistent"]\n\nUser input`,
);
});
it("should handle multiple attachments", async () => {
ideMessenger.responseHandlers["context/getContextItems"] =
customGetContextItems;
ideMessenger.responses["readFile"] = "Test file content";
const rawContent = "Content with {{{ diff }}} and {{{ file.txt }}}";
const command = getTestPromptV1Command(rawContent);
const rendered = await getRenderedV1Prompt(
ideMessenger,
command,
"User input",
[],
);
expect(rendered).toBe(
"Content with Diff provider content and Test file content\n\nUser input",
);
});
});

View file

@ -0,0 +1,58 @@
import {
ContextProviderName,
RangeInFile,
SlashCommandDescWithSource,
} from "core";
import { SUPPORTED_PROMPT_CONTEXT_PROVIDERS } from "core/promptFiles";
import { renderTemplatedString } from "core/util/handlebars/renderTemplatedString";
import { resolveRelativePathInDir } from "core/util/ideUtils";
import { IIdeMessenger } from "../../../../context/IdeMessenger";
export async function getRenderedV1Prompt(
ideMessenger: IIdeMessenger,
command: SlashCommandDescWithSource,
userInput: string,
selectedCode: RangeInFile[],
): Promise<string> {
if (!command.prompt) {
return "";
}
const handleBarHelpers = SUPPORTED_PROMPT_CONTEXT_PROVIDERS.map(
(name: ContextProviderName): [string, Handlebars.HelperDelegate] => [
name,
async (helperContext: any) => {
const response = await ideMessenger.request("context/getContextItems", {
fullInput: userInput,
name,
query: "",
selectedCode,
});
if (response.status === "success") {
return response.content.map((item) => item.content).join("\n\n");
} else {
throw new Error(
`Failed to get context items from provider "${name}": ${response.error}`,
);
}
},
],
);
const workspaceDirs = await ideMessenger.ide.getWorkspaceDirs();
const getUriFromPath = (path: string) => {
return resolveRelativePathInDir(path, ideMessenger.ide, workspaceDirs);
};
const handlebars = await import("handlebars");
let rendered = await renderTemplatedString(
handlebars,
command.prompt,
{ input: userInput },
handleBarHelpers,
ideMessenger.ide.readFile.bind(ideMessenger.ide),
getUriFromPath,
);
// For prompt file append the input if it isn't rendered
if (!rendered.includes(userInput)) {
rendered = rendered + `\n\n${userInput}`;
}
return rendered.trim();
}

View file

@ -0,0 +1,80 @@
import { SlashCommandDescWithSource } from "core";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { MockIdeMessenger } from "../../../../context/MockIdeMessenger";
import { getPromptV2ContextRequests } from "./renderPromptv2";
function getTestPromptV2Command(body: string): SlashCommandDescWithSource {
return {
prompt: body,
name: "test-prompt-name",
description: "test-prompt-description",
isLegacy: false,
source: "prompt-file-v2",
};
}
describe("getPromptV2ContextRequests", () => {
const ideMessenger = new MockIdeMessenger();
const firstDir = ideMessenger.responses["getWorkspaceDirs"]?.[0] ?? "";
beforeEach(async () => {
vi.clearAllMocks();
ideMessenger.resetMocks();
});
it("should render a prompt file with no attachments", async () => {
const rawContent = "Simple prompt with no attachments";
const command = getTestPromptV2Command(rawContent);
const requests = await getPromptV2ContextRequests(ideMessenger, command);
expect(requests).toHaveLength(0);
});
it("should handle URL attachments", async () => {
const rawContent = "Content with URL @https://example.com";
const command = getTestPromptV2Command(rawContent);
const requests = await getPromptV2ContextRequests(ideMessenger, command);
expect(requests).toHaveLength(1);
expect(requests[0].provider).toBe("url");
expect(requests[0].query).toBe("https://example.com");
});
it("should resolve file attachments", async () => {
const rawContent = "Content with file attachment @test.txt";
const command = getTestPromptV2Command(rawContent);
const requests = await getPromptV2ContextRequests(ideMessenger, command);
expect(requests).toHaveLength(1);
expect(requests[0].provider).toBe("file");
expect(requests[0].query).toBe(`${firstDir}/test.txt`);
});
it("should handle nested prompt files", async () => {
ideMessenger.responses["readFile"] = "Contents @myfile.txt";
const rawContent = "Main prompt with nested @test.prompt";
const command = getTestPromptV2Command(rawContent);
const requests = await getPromptV2ContextRequests(ideMessenger, command);
expect(requests).toHaveLength(2);
expect(requests[0].provider).toBe("file");
expect(requests[0].query).toBe(`${firstDir}/myfile.txt`);
expect(requests[1].provider).toBe("file");
expect(requests[1].query).toBe(`${firstDir}/test.prompt`);
});
it("should ignore unsupported providers", async () => {
ideMessenger.responses["fileExists"] = false;
const rawContent = "Content with custom provider @unsupported";
const command = getTestPromptV2Command(rawContent);
const requests = await getPromptV2ContextRequests(ideMessenger, command);
expect(requests).toHaveLength(0);
});
it("should handle multiple attachments", async () => {
const rawContent = "Content with @file1.txt and @file2.txt";
const command = getTestPromptV2Command(rawContent);
const requests = await getPromptV2ContextRequests(ideMessenger, command);
expect(requests).toHaveLength(2);
expect(requests[0].provider).toBe("file");
expect(requests[0].query).toBe(`${firstDir}/file1.txt`);
expect(requests[1].provider).toBe("file");
expect(requests[1].query).toBe(`${firstDir}/file2.txt`);
});
});

View file

@ -0,0 +1,69 @@
import { SlashCommandDescWithSource } from "core";
import { SUPPORTED_PROMPT_CONTEXT_PROVIDERS } from "core/promptFiles";
import { resolveRelativePathInDir } from "core/util/ideUtils";
import { IIdeMessenger } from "../../../../context/IdeMessenger";
import { GetContextRequest } from "./types";
export async function getPromptV2ContextRequests(
ideMessenger: IIdeMessenger,
command: SlashCommandDescWithSource,
): Promise<GetContextRequest[]> {
if (!command.prompt) {
return [];
}
const workspaceDirs = await ideMessenger.ide.getWorkspaceDirs();
const visitedFiles = new Set<string>();
if (command.promptFile) {
visitedFiles.add(command.promptFile);
}
const contextRequests: GetContextRequest[] = [];
async function addContextRequestsRecursive(promptBody: string) {
// Files
const templateMatches = promptBody.matchAll(/@([^\s]+)/g);
for (const match of templateMatches) {
const name = match[1];
if (SUPPORTED_PROMPT_CONTEXT_PROVIDERS.includes(name)) {
contextRequests.push({
provider: name,
});
continue;
}
// URLs
if (name.startsWith("http")) {
contextRequests.push({
provider: "url",
query: name,
});
continue;
}
// Files
const resolvedFileUri = await resolveRelativePathInDir(
match[1],
ideMessenger.ide,
workspaceDirs,
);
if (resolvedFileUri) {
const contents = await ideMessenger.ide.readFile(resolvedFileUri);
if (name.endsWith(".prompt")) {
if (visitedFiles.has(resolvedFileUri)) {
return [];
}
visitedFiles.add(resolvedFileUri);
// As well as any context providers it references
await addContextRequestsRecursive(contents);
}
contextRequests.push({
provider: "file",
query: resolvedFileUri,
});
}
}
}
await addContextRequestsRecursive(command.prompt);
return contextRequests;
}

View file

@ -0,0 +1,145 @@
import { MessagePart, RangeInFile, SlashCommandDescWithSource } from "core";
import { stripImages } from "core/util/messageContent";
import { IIdeMessenger } from "../../../../context/IdeMessenger";
import { renderMcpPrompt } from "./renderMcpPrompt";
import { getRenderedV1Prompt } from "./renderPromptv1";
import { getPromptV2ContextRequests } from "./renderPromptv2";
import { GetContextRequest } from "./types";
/*
Slash commands can come from many sources. Render based on the source.
*/
export async function renderSlashCommandPrompt(
ideMessenger: IIdeMessenger,
commandName: string | undefined,
parts: MessagePart[],
availableSlashCommands: SlashCommandDescWithSource[],
selectedCode: RangeInFile[],
): Promise<{
slashedParts: MessagePart[];
legacyCommandWithInput?: {
command: SlashCommandDescWithSource;
input: string;
};
contextRequests: GetContextRequest[];
}> {
const NO_COMMAND = {
slashedParts: parts,
legacyCommandWithInput: undefined,
contextRequests: [],
};
if (!commandName) {
return NO_COMMAND;
}
const command = availableSlashCommands.find((c) => c.name === commandName);
if (!command) {
return NO_COMMAND;
}
const nonTextParts = parts.filter((part) => part.type !== "text");
const textParts = parts.filter((part) => part.type === "text");
const slashedParts: MessagePart[] = [...nonTextParts];
const userInput = stripImages(textParts).trimStart();
const legacyCommandWithInput = command.isLegacy
? {
command,
input: userInput,
}
: undefined;
const contextRequests: GetContextRequest[] = [];
switch (command.source) {
case "built-in-legacy":
case "config-ts-slash-command":
/**
* For legacy slash commands, we simply insert the text "/{name}" in front of the message
* And then parsing for this is done in core
*/
slashedParts.push({
type: "text",
text: `/${command.name}${command.prompt ? " " + command.prompt : ""}${userInput ? " " + userInput : ""}`,
});
break;
case "mcp-prompt":
const renderedMcpPrompt = await renderMcpPrompt(
command,
ideMessenger,
userInput,
);
slashedParts.push({
type: "text",
text: renderedMcpPrompt,
});
break;
case "prompt-file-v1":
case "prompt-file-v2":
case "yaml-prompt-block":
case "invokable-rule":
if (!command.prompt) {
console.warn(`Invalid/empty prompt from slash command ${command.name}`);
break;
}
let renderedPrompt: string;
if (
command.source === "prompt-file-v1" ||
command.prompt.includes("{{{ input }}}")
) {
renderedPrompt = await getRenderedV1Prompt(
ideMessenger,
command,
userInput,
selectedCode,
);
} else {
const promptFileCtxRequests = await getPromptV2ContextRequests(
ideMessenger,
command,
);
contextRequests.push(...promptFileCtxRequests);
renderedPrompt = [command.prompt, userInput].join("\n\n").trim();
}
if (renderedPrompt) {
slashedParts.push({
type: "text",
text: renderedPrompt, // Includes user input
});
} else {
console.warn(
`Invalid/empty prompt + input from slash command ${command.name}`,
);
}
break;
case "built-in":
case "json-custom-command":
if (!command.prompt) {
console.warn(`Slash command ${command.name} is missing prompt`);
break;
}
let rendered = command.prompt;
if (userInput) {
rendered += `\n\n${userInput}`;
}
if (rendered) {
slashedParts.push({
type: "text",
text: rendered,
});
} else {
console.warn(
`Invalid/empty prompt + input from slash command ${command.name}`,
);
}
default:
break;
}
return {
slashedParts,
legacyCommandWithInput,
contextRequests,
};
}

View file

@ -1,7 +1,4 @@
import { Dispatch } from "@reduxjs/toolkit";
import Image from "@tiptap/extension-image";
import { Paragraph } from "@tiptap/extension-paragraph";
import { Text } from "@tiptap/extension-text";
import { JSONContent } from "@tiptap/react";
import {
ContextItemWithId,
@ -10,44 +7,35 @@ import {
MessageContent,
MessagePart,
RangeInFile,
SlashCommandDescription,
TextMessagePart,
SlashCommandDescWithSource,
} from "core";
import { ctxItemToRifWithContents } from "core/commands/util";
import { renderChatMessage, stripImages } from "core/util/messageContent";
import { getUriFileExtension } from "core/util/uri";
import { stripImages } from "core/util/messageContent";
import { IIdeMessenger } from "../../../../context/IdeMessenger";
import { setIsGatheringContext } from "../../../../redux/slices/sessionSlice";
import { CodeBlock, Mention, PromptBlock } from "../extensions";
interface MentionAttrs {
label: string;
id: string;
itemType?: string;
query?: string;
}
import { processEditorContent } from "./processEditorContent";
import { renderSlashCommandPrompt } from "./renderSlashCommand";
import { GetContextRequest } from "./types";
interface ResolveEditorContentInput {
editorState: JSONContent;
modifiers: InputModifiers;
ideMessenger: IIdeMessenger;
defaultContextProviders: DefaultContextProvider[];
availableSlashCommands: SlashCommandDescription[];
availableSlashCommands: SlashCommandDescWithSource[];
dispatch: Dispatch;
}
type ResolveEditorContentOutput = [
ContextItemWithId[],
RangeInFile[],
MessageContent,
(
interface ResolveEditorContentOutput {
selectedContextItems: ContextItemWithId[];
selectedCode: RangeInFile[];
content: MessageContent;
legacyCommandWithInput:
| {
command: SlashCommandDescription;
command: SlashCommandDescWithSource;
input: string;
}
| undefined
),
];
| undefined;
}
/**
* This function converts the input from the editor to a string, resolving any context items
@ -61,26 +49,43 @@ export async function resolveEditorContent({
availableSlashCommands,
dispatch,
}: ResolveEditorContentInput): Promise<ResolveEditorContentOutput> {
const { parts, contextItemAttrs, selectedCode, slashCommandName } =
processEditorContent(editorState);
const slashCommandWithInput = processSlashCommand(
slashCommandName,
availableSlashCommands,
const {
parts,
contextRequests: editorContextRequests,
selectedCode,
slashCommandName,
} = processEditorContent(editorState);
const {
slashedParts,
contextRequests: slashContextRequests,
legacyCommandWithInput,
} = await renderSlashCommandPrompt(
ideMessenger,
slashCommandName,
parts,
availableSlashCommands,
selectedCode,
);
const shouldGatherContext = modifiers.useCodebase || slashCommandWithInput;
const contextRequests = [...editorContextRequests, ...slashContextRequests];
const shouldGatherContext =
defaultContextProviders.length > 0 ||
modifiers.useCodebase ||
!modifiers.noContext ||
contextRequests.length > 0;
if (shouldGatherContext) {
dispatch(setIsGatheringContext(true));
}
const contextItems = await gatherContextItems({
contextItemAttrs,
const selectedContextItems = await gatherContextItems({
contextRequests,
modifiers,
ideMessenger,
defaultContextProviders,
parts,
parts: slashedParts,
selectedCode,
});
@ -88,140 +93,11 @@ export async function resolveEditorContent({
dispatch(setIsGatheringContext(false));
}
return [contextItems, selectedCode, parts, slashCommandWithInput];
}
/**
* Processes editor content and extracts parts, context items, code, and slash commands
*/
function processEditorContent(editorState: JSONContent) {
const contextItemAttrs: MentionAttrs[] = [];
const selectedCode: RangeInFile[] = [];
let slashCommandName: string | undefined;
const parts = (editorState?.content || []).reduce<MessagePart[]>(
(parts, p) => {
switch (p.type) {
case PromptBlock.name: {
slashCommandName = resvolePromptBlock(p);
}
case Paragraph.name: {
const [text, ctxItems] = resolveParagraph(p);
contextItemAttrs.push(...ctxItems);
if (!text) return parts;
// Merge with previous text part if possible
if (parts[parts.length - 1]?.type === "text") {
(parts[parts.length - 1] as TextMessagePart).text += "\n" + text;
return parts;
}
return [...parts, { type: "text", text }];
}
case CodeBlock.name: {
if (!p.attrs?.item) {
console.warn("codeBlock has no item attribute");
return parts;
}
const contextItem = p.attrs.item as ContextItemWithId;
const rif = ctxItemToRifWithContents(contextItem, true);
selectedCode.push(rif);
// If editing, only include in selectedCode
if (contextItem.editing) {
return parts;
}
const fileExtension = getUriFileExtension(rif.filepath);
const codeText = [
"\n\n```",
fileExtension,
" ",
contextItem.description,
"\n",
contextItem.content,
"\n```",
].join("");
if (parts[parts.length - 1]?.type === "text") {
(parts[parts.length - 1] as TextMessagePart).text +=
"\n" + codeText;
return parts;
}
return [...parts, { type: "text", text: codeText }];
}
case Image.name: {
return [
...parts,
{
type: "imageUrl",
imageUrl: { url: p.attrs?.src },
},
];
}
default: {
console.warn("Unexpected content type", p.type);
return parts;
}
}
},
[],
);
return { parts, contextItemAttrs, selectedCode, slashCommandName };
}
/**
* Processes slash commands and prepares the command with input
*/
function processSlashCommand(
slashCommandName: string | undefined,
availableSlashCommands: SlashCommandDescription[],
parts: MessagePart[],
): { command: SlashCommandDescription; input: string } | undefined {
if (!slashCommandName) return;
const command = availableSlashCommands.find(
(c) => c.name === slashCommandName,
);
if (!command) return;
const lastTextIndex = findLastIndex(parts, (part) => part.type === "text");
const lastTextPart = parts[lastTextIndex] as TextMessagePart;
const originalPrompt = command.prompt ? " " + command.prompt : "";
let input: string;
/**
* Although we no longer render slash command <span /> tags from the editor,
* we are inserting a slash command style text back into the text here.
* This is a a hack, but there's a number of assumptions in `core` that there
* is slash command text at the beginning of the text in order to process slash commands.
*/
if (lastTextPart) {
input = renderChatMessage({
role: "user",
content: lastTextPart.text,
}).trimStart();
lastTextPart.text = `/${command.name}${originalPrompt} ${lastTextPart.text}`;
} else {
input = "";
parts.push({ type: "text", text: `/${command.name}${originalPrompt}` });
}
return {
command,
input,
selectedContextItems,
selectedCode,
content: slashedParts,
legacyCommandWithInput,
};
}
@ -229,26 +105,44 @@ function processSlashCommand(
* Gathers context items from various sources
*/
async function gatherContextItems({
contextItemAttrs,
contextRequests,
modifiers,
ideMessenger,
defaultContextProviders,
parts,
selectedCode,
}: {
contextItemAttrs: MentionAttrs[];
contextRequests: GetContextRequest[];
modifiers: InputModifiers;
ideMessenger: IIdeMessenger;
defaultContextProviders: DefaultContextProvider[];
parts: MessagePart[];
selectedCode: RangeInFile[];
}): Promise<ContextItemWithId[]> {
const defaultRequests: GetContextRequest[] = defaultContextProviders.map(
(def) => ({
provider: def.name,
query: def.query,
}),
);
const withDefaults = [...contextRequests, ...defaultRequests];
const deduplicatedInputs = withDefaults.reduce<GetContextRequest[]>(
(acc, item) => {
if (
!acc.some((i) => i.provider === item.provider && i.query === item.query)
) {
acc.push(item);
}
return acc;
},
[],
);
let contextItems: ContextItemWithId[] = [];
// Process context item attributes
for (const item of contextItemAttrs) {
for (const item of deduplicatedInputs) {
const result = await ideMessenger.request("context/getContextItems", {
name: item.itemType === "contextProvider" ? item.id : item.itemType!,
name: item.provider,
query: item.query ?? "",
fullInput: stripImages(parts),
selectedCode,
@ -259,7 +153,10 @@ async function gatherContextItems({
}
// cmd+enter to use codebase
if (modifiers.useCodebase) {
if (
modifiers.useCodebase &&
!deduplicatedInputs.some((item) => item.provider === "codebase")
) {
const result = await ideMessenger.request("context/getContextItems", {
name: "codebase",
query: "",
@ -272,62 +169,51 @@ async function gatherContextItems({
}
}
// Include default context providers
const defaultContextItems = await Promise.all(
defaultContextProviders.map(async (provider) => {
const result = await ideMessenger.request("context/getContextItems", {
name: provider.name,
query: provider.query ?? "",
fullInput: stripImages(parts),
selectedCode,
});
if (result.status === "success") {
return result.content;
} else {
return [];
// noContext modifier adds currently open file if it's not already present
if (
!modifiers.noContext &&
!deduplicatedInputs.some((item) => item.provider === "currentFile")
) {
const currentFileResponse = await ideMessenger.request(
"context/getContextItems",
{
name: "currentFile",
query: "non-mention-usage",
fullInput: "",
selectedCode: [],
},
);
if (currentFileResponse.status === "success") {
const currentFile = currentFileResponse.content[0];
if (currentFile.uri?.value) {
currentFile.id = {
providerTitle: "file",
itemId: currentFile.uri.value,
};
contextItems.unshift(currentFile);
}
}),
);
contextItems.push(...defaultContextItems.flat());
return contextItems;
}
function findLastIndex<T>(
array: T[],
predicate: (value: T, index: number, obj: T[]) => boolean,
): number {
for (let i = array.length - 1; i >= 0; i--) {
if (predicate(array[i], i, array)) {
return i;
}
}
return -1; // if no element satisfies the predicate
}
function resvolePromptBlock(p: JSONContent): string | undefined {
return p.attrs?.item.name;
}
function resolveParagraph(p: JSONContent): [string, MentionAttrs[]] {
const contextItems: MentionAttrs[] = [];
const text = (p.content || [])
.map((child) => {
switch (child.type) {
case Text.name:
return child.text;
case Mention.name:
contextItems.push(child.attrs as MentionAttrs);
return child.attrs?.renderInlineAs ?? child.attrs?.label;
default:
console.warn("Unexpected child type", child.type);
return "";
// Deduplicates based on either providerTitle + itemId or uri type + value
const deduplicatedOutputs = contextItems.reduce<ContextItemWithId[]>(
(acc, item) => {
if (
!acc.some(
(i) =>
(i.id.providerTitle === item.id.providerTitle &&
i.id.itemId === item.id.itemId) ||
(i.uri &&
item.uri &&
i.uri.type === item.uri.type &&
i.uri.value === item.uri.value),
)
) {
acc.push(item);
}
})
.join("")
.trimStart();
return [text, contextItems];
return acc;
},
[],
);
return deduplicatedOutputs;
}

View file

@ -0,0 +1,4 @@
export interface GetContextRequest {
provider: string;
query?: string;
}

View file

@ -18,6 +18,14 @@ type MockResponses = Partial<{
[K in keyof FromWebviewProtocol]: FromWebviewProtocol[K][1];
}>;
export type MockResponseHandler<T extends keyof FromWebviewProtocol> = (
input: FromWebviewProtocol[T][0],
) => Promise<FromWebviewProtocol[T][1]>;
type MockResponseHandlers = Partial<{
[K in keyof FromWebviewProtocol]: MockResponseHandler<K>;
}>;
const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = {
fileExists: true,
getCurrentFile: {
@ -66,6 +74,7 @@ const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = {
"chatDescriber/describe": "Session summary",
applyToFile: undefined,
acceptDiff: undefined,
readFile: "File contents",
};
const DEFAULT_CHAT_RESPONSE: ChatMessage[] = [
@ -119,6 +128,7 @@ export class MockIdeMessenger implements IIdeMessenger {
}
responses: MockResponses = { ...DEFAULT_MOCK_CORE_RESPONSES };
responseHandlers: MockResponseHandlers = {};
chatResponse: ChatMessage[] = DEFAULT_CHAT_RESPONSE;
chatStreamDelay: number = 0;
setChatResponseText(text: string): void {
@ -164,6 +174,14 @@ export class MockIdeMessenger implements IIdeMessenger {
messageType: T,
data: FromWebviewProtocol[T][0],
): Promise<WebviewSingleProtocolMessage<T>> {
if (this.responseHandlers[messageType]) {
const content = await this.responseHandlers[messageType](data);
return {
status: "success",
content,
done: true,
};
}
if (messageType in this.responses) {
const content = this.responses[messageType];
return {
@ -173,7 +191,10 @@ export class MockIdeMessenger implements IIdeMessenger {
};
}
console.error(messageType);
throw new Error("MockIdeMessenger: No response defined for " + messageType);
throw new Error(
"MockIdeMessenger: No response handler or response defined for " +
messageType,
);
}
respond<T extends keyof ToWebviewProtocol>(
@ -195,6 +216,7 @@ export class MockIdeMessenger implements IIdeMessenger {
resetMocks(): void {
this.responses = { ...DEFAULT_MOCK_CORE_RESPONSES };
this.responseHandlers = {};
this.chatResponse = DEFAULT_CHAT_RESPONSE;
this.chatStreamDelay = 0;
}

View file

@ -1,4 +1,4 @@
import { SlashCommandDescription } from "core";
import { SlashCommandDescWithSource } from "core";
import { usePostHog } from "posthog-js/react";
import { useAppDispatch, useAppSelector } from "../redux/hooks";
@ -17,7 +17,7 @@ export function useBookmarkedSlashCommands() {
return bookmarkedCommands.includes(commandName);
};
const toggleBookmark = (command: SlashCommandDescription) => {
const toggleBookmark = (command: SlashCommandDescWithSource) => {
const isBookmarked = isCommandBookmarked(command.name);
posthog.capture("toggle_bookmarked_slash_command", {

View file

@ -10,16 +10,7 @@ export type ConfigState = {
};
export const EMPTY_CONFIG: BrowserSerializedContinueConfig = {
slashCommands: [
{
name: "share",
description: "Export the current chat session to markdown",
},
{
name: "cmd",
description: "Generate a shell command",
},
],
slashCommands: [],
contextProviders: [],
tools: [],
mcpServerStatuses: [],

View file

@ -1,5 +1,5 @@
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { SlashCommandDescription } from "core";
import { SlashCommandDescWithSource } from "core";
import { SerializedOrgWithProfiles } from "core/config/ProfileLifecycleManager";
const DEFAULT_SLASH_COMMANDS_BOOKMARKS_COUNT = 5;
@ -81,7 +81,7 @@ export const profilesSlice = createSlice({
state,
action: PayloadAction<{
profileId: string;
defaultSlashCommands?: SlashCommandDescription[];
defaultSlashCommands?: SlashCommandDescWithSource[];
}>,
) => {
const { profileId, defaultSlashCommands = [] } = action.payload;

View file

@ -34,27 +34,26 @@ export const streamEditThunk = createAsyncThunk<
},
ThunkApiType
>(
"chat/streamResponse",
"edit/streamResponse",
async ({ editorState, codeToEdit }, { dispatch, extra }) => {
await dispatch(
streamThunkWrapper(async () => {
dispatch(setActive());
const [contextItems, __, userInstructions, _] =
await resolveEditorContent({
editorState,
modifiers: {
noContext: true,
useCodebase: false,
},
ideMessenger: extra.ideMessenger,
defaultContextProviders: [],
availableSlashCommands: [],
dispatch,
});
const { selectedContextItems, content } = await resolveEditorContent({
editorState,
modifiers: {
noContext: true,
useCodebase: false,
},
ideMessenger: extra.ideMessenger,
defaultContextProviders: [],
availableSlashCommands: [],
dispatch,
});
const prompt = [
...contextItems.map((item) => item.content),
stripImages(userInstructions),
...selectedContextItems.map((item) => item.content),
stripImages(content),
].join("\n\n");
const response = await extra.ideMessenger.request("edit/sendPrompt", {

View file

@ -1,124 +0,0 @@
import { createAsyncThunk } from "@reduxjs/toolkit";
import { JSONContent } from "@tiptap/core";
import {
ContextItemWithId,
InputModifiers,
MessageContent,
RangeInFile,
SlashCommandDescription,
} from "core";
import * as URI from "uri-js";
import { resolveEditorContent } from "../../components/mainInput/TipTapEditor";
import { selectSelectedChatModel } from "../slices/configSlice";
import { ThunkApiType } from "../store";
export const gatherContext = createAsyncThunk<
{
selectedContextItems: ContextItemWithId[];
selectedCode: RangeInFile[];
content: MessageContent;
slashCommandWithInput:
| {
command: SlashCommandDescription;
input: string;
}
| undefined;
},
{
editorState: JSONContent;
modifiers: InputModifiers;
promptPreamble?: string;
},
ThunkApiType
>(
"chat/gatherContext",
async (
{ modifiers, editorState, promptPreamble },
{ dispatch, extra, getState },
) => {
const state = getState();
const selectedChatModel = selectSelectedChatModel(state);
const defaultContextProviders =
state.config.config.experimental?.defaultContext ?? [];
if (!selectedChatModel) {
console.error(
"gatherContext thunk: Cannot gather context, no model selected",
);
throw new Error("No chat model selected");
}
// Resolve context providers and construct new history
let [selectedContextItems, selectedCode, content, slashCommandWithInput] =
await resolveEditorContent({
editorState,
modifiers,
ideMessenger: extra.ideMessenger,
defaultContextProviders,
availableSlashCommands: state.config.config.slashCommands,
dispatch,
});
// Automatically use currently open file
if (!modifiers.noContext) {
const usingFreeTrial = false; // TODO no longer tracking free trial count, need to hook up to hub
const currentFileResponse = await extra.ideMessenger.request(
"context/getContextItems",
{
name: "currentFile",
query: "non-mention-usage",
fullInput: "",
selectedCode: [],
},
);
if (currentFileResponse.status === "success") {
const items = currentFileResponse.content;
if (items.length > 0) {
const currentFile = items[0];
const uri = currentFile.uri?.value;
// don't add the file if it's already in the context items
if (
uri &&
!selectedContextItems.find(
(item) => item.uri?.value && URI.equal(item.uri.value, uri),
)
) {
// Limit to 1000 lines if using free trial
if (usingFreeTrial) {
currentFile.content = currentFile.content
.split("\n")
.slice(0, 1000)
.join("\n");
if (!currentFile.content.endsWith("```")) {
currentFile.content += "\n```";
}
}
currentFile.id = {
providerTitle: "file",
itemId: uri,
};
selectedContextItems.unshift(currentFile);
}
}
}
}
if (promptPreamble) {
if (typeof content === "string") {
content = promptPreamble + content;
} else if (content[0].type === "text") {
content[0].text = promptPreamble + content[0].text;
}
}
return {
selectedContextItems,
selectedCode,
content,
slashCommandWithInput,
};
},
);

View file

@ -5,6 +5,7 @@ import { constructMessages } from "core/llm/constructMessages";
import { getApplicableRules } from "core/llm/rules/getSystemMessageWithRules";
import posthog from "posthog-js";
import { v4 as uuidv4 } from "uuid";
import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent";
import { getBaseSystemMessage } from "../../util";
import { selectSelectedChatModel } from "../slices/configSlice";
import {
@ -13,7 +14,6 @@ import {
updateHistoryItemAtIndex,
} from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
import { gatherContext } from "./gatherContext";
import { resetStateForNewMessage } from "./resetStateForNewMessage";
import { streamNormalInput } from "./streamNormalInput";
import { streamThunkWrapper } from "./streamThunkWrapper";
@ -25,15 +25,11 @@ export const streamResponseThunk = createAsyncThunk<
editorState: JSONContent;
modifiers: InputModifiers;
index?: number;
promptPreamble?: string;
},
ThunkApiType
>(
"chat/streamResponse",
async (
{ editorState, modifiers, index, promptPreamble },
{ dispatch, extra, getState },
) => {
async ({ editorState, modifiers, index }, { dispatch, extra, getState }) => {
await dispatch(
streamThunkWrapper(async () => {
const state = getState();
@ -49,19 +45,30 @@ export const streamResponseThunk = createAsyncThunk<
);
resetStateForNewMessage();
const result = await dispatch(
gatherContext({
editorState,
modifiers,
promptPreamble,
}),
);
const defaultContextProviders =
state.config.config.experimental?.defaultContext ?? [];
if (!selectedChatModel) {
console.error(
"gatherContext thunk: Cannot gather context, no model selected",
);
throw new Error("No chat model selected");
}
// Resolve context providers and construct new history
const {
selectedContextItems,
selectedCode,
content,
slashCommandWithInput,
} = unwrapResult(result);
legacyCommandWithInput,
} = await resolveEditorContent({
editorState,
modifiers,
ideMessenger: extra.ideMessenger,
defaultContextProviders,
availableSlashCommands: state.config.config.slashCommands,
dispatch,
});
// symbols for both context items AND selected codeblocks
const filesForSymbols = [
@ -133,9 +140,9 @@ export const streamResponseThunk = createAsyncThunk<
});
posthog.capture("userInput", {});
if (slashCommandWithInput) {
if (legacyCommandWithInput) {
posthog.capture("step run", {
step_name: slashCommandWithInput.command.name,
step_name: legacyCommandWithInput.command.name,
params: {},
});
}
@ -144,12 +151,12 @@ export const streamResponseThunk = createAsyncThunk<
await dispatch(
streamNormalInput({
messages,
legacySlashCommandData: slashCommandWithInput
legacySlashCommandData: legacyCommandWithInput
? {
command: slashCommandWithInput.command,
command: legacyCommandWithInput.command,
contextItems: selectedContextItems,
historyIndex: inputIndex,
input: slashCommandWithInput.input,
input: legacyCommandWithInput.input,
selectedCode,
}
: undefined,