Elffuss BraidHub

kikocis/continue public

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

Support tools for prompts
Changeset2b414e1c0982b989bdb1c5b9da0f556c735f5c0beaf63272bded450c5ae96dc8
AuthorNate Sesti <33237525+sestinj@users.noreply.github.com> · 2025-06-27 21:48 -07:00
CommitterGitHub <noreply@github.com> · 2025-06-27 21:48 -07:00
Parentsead518778623, 82a3f9f64f46

Browse the files at this changeset

80 files changed

deleted core/commands/index.ts +0 −88
@@ -1,88 +0,0 @@
1-import { CustomCommand, SlashCommand, SlashCommandDescription } from "../";
2-import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString";
3-import { replaceSlashCommandWithPromptInChatHistory } from "../promptFiles/v1/updateChatHistory";
4-import { renderPromptFileV2 } from "../promptFiles/v2/renderPromptFile";
5-import { renderChatMessage } from "../util/messageContent";
6-
7-import SlashCommands from "./slash";
8-
9-export function slashFromCustomCommand(
10- customCommand: CustomCommand,
11-): SlashCommand {
12- const commandName = customCommand.name.startsWith("/")
13- ? customCommand.name.substring(1)
14- : customCommand.name;
15- return {
16- name: commandName,
17- description: customCommand.description ?? "",
18- prompt: customCommand.prompt,
19- run: async function* ({
20- input,
21- llm,
22- history,
23- ide,
24- completionOptions,
25- config,
26- selectedCode,
27- fetch,
28- abortController,
29- }) {
30- // Render prompt template
31- let renderedPrompt: string;
32- if (customCommand.prompt.includes("{{{ input }}}")) {
33- renderedPrompt = await renderTemplatedString(
34- customCommand.prompt,
35- ide.readFile.bind(ide),
36- { input },
37- );
38- } else {
39- const renderedPromptFile = await renderPromptFileV2(
40- customCommand.prompt,
41- {
42- config,
43- llm,
44- ide,
45- selectedCode,
46- fetch,
47- fullInput: input,
48- embeddingsProvider: config.modelsByRole.embed[0],
49- reranker: config.modelsByRole.rerank[0],
50- },
51- );
52-
53- renderedPrompt = renderedPromptFile[1];
54- }
55-
56- // Replaces slash command messages with the rendered prompt
57- // which INCLUDES the input
58- const messages = replaceSlashCommandWithPromptInChatHistory(
59- history,
60- commandName,
61- renderedPrompt,
62- undefined,
63- );
64-
65- for await (const chunk of llm.streamChat(
66- messages,
67- abortController.signal,
68- completionOptions,
69- )) {
70- yield renderChatMessage(chunk);
71- }
72- },
73- };
74-}
75-
76-export function slashCommandFromDescription(
77- desc: SlashCommandDescription,
78-): SlashCommand | undefined {
79- const cmd = SlashCommands.find((cmd) => cmd.name === desc.name);
80- if (!cmd) {
81- return undefined;
82- }
83- return {
84- ...cmd,
85- params: desc.params,
86- description: desc.description ?? cmd.description,
87- };
88-}
added core/commands/slash/built-in-legacy/cmd.ts +62 −0
@@ -0,0 +1,62 @@
1+import { streamLines } from "../../../diff/util.js";
2+import { SlashCommand } from "../../../index.js";
3+import { removeQuotesAndEscapes } from "../../../util/index.js";
4+
5+function commandIsPotentiallyDangerous(command: string) {
6+ return (
7+ command.includes("rm -rf") ||
8+ command.includes("sudo") ||
9+ command.includes("cd / ")
10+ );
11+}
12+
13+const GenerateTerminalCommand: SlashCommand = {
14+ name: "cmd",
15+ description: "Generate a shell command",
16+ run: async function* ({ ide, llm, input }) {
17+ if (input.trim() === "") {
18+ yield "Please provide a description of the shell command you want to generate. For example, '/cmd List all files in the current directory'.";
19+ return;
20+ }
21+
22+ const gen = llm.streamComplete(
23+ `The user has made a request to run a shell command. Their description of what it should do is:
24+
25+"${input}"
26+
27+Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested. Here is the command:`,
28+ new AbortController().signal,
29+ );
30+
31+ const lines = streamLines(gen);
32+ let cmd = "";
33+ for await (const line of lines) {
34+ console.log(line);
35+ if (line.startsWith("```") && line.endsWith("```")) {
36+ cmd = line.split(" ").slice(1).join(" ").slice(0, -3);
37+ break;
38+ }
39+
40+ if (
41+ line.startsWith(">") ||
42+ line.startsWith("``") ||
43+ line.startsWith("\\begin{") ||
44+ line.trim() === ""
45+ ) {
46+ continue;
47+ }
48+
49+ cmd = removeQuotesAndEscapes(line.trim());
50+ break;
51+ }
52+
53+ yield `Generated shell command: ${cmd}`;
54+ if (commandIsPotentiallyDangerous(cmd)) {
55+ yield "\n\nWarning: This command may be potentially dangerous. Please double-check before pasting it in your terminal.";
56+ } else {
57+ await ide.runCommand(cmd);
58+ }
59+ },
60+};
61+
62+export default GenerateTerminalCommand;
added core/commands/slash/built-in-legacy/commit.ts +26 −0
@@ -0,0 +1,26 @@
1+import { SlashCommand } from "../../../index.js";
2+import { renderChatMessage } from "../../../util/messageContent.js";
3+
4+const CommitMessageCommand: SlashCommand = {
5+ name: "commit",
6+ description: "Generate a commit message for current changes",
7+ run: async function* ({ ide, llm, params, abortController }) {
8+ const includeUnstaged = params?.includeUnstaged ?? false;
9+ const diff = await ide.getDiff(includeUnstaged);
10+
11+ if (diff.length === 0) {
12+ yield "No changes detected. Make sure you are in a git repository with current changes.";
13+ return;
14+ }
15+
16+ const prompt = `${diff.join("\n")}\n\nGenerate a commit message for the above set of changes. First, give a single sentence, no more than 80 characters. Then, after 2 line breaks, give a list of no more than 5 short bullet points, each no more than 40 characters. Output nothing except for the commit message, and don't surround it in quotes.`;
17+ for await (const chunk of llm.streamChat(
18+ [{ role: "user", content: prompt }],
19+ abortController.signal,
20+ )) {
21+ yield renderChatMessage(chunk);
22+ }
23+ },
24+};
25+
26+export default CommitMessageCommand;
added core/commands/slash/built-in-legacy/draftIssue.ts +62 −0
@@ -0,0 +1,62 @@
1+import { ChatMessage, SlashCommand } from "../../../index.js";
2+import { removeQuotesAndEscapes } from "../../../util/index.js";
3+import { renderChatMessage } from "../../../util/messageContent.js";
4+
5+const PROMPT = (
6+ input: string,
7+ title: string,
8+) => `You will be asked to generate the body of a GitHub issue given a user request. You should follow these rules:
9+- Be descriptive but do not make up details
10+- If the the user request includes any code snippets that are relevant, reference them in code blocks
11+- Describe step by step how to reproduce the problem
12+- Describe the ideal solution to the problem
13+- Describe the expected behavior after the issue has been resolved
14+- This issue will be read by a team member
15+- Use markdown formatting, but you do not need to surround the entire body with triple backticks
16+{additional_instructions}
17+
18+Here is the user request: '${input}'
19+
20+Title: ${title}
21+
22+Body:\n\n`;
23+
24+const DraftIssueCommand: SlashCommand = {
25+ name: "issue",
26+ description: "Draft a GitHub issue",
27+ run: async function* ({ input, llm, history, params, abortController }) {
28+ if (params?.repositoryUrl === undefined) {
29+ yield "This command requires a repository URL to be set in the config file.";
30+ return;
31+ }
32+ let title = await llm.complete(
33+ `Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `,
34+ new AbortController().signal,
35+ { maxTokens: 30 },
36+ );
37+
38+ title = `${removeQuotesAndEscapes(title.trim())}\n\n`;
39+ yield title;
40+
41+ let body = "";
42+ const messages: ChatMessage[] = [
43+ ...history.filter((msg) => msg.role !== "system"),
44+ { role: "user", content: PROMPT(input, title) },
45+ ];
46+
47+ for await (const chunk of llm.streamChat(
48+ messages,
49+ abortController.signal,
50+ )) {
51+ body += chunk.content;
52+ yield renderChatMessage(chunk);
53+ }
54+
55+ const url = `${params.repositoryUrl}/issues/new?title=${encodeURIComponent(
56+ title,
57+ )}&body=${encodeURIComponent(body)}`;
58+ yield `\n\n[Link to draft of issue](${url})`;
59+ },
60+};
61+
62+export default DraftIssueCommand;
added core/commands/slash/built-in-legacy/http.ts +33 −0
@@ -0,0 +1,33 @@
1+import { streamResponse } from "@continuedev/fetch";
2+import { SlashCommand } from "../../../index.js";
3+import { removeQuotesAndEscapes } from "../../../util/index.js";
4+
5+const HttpSlashCommand: SlashCommand = {
6+ name: "http",
7+ description: "Call an HTTP endpoint to serve response",
8+ run: async function* ({ ide, llm, input, params, fetch }) {
9+ const url = params?.url;
10+ if (!url) {
11+ throw new Error("URL is not defined in params");
12+ }
13+ const response = await fetch(url, {
14+ method: "POST",
15+ headers: {
16+ "Content-Type": "application/json",
17+ },
18+ body: JSON.stringify({
19+ input: removeQuotesAndEscapes(input),
20+ }),
21+ });
22+
23+ // Stream the response
24+ if (response.body === null) {
25+ throw new Error("Response body is null");
26+ }
27+ for await (const chunk of streamResponse(response)) {
28+ yield chunk;
29+ }
30+ },
31+};
32+
33+export default HttpSlashCommand;
added core/commands/slash/built-in-legacy/index.ts +37 −0
@@ -0,0 +1,37 @@
1+import {
2+ SlashCommand,
3+ SlashCommandDescription,
4+ SlashCommandWithSource,
5+} from "../../..";
6+import GenerateTerminalCommand from "./cmd";
7+import CommitMessageCommand from "./commit";
8+import DraftIssueCommand from "./draftIssue";
9+import HttpSlashCommand from "./http";
10+import OnboardSlashCommand from "./onboard";
11+import ReviewMessageCommand from "./review";
12+import ShareSlashCommand from "./share";
13+
14+const LegacyBuiltInSlashCommands: SlashCommand[] = [
15+ DraftIssueCommand,
16+ ShareSlashCommand,
17+ GenerateTerminalCommand,
18+ HttpSlashCommand,
19+ CommitMessageCommand,
20+ ReviewMessageCommand,
21+ OnboardSlashCommand,
22+];
23+
24+export function getLegacyBuiltInSlashCommandFromDescription(
25+ desc: SlashCommandDescription,
26+): SlashCommandWithSource | undefined {
27+ const cmd = LegacyBuiltInSlashCommands.find((cmd) => cmd.name === desc.name);
28+ if (!cmd) {
29+ return undefined;
30+ }
31+ return {
32+ ...cmd,
33+ params: desc.params,
34+ description: desc.description ?? cmd.description,
35+ source: "built-in-legacy",
36+ };
37+}
added core/commands/slash/built-in-legacy/onboard.ts +169 −0
@@ -0,0 +1,169 @@
1+import ignore from "ignore";
2+
3+import type { FileType, IDE, SlashCommand } from "../../..";
4+import {
5+ DEFAULT_IGNORE,
6+ getGlobalContinueIgArray,
7+ gitIgArrayFromFile,
8+} from "../../../indexing/ignore";
9+import { renderChatMessage } from "../../../util/messageContent";
10+import {
11+ findUriInDirs,
12+ getUriPathBasename,
13+ joinPathsToUri,
14+} from "../../../util/uri";
15+
16+const LANGUAGE_DEP_MGMT_FILENAMES = [
17+ "package.json", // JavaScript (Node.js)
18+ "requirements.txt", // Python
19+ "Gemfile", // Ruby
20+ "pom.xml", // Java (Maven)
21+ "build.gradle", // Java (Gradle)
22+ "composer.json", // PHP
23+ "Cargo.toml", // Rust
24+ "go.mod", // Go
25+ "packages.config", // C# (.NET)
26+ "*.csproj", // C# (.NET Core)
27+ "pubspec.yaml", // Dart
28+ "Project.toml", // Julia
29+ "mix.exs", // Elixir
30+ "rebar.config", // Erlang
31+ "shard.yml", // Crystal
32+ "Package.swift", // Swift
33+ "dependencies.gradle", // Kotlin (when using Gradle)
34+ "Podfile", // Objective-C/Swift (CocoaPods)
35+ "*.cabal", // Haskell
36+ "dub.json", // D
37+];
38+
39+const MAX_EXPLORE_DEPTH = 2;
40+
41+const OnboardSlashCommand: SlashCommand = {
42+ name: "onboard",
43+ description: "Familiarize yourself with the codebase",
44+ run: async function* ({ llm, ide, abortController }) {
45+ const [workspaceDir] = await ide.getWorkspaceDirs();
46+
47+ const context = await gatherProjectContext(workspaceDir, ide);
48+ const prompt = createOnboardingPrompt(context);
49+
50+ for await (const chunk of llm.streamChat(
51+ [{ role: "user", content: prompt }],
52+ abortController.signal,
53+ )) {
54+ yield renderChatMessage(chunk);
55+ }
56+ },
57+};
58+
59+async function getEntriesFilteredByIgnore(dir: string, ide: IDE) {
60+ const ig = ignore().add(DEFAULT_IGNORE).add(getGlobalContinueIgArray());
61+ const entries = await ide.listDir(dir);
62+
63+ const ignoreUri = joinPathsToUri(dir, ".gitignore");
64+ const fileExists = await ide.fileExists(ignoreUri);
65+
66+ if (fileExists) {
67+ const gitIgnore = await ide.readFile(ignoreUri);
68+ const igPatterns = gitIgArrayFromFile(gitIgnore);
69+
70+ ig.add(igPatterns);
71+ }
72+
73+ const workspaceDirs = await ide.getWorkspaceDirs();
74+
75+ const withRelativePaths = entries
76+ .filter(
77+ (entry) =>
78+ entry[1] === (1 as FileType.File) ||
79+ entry[1] === (2 as FileType.Directory),
80+ )
81+ .map((entry) => {
82+ const { relativePathOrBasename } = findUriInDirs(entry[0], workspaceDirs);
83+ return {
84+ uri: entry[0],
85+ type: entry[1],
86+ basename: getUriPathBasename(entry[0]),
87+ relativePath:
88+ relativePathOrBasename +
89+ (entry[1] === (2 as FileType.Directory) ? "/" : ""),
90+ };
91+ });
92+
93+ return withRelativePaths.filter((entry) => !ig.ignores(entry.relativePath));
94+}
95+
96+async function gatherProjectContext(
97+ workspaceDir: string,
98+ ide: IDE,
99+): Promise<string> {
100+ let context = "";
101+ async function exploreDirectory(dir: string, currentDepth: number = 0) {
102+ if (currentDepth > MAX_EXPLORE_DEPTH) {
103+ return;
104+ }
105+
106+ const entries = await getEntriesFilteredByIgnore(dir, ide);
107+
108+ for (const entry of entries) {
109+ if (entry.type === (2 as FileType.Directory)) {
110+ context += `\nFolder: ${entry.relativePath}\n`;
111+ await exploreDirectory(entry.uri, currentDepth + 1);
112+ } else {
113+ if (entry.basename.toLowerCase() === "readme.md") {
114+ const content = await ide.readFile(entry.uri);
115+ context += `README for ${entry.relativePath}:\n${content}\n\n`;
116+ } else if (LANGUAGE_DEP_MGMT_FILENAMES.includes(entry.basename)) {
117+ const content = await ide.readFile(entry.uri);
118+ context += `${entry.basename} for ${entry.relativePath}:\n${content}\n\n`;
119+ }
120+ }
121+ }
122+ }
123+
124+ await exploreDirectory(workspaceDir);
125+
126+ return context;
127+}
128+
129+function createOnboardingPrompt(context: string): string {
130+ return `
131+ As a helpful AI assistant, your task is to onboard a new developer to this project.
132+ Use the following context about the project structure, READMEs, and dependency files to create a comprehensive overview:
133+
134+ ${context}
135+
136+ Please provide an overview of the project with the following guidelines:
137+ - Determine the most important folders in the project, at most 10
138+ - Go through each important folder step-by-step:
139+ - Explain what each folder does in isolation by summarzing the README or package.json file, if available
140+ - Mention the most popular or common packages used in that folder and their roles.
141+ - After covering individual folders, zoom out to explain at most 5 high-level insights about the project's architecture:
142+ - How different parts of the codebase fit together.
143+ - The overall project architecture or design patterns evident from the folder structure and dependencies.
144+ - Provide at most 5 additional insights on the project's architecture that weren't covered in the folder-by-folder breakdown.
145+
146+ Your response should be structured, clear, and focused on giving the new developer both a detailed understanding of individual components and a high-level overview of the project as a whole.
147+
148+ Here is an example of a valid response:
149+
150+ ## Important folders
151+
152+ ### /folder1
153+ - Description: Contains the main application logic.
154+ - Key packages: Express.js for routing, Mongoose for database operations.
155+
156+ #### /folder1/folder2
157+
158+ ## Project Architecture
159+ - The frontend is built using React and Redux for state management.
160+ - The backend is a Node.js application using Express.js for routing and Mongoose for database operations.
161+ - The application follows a Model-View-Controller (MVC) architecture.
162+
163+ ## Additional Insights
164+ - The project is using a monorepo structure.
165+ - The project uses TypeScript for type checking.
166+ `;
167+}
168+
169+export default OnboardSlashCommand;
added core/commands/slash/built-in-legacy/review.ts +55 −0
@@ -0,0 +1,55 @@
1+import { ChatMessage, SlashCommand } from "../../../index.js";
2+import { renderChatMessage } from "../../../util/messageContent.js";
3+
4+const prompt = `
5+ Review the following code, focusing on Readability, Maintainability, Code Smells, Speed, and Memory Performance. Provide feedback with these guidelines:
6+
7+ Tone: Friendly casual tone of a fellow engineer, ensure the feedback is clear and focused on practical improvements.
8+ Orderly Analysis: Address the code sequentially, from top to bottom, to ensure a thorough review without skipping any parts.
9+ Descriptive Feedback: Avoid referencing line numbers directly, as they may vary. Instead, describe the code sections or specific constructs that need attention, explaining the reasons clearly.
10+ Provide Examples: For each issue identified, offer an example of how the code could be improved or rewritten for better clarity, performance, or maintainability.
11+ Your response should be structured to first identify the issue, then explain why it’s a problem, and finally, offer a solution with example code.`;
12+
13+function getLastUserHistory(history: ChatMessage[]): string {
14+ const lastUserHistory = history
15+ .reverse()
16+ .find((message) => message.role === "user");
17+
18+ if (!lastUserHistory) {
19+ return "";
20+ }
21+
22+ if (Array.isArray(lastUserHistory.content)) {
23+ return lastUserHistory.content.reduce(
24+ (acc: string, current: { type: string; text?: string }) => {
25+ return current.type === "text" && current.text
26+ ? acc + current.text
27+ : acc;
28+ },
29+ "",
30+ );
31+ }
32+
33+ return typeof lastUserHistory.content === "string"
34+ ? lastUserHistory.content
35+ : "";
36+}
37+
38+const ReviewMessageCommand: SlashCommand = {
39+ name: "review",
40+ description: "Review code and give feedback",
41+ run: async function* ({ llm, history, abortController }) {
42+ const reviewText = getLastUserHistory(history).replace("\\review", "");
43+
44+ const content = `${prompt} \r\n ${reviewText}`;
45+
46+ for await (const chunk of llm.streamChat(
47+ [{ role: "user", content: content }],
48+ abortController.signal,
49+ )) {
50+ yield renderChatMessage(chunk);
51+ }
52+ },
53+};
54+
55+export default ReviewMessageCommand;
added core/commands/slash/built-in-legacy/share.ts +101 −0
@@ -0,0 +1,101 @@
1+import fs from "fs";
2+import { homedir } from "node:os";
3+import { fileURLToPath, pathToFileURL } from "node:url";
4+import path from "path";
5+
6+import { languageForFilepath } from "../../../autocomplete/constants/AutocompleteLanguageInfo.js";
7+import { SlashCommand } from "../../../index.js";
8+import { renderChatMessage } from "../../../util/messageContent.js";
9+import { getContinueGlobalPath } from "../../../util/paths.js";
10+
11+// If useful elsewhere, helper funcs should move to core/util/index.ts or similar
12+function getOffsetDatetime(date: Date): Date {
13+ const offset = date.getTimezoneOffset();
14+ const offsetHours = Math.floor(offset / 60);
15+ const offsetMinutes = offset % 60;
16+ date.setHours(date.getHours() - offsetHours);
17+ date.setMinutes(date.getMinutes() - offsetMinutes);
18+
19+ return date;
20+}
21+
22+function asBasicISOString(date: Date): string {
23+ const isoString = date.toISOString();
24+
25+ return isoString.replace(/[-:]|(\.\d+Z)/g, "");
26+}
27+
28+function reformatCodeBlocks(msgText: string): string {
29+ const codeBlockFenceRegex = /```((.*?\.(\w+))\s*.*)\n/g;
30+ msgText = msgText.replace(
31+ codeBlockFenceRegex,
32+ (match, metadata, filename, extension) => {
33+ const lang = languageForFilepath(filename);
34+ return `\`\`\`${extension}\n${lang.singleLineComment} ${metadata}\n`;
35+ },
36+ );
37+ // Appease the markdown linter
38+ return msgText.replace(/```\n```/g, "```\n\n```");
39+}
40+
41+const ShareSlashCommand: SlashCommand = {
42+ name: "share",
43+ description: "Export the current chat session to markdown",
44+ run: async function* ({ ide, history, params }) {
45+ const now = new Date();
46+
47+ let content = `### [Continue](https://continue.dev) session transcript\n Exported: ${now.toLocaleString()}`;
48+
49+ // As currently implemented, the /share command is by definition the last
50+ // message in the chat history, this will omit it
51+ for (const msg of history.slice(0, history.length - 1)) {
52+ let msgText = msg.content;
53+ msgText = renderChatMessage(msg);
54+
55+ if (msg.role === "user" && msgText.search("```") > -1) {
56+ msgText = reformatCodeBlocks(msgText);
57+ }
58+
59+ // format messages as blockquotes
60+ msgText = msgText.replace(/^/gm, "> ");
61+
62+ content += `\n\n#### ${
63+ msg.role === "user" ? "_User_" : "_Assistant_"
64+ }\n\n${msgText}`;
65+ }
66+
67+ let outputDir: string = params?.outputDir ?? getContinueGlobalPath();
68+
69+ if (outputDir.startsWith("~")) {
70+ outputDir = outputDir.replace(/^~/, homedir);
71+ } else if (
72+ outputDir.startsWith("./") ||
73+ outputDir.startsWith(".\\") ||
74+ outputDir === "."
75+ ) {
76+ const workspaceDirs = await ide.getWorkspaceDirs();
77+ // Although the most common situation is to have one directory open in a
78+ // workspace it's also possible to have just a file open without an
79+ // associated directory or to use multi-root workspaces in which multiple
80+ // folders are included. We default to using the first item in the list, if
81+ // it exists.
82+ const workspaceDirectory = workspaceDirs?.[0] || "";
83+ outputDir = outputDir.replace(/^./, fileURLToPath(workspaceDirectory));
84+ }
85+
86+ if (!fs.existsSync(outputDir)) {
87+ fs.mkdirSync(outputDir, { recursive: true });
88+ }
89+
90+ const dtString = asBasicISOString(getOffsetDatetime(now));
91+ const outPath = path.join(outputDir, `${dtString}_session.md`); //TODO: more flexible naming?
92+
93+ const fileUrl = pathToFileURL(outPath).toString(); // TODO switch from path to URI above ^
94+ await ide.writeFile(fileUrl, content);
95+ await ide.openFile(fileUrl);
96+
97+ yield `The session transcript has been saved to a markdown file at \`${outPath}\`.`;
98+ },
99+};
100+
101+export default ShareSlashCommand;
deleted core/commands/slash/cmd.ts +0 −62
@@ -1,62 +0,0 @@
1-import { streamLines } from "../../diff/util.js";
2-import { SlashCommand } from "../../index.js";
3-import { removeQuotesAndEscapes } from "../../util/index.js";
4-
5-function commandIsPotentiallyDangerous(command: string) {
6- return (
7- command.includes("rm -rf") ||
8- command.includes("sudo") ||
9- command.includes("cd / ")
10- );
11-}
12-
13-const GenerateTerminalCommand: SlashCommand = {
14- name: "cmd",
15- description: "Generate a shell command",
16- run: async function* ({ ide, llm, input }) {
17- if (input.trim() === "") {
18- yield "Please provide a description of the shell command you want to generate. For example, '/cmd List all files in the current directory'.";
19- return;
20- }
21-
22- const gen = llm.streamComplete(
23- `The user has made a request to run a shell command. Their description of what it should do is:
24-
25-"${input}"
26-
27-Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested. Here is the command:`,
28- new AbortController().signal,
29- );
30-
31- const lines = streamLines(gen);
32- let cmd = "";
33- for await (const line of lines) {
34- console.log(line);
35- if (line.startsWith("```") && line.endsWith("```")) {
36- cmd = line.split(" ").slice(1).join(" ").slice(0, -3);
37- break;
38- }
39-
40- if (
41- line.startsWith(">") ||
42- line.startsWith("``") ||
43- line.startsWith("\\begin{") ||
44- line.trim() === ""
45- ) {
46- continue;
47- }
48-
49- cmd = removeQuotesAndEscapes(line.trim());
50- break;
51- }
52-
53- yield `Generated shell command: ${cmd}`;
54- if (commandIsPotentiallyDangerous(cmd)) {
55- yield "\n\nWarning: This command may be potentially dangerous. Please double-check before pasting it in your terminal.";
56- } else {
57- await ide.runCommand(cmd);
58- }
59- },
60-};
61-
62-export default GenerateTerminalCommand;
deleted core/commands/slash/commit.ts +0 −26
@@ -1,26 +0,0 @@
1-import { SlashCommand } from "../../index.js";
2-import { renderChatMessage } from "../../util/messageContent.js";
3-
4-const CommitMessageCommand: SlashCommand = {
5- name: "commit",
6- description: "Generate a commit message for current changes",
7- run: async function* ({ ide, llm, params, abortController }) {
8- const includeUnstaged = params?.includeUnstaged ?? false;
9- const diff = await ide.getDiff(includeUnstaged);
10-
11- if (diff.length === 0) {
12- yield "No changes detected. Make sure you are in a git repository with current changes.";
13- return;
14- }
15-
16- const prompt = `${diff.join("\n")}\n\nGenerate a commit message for the above set of changes. First, give a single sentence, no more than 80 characters. Then, after 2 line breaks, give a list of no more than 5 short bullet points, each no more than 40 characters. Output nothing except for the commit message, and don't surround it in quotes.`;
17- for await (const chunk of llm.streamChat(
18- [{ role: "user", content: prompt }],
19- abortController.signal,
20- )) {
21- yield renderChatMessage(chunk);
22- }
23- },
24-};
25-
26-export default CommitMessageCommand;
added core/commands/slash/customSlashCommand.ts +15 −0
@@ -0,0 +1,15 @@
1+import { CustomCommand, SlashCommandWithSource } from "../..";
2+
3+export function convertCustomCommandToSlashCommand(
4+ customCommand: CustomCommand,
5+): SlashCommandWithSource {
6+ const commandName = customCommand.name.startsWith("/")
7+ ? customCommand.name.substring(1)
8+ : customCommand.name;
9+ return {
10+ name: commandName,
11+ description: customCommand.description ?? "",
12+ prompt: customCommand.prompt,
13+ source: "json-custom-command",
14+ };
15+}
deleted core/commands/slash/draftIssue.ts +0 −62
@@ -1,62 +0,0 @@
1-import { ChatMessage, SlashCommand } from "../../index.js";
2-import { removeQuotesAndEscapes } from "../../util/index.js";
3-import { renderChatMessage } from "../../util/messageContent.js";
4-
5-const PROMPT = (
6- input: string,
7- title: string,
8-) => `You will be asked to generate the body of a GitHub issue given a user request. You should follow these rules:
9-- Be descriptive but do not make up details
10-- If the the user request includes any code snippets that are relevant, reference them in code blocks
11-- Describe step by step how to reproduce the problem
12-- Describe the ideal solution to the problem
13-- Describe the expected behavior after the issue has been resolved
14-- This issue will be read by a team member
15-- Use markdown formatting, but you do not need to surround the entire body with triple backticks
16-{additional_instructions}
17-
18-Here is the user request: '${input}'
19-
20-Title: ${title}
21-
22-Body:\n\n`;
23-
24-const DraftIssueCommand: SlashCommand = {
25- name: "issue",
26- description: "Draft a GitHub issue",
27- run: async function* ({ input, llm, history, params, abortController }) {
28- if (params?.repositoryUrl === undefined) {
29- yield "This command requires a repository URL to be set in the config file.";
30- return;
31- }
32- let title = await llm.complete(
33- `Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `,
34- new AbortController().signal,
35- { maxTokens: 30 },
36- );
37-
38- title = `${removeQuotesAndEscapes(title.trim())}\n\n`;
39- yield title;
40-
41- let body = "";
42- const messages: ChatMessage[] = [
43- ...history.filter((msg) => msg.role !== "system"),
44- { role: "user", content: PROMPT(input, title) },
45- ];
46-
47- for await (const chunk of llm.streamChat(
48- messages,
49- abortController.signal,
50- )) {
51- body += chunk.content;
52- yield renderChatMessage(chunk);
53- }
54-
55- const url = `${params.repositoryUrl}/issues/new?title=${encodeURIComponent(
56- title,
57- )}&body=${encodeURIComponent(body)}`;
58- yield `\n\n[Link to draft of issue](${url})`;
59- },
60-};
61-
62-export default DraftIssueCommand;
deleted core/commands/slash/http.ts +0 −33
@@ -1,33 +0,0 @@
1-import { streamResponse } from "@continuedev/fetch";
2-import { SlashCommand } from "../../index.js";
3-import { removeQuotesAndEscapes } from "../../util/index.js";
4-
5-const HttpSlashCommand: SlashCommand = {
6- name: "http",
7- description: "Call an HTTP endpoint to serve response",
8- run: async function* ({ ide, llm, input, params, fetch }) {
9- const url = params?.url;
10- if (!url) {
11- throw new Error("URL is not defined in params");
12- }
13- const response = await fetch(url, {
14- method: "POST",
15- headers: {
16- "Content-Type": "application/json",
17- },
18- body: JSON.stringify({
19- input: removeQuotesAndEscapes(input),
20- }),
21- });
22-
23- // Stream the response
24- if (response.body === null) {
25- throw new Error("Response body is null");
26- }
27- for await (const chunk of streamResponse(response)) {
28- yield chunk;
29- }
30- },
31-};
32-
33-export default HttpSlashCommand;
deleted core/commands/slash/index.ts +0 −17
@@ -1,17 +0,0 @@
1-import GenerateTerminalCommand from "./cmd";
2-import CommitMessageCommand from "./commit";
3-import DraftIssueCommand from "./draftIssue";
4-import HttpSlashCommand from "./http";
5-import OnboardSlashCommand from "./onboard";
6-import ReviewMessageCommand from "./review";
7-import ShareSlashCommand from "./share";
8-
9-export default [
10- DraftIssueCommand,
11- ShareSlashCommand,
12- GenerateTerminalCommand,
13- HttpSlashCommand,
14- CommitMessageCommand,
15- ReviewMessageCommand,
16- OnboardSlashCommand,
17-];
deleted core/commands/slash/mcp.ts +0 −70
@@ -1,70 +0,0 @@
1-import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2-
3-import { PromptMessage } from "@modelcontextprotocol/sdk/types.js";
4-import { ChatMessage, SlashCommand } from "../../index.js";
5-import { renderChatMessage } from "../../util/messageContent.js";
6-export function constructMcpSlashCommand(
7- client: Client,
8- name: string,
9- description?: string,
10- args?: string[],
11-): SlashCommand {
12- return {
13- name,
14- description: description ?? "MCP Prompt",
15- params: {},
16- run: async function* (context) {
17- const argsObject: { [key: string]: string } = {};
18- const userInput = context.input.split(" ").slice(1).join(" ");
19- if (args) {
20- args.forEach((arg, i) => {
21- argsObject[arg] = ""; // userInput
22- });
23- }
24-
25- const result = await client.getPrompt({ name, arguments: argsObject });
26- const mcpMessages: PromptMessage[] = result.messages;
27- const messages: ChatMessage[] = mcpMessages.map((msg) => {
28- if (msg.content.type !== "text") {
29- throw new Error(
30- "Continue currently only supports text prompts through MCP",
31- );
32- }
33- return {
34- content: msg.content.text,
35- role: msg.role,
36- };
37- });
38-
39- if (messages.length === 0) {
40- yield "The MCP prompt returned no messages";
41- return;
42- }
43-
44- if (userInput) {
45- const lastMessage = messages.at(-1);
46- if (!lastMessage || lastMessage.role !== "user") {
47- messages.push({
48- role: "user",
49- content: userInput,
50- });
51- } else {
52- let newContent = renderChatMessage(lastMessage);
53- if (newContent) {
54- newContent += "\n\n";
55- }
56- newContent += userInput;
57- lastMessage.content = newContent;
58- }
59- }
60-
61- for await (const chunk of context.llm.streamChat(
62- messages,
63- context.abortController.signal,
64- context.completionOptions,
65- )) {
66- yield renderChatMessage(chunk);
67- }
68- },
69- };
70-}
added core/commands/slash/mcpSlashCommand.ts +34 −0
@@ -0,0 +1,34 @@
1+import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2+
3+import { SlashCommandWithSource } from "../../index.js";
4+
5+export function constructMcpSlashCommand(
6+ client: Client,
7+ name: string,
8+ description?: string,
9+ args?: string[],
10+): SlashCommandWithSource {
11+ return {
12+ name,
13+ description: description ?? "MCP Prompt",
14+ source: "mcp-prompt",
15+ params: {},
16+ };
17+}
18+
19+export function stringifyMcpPrompt(
20+ prompt: Awaited<ReturnType<typeof Client.prototype.getPrompt>>,
21+): string {
22+ const { messages } = prompt;
23+ let stringified = "";
24+ for (const message of messages) {
25+ if (message.content.type === "text") {
26+ stringified += `<${message.content.role}/>\n${message.content.text}\n<${message.content.role}/>`;
27+ } else {
28+ console.warn(
29+ `MCP Prompt conversion warning: ${message.content.type} content is not yet supported, message skipped`,
30+ );
31+ }
32+ }
33+ return stringified;
34+}
deleted core/commands/slash/onboard.ts +0 −169
@@ -1,169 +0,0 @@
1-import ignore from "ignore";
2-
3-import type { FileType, IDE, SlashCommand } from "../..";
4-import {
5- DEFAULT_IGNORE,
6- getGlobalContinueIgArray,
7- gitIgArrayFromFile,
8-} from "../../indexing/ignore";
9-import { renderChatMessage } from "../../util/messageContent";
10-import {
11- findUriInDirs,
12- getUriPathBasename,
13- joinPathsToUri,
14-} from "../../util/uri";
15-
16-const LANGUAGE_DEP_MGMT_FILENAMES = [
17- "package.json", // JavaScript (Node.js)
18- "requirements.txt", // Python
19- "Gemfile", // Ruby
20- "pom.xml", // Java (Maven)
21- "build.gradle", // Java (Gradle)
22- "composer.json", // PHP
23- "Cargo.toml", // Rust
24- "go.mod", // Go
25- "packages.config", // C# (.NET)
26- "*.csproj", // C# (.NET Core)
27- "pubspec.yaml", // Dart
28- "Project.toml", // Julia
29- "mix.exs", // Elixir
30- "rebar.config", // Erlang
31- "shard.yml", // Crystal
32- "Package.swift", // Swift
33- "dependencies.gradle", // Kotlin (when using Gradle)
34- "Podfile", // Objective-C/Swift (CocoaPods)
35- "*.cabal", // Haskell
36- "dub.json", // D
37-];
38-
39-const MAX_EXPLORE_DEPTH = 2;
40-
41-const OnboardSlashCommand: SlashCommand = {
42- name: "onboard",
43- description: "Familiarize yourself with the codebase",
44- run: async function* ({ llm, ide, abortController }) {
45- const [workspaceDir] = await ide.getWorkspaceDirs();
46-
47- const context = await gatherProjectContext(workspaceDir, ide);
48- const prompt = createOnboardingPrompt(context);
49-
50- for await (const chunk of llm.streamChat(
51- [{ role: "user", content: prompt }],
52- abortController.signal,
53- )) {
54- yield renderChatMessage(chunk);
55- }
56- },
57-};
58-
59-async function getEntriesFilteredByIgnore(dir: string, ide: IDE) {
60- const ig = ignore().add(DEFAULT_IGNORE).add(getGlobalContinueIgArray());
61- const entries = await ide.listDir(dir);
62-
63- const ignoreUri = joinPathsToUri(dir, ".gitignore");
64- const fileExists = await ide.fileExists(ignoreUri);
65-
66- if (fileExists) {
67- const gitIgnore = await ide.readFile(ignoreUri);
68- const igPatterns = gitIgArrayFromFile(gitIgnore);
69-
70- ig.add(igPatterns);
71- }
72-
73- const workspaceDirs = await ide.getWorkspaceDirs();
74-
75- const withRelativePaths = entries
76- .filter(
77- (entry) =>
78- entry[1] === (1 as FileType.File) ||
79- entry[1] === (2 as FileType.Directory),
80- )
81- .map((entry) => {
82- const { relativePathOrBasename } = findUriInDirs(entry[0], workspaceDirs);
83- return {
84- uri: entry[0],
85- type: entry[1],
86- basename: getUriPathBasename(entry[0]),
87- relativePath:
88- relativePathOrBasename +
89- (entry[1] === (2 as FileType.Directory) ? "/" : ""),
90- };
91- });
92-
93- return withRelativePaths.filter((entry) => !ig.ignores(entry.relativePath));
94-}
95-
96-async function gatherProjectContext(
97- workspaceDir: string,
98- ide: IDE,
99-): Promise<string> {
100- let context = "";
101- async function exploreDirectory(dir: string, currentDepth: number = 0) {
102- if (currentDepth > MAX_EXPLORE_DEPTH) {
103- return;
104- }
105-
106- const entries = await getEntriesFilteredByIgnore(dir, ide);
107-
108- for (const entry of entries) {
109- if (entry.type === (2 as FileType.Directory)) {
110- context += `\nFolder: ${entry.relativePath}\n`;
111- await exploreDirectory(entry.uri, currentDepth + 1);
112- } else {
113- if (entry.basename.toLowerCase() === "readme.md") {
114- const content = await ide.readFile(entry.uri);
115- context += `README for ${entry.relativePath}:\n${content}\n\n`;
116- } else if (LANGUAGE_DEP_MGMT_FILENAMES.includes(entry.basename)) {
117- const content = await ide.readFile(entry.uri);
118- context += `${entry.basename} for ${entry.relativePath}:\n${content}\n\n`;
119- }
120- }
121- }
122- }
123-
124- await exploreDirectory(workspaceDir);
125-
126- return context;
127-}
128-
129-function createOnboardingPrompt(context: string): string {
130- return `
131- As a helpful AI assistant, your task is to onboard a new developer to this project.
132- Use the following context about the project structure, READMEs, and dependency files to create a comprehensive overview:
133-
134- ${context}
135-
136- Please provide an overview of the project with the following guidelines:
137- - Determine the most important folders in the project, at most 10
138- - Go through each important folder step-by-step:
139- - Explain what each folder does in isolation by summarzing the README or package.json file, if available
140- - Mention the most popular or common packages used in that folder and their roles.
141- - After covering individual folders, zoom out to explain at most 5 high-level insights about the project's architecture:
142- - How different parts of the codebase fit together.
143- - The overall project architecture or design patterns evident from the folder structure and dependencies.
144- - Provide at most 5 additional insights on the project's architecture that weren't covered in the folder-by-folder breakdown.
145-
146- Your response should be structured, clear, and focused on giving the new developer both a detailed understanding of individual components and a high-level overview of the project as a whole.
147-
148- Here is an example of a valid response:
149-
150- ## Important folders
151-
152- ### /folder1
153- - Description: Contains the main application logic.
154- - Key packages: Express.js for routing, Mongoose for database operations.
155-
156- #### /folder1/folder2
157-
158- ## Project Architecture
159- - The frontend is built using React and Redux for state management.
160- - The backend is a Node.js application using Express.js for routing and Mongoose for database operations.
161- - The application follows a Model-View-Controller (MVC) architecture.
162-
163- ## Additional Insights
164- - The project is using a monorepo structure.
165- - The project uses TypeScript for type checking.
166- `;
167-}
168-
169-export default OnboardSlashCommand;
added core/commands/slash/promptBlockSlashCommand.ts +13 −0
@@ -0,0 +1,13 @@
1+import { Prompt } from "@continuedev/config-yaml";
2+import { SlashCommandWithSource } from "../..";
3+
4+export function convertPromptBlockToSlashCommand(
5+ prompt: Prompt,
6+): SlashCommandWithSource {
7+ return {
8+ name: prompt.name,
9+ description: prompt.description ?? "",
10+ prompt: prompt.prompt,
11+ source: "yaml-prompt-block",
12+ };
13+}
added core/commands/slash/promptFileSlashCommand.ts +21 −0
@@ -0,0 +1,21 @@
1+import { SlashCommandWithSource } from "../..";
2+import { parsePromptFile } from "../../promptFiles/parsePromptFile";
3+
4+export function slashCommandFromPromptFile(
5+ path: string,
6+ content: string,
7+): SlashCommandWithSource | null {
8+ const { name, description, systemMessage, prompt, version } = parsePromptFile(
9+ path,
10+ content,
11+ );
12+
13+ return {
14+ name,
15+ description,
16+ prompt,
17+ source: version === 1 ? "prompt-file-v1" : "prompt-file-v2",
18+ promptFile: path,
19+ overrideSystemMessage: systemMessage,
20+ };
21+}
deleted core/commands/slash/review.ts +0 −55
@@ -1,55 +0,0 @@
1-import { ChatMessage, SlashCommand } from "../../index.js";
2-import { renderChatMessage } from "../../util/messageContent.js";
3-
4-const prompt = `
5- Review the following code, focusing on Readability, Maintainability, Code Smells, Speed, and Memory Performance. Provide feedback with these guidelines:
6-
7- Tone: Friendly casual tone of a fellow engineer, ensure the feedback is clear and focused on practical improvements.
8- Orderly Analysis: Address the code sequentially, from top to bottom, to ensure a thorough review without skipping any parts.
9- Descriptive Feedback: Avoid referencing line numbers directly, as they may vary. Instead, describe the code sections or specific constructs that need attention, explaining the reasons clearly.
10- Provide Examples: For each issue identified, offer an example of how the code could be improved or rewritten for better clarity, performance, or maintainability.
11- Your response should be structured to first identify the issue, then explain why it’s a problem, and finally, offer a solution with example code.`;
12-
13-function getLastUserHistory(history: ChatMessage[]): string {
14- const lastUserHistory = history
15- .reverse()
16- .find((message) => message.role === "user");
17-
18- if (!lastUserHistory) {
19- return "";
20- }
21-
22- if (Array.isArray(lastUserHistory.content)) {
23- return lastUserHistory.content.reduce(
24- (acc: string, current: { type: string; text?: string }) => {
25- return current.type === "text" && current.text
26- ? acc + current.text
27- : acc;
28- },
29- "",
30- );
31- }
32-
33- return typeof lastUserHistory.content === "string"
34- ? lastUserHistory.content
35- : "";
36-}
37-
38-const ReviewMessageCommand: SlashCommand = {
39- name: "review",
40- description: "Review code and give feedback",
41- run: async function* ({ llm, history, abortController }) {
42- const reviewText = getLastUserHistory(history).replace("\\review", "");
43-
44- const content = `${prompt} \r\n ${reviewText}`;
45-
46- for await (const chunk of llm.streamChat(
47- [{ role: "user", content: content }],
48- abortController.signal,
49- )) {
50- yield renderChatMessage(chunk);
51- }
52- },
53-};
54-
55-export default ReviewMessageCommand;
deleted core/commands/slash/share.ts +0 −101
@@ -1,101 +0,0 @@
1-import fs from "fs";
2-import { homedir } from "node:os";
3-import { fileURLToPath, pathToFileURL } from "node:url";
4-import path from "path";
5-
6-import { languageForFilepath } from "../../autocomplete/constants/AutocompleteLanguageInfo.js";
7-import { SlashCommand } from "../../index.js";
8-import { renderChatMessage } from "../../util/messageContent.js";
9-import { getContinueGlobalPath } from "../../util/paths.js";
10-
11-// If useful elsewhere, helper funcs should move to core/util/index.ts or similar
12-function getOffsetDatetime(date: Date): Date {
13- const offset = date.getTimezoneOffset();
14- const offsetHours = Math.floor(offset / 60);
15- const offsetMinutes = offset % 60;
16- date.setHours(date.getHours() - offsetHours);
17- date.setMinutes(date.getMinutes() - offsetMinutes);
18-
19- return date;
20-}
21-
22-function asBasicISOString(date: Date): string {
23- const isoString = date.toISOString();
24-
25- return isoString.replace(/[-:]|(\.\d+Z)/g, "");
26-}
27-
28-function reformatCodeBlocks(msgText: string): string {
29- const codeBlockFenceRegex = /```((.*?\.(\w+))\s*.*)\n/g;
30- msgText = msgText.replace(
31- codeBlockFenceRegex,
32- (match, metadata, filename, extension) => {
33- const lang = languageForFilepath(filename);
34- return `\`\`\`${extension}\n${lang.singleLineComment} ${metadata}\n`;
35- },
36- );
37- // Appease the markdown linter
38- return msgText.replace(/```\n```/g, "```\n\n```");
39-}
40-
41-const ShareSlashCommand: SlashCommand = {
42- name: "share",
43- description: "Export the current chat session to markdown",
44- run: async function* ({ ide, history, params }) {
45- const now = new Date();
46-
47- let content = `### [Continue](https://continue.dev) session transcript\n Exported: ${now.toLocaleString()}`;
48-
49- // As currently implemented, the /share command is by definition the last
50- // message in the chat history, this will omit it
51- for (const msg of history.slice(0, history.length - 1)) {
52- let msgText = msg.content;
53- msgText = renderChatMessage(msg);
54-
55- if (msg.role === "user" && msgText.search("```") > -1) {
56- msgText = reformatCodeBlocks(msgText);
57- }
58-
59- // format messages as blockquotes
60- msgText = msgText.replace(/^/gm, "> ");
61-
62- content += `\n\n#### ${
63- msg.role === "user" ? "_User_" : "_Assistant_"
64- }\n\n${msgText}`;
65- }
66-
67- let outputDir: string = params?.outputDir ?? getContinueGlobalPath();
68-
69- if (outputDir.startsWith("~")) {
70- outputDir = outputDir.replace(/^~/, homedir);
71- } else if (
72- outputDir.startsWith("./") ||
73- outputDir.startsWith(".\\") ||
74- outputDir === "."
75- ) {
76- const workspaceDirs = await ide.getWorkspaceDirs();
77- // Although the most common situation is to have one directory open in a
78- // workspace it's also possible to have just a file open without an
79- // associated directory or to use multi-root workspaces in which multiple
80- // folders are included. We default to using the first item in the list, if
81- // it exists.
82- const workspaceDirectory = workspaceDirs?.[0] || "";
83- outputDir = outputDir.replace(/^./, fileURLToPath(workspaceDirectory));
84- }
85-
86- if (!fs.existsSync(outputDir)) {
87- fs.mkdirSync(outputDir, { recursive: true });
88- }
89-
90- const dtString = asBasicISOString(getOffsetDatetime(now));
91- const outPath = path.join(outputDir, `${dtString}_session.md`); //TODO: more flexible naming?
92-
93- const fileUrl = pathToFileURL(outPath).toString(); // TODO switch from path to URI above ^
94- await ide.writeFile(fileUrl, content);
95- await ide.openFile(fileUrl);
96-
97- yield `The session transcript has been saved to a markdown file at \`${outPath}\`.`;
98- },
99-};
100-
101-export default ShareSlashCommand;
modified core/commands/util.ts +1 −1
@@ -16,7 +16,7 @@
1616 return {
1717 content: rif.contents,
1818 name: `${basename} ${rangeStr}`,
19- description: `${relativePathOrBasename} ${rangeStr}`, // This is passed to the LLM - do not pass full URI
19+ description: `${relativePathOrBasename} ${rangeStr}`,
2020 id: {
2121 providerTitle: "code",
2222 itemId: uuidv4(),
modified core/config/load.ts +33 −17
@@ -30,12 +30,11 @@
3030 ModelDescription,
3131 RerankerDescription,
3232 SerializedContinueConfig,
33- SlashCommand,
33+ SlashCommandWithSource,
3434 } from "..";
35-import {
36- slashCommandFromDescription,
37- slashFromCustomCommand,
38-} from "../commands/index";
35+import { getLegacyBuiltInSlashCommandFromDescription } from "../commands/slash/built-in-legacy";
36+import { convertCustomCommandToSlashCommand } from "../commands/slash/customSlashCommand";
37+import { slashCommandFromPromptFile } from "../commands/slash/promptFileSlashCommand";
3938 import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton";
4039 import CodebaseContextProvider from "../context/providers/CodebaseContextProvider";
4140 import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider";
@@ -48,8 +47,7 @@
4847 import CustomLLMClass from "../llm/llms/CustomLLM";
4948 import { LLMReranker } from "../llm/llms/llm";
5049 import TransformersJsEmbeddingsProvider from "../llm/llms/TransformersJsEmbeddingsProvider";
51-import { slashCommandFromPromptFileV1 } from "../promptFiles/v1/slashCommandFromPromptFile";
52-import { getAllPromptFiles } from "../promptFiles/v2/getPromptFiles";
50+import { getAllPromptFiles } from "../promptFiles/getPromptFiles";
5351 import { copyOf } from "../util";
5452 import { GlobalContext } from "../util/GlobalContext";
5553 import mergeJson from "../util/merge";
@@ -66,6 +64,7 @@
6664 import { localPathToUri } from "../util/pathToUri";
6765
6866 import { baseToolDefinitions } from "../tools";
67+import { resolveRelativePathInDir } from "../util/ideUtils";
6968 import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
7069 import {
7170 getModelByRole,
@@ -174,15 +173,15 @@
174173 ide: IDE,
175174 ): Promise<Config> {
176175 // DEPRECATED - load custom slash commands
177- const slashCommands: SlashCommand[] = [];
176+ const slashCommands: SlashCommandWithSource[] = [];
178177 for (const command of initial.slashCommands || []) {
179- const newCommand = slashCommandFromDescription(command);
178+ const newCommand = getLegacyBuiltInSlashCommandFromDescription(command);
180179 if (newCommand) {
181180 slashCommands.push(newCommand);
182181 }
183182 }
184183 for (const command of initial.customCommands || []) {
185- slashCommands.push(slashFromCustomCommand(command));
184+ slashCommands.push(convertCustomCommandToSlashCommand(command));
186185 }
187186
188187 // DEPRECATED - load slash commands from v1 prompt files
@@ -194,7 +193,7 @@
194193 );
195194
196195 for (const file of promptFiles) {
197- const slashCommand = slashCommandFromPromptFileV1(file.path, file.content);
196+ const slashCommand = slashCommandFromPromptFile(file.path, file.content);
198197 if (slashCommand) {
199198 slashCommands.push(slashCommand);
200199 }
@@ -254,7 +253,10 @@
254253 loadPromptFiles?: boolean;
255254 }): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
256255 const errors: ConfigValidationError[] = [];
257-
256+ const workspaceDirs = await ide.getWorkspaceDirs();
257+ const getUriFromPath = (path: string) => {
258+ return resolveRelativePathInDir(path, ide, workspaceDirs);
259+ };
258260 // Auto-detect models
259261 let models: BaseLLM[] = [];
260262 await Promise.all(
@@ -263,6 +265,7 @@
263265 const llm = await llmFromDescription(
264266 desc,
265267 ide.readFile.bind(ide),
268+ getUriFromPath,
266269 uniqueId,
267270 ideSettings,
268271 llmLogger,
@@ -284,6 +287,7 @@
284287 title: modelName,
285288 },
286289 ide.readFile.bind(ide),
290+ getUriFromPath,
287291 uniqueId,
288292 ideSettings,
289293 llmLogger,
@@ -360,6 +364,7 @@
360364 const llm = await llmFromDescription(
361365 desc,
362366 ide.readFile.bind(ide),
367+ getUriFromPath,
363368 uniqueId,
364369 ideSettings,
365370 llmLogger,
@@ -529,7 +534,7 @@
529534 contextProviders,
530535 tools: [...baseToolDefinitions],
531536 mcpServerStatuses: [],
532- slashCommands: config.slashCommands ?? [],
537+ slashCommands: [],
533538 modelsByRole: {
534539 chat: models,
535540 edit: models,
@@ -551,6 +556,17 @@
551556 rules: [],
552557 };
553558
559+ for (const cmd of config.slashCommands ?? []) {
560+ if ("source" in cmd) {
561+ continueConfig.slashCommands.push(cmd);
562+ } else {
563+ continueConfig.slashCommands.push({
564+ ...cmd,
565+ source: "config-ts-slash-command",
566+ });
567+ }
568+ }
569+
554570 if (config.systemMessage) {
555571 continueConfig.rules.unshift({
556572 rule: config.systemMessage,
@@ -651,9 +667,10 @@
651667 return {
652668 allowAnonymousTelemetry: final.allowAnonymousTelemetry,
653669 completionOptions: final.completionOptions,
654- slashCommands: final.slashCommands?.map(
655- ({ run, ...slashCommandDescription }) => slashCommandDescription,
656- ),
670+ slashCommands: final.slashCommands?.map(({ run, ...rest }) => ({
671+ ...rest,
672+ isLegacy: !!run,
673+ })),
657674 contextProviders: final.contextProviders?.map((c) => c.description),
658675 disableIndexing: final.disableIndexing,
659676 disableSessionTitles: final.disableSessionTitles,
@@ -975,7 +992,6 @@
975992
976993 export {
977994 finalToBrowserConfig,
978- intermediateToFinalConfig,
979995 loadContinueConfigFromJson,
980996 type BrowserSerializedContinueConfig,
981997 };
modified core/config/profile/doLoadConfig.ts +10 −9
@@ -16,9 +16,9 @@
1616 ILLMLogger,
1717 RuleWithSource,
1818 SerializedContinueConfig,
19+ SlashCommandDescWithSource,
1920 Tool,
2021 } from "../../";
21-import { constructMcpSlashCommand } from "../../commands/slash/mcp";
2222 import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
2323 import MCPContextProvider from "../../context/providers/MCPContextProvider";
2424 import RulesContextProvider from "../../context/providers/RulesContextProvider";
@@ -190,14 +190,15 @@
190190 }));
191191 newConfig.tools.push(...serverTools);
192192
193- const serverSlashCommands = server.prompts.map((prompt) =>
194- constructMcpSlashCommand(
195- server.client,
196- prompt.name,
197- prompt.description,
198- prompt.arguments?.map((a: any) => a.name),
199- ),
200- );
193+ const serverSlashCommands: SlashCommandDescWithSource[] =
194+ server.prompts.map((prompt) => ({
195+ name: prompt.name,
196+ description: prompt.description ?? "MCP Prompt",
197+ source: "mcp-prompt",
198+ isLegacy: false,
199+ mcpServerName: server.name, // Used in client to retrieve prompt
200+ mcpArgs: prompt.arguments,
201+ }));
201202 newConfig.slashCommands.push(...serverSlashCommands);
202203
203204 const submenuItems = server.resources
modified core/config/yaml/loadYaml.ts +5 −5
@@ -25,7 +25,6 @@
2525 ILLMLogger,
2626 RuleWithSource,
2727 } from "../..";
28-import { slashFromCustomCommand } from "../../commands";
2928 import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
3029 import CodebaseContextProvider from "../../context/providers/CodebaseContextProvider";
3130 import DocsContextProvider from "../../context/providers/DocsContextProvider";
@@ -33,11 +32,12 @@
3332 import { contextProviderClassFromName } from "../../context/providers/index";
3433 import { ControlPlaneClient } from "../../control-plane/client";
3534 import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
36-import { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandFromPromptFile";
37-import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles";
35+import { getAllPromptFiles } from "../../promptFiles/getPromptFiles";
3836 import { GlobalContext } from "../../util/GlobalContext";
3937 import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
4038
39+import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand";
40+import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand";
4141 import { getControlPlaneEnvSync } from "../../control-plane/env";
4242 import { getToolsForIde } from "../../tools";
4343 import { getCleanUriPath } from "../../util/uri";
@@ -263,7 +263,7 @@
263263
264264 promptFiles.forEach((file) => {
265265 try {
266- const slashCommand = slashCommandFromPromptFileV1(
266+ const slashCommand = slashCommandFromPromptFile(
267267 file.path,
268268 file.content,
269269 );
@@ -286,7 +286,7 @@
286286
287287 config.prompts?.forEach((prompt) => {
288288 try {
289- const slashCommand = slashFromCustomCommand(prompt);
289+ const slashCommand = convertPromptBlockToSlashCommand(prompt);
290290 continueConfig.slashCommands?.push(slashCommand);
291291 } catch (e) {
292292 localErrors.push({
modified core/context/mcp/MCPManagerSingleton.ts +17 −0
@@ -161,4 +161,21 @@
161161 client: connection.client,
162162 }));
163163 }
164+
165+ async getPrompt(
166+ serverName: string,
167+ promptName: string,
168+ args: Record<string, string> = {},
169+ ) {
170+ const connection = this.connections.get(serverName);
171+ if (!connection) {
172+ throw new Error(
173+ `Error getting prompt: MCP Connection ${serverName} not found`,
174+ );
175+ }
176+ return await connection.client.getPrompt({
177+ name: promptName,
178+ arguments: args,
179+ });
180+ }
164181 }
modified core/context/providers/TerminalContextProvider.ts +3 −1
@@ -21,7 +21,9 @@
2121 return [
2222 {
2323 description: "The contents of the terminal",
24- content: `Current terminal contents:\n\n${content}`,
24+ content: `Current terminal contents:\n\n${
25+ content || "The terminal is empty."
26+ }`,
2527 name: "Terminal",
2628 },
2729 ];
modified core/core.ts +15 −1
@@ -21,7 +21,7 @@
2121 import DocsService from "./indexing/docs/DocsService";
2222 import { countTokens } from "./llm/countTokens";
2323 import Ollama from "./llm/llms/Ollama";
24-import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile";
24+import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile";
2525 import { callTool } from "./tools/callTool";
2626 import { ChatDescriber } from "./util/chatDescriber";
2727 import { clipboardCache } from "./util/clipboardCache";
@@ -50,6 +50,7 @@
5050
5151 import { BLOCK_TYPES, ConfigYaml } from "@continuedev/config-yaml";
5252 import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache";
53+import { stringifyMcpPrompt } from "./commands/slash/mcpSlashCommand";
5354 import { isLocalDefinitionFile } from "./config/loadLocalAssistants";
5455 import {
5556 setupLocalConfig,
@@ -381,6 +382,19 @@
381382 on("mcp/reloadServer", async (msg) => {
382383 await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
383384 });
385+ on("mcp/getPrompt", async (msg) => {
386+ const { serverName, promptName, args } = msg.data;
387+ const prompt = await MCPManagerSingleton.getInstance().getPrompt(
388+ serverName,
389+ promptName,
390+ args,
391+ );
392+ const stringifiedPrompt = stringifyMcpPrompt(prompt);
393+ return {
394+ prompt: stringifiedPrompt,
395+ description: prompt.description,
396+ };
397+ });
384398 // Context providers
385399 on("context/addDocs", async (msg) => {
386400 void this.docsService.indexAndAdd(msg.data);
modified core/index.d.ts +41 −12
@@ -838,15 +838,44 @@
838838 abortController: AbortController;
839839 }
840840
841-export interface SlashCommand {
841+/* Be careful changing SlashCommand or SlashCommandDescription, config.ts can break */
842+export interface SlashCommandDescription {
842843 name: string;
843844 description: string;
844845 prompt?: string;
845846 params?: { [key: string]: any };
846- promptFile?: string;
847+}
848+
849+export interface SlashCommand extends SlashCommandDescription {
847850 run: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>;
848851 }
849852
853+export interface SlashCommandWithSource extends SlashCommandDescription {
854+ run?: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>; // Optional - only needed for legacy
855+ source: SlashCommandSource;
856+ promptFile?: string;
857+ overrideSystemMessage?: string;
858+}
859+
860+export type SlashCommandSource =
861+ | "built-in-legacy"
862+ | "built-in"
863+ | "json-custom-command"
864+ | "config-ts-slash-command"
865+ | "yaml-prompt-block"
866+ | "mcp-prompt"
867+ | "prompt-file-v1"
868+ | "prompt-file-v2"
869+ | "invokable-rule";
870+
871+export interface SlashCommandDescWithSource extends SlashCommandDescription {
872+ isLegacy: boolean; // Maps to if slashcommand.run exists
873+ source: SlashCommandSource;
874+ promptFile?: string;
875+ mcpServerName?: string;
876+ mcpArgs?: MCPPromptArgs;
877+}
878+
850879 // Config
851880
852881 export type StepName =
@@ -947,8 +976,6 @@
947976 params: { [key: string]: any };
948977 }
949978
950-export type SlashCommandDescription = Omit<SlashCommand, "run">;
951-
952979 export interface CustomCommand {
953980 name: string;
954981 prompt: string;
@@ -1172,14 +1199,16 @@
11721199 | "error"
11731200 | "not-connected";
11741201
1202+export type MCPPromptArgs = {
1203+ name: string;
1204+ description?: string;
1205+ required?: boolean;
1206+}[];
1207+
11751208 export interface MCPPrompt {
11761209 name: string;
11771210 description?: string;
1178- arguments?: {
1179- name: string;
1180- description?: string;
1181- required?: boolean;
1182- }[];
1211+ arguments?: MCPPromptArgs;
11831212 }
11841213
11851214 // Leaving here to ideate on
@@ -1444,7 +1473,7 @@
14441473 /** Request options that will be applied to all models and context providers */
14451474 requestOptions?: RequestOptions;
14461475 /** The list of slash commands that will be available in the sidebar */
1447- slashCommands?: SlashCommand[];
1476+ slashCommands?: (SlashCommand | SlashCommandWithSource)[];
14481477 /** Each entry in this array will originally be a ContextProviderWithParams, the same object from your config.json, but you may add CustomContextProviders.
14491478 * A CustomContextProvider requires you only to define a title and getContextItems function. When you type '@title <query>', Continue will call `getContextItems(query)`.
14501479 */
@@ -1481,7 +1510,7 @@
14811510 // systemMessage?: string;
14821511 completionOptions?: BaseCompletionOptions;
14831512 requestOptions?: RequestOptions;
1484- slashCommands: SlashCommand[];
1513+ slashCommands: SlashCommandWithSource[];
14851514 contextProviders: IContextProvider[];
14861515 disableSessionTitles?: boolean;
14871516 disableIndexing?: boolean;
@@ -1504,7 +1533,7 @@
15041533 // systemMessage?: string;
15051534 completionOptions?: BaseCompletionOptions;
15061535 requestOptions?: RequestOptions;
1507- slashCommands: SlashCommandDescription[];
1536+ slashCommands: SlashCommandDescWithSource[];
15081537 contextProviders: ContextProviderDescription[];
15091538 disableIndexing?: boolean;
15101539 disableSessionTitles?: boolean;
modified core/llm/llms/index.ts +7 −3
@@ -1,3 +1,4 @@
1+import Handlebars from "handlebars";
12 import {
23 BaseCompletionOptions,
34 IdeSettings,
@@ -6,10 +7,9 @@
67 JSONModelDescription,
78 LLMOptions,
89 } from "../..";
9-import { renderTemplatedString } from "../../promptFiles/v1/renderTemplatedString";
10+import { renderTemplatedString } from "../../util/handlebars/renderTemplatedString";
1011 import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../constructMessages";
1112 import { BaseLLM } from "../index";
12-
1313 import Anthropic from "./Anthropic";
1414 import Asksage from "./Asksage";
1515 import Azure from "./Azure";
@@ -121,6 +121,7 @@
121121 export async function llmFromDescription(
122122 desc: JSONModelDescription,
123123 readFile: (filepath: string) => Promise<string>,
124+ getUriFromPath: (path: string) => Promise<string | undefined>,
124125 uniqueId: string,
125126 ideSettings: IdeSettings,
126127 llmLogger: ILLMLogger,
@@ -142,9 +143,12 @@
142143 baseChatSystemMessage = DEFAULT_CHAT_SYSTEM_MESSAGE;
143144 baseChatSystemMessage += "\n\n";
144145 baseChatSystemMessage += await renderTemplatedString(
146+ Handlebars,
145147 desc.systemMessage,
146- readFile,
147148 {},
149+ [],
150+ readFile,
151+ getUriFromPath,
148152 );
149153 }
150154
modified core/llm/streamChat.ts +6 −0
@@ -59,6 +59,12 @@
5959 },
6060 true,
6161 );
62+ if (!slashCommand.run) {
63+ console.error(
64+ `Slash command ${command.name} (${command.source}) has no run function`,
65+ );
66+ throw new Error(`Slash command not found`);
67+ }
6268
6369 const gen = slashCommand.run({
6470 input,
added core/promptFiles/createNewPromptFile.ts +76 −0
@@ -0,0 +1,76 @@
1+import { IDE } from "..";
2+import { GlobalContext } from "../util/GlobalContext";
3+import { joinPathsToUri } from "../util/uri";
4+
5+const FIRST_TIME_DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file
6+# It is used to define and reuse prompts within Continue
7+# Each .prompt file can be accessed by typing "@prompts" in the Chat input
8+
9+# A prompt file consists of two parts:
10+# 1. Everything above the "---" is YAML. Here you can set "temperature", "description", and other options
11+# 2. Everything below the "---" is the prompt body
12+
13+# If you do not want to set any options, you do not need to include the "---"
14+
15+# In the body, you can reference:
16+# 1. Files, using either absolute or relative paths (based on the workspace root)
17+ # @README.md
18+ # @src/test/test.py
19+ # @/Users/me/Desktop/my-project/src/test/test.py
20+# 2. URLs, for example
21+ # @https://example.com
22+# 3. Context providers, for example
23+ # @currentFile
24+ # @os
25+ # @repo-map
26+
27+# To learn more, see the full .prompt file reference: https://docs.continue.dev/features/prompt-files
28+name: Example
29+description: Example prompt file
30+---
31+
32+Here is information about the current repo:
33+
34+@README.md`;
35+
36+const DEFAULT_PROMPT_FILE = "";
37+
38+export async function createNewPromptFileV2(
39+ ide: IDE,
40+ promptPath: string | undefined,
41+): Promise<void> {
42+ const workspaceDirs = await ide.getWorkspaceDirs();
43+ if (workspaceDirs.length === 0) {
44+ throw new Error(
45+ "No workspace directories found. Make sure you've opened a folder in your IDE.",
46+ );
47+ }
48+
49+ const baseDirUri = joinPathsToUri(
50+ workspaceDirs[0],
51+ promptPath ?? ".continue/prompts",
52+ );
53+
54+ // Find the first available filename
55+ let counter = 0;
56+ let promptFileUri: string;
57+ do {
58+ const suffix = counter === 0 ? "" : `-${counter}`;
59+ promptFileUri = joinPathsToUri(
60+ baseDirUri,
61+ `new-prompt-file${suffix}.prompt`,
62+ );
63+ counter++;
64+ } while (await ide.fileExists(promptFileUri));
65+
66+ const globalContext = new GlobalContext();
67+ const PROMPT_FILE =
68+ globalContext.get("hasAlreadyCreatedAPromptFile") === true
69+ ? DEFAULT_PROMPT_FILE
70+ : FIRST_TIME_DEFAULT_PROMPT_FILE;
71+
72+ globalContext.update("hasAlreadyCreatedAPromptFile", true);
73+
74+ await ide.writeFile(promptFileUri, PROMPT_FILE);
75+ await ide.openFile(promptFileUri);
76+}
added core/promptFiles/getPromptFiles.ts +66 −0
@@ -0,0 +1,66 @@
1+import { DEFAULT_PROMPTS_FOLDER_V1, DEFAULT_PROMPTS_FOLDER_V2 } from ".";
2+import { IDE } from "..";
3+import { walkDir } from "../indexing/walkDir";
4+import { readAllGlobalPromptFiles } from "../util/paths";
5+import { joinPathsToUri } from "../util/uri";
6+
7+export async function getPromptFilesFromDir(
8+ ide: IDE,
9+ dir: string,
10+): Promise<{ path: string; content: string }[]> {
11+ try {
12+ const exists = await ide.fileExists(dir);
13+
14+ if (!exists) {
15+ return [];
16+ }
17+
18+ const uris = await walkDir(dir, ide, {
19+ source: "get dir prompt files",
20+ });
21+ const promptFilePaths = uris.filter((p) => p.endsWith(".prompt"));
22+ const results = promptFilePaths.map(async (uri) => {
23+ const content = await ide.readFile(uri); // make a try catch
24+ return { path: uri, content };
25+ });
26+ return Promise.all(results);
27+ } catch (e) {
28+ console.error(e);
29+ return [];
30+ }
31+}
32+
33+export async function getAllPromptFiles(
34+ ide: IDE,
35+ overridePromptFolder?: string,
36+ checkV1DefaultFolder: boolean = false,
37+): Promise<{ path: string; content: string }[]> {
38+ const workspaceDirs = await ide.getWorkspaceDirs();
39+ let promptFiles: { path: string; content: string }[] = [];
40+
41+ let dirsToCheck = [DEFAULT_PROMPTS_FOLDER_V2];
42+ if (checkV1DefaultFolder) {
43+ dirsToCheck.push(DEFAULT_PROMPTS_FOLDER_V1);
44+ }
45+ if (overridePromptFolder) {
46+ dirsToCheck = [overridePromptFolder];
47+ }
48+
49+ const fullDirs = workspaceDirs
50+ .map((dir) => dirsToCheck.map((d) => joinPathsToUri(dir, d)))
51+ .flat();
52+
53+ promptFiles = (
54+ await Promise.all(fullDirs.map((dir) => getPromptFilesFromDir(ide, dir)))
55+ ).flat();
56+
57+ // Also read from ~/.continue/.prompts
58+ promptFiles.push(...readAllGlobalPromptFiles());
59+
60+ return await Promise.all(
61+ promptFiles.map(async (file) => {
62+ const content = await ide.readFile(file.path);
63+ return { path: file.path, content };
64+ }),
65+ );
66+}
added core/promptFiles/index.ts +19 −0
@@ -0,0 +1,19 @@
1+import { ContextProviderName } from "..";
2+
3+export const DEFAULT_PROMPTS_FOLDER_V1 = ".prompts";
4+export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts";
5+
6+export const SUPPORTED_PROMPT_CONTEXT_PROVIDERS: ContextProviderName[] = [
7+ "file",
8+ "clipboard",
9+ "repo-map",
10+ "currentFile",
11+ "os",
12+ "problems",
13+ "codebase",
14+ "tree",
15+ "open",
16+ "debugger",
17+ "terminal",
18+ "diff",
19+];
added core/promptFiles/parsePromptFile.ts +24 −0
@@ -0,0 +1,24 @@
1+import * as YAML from "yaml";
2+
3+import { getLastNPathParts } from "../util/uri";
4+
5+export function parsePromptFile(path: string, content: string) {
6+ let [preambleRaw, prompt] = content.split("\n---\n");
7+ if (prompt === undefined) {
8+ prompt = preambleRaw;
9+ preambleRaw = "";
10+ }
11+
12+ const preamble = YAML.parse(preambleRaw) ?? {};
13+ const name = preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0];
14+ const description = preamble.description ?? name;
15+ const version = preamble.version ?? 2;
16+
17+ let systemMessage: string | undefined = undefined;
18+ if (prompt.includes("<system>")) {
19+ systemMessage = prompt.split("<system>")[1].split("</system>")[0].trim();
20+ prompt = prompt.split("</system>")[1].trim();
21+ }
22+
23+ return { name, description, systemMessage, prompt, version };
24+}
deleted core/promptFiles/v1/getContextProviderHelpers.ts +0 −38
@@ -1,38 +0,0 @@
1-import Handlebars from "handlebars";
2-import { ContextItem, ContinueSDK, IContextProvider } from "../..";
3-
4-function createContextItem(item: ContextItem, provider: IContextProvider) {
5- return {
6- ...item,
7- id: {
8- itemId: item.description,
9- providerTitle: provider.description.title,
10- },
11- };
12-}
13-
14-export function getContextProviderHelpers(
15- context: ContinueSDK,
16-): Array<[string, Handlebars.HelperDelegate]> | undefined {
17- return context.config.contextProviders?.map((provider: IContextProvider) => [
18- provider.description.title,
19- async (helperContext: any) => {
20- const items = await provider.getContextItems(helperContext, {
21- config: context.config,
22- embeddingsProvider: context.config.selectedModelByRole.embed,
23- fetch: context.fetch,
24- fullInput: context.input,
25- ide: context.ide,
26- llm: context.llm,
27- reranker: context.config.selectedModelByRole.rerank,
28- selectedCode: context.selectedCode,
29- });
30-
31- items.forEach((item) =>
32- context.addContextItem(createContextItem(item, provider)),
33- );
34-
35- return items.map((item) => item.content).join("\n\n");
36- },
37- ]);
38-}
deleted core/promptFiles/v1/handlebarUtils.ts +0 −117
@@ -1,117 +0,0 @@
1-import Handlebars from "handlebars";
2-import { v4 as uuidv4 } from "uuid";
3-
4-function convertToLetter(num: number): string {
5- let result = "";
6- while (num > 0) {
7- const remainder = (num - 1) % 26;
8- result = String.fromCharCode(97 + remainder) + result;
9- num = Math.floor((num - 1) / 26);
10- }
11- return result;
12-}
13-
14-/**
15- * We replace filepaths with alphabetic characters to handle
16- * escaping issues.
17- */
18-const replaceFilepaths = (
19- value: string,
20- ctxProviderNames: string[],
21-): [string, { [key: string]: string }] => {
22- const ast = Handlebars.parse(value);
23-
24- const keysToFilepath: { [key: string]: string } = {};
25-
26- let keyIndex = 1;
27-
28- for (const i in ast.body) {
29- const node = ast.body[i] as any;
30-
31- if (node.type === "MustacheStatement") {
32- const originalNodeVal = node.path.original;
33- const isFilepath = !ctxProviderNames.includes(originalNodeVal);
34-
35- if (isFilepath) {
36- const letter = convertToLetter(keyIndex);
37-
38- keysToFilepath[letter] = originalNodeVal;
39-
40- value = value.replace(
41- new RegExp(`{{\\s*${originalNodeVal}\\s*}}`),
42- `{{${letter}}}`,
43- );
44-
45- keyIndex++;
46- }
47- }
48- }
49-
50- return [value, keysToFilepath];
51-};
52-
53-export function registerHelpers(
54- helpers: Array<[string, Handlebars.HelperDelegate]>,
55-): {
56- [key: string]: Promise<string>;
57-} {
58- const promises: { [key: string]: Promise<string> } = {};
59-
60- for (const [name, helper] of helpers) {
61- Handlebars.registerHelper(name, (...args) => {
62- const id = uuidv4();
63- promises[id] = helper(...args);
64- return `__${id}__`;
65- });
66- }
67-
68- return promises;
69-}
70-
71-export async function prepareTemplateAndData(
72- template: string,
73- readFile: (filepath: string) => Promise<string>,
74- inputData: Record<string, string>,
75- ctxProviderNames: string[],
76-): Promise<[string, any]> {
77- const [newTemplate, vars] = replaceFilepaths(template, ctxProviderNames);
78-
79- const data: any = { ...inputData };
80-
81- for (const [replacedName, originalCtxProviderName] of Object.entries(vars)) {
82- data[replacedName] =
83- inputData[originalCtxProviderName] ?? originalCtxProviderName;
84-
85- // If it's not a context provider, assume it's a filepath.
86- if (!ctxProviderNames.includes(originalCtxProviderName)) {
87- const fileContents = await readFile(vars[replacedName]);
88-
89- if (fileContents) {
90- data[replacedName] = fileContents;
91- }
92- }
93- }
94-
95- return [newTemplate, data];
96-}
97-
98-export function compileAndRenderTemplate(
99- template: string,
100- data: Record<string, string>,
101-): string {
102- const templateFn = Handlebars.compile(template);
103- return templateFn(data);
104-}
105-
106-export async function resolveHelperPromises(
107- renderedString: string,
108- promises: { [key: string]: Promise<string> },
109-): Promise<string> {
110- await Promise.all(Object.values(promises));
111-
112- for (const id in promises) {
113- renderedString = renderedString.replace(`__${id}__`, await promises[id]);
114- }
115-
116- return renderedString;
117-}
deleted core/promptFiles/v1/index.ts +0 −1
@@ -1,1 +0,0 @@
1-export const DEFAULT_PROMPTS_FOLDER_V1 = ".prompts";
deleted core/promptFiles/v1/renderTemplatedString.ts +0 −30
@@ -1,30 +0,0 @@
1-import {
2- compileAndRenderTemplate,
3- prepareTemplateAndData,
4- registerHelpers,
5- resolveHelperPromises,
6-} from "./handlebarUtils";
7-
8-export async function renderTemplatedString(
9- template: string,
10- readFile: (filepath: string) => Promise<string>,
11- inputData: Record<string, string>,
12- availableHelpers?: Array<[string, Handlebars.HelperDelegate]>,
13-): Promise<string> {
14- const helperPromises = availableHelpers
15- ? registerHelpers(availableHelpers)
16- : {};
17-
18- const ctxProviderNames = availableHelpers?.map((h) => h[0]) ?? [];
19-
20- const [newTemplate, data] = await prepareTemplateAndData(
21- template,
22- readFile,
23- inputData,
24- ctxProviderNames,
25- );
26-
27- let renderedString = compileAndRenderTemplate(newTemplate, data);
28-
29- return resolveHelperPromises(renderedString, helperPromises);
30-}
deleted core/promptFiles/v1/slashCommandFromPromptFile.ts +0 −89
@@ -1,89 +0,0 @@
1-import { ContinueSDK, SlashCommand } from "../..";
2-import { getDiffsFromCache } from "../../autocomplete/snippets/gitDiffCache";
3-import { renderChatMessage } from "../../util/messageContent";
4-import { getLastNPathParts } from "../../util/uri";
5-import { parsePromptFileV1V2 } from "../v2/parsePromptFileV1V2";
6-import { renderPromptFileV2 } from "../v2/renderPromptFile";
7-
8-import { getContextProviderHelpers } from "./getContextProviderHelpers";
9-import { renderTemplatedString } from "./renderTemplatedString";
10-import { replaceSlashCommandWithPromptInChatHistory } from "./updateChatHistory";
11-
12-export function extractName(preamble: { name?: string }, path: string): string {
13- return preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0];
14-}
15-
16-async function renderPromptV1(
17- prompt: string,
18- context: ContinueSDK,
19- userInput: string,
20-) {
21- const helpers = getContextProviderHelpers(context);
22-
23- const inputData: Record<string, string> = {
24- input: userInput,
25- };
26-
27- // A few context providers that don't need to be in config.json to work in .prompt files
28- if (helpers?.find((helper) => helper[0] === "diff")) {
29- const diffs = await getDiffsFromCache(context.ide);
30- inputData.diff = diffs.join("\n");
31- }
32- if (helpers?.find((helper) => helper[0] === "currentFile")) {
33- const currentFile = await context.ide.getCurrentFile();
34- if (currentFile) {
35- inputData.currentFile = currentFile.path;
36- }
37- }
38-
39- return renderTemplatedString(
40- prompt,
41- context.ide.readFile.bind(context.ide),
42- inputData,
43- helpers,
44- );
45-}
46-
47-export function slashCommandFromPromptFileV1(
48- path: string,
49- content: string,
50-): SlashCommand | null {
51- const { name, description, systemMessage, prompt } = parsePromptFileV1V2(
52- path,
53- content,
54- );
55-
56- return {
57- name,
58- description,
59- prompt,
60- promptFile: path,
61- run: async function* (context) {
62- const [_, renderedPrompt] = await renderPromptFileV2(prompt, {
63- config: context.config,
64- fullInput: context.input,
65- embeddingsProvider: context.config.modelsByRole.embed[0],
66- reranker: context.config.modelsByRole.rerank[0],
67- llm: context.llm,
68- ide: context.ide,
69- selectedCode: context.selectedCode,
70- fetch: context.fetch,
71- });
72-
73- const messages = replaceSlashCommandWithPromptInChatHistory(
74- context.history,
75- name,
76- renderedPrompt,
77- systemMessage,
78- );
79-
80- for await (const chunk of context.llm.streamChat(
81- messages,
82- context.abortController.signal,
83- context.completionOptions,
84- )) {
85- yield renderChatMessage(chunk);
86- }
87- },
88- };
89-}
deleted core/promptFiles/v1/updateChatHistory.ts +0 −64
@@ -1,64 +0,0 @@
1-import { ChatMessage } from "../..";
2-
3-export function replaceSlashCommandWithPromptInChatHistory(
4- history: ChatMessage[],
5- commandName: string,
6- renderedPrompt: string,
7- systemMessageOverride?: string,
8-): ChatMessage[] {
9- const messages = [...history];
10-
11- for (let i = messages.length - 1; i >= 0; i--) {
12- const { role, content } = messages[i];
13- if (role !== "user") {
14- continue;
15- }
16-
17- if (Array.isArray(content)) {
18- if (
19- content.some(
20- (part) =>
21- part.type === "text" && part.text?.startsWith(`/${commandName}`),
22- )
23- ) {
24- messages[i] = updateArrayContent(
25- messages[i],
26- commandName,
27- renderedPrompt,
28- );
29- break;
30- }
31- } else if (
32- typeof content === "string" &&
33- content.startsWith(`/${commandName}`)
34- ) {
35- messages[i] = { ...messages[i], content: renderedPrompt };
36- break;
37- }
38- }
39-
40- if (systemMessageOverride) {
41- if (messages[0]?.role === "system") {
42- messages[0].content = systemMessageOverride;
43- } else {
44- messages.unshift({ role: "system", content: systemMessageOverride });
45- }
46- }
47-
48- return messages;
49-}
50-
51-function updateArrayContent(
52- message: any,
53- commandName: string,
54- renderedPrompt: string,
55-) {
56- return {
57- ...message,
58- content: message.content.map((part: any) =>
59- part.text?.startsWith(`/${commandName}`)
60- ? { ...part, text: renderedPrompt }
61- : part,
62- ),
63- };
64-}
deleted core/promptFiles/v2/createNewPromptFile.ts +0 −76
@@ -1,76 +0,0 @@
1-import { IDE } from "../..";
2-import { GlobalContext } from "../../util/GlobalContext";
3-import { joinPathsToUri } from "../../util/uri";
4-
5-const FIRST_TIME_DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file
6-# It is used to define and reuse prompts within Continue
7-# Each .prompt file can be accessed by typing "@prompts" in the Chat input
8-
9-# A prompt file consists of two parts:
10-# 1. Everything above the "---" is YAML. Here you can set "temperature", "description", and other options
11-# 2. Everything below the "---" is the prompt body
12-
13-# If you do not want to set any options, you do not need to include the "---"
14-
15-# In the body, you can reference:
16-# 1. Files, using either absolute or relative paths (based on the workspace root)
17- # @README.md
18- # @src/test/test.py
19- # @/Users/me/Desktop/my-project/src/test/test.py
20-# 2. URLs, for example
21- # @https://example.com
22-# 3. Context providers, for example
23- # @currentFile
24- # @os
25- # @repo-map
26-
27-# To learn more, see the full .prompt file reference: https://docs.continue.dev/features/prompt-files
28-name: Example
29-description: Example prompt file
30----
31-
32-Here is information about the current repo:
33-
34-@README.md`;
35-
36-const DEFAULT_PROMPT_FILE = "";
37-
38-export async function createNewPromptFileV2(
39- ide: IDE,
40- promptPath: string | undefined,
41-): Promise<void> {
42- const workspaceDirs = await ide.getWorkspaceDirs();
43- if (workspaceDirs.length === 0) {
44- throw new Error(
45- "No workspace directories found. Make sure you've opened a folder in your IDE.",
46- );
47- }
48-
49- const baseDirUri = joinPathsToUri(
50- workspaceDirs[0],
51- promptPath ?? ".continue/prompts",
52- );
53-
54- // Find the first available filename
55- let counter = 0;
56- let promptFileUri: string;
57- do {
58- const suffix = counter === 0 ? "" : `-${counter}`;
59- promptFileUri = joinPathsToUri(
60- baseDirUri,
61- `new-prompt-file${suffix}.prompt`,
62- );
63- counter++;
64- } while (await ide.fileExists(promptFileUri));
65-
66- const globalContext = new GlobalContext();
67- const PROMPT_FILE =
68- globalContext.get("hasAlreadyCreatedAPromptFile") === true
69- ? DEFAULT_PROMPT_FILE
70- : FIRST_TIME_DEFAULT_PROMPT_FILE;
71-
72- globalContext.update("hasAlreadyCreatedAPromptFile", true);
73-
74- await ide.writeFile(promptFileUri, PROMPT_FILE);
75- await ide.openFile(promptFileUri);
76-}
deleted core/promptFiles/v2/getPromptFiles.ts +0 −67
@@ -1,67 +0,0 @@
1-import { IDE } from "../..";
2-import { walkDir } from "../../indexing/walkDir";
3-import { readAllGlobalPromptFiles } from "../../util/paths";
4-import { joinPathsToUri } from "../../util/uri";
5-import { DEFAULT_PROMPTS_FOLDER_V1 } from "../v1";
6-
7-export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts";
8-export async function getPromptFilesFromDir(
9- ide: IDE,
10- dir: string,
11-): Promise<{ path: string; content: string }[]> {
12- try {
13- const exists = await ide.fileExists(dir);
14-
15- if (!exists) {
16- return [];
17- }
18-
19- const uris = await walkDir(dir, ide, {
20- source: "get dir prompt files",
21- });
22- const promptFilePaths = uris.filter((p) => p.endsWith(".prompt"));
23- const results = promptFilePaths.map(async (uri) => {
24- const content = await ide.readFile(uri); // make a try catch
25- return { path: uri, content };
26- });
27- return Promise.all(results);
28- } catch (e) {
29- console.error(e);
30- return [];
31- }
32-}
33-
34-export async function getAllPromptFiles(
35- ide: IDE,
36- overridePromptFolder?: string,
37- checkV1DefaultFolder: boolean = false,
38-): Promise<{ path: string; content: string }[]> {
39- const workspaceDirs = await ide.getWorkspaceDirs();
40- let promptFiles: { path: string; content: string }[] = [];
41-
42- let dirsToCheck = [DEFAULT_PROMPTS_FOLDER_V2];
43- if (checkV1DefaultFolder) {
44- dirsToCheck.push(DEFAULT_PROMPTS_FOLDER_V1);
45- }
46- if (overridePromptFolder) {
47- dirsToCheck = [overridePromptFolder];
48- }
49-
50- const fullDirs = workspaceDirs
51- .map((dir) => dirsToCheck.map((d) => joinPathsToUri(dir, d)))
52- .flat();
53-
54- promptFiles = (
55- await Promise.all(fullDirs.map((dir) => getPromptFilesFromDir(ide, dir)))
56- ).flat();
57-
58- // Also read from ~/.continue/.prompts
59- promptFiles.push(...readAllGlobalPromptFiles());
60-
61- return await Promise.all(
62- promptFiles.map(async (file) => {
63- const content = await ide.readFile(file.path);
64- return { path: file.path, content };
65- }),
66- );
67-}
deleted core/promptFiles/v2/parse.ts +0 −34
@@ -1,34 +0,0 @@
1-import * as YAML from "yaml";
2-
3-import { getLastNPathParts } from "../../util/uri";
4-
5-export function extractName(preamble: { name?: string }, path: string): string {
6- return preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0];
7-}
8-
9-export function getPreambleAndBody(content: string): [string, string] {
10- let [preamble, body] = content.split("\n---\n");
11- if (body === undefined) {
12- // This means there is no preamble
13- body = preamble;
14- preamble = "";
15- }
16- return [preamble, body];
17-}
18-
19-export function parsePreamble(
20- path: string,
21- content: string,
22-): { [key: string]: any; name: string; description: string } {
23- const [preambleRaw, _] = getPreambleAndBody(content);
24-
25- const preamble = YAML.parse(preambleRaw) ?? {};
26- const name = extractName(preamble, path);
27- const description = preamble.description ?? name;
28-
29- return {
30- ...preamble,
31- name,
32- description,
33- };
34-}
deleted core/promptFiles/v2/parsePromptFileV1V2.ts +0 −24
@@ -1,24 +0,0 @@
1-import * as YAML from "yaml";
2-
3-import { getLastNPathParts } from "../../util/uri";
4-
5-export function parsePromptFileV1V2(path: string, content: string) {
6- let [preambleRaw, prompt] = content.split("\n---\n");
7- if (prompt === undefined) {
8- prompt = preambleRaw;
9- preambleRaw = "";
10- }
11-
12- const preamble = YAML.parse(preambleRaw) ?? {};
13- const name = preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0];
14- const description = preamble.description ?? name;
15- const version = preamble.version ?? 2;
16-
17- let systemMessage: string | undefined = undefined;
18- if (prompt.includes("<system>")) {
19- systemMessage = prompt.split("<system>")[1].split("</system>")[0].trim();
20- prompt = prompt.split("</system>")[1].trim();
21- }
22-
23- return { name, description, systemMessage, prompt, version };
24-}
deleted core/promptFiles/v2/renderPromptFile.ts +0 −84
@@ -1,84 +0,0 @@
1-import { ContextItem, ContextProviderExtras } from "../..";
2-import { contextProviderClassFromName } from "../../context/providers";
3-import { getUrlContextItems } from "../../context/providers/URLContextProvider";
4-import { resolveRelativePathInDir } from "../../util/ideUtils";
5-import { getUriPathBasename } from "../../util/uri";
6-
7-import { getPreambleAndBody } from "./parse";
8-
9-async function resolveAttachment(
10- name: string,
11- extras: ContextProviderExtras,
12-): Promise<ContextItem[]> {
13- // Context providers
14- const contextProvider = extras.config.contextProviders?.find(
15- (provider) => provider.description.title === name,
16- );
17- if (contextProvider) {
18- const items = await contextProvider.getContextItems("", extras);
19- return items;
20- } else {
21- // Just instantiate it here
22- const providerClass = contextProviderClassFromName(name) as any;
23- if (providerClass) {
24- const providerInstance = new providerClass({});
25- return providerInstance.getContextItems("", extras);
26- }
27- }
28-
29- // Files
30- const resolvedFileUri = await resolveRelativePathInDir(name, extras.ide);
31- if (resolvedFileUri) {
32- let subItems: ContextItem[] = [];
33- if (name.endsWith(".prompt")) {
34- // Recurse
35- const [items, _] = await renderPromptFileV2(
36- await extras.ide.readFile(resolvedFileUri),
37- extras,
38- );
39- subItems.push(...items);
40- }
41-
42- const content = `\`\`\`${name}\n${await extras.ide.readFile(resolvedFileUri)}\n\`\`\``;
43- return [
44- ...subItems,
45- {
46- name: getUriPathBasename(resolvedFileUri),
47- content,
48- description: resolvedFileUri,
49- },
50- ];
51- }
52-
53- // URLs
54- if (name.startsWith("http")) {
55- const items = getUrlContextItems(name, extras.fetch);
56- return items;
57- }
58-
59- return [];
60-}
61-
62-export async function renderPromptFileV2(
63- rawContent: string,
64- extras: ContextProviderExtras,
65-): Promise<[ContextItem[], string]> {
66- const [_, body] = getPreambleAndBody(rawContent);
67-
68- const contextItemsPromises: Promise<ContextItem[]>[] = [];
69- const renderedBody = body.replace(/@([^\s]+)/g, (match, name) => {
70- contextItemsPromises.push(resolveAttachment(name, extras));
71- return match;
72- });
73-
74- const contextItems = (await Promise.all(contextItemsPromises)).flat();
75- const renderedPrompt = [
76- ...contextItems.map((item) => item.content),
77- renderedBody,
78- extras.fullInput,
79- ]
80- .join("\n\n")
81- .trim();
82-
83- return [contextItems, renderedPrompt];
84-}
deleted core/promptFiles/v2/renderPromptFile.vitest.ts +0 −175
@@ -1,175 +0,0 @@
1-import { ContextProviderExtras, ILLM, RangeInFile } from "../..";
2-import { testConfigHandler, testIde } from "../../test/fixtures";
3-import {
4- addToTestDir,
5- setUpTestDir,
6- tearDownTestDir,
7-} from "../../test/testDir";
8-import { renderPromptFileV2 } from "./renderPromptFile";
9-
10-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
11-
12-vi.mock(
13- import("../../context/providers/URLContextProvider"),
14- async (importOriginal) => {
15- const actual = await importOriginal();
16- return {
17- ...actual,
18- getUrlContextItems: vi.fn().mockResolvedValue([
19- {
20- description: "https://example.com",
21- content: "Example Content",
22- name: "Example site",
23- uri: {
24- type: "url",
25- value: "https://example.com",
26- },
27- },
28- ]),
29- };
30- },
31-);
32-
33-describe("renderPromptFileV2", () => {
34- let extras: ContextProviderExtras;
35- const mockGetContextItems = vi.fn().mockResolvedValue([
36- {
37- name: "custom",
38- content: "Custom provider content",
39- description: "Custom provider",
40- },
41- ]);
42- beforeEach(async () => {
43- const { config } = await testConfigHandler.loadConfig();
44-
45- // Setup mock extras
46- extras = {
47- config: {
48- ...config!,
49- contextProviders: [
50- {
51- description: {
52- type: "normal",
53- title: "CustomProvider",
54- displayTitle: "Custom Provider",
55- description: "A custom context provider",
56- },
57- loadSubmenuItems: vi.fn().mockResolvedValue([]),
58- getContextItems: mockGetContextItems,
59- },
60- ],
61- },
62- fullInput: "User input",
63- embeddingsProvider: null,
64- reranker: null,
65- llm: {} as ILLM,
66- ide: testIde,
67- selectedCode: [] as RangeInFile[],
68- fetch: vi.fn(),
69- };
70-
71- // Clear all mocks
72- vi.clearAllMocks();
73- setUpTestDir();
74- });
75-
76- afterEach(() => {
77- tearDownTestDir();
78- });
79-
80- it("should render a prompt file with no attachments", async () => {
81- const rawContent = "Simple prompt with no attachments";
82- const [contextItems, renderedPrompt] = await renderPromptFileV2(
83- rawContent,
84- extras,
85- );
86-
87- expect(contextItems).toHaveLength(0);
88- expect(renderedPrompt).toBe(
89- "Simple prompt with no attachments\n\nUser input",
90- );
91- });
92-
93- it("should handle URL attachments", async () => {
94- const rawContent = "Content with URL @https://example.com";
95-
96- const [contextItems, renderedPrompt] = await renderPromptFileV2(
97- rawContent,
98- extras,
99- );
100-
101- expect(contextItems).toHaveLength(1);
102- expect(renderedPrompt).toContain("Example Content");
103- });
104-
105- it("should resolve file attachments", async () => {
106- const rawContent = "Content with file attachment @test.txt";
107-
108- addToTestDir([["test.txt", "File content"]]);
109-
110- const [contextItems, renderedPrompt] = await renderPromptFileV2(
111- rawContent,
112- extras,
113- );
114-
115- expect(contextItems).toHaveLength(1);
116- expect(renderedPrompt).toContain("```test.txt\nFile content\n```");
117- expect(renderedPrompt).toContain("Content with file attachment @test.txt");
118- });
119-
120- it("should handle nested prompt files", async () => {
121- const rawContent = "Main prompt with nested @nested.prompt";
122- addToTestDir([
123- ["nested.prompt", "Nested prompt content with @CustomProvider"],
124- ]);
125-
126- const [contextItems, renderedPrompt] = await renderPromptFileV2(
127- rawContent,
128- extras,
129- );
130-
131- expect(renderedPrompt).toContain("Custom provider content");
132- });
133-
134- it("should handle custom context providers", async () => {
135- const rawContent = "Content with custom provider @CustomProvider";
136-
137- const [contextItems, renderedPrompt] = await renderPromptFileV2(
138- rawContent,
139- extras,
140- );
141-
142- expect(contextItems).toHaveLength(1);
143- expect(renderedPrompt).toContain("Custom provider content");
144- expect(mockGetContextItems).toHaveBeenCalled();
145- });
146-
147- it("should handle multiple attachments", async () => {
148- const rawContent = "Content with @file1.txt and @file2.txt";
149- addToTestDir([
150- ["file1.txt", "Content 1"],
151- ["file2.txt", "Content 2"],
152- ]);
153-
154- const [contextItems, renderedPrompt] = await renderPromptFileV2(
155- rawContent,
156- extras,
157- );
158-
159- expect(contextItems).toHaveLength(2);
160- expect(renderedPrompt).toContain("```file1.txt\nContent 1\n```");
161- expect(renderedPrompt).toContain("```file2.txt\nContent 2\n```");
162- });
163-
164- it("should handle failed attachment resolutions gracefully", async () => {
165- const rawContent = "Content with @nonexistent";
166-
167- const [contextItems, renderedPrompt] = await renderPromptFileV2(
168- rawContent,
169- extras,
170- );
171-
172- expect(contextItems).toHaveLength(0);
173- expect(renderedPrompt).toBe("Content with @nonexistent\n\nUser input");
174- });
175-});
modified core/protocol/core.ts +13 −2
@@ -29,7 +29,7 @@
2929 Session,
3030 SessionMetadata,
3131 SiteIndexingConfig,
32- SlashCommandDescription,
32+ SlashCommandDescWithSource,
3333 StreamDiffLinesPayload,
3434 ToolCall,
3535 } from "../";
@@ -118,6 +118,17 @@
118118 },
119119 void,
120120 ];
121+ "mcp/getPrompt": [
122+ {
123+ serverName: string;
124+ promptName: string;
125+ args?: Record<string, string>;
126+ },
127+ {
128+ prompt: string;
129+ description: string | undefined;
130+ },
131+ ];
121132 "context/getSymbolsForFiles": [{ uris: string[] }, FileSymbolMap];
122133 "context/loadSubmenuItems": [{ title: string }, ContextSubmenuItem[]];
123134 "autocomplete/complete": [AutocompleteInput, string[]];
@@ -141,7 +152,7 @@
141152 completionOptions: LLMFullCompletionOptions;
142153 title: string;
143154 legacySlashCommandData?: {
144- command: SlashCommandDescription;
155+ command: SlashCommandDescWithSource;
145156 input: string;
146157 contextItems: ContextItemWithId[];
147158 historyIndex: number;
modified core/protocol/passThrough.ts +1 −0
@@ -27,6 +27,7 @@
2727 "config/updateSharedConfig",
2828 "config/updateSelectedModel",
2929 "mcp/reloadServer",
30+ "mcp/getPrompt",
3031 "context/getContextItems",
3132 "context/getSymbolsForFiles",
3233 "context/loadSubmenuItems",
added core/util/handlebars/handlebarUtils.ts +111 −0
@@ -0,0 +1,111 @@
1+import { v4 as uuidv4 } from "uuid";
2+
3+export type HandlebarsType = typeof import("handlebars");
4+
5+function convertToLetter(num: number): string {
6+ let result = "";
7+ while (num > 0) {
8+ const remainder = (num - 1) % 26;
9+ result = String.fromCharCode(97 + remainder) + result;
10+ num = Math.floor((num - 1) / 26);
11+ }
12+ return result;
13+}
14+
15+export function registerHelpers(
16+ handlebars: HandlebarsType,
17+ helpers: Array<[string, Handlebars.HelperDelegate]>,
18+): {
19+ [key: string]: Promise<string>;
20+} {
21+ const promises: { [key: string]: Promise<string> } = {};
22+
23+ for (const [name, helper] of helpers) {
24+ handlebars.registerHelper(name, (...args) => {
25+ const id = uuidv4();
26+ promises[id] = helper(...args);
27+ return `__${id}__`;
28+ });
29+ }
30+
31+ return promises;
32+}
33+
34+export async function prepareTemplatedFilepaths(
35+ handlebars: HandlebarsType,
36+ template: string,
37+ inputData: Record<string, string>,
38+ ctxProviderNames: string[],
39+ readFile: (filepath: string) => Promise<string>,
40+ getUriFromPath: (path: string) => Promise<string | undefined>,
41+) {
42+ // First, replace filepaths with letters to avoid escaping issues
43+ const ast = handlebars.parse(template);
44+
45+ const filepathLetters: Map<string, string> = new Map();
46+ const requiredContextProviders: Set<string> = new Set();
47+ let withLetterKeys = template;
48+
49+ let letterIndex = 1;
50+
51+ for (const i in ast.body) {
52+ const node = ast.body[i] as any;
53+
54+ if (node.type === "MustacheStatement") {
55+ const originalNodeVal = node.path.original;
56+ if (originalNodeVal.toLowerCase() === "input") {
57+ continue;
58+ }
59+ const isFilepath = !ctxProviderNames.includes(originalNodeVal);
60+
61+ if (isFilepath) {
62+ const letter = convertToLetter(letterIndex);
63+
64+ filepathLetters.set(letter, originalNodeVal);
65+
66+ withLetterKeys = withLetterKeys.replace(
67+ new RegExp(`{{\\s*${originalNodeVal}\\s*}}`),
68+ `{{${letter}}}`,
69+ );
70+
71+ letterIndex++;
72+ } else {
73+ requiredContextProviders.add(originalNodeVal);
74+ }
75+ }
76+ }
77+
78+ // Then, resolve the filepaths to their actual content and add to template data
79+ // Fallback to simple error string if file read fails
80+ const templateData = { ...inputData };
81+
82+ for (const [letter, filepath] of filepathLetters.entries()) {
83+ try {
84+ const uri = await getUriFromPath(filepath);
85+ if (uri) {
86+ const fileContents = await readFile(uri);
87+ templateData[letter] = fileContents;
88+ } else {
89+ throw new Error(`File not found: ${filepath}`);
90+ }
91+ } catch (e) {
92+ console.error(`Error reading file in prompt file ${filepath}:`, e);
93+ templateData[letter] = `[Error reading file "${filepath}"]`;
94+ }
95+ }
96+
97+ return { withLetterKeys, templateData, requiredContextProviders };
98+}
99+
100+export async function resolveHelperPromises(
101+ renderedString: string,
102+ promises: { [key: string]: Promise<string> },
103+): Promise<string> {
104+ await Promise.all(Object.values(promises));
105+
106+ for (const id in promises) {
107+ renderedString = renderedString.replace(`__${id}__`, await promises[id]);
108+ }
109+
110+ return renderedString;
111+}
added core/util/handlebars/renderTemplatedString.ts +35 −0
@@ -0,0 +1,35 @@
1+import {
2+ prepareTemplatedFilepaths,
3+ registerHelpers,
4+ resolveHelperPromises,
5+ type HandlebarsType,
6+} from "./handlebarUtils";
7+
8+export async function renderTemplatedString(
9+ handlebars: HandlebarsType,
10+ template: string,
11+ inputData: Record<string, string>,
12+ availableHelpers: Array<[string, Handlebars.HelperDelegate]>,
13+ readFile: (filepath: string) => Promise<string>,
14+ getUriFromPath: (path: string) => Promise<string | undefined>,
15+): Promise<string> {
16+ const helperPromises = availableHelpers
17+ ? registerHelpers(handlebars, availableHelpers)
18+ : {};
19+
20+ const ctxProviderNames = availableHelpers?.map((h) => h[0]) ?? [];
21+
22+ const { withLetterKeys, templateData } = await prepareTemplatedFilepaths(
23+ handlebars,
24+ template,
25+ inputData,
26+ ctxProviderNames,
27+ readFile,
28+ getUriFromPath,
29+ );
30+
31+ const templateFn = handlebars.compile(withLetterKeys);
32+ const renderedString = templateFn(templateData);
33+
34+ return resolveHelperPromises(renderedString, helperPromises);
35+}
modified core/util/uri.ts +2 −0
@@ -188,6 +188,7 @@
188188 dirUriCandidates,
189189 );
190190 const baseName = getUriPathBasename(uri);
191+ const extension = getFileExtensionFromBasename(baseName);
191192 const last2Parts = getLastNUriRelativePathParts(dirUriCandidates, uri, 2);
192193 return {
193194 uri,
@@ -195,5 +196,6 @@
195196 foundInDir,
196197 last2Parts,
197198 baseName,
199+ extension,
198200 };
199201 }
modified extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt +1 −0
@@ -92,6 +92,7 @@
9292 "config/updateSharedConfig",
9393 "config/updateSelectedModel",
9494 "mcp/reloadServer",
95+ "mcp/getPrompt",
9596 "context/getContextItems",
9697 "context/getSymbolsForFiles",
9798 "context/loadSubmenuItems",
modified gui/package-lock.json +0 −0

Not shown: the file is larger than the hub shows, or this page holds as much as it shows. View the file.

modified gui/package.json +1 −0
@@ -40,6 +40,7 @@
4040 "dompurify": "^3.0.6",
4141 "downshift": "^7.6.0",
4242 "escape-carriage": "^1.3.1",
43+ "handlebars": "^4.7.8",
4344 "lodash": "^4.17.21",
4445 "lowlight": "^3.3.0",
4546 "minisearch": "^7.0.2",
modified gui/src/components/ConversationStarters/ConversationStarterCard.tsx +3 −3
@@ -1,9 +1,9 @@
11 import { ChatBubbleLeftIcon } from "@heroicons/react/24/outline";
2-import { SlashCommandDescription } from "core";
2+import { SlashCommandDescWithSource } from "core";
33
44 interface ConversationStarterCardProps {
5- command: SlashCommandDescription;
6- onClick: (command: SlashCommandDescription) => void;
5+ command: SlashCommandDescWithSource;
6+ onClick: (command: SlashCommandDescWithSource) => void;
77 }
88
99 export function ConversationStarterCard({
modified gui/src/components/ConversationStarters/ConversationStarterCards.tsx +7 −3
@@ -1,4 +1,4 @@
1-import { SlashCommandDescription } from "core";
1+import { SlashCommandDescWithSource } from "core";
22 import { useState } from "react";
33 import { useBookmarkedSlashCommands } from "../../hooks/useBookmarkedSlashCommands";
44 import { useAppDispatch, useAppSelector } from "../../redux/hooks";
@@ -23,8 +23,12 @@
2323 isCommandBookmarked(command.name),
2424 );
2525
26- function onClick(command: SlashCommandDescription) {
27- mainEditor?.commands.insertPrompt(command);
26+ function onClick(command: SlashCommandDescWithSource) {
27+ mainEditor?.commands.insertPrompt({
28+ description: command.description,
29+ title: command.name,
30+ content: command.prompt,
31+ });
2832 }
2933
3034 if (bookmarkedSlashCommands.length === 0) {
modified gui/src/components/ConversationStarters/__tests__/utils.test.ts +10 −2
@@ -1,27 +1,35 @@
1-import { SlashCommandDescription } from "core";
1+import { SlashCommandDescWithSource } from "core";
22 import { sortCommandsByBookmarkStatus } from "../utils";
33
44 describe("sortCommandsByBookmarkStatus", () => {
5- const mockCommands: SlashCommandDescription[] = [
5+ const mockCommands: SlashCommandDescWithSource[] = [
66 {
77 name: "command1",
88 description: "First command",
99 prompt: "This is command 1",
10+ source: "built-in",
11+ isLegacy: false,
1012 },
1113 {
1214 name: "command2",
1315 description: "Second command",
1416 prompt: "This is command 2",
17+ source: "built-in",
18+ isLegacy: false,
1519 },
1620 {
1721 name: "command3",
1822 description: "Third command",
1923 prompt: "This is command 3",
24+ source: "built-in",
25+ isLegacy: false,
2026 },
2127 {
2228 name: "command4",
2329 description: "Fourth command",
2430 prompt: "This is command 4",
31+ source: "built-in",
32+ isLegacy: false,
2533 },
2634 ];
2735
modified gui/src/components/ConversationStarters/utils.ts +3 −3
@@ -1,4 +1,4 @@
1-import { SlashCommandDescription } from "core";
1+import { SlashCommandDescWithSource } from "core";
22 import {} from "core/config/default";
33
44 /**
@@ -8,9 +8,9 @@
88 * @returns A new sorted array with bookmarked commands first
99 */
1010 export function sortCommandsByBookmarkStatus(
11- commands: SlashCommandDescription[],
11+ commands: SlashCommandDescWithSource[],
1212 bookmarkedCommands: string[],
13-): SlashCommandDescription[] {
13+): SlashCommandDescWithSource[] {
1414 return [...commands].sort((a, b) => {
1515 const aIsBookmarked = bookmarkedCommands.includes(a.name);
1616 const bIsBookmarked = bookmarkedCommands.includes(b.name);
modified gui/src/components/mainInput/Lump/sections/PromptsSection.tsx +17 −10
@@ -4,7 +4,7 @@
44 PencilIcon,
55 } from "@heroicons/react/24/outline";
66 import { BookmarkIcon as BookmarkSolid } from "@heroicons/react/24/solid";
7-import { SlashCommandDescription } from "core";
7+import { SlashCommandDescWithSource } from "core";
88 import { useContext, useMemo } from "react";
99 import { useAuth } from "../../../../context/Auth";
1010 import { IdeMessengerContext } from "../../../../context/IdeMessenger";
@@ -15,10 +15,12 @@
1515 import { useLump } from "../LumpContext";
1616 import { ExploreBlocksButton } from "./ExploreBlocksButton";
1717
18-type PromptWithSlug = SlashCommandDescription & { slug?: string };
18+interface PromptCommandWithSlug extends SlashCommandDescWithSource {
19+ slug?: string;
20+}
1921
2022 interface PromptRowProps {
21- prompt: PromptWithSlug;
23+ prompt: PromptCommandWithSlug;
2224 isBookmarked: boolean;
2325 setIsBookmarked: (isBookmarked: boolean) => void;
2426 onEdit?: () => void;
@@ -38,7 +40,11 @@
3840
3941 const handlePromptClick = (e: React.MouseEvent) => {
4042 e.stopPropagation();
41- mainEditor?.commands.insertPrompt(prompt);
43+ mainEditor?.commands.insertPrompt({
44+ title: prompt.name,
45+ description: prompt.description,
46+ content: prompt.prompt,
47+ });
4248 hideLump();
4349 };
4450
@@ -102,7 +108,7 @@
102108 (state) => state.config.config.slashCommands ?? [],
103109 );
104110
105- const handleEdit = (prompt: PromptWithSlug) => {
111+ const handleEdit = (prompt: PromptCommandWithSlug) => {
106112 if (prompt.promptFile) {
107113 ideMessenger.post("openFile", {
108114 path: prompt.promptFile,
@@ -120,23 +126,24 @@
120126 };
121127
122128 const sortedCommands = useMemo(() => {
123- const promptsWithSlug: PromptWithSlug[] = structuredClone(slashCommands);
129+ const promptsWithSlug: PromptCommandWithSlug[] =
130+ structuredClone(slashCommands);
124131 // get the slugs from rawYaml
125132 if (selectedProfile?.rawYaml) {
126133 const parsed = parseConfigYaml(selectedProfile.rawYaml);
127134 const parsedPrompts = parsed.prompts ?? [];
128135
129136 let index = 0;
130- for (const prompt of promptsWithSlug) {
137+ for (const commandWithSlug of promptsWithSlug) {
131138 // skip for local prompt files
132- if (prompt.promptFile) continue;
139+ if (commandWithSlug.promptFile) continue;
133140
134141 const yamlPrompt = parsedPrompts[index];
135142 if (yamlPrompt) {
136143 if ("uses" in yamlPrompt) {
137- prompt.slug = yamlPrompt.uses;
144+ commandWithSlug.slug = yamlPrompt.uses;
138145 } else {
139- prompt.slug = `${selectedProfile?.fullSlug.ownerSlug}/${selectedProfile?.fullSlug.packageSlug}`;
146+ commandWithSlug.slug = `${selectedProfile?.fullSlug.ownerSlug}/${selectedProfile?.fullSlug.packageSlug}`;
140147 }
141148 }
142149 index = index + 1;
modified gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlock.ts +12 −9
@@ -1,8 +1,9 @@
11 import { mergeAttributes, Node } from "@tiptap/core";
22 import { Node as ProseMirrorNode } from "@tiptap/pm/model";
33 import { ReactNodeViewRenderer } from "@tiptap/react";
4-import { ContextItemWithId, SlashCommandDescription } from "core";
4+import { ContextItemWithId } from "core";
55 import { MAIN_EDITOR_INPUT_ID } from "../../../../../pages/gui/Chat";
6+import { ComboBoxItem } from "../../../types";
67 import { PromptBlockPreview } from "./PromptBlockPreview";
78
89 export interface PromptBlockOptions {
@@ -20,7 +21,9 @@
2021 /**
2122 * Insert a prompt block into the editor
2223 */
23- insertPrompt: (item: SlashCommandDescription) => ReturnType;
24+ insertPrompt: (
25+ item: Pick<ComboBoxItem, "title" | "content" | "description">,
26+ ) => ReturnType;
2427
2528 /**
2629 * Clear all prompt blocks from the editor
@@ -76,15 +79,15 @@
7679 addCommands() {
7780 return {
7881 insertPrompt:
79- (prompt: SlashCommandDescription) =>
82+ (item) =>
8083 ({ chain }) => {
81- const item: ContextItemWithId = {
82- content: prompt.prompt ?? "",
83- name: prompt.name,
84- description: prompt.description,
84+ const contextItem: ContextItemWithId = {
85+ content: item.content ?? "",
86+ name: item.title,
87+ description: item.description,
8588 id: {
8689 providerTitle: "prompt",
87- itemId: prompt.name,
90+ itemId: item.title,
8891 },
8992 };
9093
@@ -93,7 +96,7 @@
9396 .insertContentAt(0, {
9497 type: this.name,
9598 attrs: {
96- item,
99+ item: contextItem,
97100 inputId: MAIN_EDITOR_INPUT_ID,
98101 },
99102 })
modified gui/src/components/mainInput/TipTapEditor/extensions/SlashCommand.ts +1 −5
@@ -22,11 +22,7 @@
2222 // First delete the slash character and any text after it
2323 editor.chain().focus().deleteRange(range).run();
2424
25- editor.commands.insertPrompt({
26- name: props.title,
27- description: props.description,
28- prompt: props.content,
29- });
25+ editor.commands.insertPrompt(props);
3026 },
3127 },
3228 };
added gui/src/components/mainInput/TipTapEditor/utils/processEditorContent.test.ts +536 −0
@@ -0,0 +1,536 @@
1+import { JSONContent } from "@tiptap/react";
2+import { ContextItemWithId } from "core";
3+import { expect, test, vi } from "vitest";
4+import { processEditorContent } from "./processEditorContent";
5+
6+describe("processEditorContent", () => {
7+ // Create some reusable test data
8+ const createContextItem = (
9+ content: string,
10+ description: string,
11+ fileUri?: string,
12+ editing?: boolean,
13+ ): ContextItemWithId => ({
14+ id: { providerTitle: "test", itemId: "test-id" },
15+ content,
16+ description,
17+ name: "Test Item",
18+ editing,
19+ uri: fileUri ? { type: "file", value: fileUri } : undefined,
20+ });
21+
22+ test("processEditorContent should return empty arrays when content is empty", () => {
23+ // Empty editor state
24+ const emptyEditorState: JSONContent = {
25+ type: "doc",
26+ content: [],
27+ };
28+
29+ const result = processEditorContent(emptyEditorState);
30+
31+ expect(result.parts).toEqual([]);
32+ expect(result.contextRequests).toEqual([]);
33+ expect(result.selectedCode).toEqual([]);
34+ expect(result.slashCommandName).toBeUndefined();
35+ });
36+
37+ test("processEditorContent should process text paragraphs", () => {
38+ const editorState: JSONContent = {
39+ type: "doc",
40+ content: [
41+ {
42+ type: "paragraph",
43+ content: [
44+ {
45+ type: "text",
46+ text: "Hello world",
47+ },
48+ ],
49+ },
50+ {
51+ type: "paragraph",
52+ content: [
53+ {
54+ type: "text",
55+ text: "This is another paragraph",
56+ },
57+ ],
58+ },
59+ ],
60+ };
61+
62+ const result = processEditorContent(editorState);
63+
64+ expect(result.parts).toEqual([
65+ {
66+ type: "text",
67+ text: "Hello world\nThis is another paragraph",
68+ },
69+ ]);
70+ expect(result.contextRequests).toEqual([]);
71+ expect(result.selectedCode).toEqual([]);
72+ });
73+
74+ test("processEditorContent should detect slash commands", () => {
75+ const editorState: JSONContent = {
76+ type: "doc",
77+ content: [
78+ {
79+ type: "prompt-block",
80+ attrs: {
81+ item: {
82+ name: "test-command",
83+ },
84+ },
85+ },
86+ {
87+ type: "paragraph",
88+ content: [
89+ {
90+ type: "text",
91+ text: "Some text after the prompt",
92+ },
93+ ],
94+ },
95+ ],
96+ };
97+
98+ const result = processEditorContent(editorState);
99+
100+ expect(result.slashCommandName).toBe("test-command");
101+ expect(result.parts).toEqual([
102+ {
103+ type: "text",
104+ text: "Some text after the prompt",
105+ },
106+ ]);
107+ });
108+
109+ test("processEditorContent should handle mentions and collect context requests", () => {
110+ const editorState: JSONContent = {
111+ type: "doc",
112+ content: [
113+ {
114+ type: "paragraph",
115+ content: [
116+ {
117+ type: "text",
118+ text: "Hello ",
119+ },
120+ {
121+ type: "mention",
122+ attrs: {
123+ id: "fileSearch",
124+ label: "@fileSearch",
125+ itemType: "contextProvider",
126+ },
127+ },
128+ {
129+ type: "text",
130+ text: " and also ",
131+ },
132+ {
133+ type: "mention",
134+ attrs: {
135+ id: "github",
136+ label: "@github",
137+ itemType: "contextProvider",
138+ },
139+ },
140+ ],
141+ },
142+ ],
143+ };
144+
145+ const result = processEditorContent(editorState);
146+
147+ expect(result.parts).toEqual([
148+ {
149+ type: "text",
150+ text: "Hello @fileSearch and also @github",
151+ },
152+ ]);
153+ expect(result.contextRequests).toEqual([
154+ { provider: "fileSearch" },
155+ { provider: "github" },
156+ ]);
157+ });
158+
159+ test("processEditorContent should handle code blocks", () => {
160+ const codeItem = createContextItem(
161+ "function test() {\n return 'hello';\n}",
162+ "a description",
163+ "file:///example.js",
164+ );
165+
166+ const editorState: JSONContent = {
167+ type: "doc",
168+ content: [
169+ {
170+ type: "paragraph",
171+ content: [
172+ {
173+ type: "text",
174+ text: "Check this code:",
175+ },
176+ ],
177+ },
178+ {
179+ type: "code-block",
180+ attrs: {
181+ item: codeItem,
182+ },
183+ },
184+ ],
185+ };
186+
187+ const result = processEditorContent(editorState);
188+
189+ expect(result.parts).toEqual([
190+ {
191+ type: "text",
192+ text: "Check this code:\n\n```js example.js\nfunction test() {\n return 'hello';\n}\n```\n",
193+ },
194+ ]);
195+ expect(result.selectedCode).toHaveLength(1);
196+ expect(result.selectedCode[0].filepath).toBe("file:///example.js");
197+ });
198+
199+ test("processEditorContent should not include editing code blocks in the text", () => {
200+ const editingCodeItem = createContextItem(
201+ "function test() {\n return 'hello';\n}",
202+ "a description",
203+ "file:///editing.js",
204+ true, // Set editing to true
205+ );
206+
207+ const editorState: JSONContent = {
208+ type: "doc",
209+ content: [
210+ {
211+ type: "paragraph",
212+ content: [
213+ {
214+ type: "text",
215+ text: "Edit this code:",
216+ },
217+ ],
218+ },
219+ {
220+ type: "code-block",
221+ attrs: {
222+ item: editingCodeItem,
223+ },
224+ },
225+ ],
226+ };
227+
228+ const result = processEditorContent(editorState);
229+
230+ // The code block should not be included in parts because it's marked as editing
231+ expect(result.parts).toEqual([
232+ {
233+ type: "text",
234+ text: "Edit this code:",
235+ },
236+ ]);
237+
238+ // But it should still be in selectedCode
239+ expect(result.selectedCode).toHaveLength(1);
240+ expect(result.selectedCode[0].filepath).toBe("file:///editing.js");
241+ });
242+
243+ test("processEditorContent should handle images", () => {
244+ const editorState: JSONContent = {
245+ type: "doc",
246+ content: [
247+ {
248+ type: "paragraph",
249+ content: [
250+ {
251+ type: "text",
252+ text: "Here's an image:",
253+ },
254+ ],
255+ },
256+ {
257+ type: "image",
258+ attrs: {
259+ src: "https://example.com/image.png",
260+ },
261+ },
262+ ],
263+ };
264+
265+ const result = processEditorContent(editorState);
266+
267+ expect(result.parts).toEqual([
268+ {
269+ type: "text",
270+ text: "Here's an image:",
271+ },
272+ {
273+ type: "imageUrl",
274+ imageUrl: { url: "https://example.com/image.png" },
275+ },
276+ ]);
277+ });
278+
279+ test("processEditorContent should handle complex content with multiple elements", () => {
280+ const codeItem = createContextItem(
281+ "const x = 42;",
282+ "a description",
283+ "file:///script.ts",
284+ );
285+
286+ const editorState: JSONContent = {
287+ type: "doc",
288+ content: [
289+ {
290+ type: "prompt-block",
291+ attrs: {
292+ item: {
293+ name: "explain",
294+ },
295+ },
296+ },
297+ {
298+ type: "paragraph",
299+ content: [
300+ {
301+ type: "text",
302+ text: "Please explain this code and also check ",
303+ },
304+ {
305+ type: "mention",
306+ attrs: {
307+ id: "related",
308+ label: "@related",
309+ itemType: "similarFiles",
310+ },
311+ },
312+ ],
313+ },
314+ {
315+ type: "code-block",
316+ attrs: {
317+ item: codeItem,
318+ },
319+ },
320+ {
321+ type: "paragraph",
322+ content: [
323+ {
324+ type: "text",
325+ text: "What does this constant do?",
326+ },
327+ ],
328+ },
329+ {
330+ type: "image",
331+ attrs: {
332+ src: "https://example.com/diagram.png",
333+ },
334+ },
335+ ],
336+ };
337+
338+ const result = processEditorContent(editorState);
339+
340+ expect(result.slashCommandName).toBe("explain");
341+ expect(result.contextRequests).toEqual([{ provider: "similarFiles" }]);
342+ expect(result.selectedCode).toHaveLength(1);
343+ expect(result.selectedCode[0].filepath).toBe("file:///script.ts");
344+
345+ // `\n\n\`\`\`${extension} ${relativePathOrBasename}\n${contextItem.content}\n\`\`\`\n`;
346+
347+ expect(result.parts).toEqual([
348+ {
349+ type: "text",
350+ text: "Please explain this code and also check @related\n\n```ts script.ts\nconst x = 42;\n```\n\nWhat does this constant do?",
351+ },
352+ {
353+ type: "imageUrl",
354+ imageUrl: { url: "https://example.com/diagram.png" },
355+ },
356+ ]);
357+ });
358+
359+ test("processEditorContent should merge consecutive text parts", () => {
360+ const editorState: JSONContent = {
361+ type: "doc",
362+ content: [
363+ {
364+ type: "paragraph",
365+ content: [
366+ {
367+ type: "text",
368+ text: "First paragraph",
369+ },
370+ ],
371+ },
372+ {
373+ type: "paragraph",
374+ content: [
375+ {
376+ type: "text",
377+ text: "Second paragraph",
378+ },
379+ ],
380+ },
381+ {
382+ type: "image",
383+ attrs: {
384+ src: "https://example.com/image.png",
385+ },
386+ },
387+ {
388+ type: "paragraph",
389+ content: [
390+ {
391+ type: "text",
392+ text: "Third paragraph",
393+ },
394+ ],
395+ },
396+ ],
397+ };
398+
399+ const result = processEditorContent(editorState);
400+
401+ // First two paragraphs should be merged, but the third should be separate
402+ // because there's an image in between
403+ expect(result.parts).toEqual([
404+ {
405+ type: "text",
406+ text: "First paragraph\nSecond paragraph",
407+ },
408+ {
409+ type: "imageUrl",
410+ imageUrl: { url: "https://example.com/image.png" },
411+ },
412+ {
413+ type: "text",
414+ text: "Third paragraph",
415+ },
416+ ]);
417+ });
418+
419+ test("processEditorContent should handle unexpected content types gracefully", () => {
420+ // Testing with an unknown node type
421+ const editorState: JSONContent = {
422+ type: "doc",
423+ content: [
424+ {
425+ type: "paragraph",
426+ content: [
427+ {
428+ type: "text",
429+ text: "Normal text",
430+ },
431+ ],
432+ },
433+ {
434+ type: "unknown-type", // This type doesn't exist
435+ content: [
436+ {
437+ type: "text",
438+ text: "This should be ignored",
439+ },
440+ ],
441+ },
442+ ],
443+ };
444+
445+ // Spy on console.warn to verify it's called
446+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
447+
448+ const result = processEditorContent(editorState);
449+
450+ // Only the normal paragraph should be processed
451+ expect(result.parts).toEqual([
452+ {
453+ type: "text",
454+ text: "Normal text",
455+ },
456+ ]);
457+
458+ // Console.warn should be called for the unknown type
459+ expect(warnSpy).toHaveBeenCalledWith(
460+ "Unexpected content type",
461+ "unknown-type",
462+ );
463+
464+ warnSpy.mockRestore();
465+ });
466+
467+ test("processEditorContent should handle missing attrs in code blocks", () => {
468+ // Testing with a code block that has no item attribute
469+ const editorState: JSONContent = {
470+ type: "doc",
471+ content: [
472+ {
473+ type: "code-block",
474+ // Missing attrs property
475+ },
476+ ],
477+ };
478+
479+ // Spy on console.warn to verify it's called
480+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
481+
482+ const result = processEditorContent(editorState);
483+
484+ // No parts should be created
485+ expect(result.parts).toEqual([]);
486+ expect(result.selectedCode).toEqual([]);
487+
488+ // Console.warn should be called for the missing item attribute
489+ expect(warnSpy).toHaveBeenCalledWith("codeBlock has no item attribute");
490+
491+ warnSpy.mockRestore();
492+ });
493+
494+ test("processEditorContent should handle paragraphs with unexpected child types", () => {
495+ // Testing with a paragraph that has an unknown child type
496+ const editorState: JSONContent = {
497+ type: "doc",
498+ content: [
499+ {
500+ type: "paragraph",
501+ content: [
502+ {
503+ type: "text",
504+ text: "Normal text ",
505+ },
506+ {
507+ type: "unknown-child", // This type doesn't exist
508+ text: "This should be ignored",
509+ },
510+ ],
511+ },
512+ ],
513+ };
514+
515+ // Spy on console.warn to verify it's called
516+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
517+
518+ const result = processEditorContent(editorState);
519+
520+ // Only the normal text should be processed
521+ expect(result.parts).toEqual([
522+ {
523+ type: "text",
524+ text: "Normal text ",
525+ },
526+ ]);
527+
528+ // Console.warn should be called for the unknown child type
529+ expect(warnSpy).toHaveBeenCalledWith(
530+ "Unexpected child type",
531+ "unknown-child",
532+ );
533+
534+ warnSpy.mockRestore();
535+ });
536+});
added gui/src/components/mainInput/TipTapEditor/utils/processEditorContent.ts +119 −0
@@ -0,0 +1,119 @@
1+import Image from "@tiptap/extension-image";
2+import { Paragraph } from "@tiptap/extension-paragraph";
3+import { Text } from "@tiptap/extension-text";
4+import { JSONContent } from "@tiptap/react";
5+import {
6+ ContextItemWithId,
7+ MessagePart,
8+ RangeInFile,
9+ TextMessagePart,
10+} from "core";
11+import { ctxItemToRifWithContents } from "core/commands/util";
12+import { getUriDescription } from "core/util/uri";
13+import { CodeBlock, Mention, PromptBlock } from "../extensions";
14+import { GetContextRequest } from "./types";
15+
16+interface MentionAttrs {
17+ label: string;
18+ id: string;
19+ itemType?: string;
20+ query?: string;
21+}
22+
23+function resolvePromptBlock(p: JSONContent): string | undefined {
24+ return p.attrs?.item.name;
25+}
26+
27+function resolveParagraph(p: JSONContent): [string, GetContextRequest[]] {
28+ const contextRequests: GetContextRequest[] = [];
29+
30+ const text = (p.content || [])
31+ .map((child) => {
32+ switch (child.type) {
33+ case Text.name:
34+ return child.text;
35+ case Mention.name:
36+ const attrs = child.attrs as MentionAttrs;
37+ contextRequests.push({
38+ provider:
39+ attrs.itemType === "contextProvider" ? attrs.id : attrs.itemType!,
40+ });
41+ return child.attrs?.renderInlineAs ?? child.attrs?.label;
42+
43+ default:
44+ console.warn("Unexpected child type", child.type);
45+ return "";
46+ }
47+ })
48+ .join("")
49+ .trimStart();
50+
51+ return [text, contextRequests];
52+}
53+
54+export function processEditorContent(editorState: JSONContent) {
55+ const contextRequests: GetContextRequest[] = [];
56+ const selectedCode: RangeInFile[] = [];
57+ let slashCommandName: string | undefined;
58+
59+ const parts: MessagePart[] = [];
60+ for (const p of editorState?.content || []) {
61+ switch (p.type) {
62+ case PromptBlock.name:
63+ slashCommandName = resolvePromptBlock(p);
64+ break;
65+ case Paragraph.name:
66+ const [text, ctxItems] = resolveParagraph(p);
67+
68+ contextRequests.push(...ctxItems);
69+
70+ if (text) {
71+ // Merge with previous text part if possible
72+ if (parts[parts.length - 1]?.type === "text") {
73+ (parts[parts.length - 1] as TextMessagePart).text += "\n" + text;
74+ } else {
75+ parts.push({ type: "text", text });
76+ }
77+ }
78+ break;
79+ case CodeBlock.name:
80+ if (!p.attrs?.item) {
81+ console.warn("codeBlock has no item attribute");
82+ break;
83+ }
84+
85+ const contextItem = p.attrs.item as ContextItemWithId;
86+ const rif = ctxItemToRifWithContents(contextItem, true);
87+ selectedCode.push(rif);
88+
89+ // If editing, only include in selectedCode
90+ if (contextItem.editing) {
91+ break;
92+ }
93+
94+ const { extension, relativePathOrBasename } = getUriDescription(
95+ rif.filepath,
96+ window.workspacePaths ?? [],
97+ );
98+ const codeText = `\n\`\`\`${extension} ${relativePathOrBasename}\n${contextItem.content}\n\`\`\`\n`;
99+
100+ if (parts[parts.length - 1]?.type === "text") {
101+ (parts[parts.length - 1] as TextMessagePart).text += "\n" + codeText;
102+ } else {
103+ parts.push({ type: "text", text: codeText });
104+ }
105+ break;
106+ case Image.name:
107+ parts.push({
108+ type: "imageUrl",
109+ imageUrl: { url: p.attrs?.src },
110+ });
111+ break;
112+ default: {
113+ console.warn("Unexpected content type", p.type);
114+ }
115+ }
116+ }
117+
118+ return { parts, contextRequests, selectedCode, slashCommandName };
119+}
added gui/src/components/mainInput/TipTapEditor/utils/renderMcpPrompt.ts +32 −0
@@ -0,0 +1,32 @@
1+import { SlashCommandDescWithSource } from "core";
2+import { IIdeMessenger } from "../../../../context/IdeMessenger";
3+
4+export async function renderMcpPrompt(
5+ command: SlashCommandDescWithSource,
6+ ideMessenger: IIdeMessenger,
7+ userInput?: string,
8+) {
9+ // TODO add support for mcp prompt args using command.mcpArgs
10+ const args: { [key: string]: string } = {};
11+ if (command.mcpArgs) {
12+ command.mcpArgs.forEach((arg, i) => {
13+ args[arg.name] = "";
14+ });
15+ }
16+ const response = await ideMessenger.request("mcp/getPrompt", {
17+ serverName: command.mcpServerName!,
18+ promptName: command.name,
19+ args: args,
20+ });
21+ if (response.status === "success") {
22+ let renderedPrompt = response.content.prompt;
23+ if (userInput) {
24+ renderedPrompt += `\n\n${userInput}`;
25+ }
26+ return renderedPrompt;
27+ } else {
28+ throw new Error(
29+ `Failed to get MCP prompt for slash command ${command.name}`,
30+ );
31+ }
32+}
added gui/src/components/mainInput/TipTapEditor/utils/renderPromptv1.test.ts +128 −0
@@ -0,0 +1,128 @@
1+import { SlashCommandDescWithSource } from "core";
2+import { beforeEach, describe, it, vi } from "vitest";
3+import {
4+ MockIdeMessenger,
5+ MockResponseHandler,
6+} from "../../../../context/MockIdeMessenger";
7+import { getRenderedV1Prompt } from "./renderPromptv1";
8+
9+function getTestPromptV1Command(body: string): SlashCommandDescWithSource {
10+ return {
11+ prompt: body,
12+ name: "test-prompt-name",
13+ description: "test-prompt-description",
14+ isLegacy: false,
15+ source: "prompt-file-v1",
16+ };
17+}
18+describe("get rendered v1 prompt file", () => {
19+ const ideMessenger = new MockIdeMessenger();
20+ const firstDir = ideMessenger.responses["getWorkspaceDirs"]?.[0] ?? "";
21+ const customGetContextItems: MockResponseHandler<
22+ "context/getContextItems"
23+ > = async ({ name }) => {
24+ if (name === "diff") {
25+ return [
26+ {
27+ id: {
28+ itemId: "id",
29+ providerTitle: "diff",
30+ },
31+ name: "name",
32+ description: "description",
33+ content: "Diff provider content",
34+ },
35+ ];
36+ }
37+ return [];
38+ };
39+ beforeEach(async () => {
40+ vi.clearAllMocks();
41+ ideMessenger.resetMocks();
42+ });
43+
44+ it("should render a prompt file with no attachments or templated input", async () => {
45+ const rawContent = "Simple prompt with no attachments";
46+ const command = getTestPromptV1Command(rawContent);
47+ const rendered = await getRenderedV1Prompt(
48+ ideMessenger,
49+ command,
50+ "User input",
51+ [],
52+ );
53+ expect(rendered).toBe("Simple prompt with no attachments\n\nUser input");
54+ });
55+
56+ it("should render a prompt file templated input", async () => {
57+ const rawContent = "{{{ input }}} Simple prompt with no attachments";
58+ const command = getTestPromptV1Command(rawContent);
59+ const rendered = await getRenderedV1Prompt(
60+ ideMessenger,
61+ command,
62+ "User input",
63+ [],
64+ );
65+ expect(rendered).toBe("User input Simple prompt with no attachments");
66+ });
67+
68+ it("Should handle file attachments", async () => {
69+ ideMessenger.responses["readFile"] = "Test file content";
70+ const rawContent = "Content with URL {{{ testFile.txt }}}";
71+ const command = getTestPromptV1Command(rawContent);
72+ const rendered = await getRenderedV1Prompt(
73+ ideMessenger,
74+ command,
75+ "User input",
76+ [],
77+ );
78+ expect(rendered).toBe("Content with URL Test file content\n\nUser input");
79+ });
80+
81+ it("should handle supported providers", async () => {
82+ ideMessenger.responseHandlers["context/getContextItems"] =
83+ customGetContextItems;
84+ const rawContent = "Tell me about {{{ diff }}} please";
85+ const command = getTestPromptV1Command(rawContent);
86+ const rendered = await getRenderedV1Prompt(
87+ ideMessenger,
88+ command,
89+ "User input",
90+ [],
91+ );
92+ expect(rendered).toBe(
93+ "Tell me about Diff provider content please\n\nUser input",
94+ );
95+ });
96+
97+ it("should render file read errors within prompt", async () => {
98+ ideMessenger.responses["fileExists"] = false;
99+ const rawContent = "Content with provider {{{ nonexistent }}}";
100+ const command = getTestPromptV1Command(rawContent);
101+ const rendered = await getRenderedV1Prompt(
102+ ideMessenger,
103+ command,
104+ "User input",
105+ [],
106+ );
107+ expect(rendered).toBe(
108+ `Content with provider [Error reading file "nonexistent"]\n\nUser input`,
109+ );
110+ });
111+
112+ it("should handle multiple attachments", async () => {
113+ ideMessenger.responseHandlers["context/getContextItems"] =
114+ customGetContextItems;
115+ ideMessenger.responses["readFile"] = "Test file content";
116+ const rawContent = "Content with {{{ diff }}} and {{{ file.txt }}}";
117+ const command = getTestPromptV1Command(rawContent);
118+ const rendered = await getRenderedV1Prompt(
119+ ideMessenger,
120+ command,
121+ "User input",
122+ [],
123+ );
124+ expect(rendered).toBe(
125+ "Content with Diff provider content and Test file content\n\nUser input",
126+ );
127+ });
128+});
added gui/src/components/mainInput/TipTapEditor/utils/renderPromptv1.ts +58 −0
@@ -0,0 +1,58 @@
1+import {
2+ ContextProviderName,
3+ RangeInFile,
4+ SlashCommandDescWithSource,
5+} from "core";
6+import { SUPPORTED_PROMPT_CONTEXT_PROVIDERS } from "core/promptFiles";
7+import { renderTemplatedString } from "core/util/handlebars/renderTemplatedString";
8+import { resolveRelativePathInDir } from "core/util/ideUtils";
9+import { IIdeMessenger } from "../../../../context/IdeMessenger";
10+
11+export async function getRenderedV1Prompt(
12+ ideMessenger: IIdeMessenger,
13+ command: SlashCommandDescWithSource,
14+ userInput: string,
15+ selectedCode: RangeInFile[],
16+): Promise<string> {
17+ if (!command.prompt) {
18+ return "";
19+ }
20+ const handleBarHelpers = SUPPORTED_PROMPT_CONTEXT_PROVIDERS.map(
21+ (name: ContextProviderName): [string, Handlebars.HelperDelegate] => [
22+ name,
23+ async (helperContext: any) => {
24+ const response = await ideMessenger.request("context/getContextItems", {
25+ fullInput: userInput,
26+ name,
27+ query: "",
28+ selectedCode,
29+ });
30+ if (response.status === "success") {
31+ return response.content.map((item) => item.content).join("\n\n");
32+ } else {
33+ throw new Error(
34+ `Failed to get context items from provider "${name}": ${response.error}`,
35+ );
36+ }
37+ },
38+ ],
39+ );
40+ const workspaceDirs = await ideMessenger.ide.getWorkspaceDirs();
41+ const getUriFromPath = (path: string) => {
42+ return resolveRelativePathInDir(path, ideMessenger.ide, workspaceDirs);
43+ };
44+ const handlebars = await import("handlebars");
45+ let rendered = await renderTemplatedString(
46+ handlebars,
47+ command.prompt,
48+ { input: userInput },
49+ handleBarHelpers,
50+ ideMessenger.ide.readFile.bind(ideMessenger.ide),
51+ getUriFromPath,
52+ );
53+ // For prompt file append the input if it isn't rendered
54+ if (!rendered.includes(userInput)) {
55+ rendered = rendered + `\n\n${userInput}`;
56+ }
57+ return rendered.trim();
58+}
added gui/src/components/mainInput/TipTapEditor/utils/renderPromptv2.test.ts +80 −0
@@ -0,0 +1,80 @@
1+import { SlashCommandDescWithSource } from "core";
2+import { beforeEach, describe, expect, it, vi } from "vitest";
3+import { MockIdeMessenger } from "../../../../context/MockIdeMessenger";
4+import { getPromptV2ContextRequests } from "./renderPromptv2";
5+
6+function getTestPromptV2Command(body: string): SlashCommandDescWithSource {
7+ return {
8+ prompt: body,
9+ name: "test-prompt-name",
10+ description: "test-prompt-description",
11+ isLegacy: false,
12+ source: "prompt-file-v2",
13+ };
14+}
15+describe("getPromptV2ContextRequests", () => {
16+ const ideMessenger = new MockIdeMessenger();
17+ const firstDir = ideMessenger.responses["getWorkspaceDirs"]?.[0] ?? "";
18+ beforeEach(async () => {
19+ vi.clearAllMocks();
20+ ideMessenger.resetMocks();
21+ });
22+
23+ it("should render a prompt file with no attachments", async () => {
24+ const rawContent = "Simple prompt with no attachments";
25+ const command = getTestPromptV2Command(rawContent);
26+ const requests = await getPromptV2ContextRequests(ideMessenger, command);
27+ expect(requests).toHaveLength(0);
28+ });
29+
30+ it("should handle URL attachments", async () => {
31+ const rawContent = "Content with URL @https://example.com";
32+ const command = getTestPromptV2Command(rawContent);
33+ const requests = await getPromptV2ContextRequests(ideMessenger, command);
34+ expect(requests).toHaveLength(1);
35+ expect(requests[0].provider).toBe("url");
36+ expect(requests[0].query).toBe("https://example.com");
37+ });
38+
39+ it("should resolve file attachments", async () => {
40+ const rawContent = "Content with file attachment @test.txt";
41+ const command = getTestPromptV2Command(rawContent);
42+ const requests = await getPromptV2ContextRequests(ideMessenger, command);
43+
44+ expect(requests).toHaveLength(1);
45+ expect(requests[0].provider).toBe("file");
46+ expect(requests[0].query).toBe(`${firstDir}/test.txt`);
47+ });
48+
49+ it("should handle nested prompt files", async () => {
50+ ideMessenger.responses["readFile"] = "Contents @myfile.txt";
51+ const rawContent = "Main prompt with nested @test.prompt";
52+ const command = getTestPromptV2Command(rawContent);
53+ const requests = await getPromptV2ContextRequests(ideMessenger, command);
54+ expect(requests).toHaveLength(2);
55+ expect(requests[0].provider).toBe("file");
56+ expect(requests[0].query).toBe(`${firstDir}/myfile.txt`);
57+ expect(requests[1].provider).toBe("file");
58+ expect(requests[1].query).toBe(`${firstDir}/test.prompt`);
59+ });
60+
61+ it("should ignore unsupported providers", async () => {
62+ ideMessenger.responses["fileExists"] = false;
63+ const rawContent = "Content with custom provider @unsupported";
64+ const command = getTestPromptV2Command(rawContent);
65+ const requests = await getPromptV2ContextRequests(ideMessenger, command);
66+ expect(requests).toHaveLength(0);
67+ });
68+
69+ it("should handle multiple attachments", async () => {
70+ const rawContent = "Content with @file1.txt and @file2.txt";
71+ const command = getTestPromptV2Command(rawContent);
72+ const requests = await getPromptV2ContextRequests(ideMessenger, command);
73+
74+ expect(requests).toHaveLength(2);
75+ expect(requests[0].provider).toBe("file");
76+ expect(requests[0].query).toBe(`${firstDir}/file1.txt`);
77+ expect(requests[1].provider).toBe("file");
78+ expect(requests[1].query).toBe(`${firstDir}/file2.txt`);
79+ });
80+});
added gui/src/components/mainInput/TipTapEditor/utils/renderPromptv2.ts +69 −0
@@ -0,0 +1,69 @@
1+import { SlashCommandDescWithSource } from "core";
2+import { SUPPORTED_PROMPT_CONTEXT_PROVIDERS } from "core/promptFiles";
3+import { resolveRelativePathInDir } from "core/util/ideUtils";
4+import { IIdeMessenger } from "../../../../context/IdeMessenger";
5+import { GetContextRequest } from "./types";
6+
7+export async function getPromptV2ContextRequests(
8+ ideMessenger: IIdeMessenger,
9+ command: SlashCommandDescWithSource,
10+): Promise<GetContextRequest[]> {
11+ if (!command.prompt) {
12+ return [];
13+ }
14+ const workspaceDirs = await ideMessenger.ide.getWorkspaceDirs();
15+ const visitedFiles = new Set<string>();
16+ if (command.promptFile) {
17+ visitedFiles.add(command.promptFile);
18+ }
19+
20+ const contextRequests: GetContextRequest[] = [];
21+
22+ async function addContextRequestsRecursive(promptBody: string) {
23+ // Files
24+ const templateMatches = promptBody.matchAll(/@([^\s]+)/g);
25+ for (const match of templateMatches) {
26+ const name = match[1];
27+
28+ if (SUPPORTED_PROMPT_CONTEXT_PROVIDERS.includes(name)) {
29+ contextRequests.push({
30+ provider: name,
31+ });
32+ continue;
33+ }
34+
35+ // URLs
36+ if (name.startsWith("http")) {
37+ contextRequests.push({
38+ provider: "url",
39+ query: name,
40+ });
41+ continue;
42+ }
43+
44+ // Files
45+ const resolvedFileUri = await resolveRelativePathInDir(
46+ match[1],
47+ ideMessenger.ide,
48+ workspaceDirs,
49+ );
50+ if (resolvedFileUri) {
51+ const contents = await ideMessenger.ide.readFile(resolvedFileUri);
52+ if (name.endsWith(".prompt")) {
53+ if (visitedFiles.has(resolvedFileUri)) {
54+ return [];
55+ }
56+ visitedFiles.add(resolvedFileUri);
57+ // As well as any context providers it references
58+ await addContextRequestsRecursive(contents);
59+ }
60+ contextRequests.push({
61+ provider: "file",
62+ query: resolvedFileUri,
63+ });
64+ }
65+ }
66+ }
67+ await addContextRequestsRecursive(command.prompt);
68+ return contextRequests;
69+}
added gui/src/components/mainInput/TipTapEditor/utils/renderSlashCommand.ts +145 −0
@@ -0,0 +1,145 @@
1+import { MessagePart, RangeInFile, SlashCommandDescWithSource } from "core";
2+import { stripImages } from "core/util/messageContent";
3+import { IIdeMessenger } from "../../../../context/IdeMessenger";
4+import { renderMcpPrompt } from "./renderMcpPrompt";
5+import { getRenderedV1Prompt } from "./renderPromptv1";
6+import { getPromptV2ContextRequests } from "./renderPromptv2";
7+import { GetContextRequest } from "./types";
8+
9+/*
10+Slash commands can come from many sources. Render based on the source.
11+*/
12+export async function renderSlashCommandPrompt(
13+ ideMessenger: IIdeMessenger,
14+ commandName: string | undefined,
15+ parts: MessagePart[],
16+ availableSlashCommands: SlashCommandDescWithSource[],
17+ selectedCode: RangeInFile[],
18+): Promise<{
19+ slashedParts: MessagePart[];
20+ legacyCommandWithInput?: {
21+ command: SlashCommandDescWithSource;
22+ input: string;
23+ };
24+ contextRequests: GetContextRequest[];
25+}> {
26+ const NO_COMMAND = {
27+ slashedParts: parts,
28+ legacyCommandWithInput: undefined,
29+ contextRequests: [],
30+ };
31+ if (!commandName) {
32+ return NO_COMMAND;
33+ }
34+ const command = availableSlashCommands.find((c) => c.name === commandName);
35+ if (!command) {
36+ return NO_COMMAND;
37+ }
38+
39+ const nonTextParts = parts.filter((part) => part.type !== "text");
40+ const textParts = parts.filter((part) => part.type === "text");
41+ const slashedParts: MessagePart[] = [...nonTextParts];
42+
43+ const userInput = stripImages(textParts).trimStart();
44+
45+ const legacyCommandWithInput = command.isLegacy
46+ ? {
47+ command,
48+ input: userInput,
49+ }
50+ : undefined;
51+
52+ const contextRequests: GetContextRequest[] = [];
53+
54+ switch (command.source) {
55+ case "built-in-legacy":
56+ case "config-ts-slash-command":
57+ /**
58+ * For legacy slash commands, we simply insert the text "/{name}" in front of the message
59+ * And then parsing for this is done in core
60+ */
61+ slashedParts.push({
62+ type: "text",
63+ text: `/${command.name}${command.prompt ? " " + command.prompt : ""}${userInput ? " " + userInput : ""}`,
64+ });
65+ break;
66+ case "mcp-prompt":
67+ const renderedMcpPrompt = await renderMcpPrompt(
68+ command,
69+ ideMessenger,
70+ userInput,
71+ );
72+ slashedParts.push({
73+ type: "text",
74+ text: renderedMcpPrompt,
75+ });
76+ break;
77+ case "prompt-file-v1":
78+ case "prompt-file-v2":
79+ case "yaml-prompt-block":
80+ case "invokable-rule":
81+ if (!command.prompt) {
82+ console.warn(`Invalid/empty prompt from slash command ${command.name}`);
83+ break;
84+ }
85+ let renderedPrompt: string;
86+ if (
87+ command.source === "prompt-file-v1" ||
88+ command.prompt.includes("{{{ input }}}")
89+ ) {
90+ renderedPrompt = await getRenderedV1Prompt(
91+ ideMessenger,
92+ command,
93+ userInput,
94+ selectedCode,
95+ );
96+ } else {
97+ const promptFileCtxRequests = await getPromptV2ContextRequests(
98+ ideMessenger,
99+ command,
100+ );
101+ contextRequests.push(...promptFileCtxRequests);
102+ renderedPrompt = [command.prompt, userInput].join("\n\n").trim();
103+ }
104+
105+ if (renderedPrompt) {
106+ slashedParts.push({
107+ type: "text",
108+ text: renderedPrompt, // Includes user input
109+ });
110+ } else {
111+ console.warn(
112+ `Invalid/empty prompt + input from slash command ${command.name}`,
113+ );
114+ }
115+
116+ break;
117+ case "built-in":
118+ case "json-custom-command":
119+ if (!command.prompt) {
120+ console.warn(`Slash command ${command.name} is missing prompt`);
121+ break;
122+ }
123+ let rendered = command.prompt;
124+ if (userInput) {
125+ rendered += `\n\n${userInput}`;
126+ }
127+ if (rendered) {
128+ slashedParts.push({
129+ type: "text",
130+ text: rendered,
131+ });
132+ } else {
133+ console.warn(
134+ `Invalid/empty prompt + input from slash command ${command.name}`,
135+ );
136+ }
137+ default:
138+ break;
139+ }
140+ return {
141+ slashedParts,
142+ legacyCommandWithInput,
143+ contextRequests,
144+ };
145+}
modified gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts +112 −226
@@ -1,7 +1,4 @@
11 import { Dispatch } from "@reduxjs/toolkit";
2-import Image from "@tiptap/extension-image";
3-import { Paragraph } from "@tiptap/extension-paragraph";
4-import { Text } from "@tiptap/extension-text";
52 import { JSONContent } from "@tiptap/react";
63 import {
74 ContextItemWithId,
@@ -10,44 +7,35 @@
107 MessageContent,
118 MessagePart,
129 RangeInFile,
13- SlashCommandDescription,
14- TextMessagePart,
10+ SlashCommandDescWithSource,
1511 } from "core";
16-import { ctxItemToRifWithContents } from "core/commands/util";
17-import { renderChatMessage, stripImages } from "core/util/messageContent";
18-import { getUriFileExtension } from "core/util/uri";
12+import { stripImages } from "core/util/messageContent";
1913 import { IIdeMessenger } from "../../../../context/IdeMessenger";
2014 import { setIsGatheringContext } from "../../../../redux/slices/sessionSlice";
21-import { CodeBlock, Mention, PromptBlock } from "../extensions";
22-
23-interface MentionAttrs {
24- label: string;
25- id: string;
26- itemType?: string;
27- query?: string;
28-}
15+import { processEditorContent } from "./processEditorContent";
16+import { renderSlashCommandPrompt } from "./renderSlashCommand";
17+import { GetContextRequest } from "./types";
2918
3019 interface ResolveEditorContentInput {
3120 editorState: JSONContent;
3221 modifiers: InputModifiers;
3322 ideMessenger: IIdeMessenger;
3423 defaultContextProviders: DefaultContextProvider[];
35- availableSlashCommands: SlashCommandDescription[];
24+ availableSlashCommands: SlashCommandDescWithSource[];
3625 dispatch: Dispatch;
3726 }
3827
39-type ResolveEditorContentOutput = [
40- ContextItemWithId[],
41- RangeInFile[],
42- MessageContent,
43- (
28+interface ResolveEditorContentOutput {
29+ selectedContextItems: ContextItemWithId[];
30+ selectedCode: RangeInFile[];
31+ content: MessageContent;
32+ legacyCommandWithInput:
4433 | {
45- command: SlashCommandDescription;
34+ command: SlashCommandDescWithSource;
4635 input: string;
4736 }
48- | undefined
49- ),
50-];
37+ | undefined;
38+}
5139
5240 /**
5341 * This function converts the input from the editor to a string, resolving any context items
@@ -61,26 +49,43 @@
6149 availableSlashCommands,
6250 dispatch,
6351 }: ResolveEditorContentInput): Promise<ResolveEditorContentOutput> {
64- const { parts, contextItemAttrs, selectedCode, slashCommandName } =
65- processEditorContent(editorState);
66-
67- const slashCommandWithInput = processSlashCommand(
52+ const {
53+ parts,
54+ contextRequests: editorContextRequests,
55+ selectedCode,
56+ slashCommandName,
57+ } = processEditorContent(editorState);
58+
59+ const {
60+ slashedParts,
61+ contextRequests: slashContextRequests,
62+ legacyCommandWithInput,
63+ } = await renderSlashCommandPrompt(
64+ ideMessenger,
6865 slashCommandName,
69- availableSlashCommands,
7066 parts,
67+ availableSlashCommands,
68+ selectedCode,
7169 );
7270
73- const shouldGatherContext = modifiers.useCodebase || slashCommandWithInput;
71+ const contextRequests = [...editorContextRequests, ...slashContextRequests];
72+
73+ const shouldGatherContext =
74+ defaultContextProviders.length > 0 ||
75+ modifiers.useCodebase ||
76+ !modifiers.noContext ||
77+ contextRequests.length > 0;
78+
7479 if (shouldGatherContext) {
7580 dispatch(setIsGatheringContext(true));
7681 }
7782
78- const contextItems = await gatherContextItems({
79- contextItemAttrs,
83+ const selectedContextItems = await gatherContextItems({
84+ contextRequests,
8085 modifiers,
8186 ideMessenger,
8287 defaultContextProviders,
83- parts,
88+ parts: slashedParts,
8489 selectedCode,
8590 });
8691
@@ -88,140 +93,11 @@
8893 dispatch(setIsGatheringContext(false));
8994 }
9095
91- return [contextItems, selectedCode, parts, slashCommandWithInput];
92-}
93-
94-/**
95- * Processes editor content and extracts parts, context items, code, and slash commands
96- */
97-function processEditorContent(editorState: JSONContent) {
98- const contextItemAttrs: MentionAttrs[] = [];
99- const selectedCode: RangeInFile[] = [];
100- let slashCommandName: string | undefined;
101-
102- const parts = (editorState?.content || []).reduce<MessagePart[]>(
103- (parts, p) => {
104- switch (p.type) {
105- case PromptBlock.name: {
106- slashCommandName = resvolePromptBlock(p);
107- }
108-
109- case Paragraph.name: {
110- const [text, ctxItems] = resolveParagraph(p);
111-
112- contextItemAttrs.push(...ctxItems);
113-
114- if (!text) return parts;
115-
116- // Merge with previous text part if possible
117- if (parts[parts.length - 1]?.type === "text") {
118- (parts[parts.length - 1] as TextMessagePart).text += "\n" + text;
119- return parts;
120- }
121-
122- return [...parts, { type: "text", text }];
123- }
124-
125- case CodeBlock.name: {
126- if (!p.attrs?.item) {
127- console.warn("codeBlock has no item attribute");
128- return parts;
129- }
130-
131- const contextItem = p.attrs.item as ContextItemWithId;
132- const rif = ctxItemToRifWithContents(contextItem, true);
133- selectedCode.push(rif);
134-
135- // If editing, only include in selectedCode
136- if (contextItem.editing) {
137- return parts;
138- }
139-
140- const fileExtension = getUriFileExtension(rif.filepath);
141- const codeText = [
142- "\n\n```",
143- fileExtension,
144- " ",
145- contextItem.description,
146- "\n",
147- contextItem.content,
148- "\n```",
149- ].join("");
150-
151- if (parts[parts.length - 1]?.type === "text") {
152- (parts[parts.length - 1] as TextMessagePart).text +=
153- "\n" + codeText;
154- return parts;
155- }
156-
157- return [...parts, { type: "text", text: codeText }];
158- }
159-
160- case Image.name: {
161- return [
162- ...parts,
163- {
164- type: "imageUrl",
165- imageUrl: { url: p.attrs?.src },
166- },
167- ];
168- }
169-
170- default: {
171- console.warn("Unexpected content type", p.type);
172- return parts;
173- }
174- }
175- },
176- [],
177- );
178-
179- return { parts, contextItemAttrs, selectedCode, slashCommandName };
180-}
181-
182-/**
183- * Processes slash commands and prepares the command with input
184- */
185-function processSlashCommand(
186- slashCommandName: string | undefined,
187- availableSlashCommands: SlashCommandDescription[],
188- parts: MessagePart[],
189-): { command: SlashCommandDescription; input: string } | undefined {
190- if (!slashCommandName) return;
191-
192- const command = availableSlashCommands.find(
193- (c) => c.name === slashCommandName,
194- );
195-
196- if (!command) return;
197-
198- const lastTextIndex = findLastIndex(parts, (part) => part.type === "text");
199- const lastTextPart = parts[lastTextIndex] as TextMessagePart;
200-
201- const originalPrompt = command.prompt ? " " + command.prompt : "";
202-
203- let input: string;
204-
205- /**
206- * Although we no longer render slash command <span /> tags from the editor,
207- * we are inserting a slash command style text back into the text here.
208- * This is a a hack, but there's a number of assumptions in `core` that there
209- * is slash command text at the beginning of the text in order to process slash commands.
210- */
211- if (lastTextPart) {
212- input = renderChatMessage({
213- role: "user",
214- content: lastTextPart.text,
215- }).trimStart();
216- lastTextPart.text = `/${command.name}${originalPrompt} ${lastTextPart.text}`;
217- } else {
218- input = "";
219- parts.push({ type: "text", text: `/${command.name}${originalPrompt}` });
220- }
221-
22296 return {
223- command,
224- input,
97+ selectedContextItems,
98+ selectedCode,
99+ content: slashedParts,
100+ legacyCommandWithInput,
225101 };
226102 }
227103
@@ -229,26 +105,44 @@
229105 * Gathers context items from various sources
230106 */
231107 async function gatherContextItems({
232- contextItemAttrs,
108+ contextRequests,
233109 modifiers,
234110 ideMessenger,
235111 defaultContextProviders,
236112 parts,
237113 selectedCode,
238114 }: {
239- contextItemAttrs: MentionAttrs[];
115+ contextRequests: GetContextRequest[];
240116 modifiers: InputModifiers;
241117 ideMessenger: IIdeMessenger;
242118 defaultContextProviders: DefaultContextProvider[];
243119 parts: MessagePart[];
244120 selectedCode: RangeInFile[];
245121 }): Promise<ContextItemWithId[]> {
122+ const defaultRequests: GetContextRequest[] = defaultContextProviders.map(
123+ (def) => ({
124+ provider: def.name,
125+ query: def.query,
126+ }),
127+ );
128+ const withDefaults = [...contextRequests, ...defaultRequests];
129+ const deduplicatedInputs = withDefaults.reduce<GetContextRequest[]>(
130+ (acc, item) => {
131+ if (
132+ !acc.some((i) => i.provider === item.provider && i.query === item.query)
133+ ) {
134+ acc.push(item);
135+ }
136+ return acc;
137+ },
138+ [],
139+ );
246140 let contextItems: ContextItemWithId[] = [];
247141
248142 // Process context item attributes
249- for (const item of contextItemAttrs) {
143+ for (const item of deduplicatedInputs) {
250144 const result = await ideMessenger.request("context/getContextItems", {
251- name: item.itemType === "contextProvider" ? item.id : item.itemType!,
145+ name: item.provider,
252146 query: item.query ?? "",
253147 fullInput: stripImages(parts),
254148 selectedCode,
@@ -259,7 +153,10 @@
259153 }
260154
261155 // cmd+enter to use codebase
262- if (modifiers.useCodebase) {
156+ if (
157+ modifiers.useCodebase &&
158+ !deduplicatedInputs.some((item) => item.provider === "codebase")
159+ ) {
263160 const result = await ideMessenger.request("context/getContextItems", {
264161 name: "codebase",
265162 query: "",
@@ -272,62 +169,51 @@
272169 }
273170 }
274171
275- // Include default context providers
276- const defaultContextItems = await Promise.all(
277- defaultContextProviders.map(async (provider) => {
278- const result = await ideMessenger.request("context/getContextItems", {
279- name: provider.name,
280- query: provider.query ?? "",
281- fullInput: stripImages(parts),
282- selectedCode,
283- });
284- if (result.status === "success") {
285- return result.content;
286- } else {
287- return [];
172+ // noContext modifier adds currently open file if it's not already present
173+ if (
174+ !modifiers.noContext &&
175+ !deduplicatedInputs.some((item) => item.provider === "currentFile")
176+ ) {
177+ const currentFileResponse = await ideMessenger.request(
178+ "context/getContextItems",
179+ {
180+ name: "currentFile",
181+ query: "non-mention-usage",
182+ fullInput: "",
183+ selectedCode: [],
184+ },
185+ );
186+ if (currentFileResponse.status === "success") {
187+ const currentFile = currentFileResponse.content[0];
188+ if (currentFile.uri?.value) {
189+ currentFile.id = {
190+ providerTitle: "file",
191+ itemId: currentFile.uri.value,
192+ };
193+ contextItems.unshift(currentFile);
288194 }
289- }),
290- );
291- contextItems.push(...defaultContextItems.flat());
292-
293- return contextItems;
294-}
295-
296-function findLastIndex<T>(
297- array: T[],
298- predicate: (value: T, index: number, obj: T[]) => boolean,
299-): number {
300- for (let i = array.length - 1; i >= 0; i--) {
301- if (predicate(array[i], i, array)) {
302- return i;
303195 }
304196 }
305- return -1; // if no element satisfies the predicate
306-}
307-
308-function resvolePromptBlock(p: JSONContent): string | undefined {
309- return p.attrs?.item.name;
310-}
311197
312-function resolveParagraph(p: JSONContent): [string, MentionAttrs[]] {
313- const contextItems: MentionAttrs[] = [];
314-
315- const text = (p.content || [])
316- .map((child) => {
317- switch (child.type) {
318- case Text.name:
319- return child.text;
320- case Mention.name:
321- contextItems.push(child.attrs as MentionAttrs);
322- return child.attrs?.renderInlineAs ?? child.attrs?.label;
323-
324- default:
325- console.warn("Unexpected child type", child.type);
326- return "";
198+ // Deduplicates based on either providerTitle + itemId or uri type + value
199+ const deduplicatedOutputs = contextItems.reduce<ContextItemWithId[]>(
200+ (acc, item) => {
201+ if (
202+ !acc.some(
203+ (i) =>
204+ (i.id.providerTitle === item.id.providerTitle &&
205+ i.id.itemId === item.id.itemId) ||
206+ (i.uri &&
207+ item.uri &&
208+ i.uri.type === item.uri.type &&
209+ i.uri.value === item.uri.value),
210+ )
211+ ) {
212+ acc.push(item);
327213 }
328- })
329- .join("")
330- .trimStart();
331-
332- return [text, contextItems];
214+ return acc;
215+ },
216+ [],
217+ );
218+ return deduplicatedOutputs;
333219 }
added gui/src/components/mainInput/TipTapEditor/utils/types.ts +4 −0
@@ -0,0 +1,4 @@
1+export interface GetContextRequest {
2+ provider: string;
3+ query?: string;
4+}
modified gui/src/context/MockIdeMessenger.ts +23 −1
@@ -18,6 +18,14 @@
1818 [K in keyof FromWebviewProtocol]: FromWebviewProtocol[K][1];
1919 }>;
2020
21+export type MockResponseHandler<T extends keyof FromWebviewProtocol> = (
22+ input: FromWebviewProtocol[T][0],
23+) => Promise<FromWebviewProtocol[T][1]>;
24+
25+type MockResponseHandlers = Partial<{
26+ [K in keyof FromWebviewProtocol]: MockResponseHandler<K>;
27+}>;
28+
2129 const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = {
2230 fileExists: true,
2331 getCurrentFile: {
@@ -66,6 +74,7 @@
6674 "chatDescriber/describe": "Session summary",
6775 applyToFile: undefined,
6876 acceptDiff: undefined,
77+ readFile: "File contents",
6978 };
7079
7180 const DEFAULT_CHAT_RESPONSE: ChatMessage[] = [
@@ -119,6 +128,7 @@
119128 }
120129
121130 responses: MockResponses = { ...DEFAULT_MOCK_CORE_RESPONSES };
131+ responseHandlers: MockResponseHandlers = {};
122132 chatResponse: ChatMessage[] = DEFAULT_CHAT_RESPONSE;
123133 chatStreamDelay: number = 0;
124134 setChatResponseText(text: string): void {
@@ -164,6 +174,14 @@
164174 messageType: T,
165175 data: FromWebviewProtocol[T][0],
166176 ): Promise<WebviewSingleProtocolMessage<T>> {
177+ if (this.responseHandlers[messageType]) {
178+ const content = await this.responseHandlers[messageType](data);
179+ return {
180+ status: "success",
181+ content,
182+ done: true,
183+ };
184+ }
167185 if (messageType in this.responses) {
168186 const content = this.responses[messageType];
169187 return {
@@ -173,7 +191,10 @@
173191 };
174192 }
175193 console.error(messageType);
176- throw new Error("MockIdeMessenger: No response defined for " + messageType);
194+ throw new Error(
195+ "MockIdeMessenger: No response handler or response defined for " +
196+ messageType,
197+ );
177198 }
178199
179200 respond<T extends keyof ToWebviewProtocol>(
@@ -195,6 +216,7 @@
195216
196217 resetMocks(): void {
197218 this.responses = { ...DEFAULT_MOCK_CORE_RESPONSES };
219+ this.responseHandlers = {};
198220 this.chatResponse = DEFAULT_CHAT_RESPONSE;
199221 this.chatStreamDelay = 0;
200222 }
modified gui/src/hooks/useBookmarkedSlashCommands.ts +2 −2
@@ -1,4 +1,4 @@
1-import { SlashCommandDescription } from "core";
1+import { SlashCommandDescWithSource } from "core";
22 import { usePostHog } from "posthog-js/react";
33
44 import { useAppDispatch, useAppSelector } from "../redux/hooks";
@@ -17,7 +17,7 @@
1717 return bookmarkedCommands.includes(commandName);
1818 };
1919
20- const toggleBookmark = (command: SlashCommandDescription) => {
20+ const toggleBookmark = (command: SlashCommandDescWithSource) => {
2121 const isBookmarked = isCommandBookmarked(command.name);
2222
2323 posthog.capture("toggle_bookmarked_slash_command", {
modified gui/src/redux/slices/configSlice.ts +1 −10
@@ -10,16 +10,7 @@
1010 };
1111
1212 export const EMPTY_CONFIG: BrowserSerializedContinueConfig = {
13- slashCommands: [
14- {
15- name: "share",
16- description: "Export the current chat session to markdown",
17- },
18- {
19- name: "cmd",
20- description: "Generate a shell command",
21- },
22- ],
13+ slashCommands: [],
2314 contextProviders: [],
2415 tools: [],
2516 mcpServerStatuses: [],
modified gui/src/redux/slices/profilesSlice.ts +2 −2
@@ -1,5 +1,5 @@
11 import { createSlice, PayloadAction } from "@reduxjs/toolkit";
2-import { SlashCommandDescription } from "core";
2+import { SlashCommandDescWithSource } from "core";
33 import { SerializedOrgWithProfiles } from "core/config/ProfileLifecycleManager";
44
55 const DEFAULT_SLASH_COMMANDS_BOOKMARKS_COUNT = 5;
@@ -81,7 +81,7 @@
8181 state,
8282 action: PayloadAction<{
8383 profileId: string;
84- defaultSlashCommands?: SlashCommandDescription[];
84+ defaultSlashCommands?: SlashCommandDescWithSource[];
8585 }>,
8686 ) => {
8787 const { profileId, defaultSlashCommands = [] } = action.payload;
modified gui/src/redux/thunks/edit.ts +14 −15
@@ -34,27 +34,26 @@
3434 },
3535 ThunkApiType
3636 >(
37- "chat/streamResponse",
37+ "edit/streamResponse",
3838 async ({ editorState, codeToEdit }, { dispatch, extra }) => {
3939 await dispatch(
4040 streamThunkWrapper(async () => {
4141 dispatch(setActive());
42- const [contextItems, __, userInstructions, _] =
43- await resolveEditorContent({
44- editorState,
45- modifiers: {
46- noContext: true,
47- useCodebase: false,
48- },
49- ideMessenger: extra.ideMessenger,
50- defaultContextProviders: [],
51- availableSlashCommands: [],
52- dispatch,
53- });
42+ const { selectedContextItems, content } = await resolveEditorContent({
43+ editorState,
44+ modifiers: {
45+ noContext: true,
46+ useCodebase: false,
47+ },
48+ ideMessenger: extra.ideMessenger,
49+ defaultContextProviders: [],
50+ availableSlashCommands: [],
51+ dispatch,
52+ });
5453
5554 const prompt = [
56- ...contextItems.map((item) => item.content),
57- stripImages(userInstructions),
55+ ...selectedContextItems.map((item) => item.content),
56+ stripImages(content),
5857 ].join("\n\n");
5958
6059 const response = await extra.ideMessenger.request("edit/sendPrompt", {
deleted gui/src/redux/thunks/gatherContext.ts +0 −124
@@ -1,124 +0,0 @@
1-import { createAsyncThunk } from "@reduxjs/toolkit";
2-import { JSONContent } from "@tiptap/core";
3-import {
4- ContextItemWithId,
5- InputModifiers,
6- MessageContent,
7- RangeInFile,
8- SlashCommandDescription,
9-} from "core";
10-import * as URI from "uri-js";
11-import { resolveEditorContent } from "../../components/mainInput/TipTapEditor";
12-import { selectSelectedChatModel } from "../slices/configSlice";
13-import { ThunkApiType } from "../store";
14-
15-export const gatherContext = createAsyncThunk<
16- {
17- selectedContextItems: ContextItemWithId[];
18- selectedCode: RangeInFile[];
19- content: MessageContent;
20- slashCommandWithInput:
21- | {
22- command: SlashCommandDescription;
23- input: string;
24- }
25- | undefined;
26- },
27- {
28- editorState: JSONContent;
29- modifiers: InputModifiers;
30- promptPreamble?: string;
31- },
32- ThunkApiType
33->(
34- "chat/gatherContext",
35- async (
36- { modifiers, editorState, promptPreamble },
37- { dispatch, extra, getState },
38- ) => {
39- const state = getState();
40- const selectedChatModel = selectSelectedChatModel(state);
41-
42- const defaultContextProviders =
43- state.config.config.experimental?.defaultContext ?? [];
44-
45- if (!selectedChatModel) {
46- console.error(
47- "gatherContext thunk: Cannot gather context, no model selected",
48- );
49- throw new Error("No chat model selected");
50- }
51-
52- // Resolve context providers and construct new history
53- let [selectedContextItems, selectedCode, content, slashCommandWithInput] =
54- await resolveEditorContent({
55- editorState,
56- modifiers,
57- ideMessenger: extra.ideMessenger,
58- defaultContextProviders,
59- availableSlashCommands: state.config.config.slashCommands,
60- dispatch,
61- });
62-
63- // Automatically use currently open file
64- if (!modifiers.noContext) {
65- const usingFreeTrial = false; // TODO no longer tracking free trial count, need to hook up to hub
66-
67- const currentFileResponse = await extra.ideMessenger.request(
68- "context/getContextItems",
69- {
70- name: "currentFile",
71- query: "non-mention-usage",
72- fullInput: "",
73- selectedCode: [],
74- },
75- );
76- if (currentFileResponse.status === "success") {
77- const items = currentFileResponse.content;
78- if (items.length > 0) {
79- const currentFile = items[0];
80- const uri = currentFile.uri?.value;
81-
82- // don't add the file if it's already in the context items
83- if (
84- uri &&
85- !selectedContextItems.find(
86- (item) => item.uri?.value && URI.equal(item.uri.value, uri),
87- )
88- ) {
89- // Limit to 1000 lines if using free trial
90- if (usingFreeTrial) {
91- currentFile.content = currentFile.content
92- .split("\n")
93- .slice(0, 1000)
94- .join("\n");
95- if (!currentFile.content.endsWith("```")) {
96- currentFile.content += "\n```";
97- }
98- }
99- currentFile.id = {
100- providerTitle: "file",
101- itemId: uri,
102- };
103- selectedContextItems.unshift(currentFile);
104- }
105- }
106- }
107- }
108-
109- if (promptPreamble) {
110- if (typeof content === "string") {
111- content = promptPreamble + content;
112- } else if (content[0].type === "text") {
113- content[0].text = promptPreamble + content[0].text;
114- }
115- }
116-
117- return {
118- selectedContextItems,
119- selectedCode,
120- content,
121- slashCommandWithInput,
122- };
123- },
124-);
modified gui/src/redux/thunks/streamResponse.ts +27 −20
@@ -5,6 +5,7 @@
55 import { getApplicableRules } from "core/llm/rules/getSystemMessageWithRules";
66 import posthog from "posthog-js";
77 import { v4 as uuidv4 } from "uuid";
8+import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent";
89 import { getBaseSystemMessage } from "../../util";
910 import { selectSelectedChatModel } from "../slices/configSlice";
1011 import {
@@ -13,7 +14,6 @@
1314 updateHistoryItemAtIndex,
1415 } from "../slices/sessionSlice";
1516 import { ThunkApiType } from "../store";
16-import { gatherContext } from "./gatherContext";
1717 import { resetStateForNewMessage } from "./resetStateForNewMessage";
1818 import { streamNormalInput } from "./streamNormalInput";
1919 import { streamThunkWrapper } from "./streamThunkWrapper";
@@ -25,15 +25,11 @@
2525 editorState: JSONContent;
2626 modifiers: InputModifiers;
2727 index?: number;
28- promptPreamble?: string;
2928 },
3029 ThunkApiType
3130 >(
3231 "chat/streamResponse",
33- async (
34- { editorState, modifiers, index, promptPreamble },
35- { dispatch, extra, getState },
36- ) => {
32+ async ({ editorState, modifiers, index }, { dispatch, extra, getState }) => {
3733 await dispatch(
3834 streamThunkWrapper(async () => {
3935 const state = getState();
@@ -49,19 +45,30 @@
4945 );
5046 resetStateForNewMessage();
5147
52- const result = await dispatch(
53- gatherContext({
54- editorState,
55- modifiers,
56- promptPreamble,
57- }),
58- );
48+ const defaultContextProviders =
49+ state.config.config.experimental?.defaultContext ?? [];
50+
51+ if (!selectedChatModel) {
52+ console.error(
53+ "gatherContext thunk: Cannot gather context, no model selected",
54+ );
55+ throw new Error("No chat model selected");
56+ }
57+
58+ // Resolve context providers and construct new history
5959 const {
6060 selectedContextItems,
6161 selectedCode,
6262 content,
63- slashCommandWithInput,
64- } = unwrapResult(result);
63+ legacyCommandWithInput,
64+ } = await resolveEditorContent({
65+ editorState,
66+ modifiers,
67+ ideMessenger: extra.ideMessenger,
68+ defaultContextProviders,
69+ availableSlashCommands: state.config.config.slashCommands,
70+ dispatch,
71+ });
6572
6673 // symbols for both context items AND selected codeblocks
6774 const filesForSymbols = [
@@ -133,9 +140,9 @@
133140 });
134141 posthog.capture("userInput", {});
135142
136- if (slashCommandWithInput) {
143+ if (legacyCommandWithInput) {
137144 posthog.capture("step run", {
138- step_name: slashCommandWithInput.command.name,
145+ step_name: legacyCommandWithInput.command.name,
139146 params: {},
140147 });
141148 }
@@ -144,12 +151,12 @@
144151 await dispatch(
145152 streamNormalInput({
146153 messages,
147- legacySlashCommandData: slashCommandWithInput
154+ legacySlashCommandData: legacyCommandWithInput
148155 ? {
149- command: slashCommandWithInput.command,
156+ command: legacyCommandWithInput.command,
150157 contextItems: selectedContextItems,
151158 historyIndex: inputIndex,
152- input: slashCommandWithInput.input,
159+ input: legacyCommandWithInput.input,
153160 selectedCode,
154161 }
155162 : undefined,