WIP: render slash commands
This commit is contained in:
parent
ff4dcdce73
commit
fb5beb042e
20 changed files with 321 additions and 248 deletions
|
|
@ -1,8 +1,4 @@
|
|||
import { CustomCommand, SlashCommandWithSource } from "../..";
|
||||
import { renderTemplatedString } from "../../promptFiles/v1/renderTemplatedString";
|
||||
import { replaceSlashCommandWithPromptInChatHistory } from "../../promptFiles/v1/updateChatHistory";
|
||||
import { renderPromptFileV2 } from "../../promptFiles/v2/renderPromptFile";
|
||||
import { renderChatMessage } from "../../util/messageContent";
|
||||
|
||||
export function convertCustomCommandToSlashCommand(
|
||||
customCommand: CustomCommand,
|
||||
|
|
@ -15,59 +11,5 @@ export function convertCustomCommandToSlashCommand(
|
|||
description: customCommand.description ?? "",
|
||||
prompt: customCommand.prompt,
|
||||
source: "json-custom-command",
|
||||
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.selectedModelByRole.embed,
|
||||
reranker: config.selectedModelByRole.rerank,
|
||||
},
|
||||
);
|
||||
|
||||
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);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,7 @@
|
|||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
|
||||
import { PromptMessage } from "@modelcontextprotocol/sdk/types.js";
|
||||
import { ChatMessage, SlashCommandWithSource } from "../../index.js";
|
||||
import { renderChatMessage } from "../../util/messageContent.js";
|
||||
import { SlashCommandWithSource } from "../../index.js";
|
||||
|
||||
export function constructMcpSlashCommand(
|
||||
client: Client,
|
||||
name: string,
|
||||
|
|
@ -14,58 +13,22 @@ export function constructMcpSlashCommand(
|
|||
description: description ?? "MCP Prompt",
|
||||
source: "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);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
|
|
|||
12
core/commands/slash/promptBlockSlashCommand.ts
Normal file
12
core/commands/slash/promptBlockSlashCommand.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import { CustomCommand, SlashCommandWithSource } from "../..";
|
||||
|
||||
export function convertPromptBlockToSlashCommand(
|
||||
customCommand: CustomCommand,
|
||||
): SlashCommandWithSource {
|
||||
return {
|
||||
name: customCommand.name,
|
||||
description: customCommand.description ?? "",
|
||||
prompt: customCommand.prompt,
|
||||
source: "yaml-prompt-block",
|
||||
};
|
||||
}
|
||||
|
|
@ -1,13 +1,10 @@
|
|||
import { ContinueSDK, SlashCommandWithSource } from "../..";
|
||||
import { getDiffsFromCache } from "../../autocomplete/snippets/gitDiffCache";
|
||||
import { parsePromptFileV1V2 } from "../../promptFiles/v2/parsePromptFileV1V2";
|
||||
import { renderPromptFileV2 } from "../../promptFiles/v2/renderPromptFile";
|
||||
import { renderChatMessage } from "../../util/messageContent";
|
||||
import { getLastNPathParts } from "../../util/uri";
|
||||
|
||||
import { getContextProviderHelpers } from "../../promptFiles/v1/getContextProviderHelpers";
|
||||
import { renderTemplatedString } from "../../promptFiles/v1/renderTemplatedString";
|
||||
import { replaceSlashCommandWithPromptInChatHistory } from "../../promptFiles/v1/updateChatHistory";
|
||||
|
||||
export function extractName(preamble: { name?: string }, path: string): string {
|
||||
return preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0];
|
||||
|
|
@ -59,32 +56,5 @@ export function slashCommandFromPromptFileV1(
|
|||
prompt,
|
||||
source: ".prompt-file",
|
||||
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);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ import {
|
|||
ModelDescription,
|
||||
RerankerDescription,
|
||||
SerializedContinueConfig,
|
||||
SlashCommand,
|
||||
SlashCommandWithSource,
|
||||
} from "..";
|
||||
import { getLegacyBuiltInSlashCommandFromDescription } from "../commands/slash/built-in-legacy";
|
||||
import { convertCustomCommandToSlashCommand } from "../commands/slash/customSlashCommand";
|
||||
|
|
@ -172,7 +172,7 @@ 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 = getLegacyBuiltInSlashCommandFromDescription(command);
|
||||
if (newCommand) {
|
||||
|
|
@ -660,7 +660,10 @@ async function finalToBrowserConfig(
|
|||
return {
|
||||
allowAnonymousTelemetry: final.allowAnonymousTelemetry,
|
||||
completionOptions: final.completionOptions,
|
||||
slashCommands: final.slashCommands?.map(({ run, ...rest }) => rest),
|
||||
slashCommands: final.slashCommands?.map(({ run, ...rest }) => ({
|
||||
...rest,
|
||||
isLegacy: !!run,
|
||||
})),
|
||||
contextProviders: final.contextProviders?.map((c) => c.description),
|
||||
disableIndexing: final.disableIndexing,
|
||||
disableSessionTitles: final.disableSessionTitles,
|
||||
|
|
|
|||
|
|
@ -16,9 +16,9 @@ import {
|
|||
ILLMLogger,
|
||||
RuleWithSource,
|
||||
SerializedContinueConfig,
|
||||
SlashCommandDescWithSource,
|
||||
Tool,
|
||||
} from "../../";
|
||||
import { constructMcpSlashCommand } from "../../commands/slash/mcpSlashCommand";
|
||||
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
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles";
|
|||
import { GlobalContext } from "../../util/GlobalContext";
|
||||
import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
|
||||
|
||||
import { convertCustomCommandToSlashCommand } from "../../commands/slash/customSlashCommand";
|
||||
import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand";
|
||||
import { getControlPlaneEnvSync } from "../../control-plane/env";
|
||||
import { baseToolDefinitions } from "../../tools";
|
||||
import { getCleanUriPath } from "../../util/uri";
|
||||
|
|
@ -286,7 +286,7 @@ async function configYamlToContinueConfig(options: {
|
|||
|
||||
config.prompts?.forEach((prompt) => {
|
||||
try {
|
||||
const slashCommand = convertCustomCommandToSlashCommand(prompt);
|
||||
const slashCommand = convertPromptBlockToSlashCommand(prompt);
|
||||
continueConfig.slashCommands?.push(slashCommand);
|
||||
} catch (e) {
|
||||
localErrors.push({
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
14
core/core.ts
14
core/core.ts
|
|
@ -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);
|
||||
|
|
|
|||
26
core/index.d.ts
vendored
26
core/index.d.ts
vendored
|
|
@ -848,6 +848,12 @@ 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;
|
||||
}
|
||||
|
||||
export type SlashCommandSource =
|
||||
| "built-in-legacy"
|
||||
| "built-in"
|
||||
|
|
@ -859,13 +865,11 @@ export type SlashCommandSource =
|
|||
| "invokable-rule";
|
||||
|
||||
export interface SlashCommandDescWithSource extends SlashCommandDescription {
|
||||
isLegacy: boolean; // Maps to if slashcommand.run exists
|
||||
source: SlashCommandSource;
|
||||
promptFile?: string;
|
||||
}
|
||||
|
||||
export interface SlashCommandWithSource extends SlashCommand {
|
||||
source: SlashCommandSource;
|
||||
promptFile?: string;
|
||||
mcpServerName?: string;
|
||||
mcpArgs?: MCPPromptArgs;
|
||||
}
|
||||
|
||||
// Config
|
||||
|
|
@ -1191,14 +1195,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
|
||||
|
|
|
|||
|
|
@ -59,6 +59,9 @@ export async function* llmStreamChat(
|
|||
},
|
||||
true,
|
||||
);
|
||||
if (!slashCommand.run) {
|
||||
throw new Error(`Slash command ${command.name} is not a legacy command`);
|
||||
}
|
||||
|
||||
const gen = slashCommand.run({
|
||||
input,
|
||||
|
|
|
|||
|
|
@ -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[]];
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -92,6 +92,7 @@ class MessageTypes {
|
|||
"config/updateSharedConfig",
|
||||
"config/updateSelectedModel",
|
||||
"mcp/reloadServer",
|
||||
"mcp/getPrompt",
|
||||
"context/getContextItems",
|
||||
"context/getSymbolsForFiles",
|
||||
"context/loadSubmenuItems",
|
||||
|
|
|
|||
|
|
@ -8,24 +8,28 @@ describe("sortCommandsByBookmarkStatus", () => {
|
|||
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,
|
||||
},
|
||||
];
|
||||
|
||||
|
|
|
|||
|
|
@ -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, SlashCommandDescWithSource } 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,7 @@ declare module "@tiptap/core" {
|
|||
/**
|
||||
* Insert a prompt block into the editor
|
||||
*/
|
||||
insertPrompt: (item: SlashCommandDescWithSource) => ReturnType;
|
||||
insertPrompt: (item: ComboBoxItem) => ReturnType;
|
||||
|
||||
/**
|
||||
* Clear all prompt blocks from the editor
|
||||
|
|
@ -76,12 +77,12 @@ export const PromptBlock = Node.create<PromptBlockOptions>({
|
|||
addCommands() {
|
||||
return {
|
||||
insertPrompt:
|
||||
(prompt: SlashCommandDescWithSource) =>
|
||||
(item: ComboBoxItem) =>
|
||||
({ 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,
|
||||
|
|
@ -93,7 +94,7 @@ export const PromptBlock = Node.create<PromptBlockOptions>({
|
|||
.insertContentAt(0, {
|
||||
type: this.name,
|
||||
attrs: {
|
||||
item,
|
||||
item: contextItem,
|
||||
inputId: MAIN_EDITOR_INPUT_ID,
|
||||
},
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
},
|
||||
},
|
||||
};
|
||||
|
|
|
|||
|
|
@ -14,6 +14,8 @@ import {
|
|||
TextMessagePart,
|
||||
} from "core";
|
||||
import { ctxItemToRifWithContents } from "core/commands/util";
|
||||
import { renderTemplatedString } from "core/promptFiles/v1/renderTemplatedString";
|
||||
import { parsePromptFileV1V2 } from "core/promptFiles/v2/parsePromptFileV1V2";
|
||||
import { renderChatMessage, stripImages } from "core/util/messageContent";
|
||||
import { getUriFileExtension } from "core/util/uri";
|
||||
import { IIdeMessenger } from "../../../../context/IdeMessenger";
|
||||
|
|
@ -36,18 +38,17 @@ interface ResolveEditorContentInput {
|
|||
dispatch: Dispatch;
|
||||
}
|
||||
|
||||
type ResolveEditorContentOutput = [
|
||||
ContextItemWithId[],
|
||||
RangeInFile[],
|
||||
MessageContent,
|
||||
(
|
||||
interface ResolveEditorContentOutput {
|
||||
selectedContextItems: ContextItemWithId[];
|
||||
selectedCode: RangeInFile[];
|
||||
content: MessageContent;
|
||||
legacyCommandWithInput:
|
||||
| {
|
||||
command: SlashCommandDescWithSource;
|
||||
input: string;
|
||||
}
|
||||
| undefined
|
||||
),
|
||||
];
|
||||
| undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* This function converts the input from the editor to a string, resolving any context items
|
||||
|
|
@ -61,26 +62,38 @@ export async function resolveEditorContent({
|
|||
availableSlashCommands,
|
||||
dispatch,
|
||||
}: ResolveEditorContentInput): Promise<ResolveEditorContentOutput> {
|
||||
const { parts, contextItemAttrs, selectedCode, slashCommandName } =
|
||||
processEditorContent(editorState);
|
||||
const {
|
||||
parts,
|
||||
contextItemAttrs: editorContextAttrs,
|
||||
selectedCode,
|
||||
slashCommandName,
|
||||
} = processEditorContent(editorState);
|
||||
|
||||
const slashCommandWithInput = processSlashCommand(
|
||||
const {
|
||||
parts: slashParts,
|
||||
legacyCommandWithInput,
|
||||
contextAttrs: slashContextAttrs = [],
|
||||
} = (await renderSlashCommandPrompt(
|
||||
ideMessenger,
|
||||
slashCommandName,
|
||||
availableSlashCommands,
|
||||
parts,
|
||||
);
|
||||
)) ?? {};
|
||||
|
||||
const shouldGatherContext = modifiers.useCodebase || slashCommandWithInput;
|
||||
const contextItemAttrs = [...editorContextAttrs, ...slashContextAttrs];
|
||||
|
||||
const shouldGatherContext =
|
||||
modifiers.useCodebase || contextItemAttrs.length > 0;
|
||||
if (shouldGatherContext) {
|
||||
dispatch(setIsGatheringContext(true));
|
||||
}
|
||||
|
||||
const contextItems = await gatherContextItems({
|
||||
const selectedContextItems = await gatherContextItems({
|
||||
contextItemAttrs,
|
||||
modifiers,
|
||||
ideMessenger,
|
||||
defaultContextProviders,
|
||||
parts,
|
||||
parts: slashParts ?? parts,
|
||||
selectedCode,
|
||||
});
|
||||
|
||||
|
|
@ -88,7 +101,12 @@ export async function resolveEditorContent({
|
|||
dispatch(setIsGatheringContext(false));
|
||||
}
|
||||
|
||||
return [contextItems, selectedCode, parts, slashCommandWithInput];
|
||||
return {
|
||||
selectedContextItems,
|
||||
selectedCode,
|
||||
content: slashParts ?? parts,
|
||||
legacyCommandWithInput,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -178,15 +196,25 @@ function processEditorContent(editorState: JSONContent) {
|
|||
|
||||
return { parts, contextItemAttrs, selectedCode, slashCommandName };
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes slash commands and prepares the command with input
|
||||
*/
|
||||
function processSlashCommand(
|
||||
async function renderSlashCommandPrompt(
|
||||
ideMessenger: IIdeMessenger,
|
||||
slashCommandName: string | undefined,
|
||||
availableSlashCommands: SlashCommandDescWithSource[],
|
||||
parts: MessagePart[],
|
||||
): { command: SlashCommandDescWithSource; input: string } | undefined {
|
||||
): Promise<
|
||||
| {
|
||||
slashedParts: MessagePart[];
|
||||
legacyCommandWithInput?: {
|
||||
command: SlashCommandDescWithSource;
|
||||
input: string;
|
||||
};
|
||||
contextAttrs: MentionAttrs[];
|
||||
}
|
||||
| undefined
|
||||
> {
|
||||
if (!slashCommandName) return;
|
||||
|
||||
const command = availableSlashCommands.find(
|
||||
|
|
@ -195,33 +223,130 @@ function processSlashCommand(
|
|||
|
||||
if (!command) return;
|
||||
|
||||
const lastTextIndex = findLastIndex(parts, (part) => part.type === "text");
|
||||
const lastTextPart = parts[lastTextIndex] as TextMessagePart;
|
||||
const nonTextParts = parts.filter((part) => part.type !== "text");
|
||||
const slashedParts: MessagePart[] = [...nonTextParts];
|
||||
const textParts = parts.filter((part) => part.type === "text");
|
||||
|
||||
const originalPrompt = command.prompt ? " " + command.prompt : "";
|
||||
const userInput = textParts.length
|
||||
? renderChatMessage({
|
||||
role: "user",
|
||||
content: textParts,
|
||||
}).trimStart()
|
||||
: "";
|
||||
|
||||
let input: string;
|
||||
const legacyCommandWithInput = command.isLegacy
|
||||
? {
|
||||
command,
|
||||
input: userInput,
|
||||
}
|
||||
: undefined;
|
||||
|
||||
/**
|
||||
* 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}` });
|
||||
const contextItemAttrs: MentionAttrs[] = [];
|
||||
|
||||
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":
|
||||
// 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") {
|
||||
slashedParts.push({
|
||||
type: "text",
|
||||
text: `${response.content.prompt}${userInput ? "\n\n" + userInput : ""}`,
|
||||
});
|
||||
} else {
|
||||
throw new Error(
|
||||
`Failed to get MCP prompt for slash command ${slashCommandName}`,
|
||||
);
|
||||
}
|
||||
break;
|
||||
case ".prompt-file":
|
||||
if (!command.promptFile || !command.prompt) {
|
||||
throw new Error(
|
||||
`Invalid/empty prompt from slash command ${command.name}`,
|
||||
);
|
||||
}
|
||||
const { name, description, systemMessage, prompt } = parsePromptFileV1V2(
|
||||
command.promptFile,
|
||||
command.prompt,
|
||||
);
|
||||
case "yaml-prompt-block":
|
||||
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,
|
||||
});
|
||||
|
||||
// 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.selectedModelByRole.embed,
|
||||
reranker: config.selectedModelByRole.rerank,
|
||||
},
|
||||
);
|
||||
|
||||
renderedPrompt = renderedPromptFile[1];
|
||||
}
|
||||
|
||||
const renderedPrompt = renderPromptFile();
|
||||
slashedParts.push({
|
||||
type: "text",
|
||||
text: renderedPrompt, // Includes user input
|
||||
});
|
||||
case "built-in":
|
||||
case "invokable-rule":
|
||||
case "json-custom-command":
|
||||
if (!command.prompt) {
|
||||
throw new Error(`Slash command ${slashCommandName} is missing prompt`);
|
||||
}
|
||||
slashedParts.push({
|
||||
type: "text",
|
||||
text: `${command.prompt}${userInput ? "\n\n" + userInput : ""}`,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
command,
|
||||
input,
|
||||
slashedParts,
|
||||
legacyCommandWithInput,
|
||||
contextAttrs: [],
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -33,27 +33,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", {
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import {
|
|||
InputModifiers,
|
||||
MessageContent,
|
||||
RangeInFile,
|
||||
SlashCommandDescription,
|
||||
SlashCommandDescWithSource,
|
||||
} from "core";
|
||||
import * as URI from "uri-js";
|
||||
import { resolveEditorContent } from "../../components/mainInput/TipTapEditor";
|
||||
|
|
@ -19,7 +19,7 @@ export const gatherContext = createAsyncThunk<
|
|||
content: MessageContent;
|
||||
legacyCommandWithInput:
|
||||
| {
|
||||
command: SlashCommandDescription;
|
||||
command: SlashCommandDescWithSource;
|
||||
input: string;
|
||||
}
|
||||
| undefined;
|
||||
|
|
@ -50,15 +50,19 @@ export const gatherContext = createAsyncThunk<
|
|||
}
|
||||
|
||||
// Resolve context providers and construct new history
|
||||
let [selectedContextItems, selectedCode, content, legacyCommandWithInput] =
|
||||
await resolveEditorContent({
|
||||
editorState,
|
||||
modifiers,
|
||||
ideMessenger: extra.ideMessenger,
|
||||
defaultContextProviders,
|
||||
availableSlashCommands: state.config.config.slashCommands,
|
||||
dispatch,
|
||||
});
|
||||
let {
|
||||
selectedContextItems,
|
||||
selectedCode,
|
||||
content,
|
||||
legacyCommandWithInput,
|
||||
} = await resolveEditorContent({
|
||||
editorState,
|
||||
modifiers,
|
||||
ideMessenger: extra.ideMessenger,
|
||||
defaultContextProviders,
|
||||
availableSlashCommands: state.config.config.slashCommands,
|
||||
dispatch,
|
||||
});
|
||||
|
||||
// Automatically use currently open file
|
||||
if (!modifiers.noContext) {
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue