render prompt slash commands on client
This commit is contained in:
parent
2c352ea7c3
commit
5be8bf765c
25 changed files with 366 additions and 586 deletions
|
|
@ -1,51 +1,11 @@
|
|||
import { ContinueSDK, SlashCommandWithSource } from "../..";
|
||||
import { getDiffsFromCache } from "../../autocomplete/snippets/gitDiffCache";
|
||||
import { parsePromptFileV1V2 } from "../../promptFiles/v2/parsePromptFileV1V2";
|
||||
import { getLastNPathParts } from "../../util/uri";
|
||||
|
||||
import { getContextProviderHelpers } from "../../promptFiles/v1/getContextProviderHelpers";
|
||||
import { renderTemplatedString } from "../../promptFiles/v1/renderTemplatedString";
|
||||
|
||||
export function extractName(preamble: { name?: string }, path: string): string {
|
||||
return preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0];
|
||||
}
|
||||
|
||||
async function renderPromptV1(
|
||||
prompt: string,
|
||||
context: ContinueSDK,
|
||||
userInput: string,
|
||||
) {
|
||||
const helpers = getContextProviderHelpers(context);
|
||||
|
||||
const inputData: Record<string, string> = {
|
||||
input: userInput,
|
||||
};
|
||||
|
||||
// A few context providers that don't need to be in config.json to work in .prompt files
|
||||
if (helpers?.find((helper) => helper[0] === "diff")) {
|
||||
const diffs = await getDiffsFromCache(context.ide);
|
||||
inputData.diff = diffs.join("\n");
|
||||
}
|
||||
if (helpers?.find((helper) => helper[0] === "currentFile")) {
|
||||
const currentFile = await context.ide.getCurrentFile();
|
||||
if (currentFile) {
|
||||
inputData.currentFile = currentFile.path;
|
||||
}
|
||||
}
|
||||
|
||||
return renderTemplatedString(
|
||||
prompt,
|
||||
context.ide.readFile.bind(context.ide),
|
||||
inputData,
|
||||
helpers,
|
||||
);
|
||||
}
|
||||
import { SlashCommandWithSource } from "../..";
|
||||
import { parsePromptFile } from "../../promptFiles/parsePromptFile";
|
||||
|
||||
export function slashCommandFromPromptFileV1(
|
||||
path: string,
|
||||
content: string,
|
||||
): SlashCommandWithSource | null {
|
||||
const { name, description, systemMessage, prompt } = parsePromptFileV1V2(
|
||||
const { name, description, systemMessage, prompt } = parsePromptFile(
|
||||
path,
|
||||
content,
|
||||
);
|
||||
|
|
@ -54,7 +14,7 @@ export function slashCommandFromPromptFileV1(
|
|||
name,
|
||||
description,
|
||||
prompt,
|
||||
source: ".prompt-file",
|
||||
source: "prompt-file-v1",
|
||||
promptFile: path,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -47,7 +47,7 @@ import { LLMClasses, llmFromDescription } from "../llm/llms";
|
|||
import CustomLLMClass from "../llm/llms/CustomLLM";
|
||||
import { LLMReranker } from "../llm/llms/llm";
|
||||
import TransformersJsEmbeddingsProvider from "../llm/llms/TransformersJsEmbeddingsProvider";
|
||||
import { getAllPromptFiles } from "../promptFiles/v2/getPromptFiles";
|
||||
import { getAllPromptFiles } from "../promptFiles/getPromptFiles";
|
||||
import { copyOf } from "../util";
|
||||
import { GlobalContext } from "../util/GlobalContext";
|
||||
import mergeJson from "../util/merge";
|
||||
|
|
@ -64,6 +64,7 @@ import {
|
|||
import { localPathToUri } from "../util/pathToUri";
|
||||
|
||||
import { baseToolDefinitions } from "../tools";
|
||||
import { resolveRelativePathInDir } from "../util/ideUtils";
|
||||
import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
|
||||
import {
|
||||
getModelByRole,
|
||||
|
|
@ -252,7 +253,10 @@ async function intermediateToFinalConfig({
|
|||
loadPromptFiles?: boolean;
|
||||
}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
|
||||
const errors: ConfigValidationError[] = [];
|
||||
|
||||
const workspaceDirs = await ide.getWorkspaceDirs();
|
||||
const getUriFromPath = (path: string) => {
|
||||
return resolveRelativePathInDir(path, ide, workspaceDirs);
|
||||
};
|
||||
// Auto-detect models
|
||||
let models: BaseLLM[] = [];
|
||||
await Promise.all(
|
||||
|
|
@ -261,6 +265,7 @@ async function intermediateToFinalConfig({
|
|||
const llm = await llmFromDescription(
|
||||
desc,
|
||||
ide.readFile.bind(ide),
|
||||
getUriFromPath,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
|
|
@ -282,6 +287,7 @@ async function intermediateToFinalConfig({
|
|||
title: modelName,
|
||||
},
|
||||
ide.readFile.bind(ide),
|
||||
getUriFromPath,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
|
|
@ -358,6 +364,7 @@ async function intermediateToFinalConfig({
|
|||
const llm = await llmFromDescription(
|
||||
desc,
|
||||
ide.readFile.bind(ide),
|
||||
getUriFromPath,
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
|
|
@ -985,7 +992,6 @@ async function loadContinueConfigFromJson(
|
|||
|
||||
export {
|
||||
finalToBrowserConfig,
|
||||
intermediateToFinalConfig,
|
||||
loadContinueConfigFromJson,
|
||||
type BrowserSerializedContinueConfig,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ import FileContextProvider from "../../context/providers/FileContextProvider";
|
|||
import { contextProviderClassFromName } from "../../context/providers/index";
|
||||
import { ControlPlaneClient } from "../../control-plane/client";
|
||||
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
|
||||
import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles";
|
||||
import { getAllPromptFiles } from "../../promptFiles/getPromptFiles";
|
||||
import { GlobalContext } from "../../util/GlobalContext";
|
||||
import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
|
||||
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ import { CodebaseIndexer } from "./indexing/CodebaseIndexer";
|
|||
import DocsService from "./indexing/docs/DocsService";
|
||||
import { countTokens } from "./llm/countTokens";
|
||||
import Ollama from "./llm/llms/Ollama";
|
||||
import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile";
|
||||
import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile";
|
||||
import { callTool } from "./tools/callTool";
|
||||
import { ChatDescriber } from "./util/chatDescriber";
|
||||
import { clipboardCache } from "./util/clipboardCache";
|
||||
|
|
|
|||
3
core/index.d.ts
vendored
3
core/index.d.ts
vendored
|
|
@ -861,7 +861,8 @@ export type SlashCommandSource =
|
|||
| "config-ts-slash-command"
|
||||
| "yaml-prompt-block"
|
||||
| "mcp-prompt"
|
||||
| ".prompt-file"
|
||||
| "prompt-file-v1"
|
||||
| "prompt-file-v2"
|
||||
| "invokable-rule";
|
||||
|
||||
export interface SlashCommandDescWithSource extends SlashCommandDescription {
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import {
|
|||
JSONModelDescription,
|
||||
LLMOptions,
|
||||
} from "../..";
|
||||
import { renderTemplatedString } from "../../promptFiles/v1/renderTemplatedString";
|
||||
import { renderTemplatedString } from "../../util/handlebars/renderTemplatedString";
|
||||
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../constructMessages";
|
||||
import { BaseLLM } from "../index";
|
||||
|
||||
|
|
@ -121,6 +121,7 @@ export const LLMClasses = [
|
|||
export async function llmFromDescription(
|
||||
desc: JSONModelDescription,
|
||||
readFile: (filepath: string) => Promise<string>,
|
||||
getUriFromPath: (path: string) => Promise<string | undefined>,
|
||||
uniqueId: string,
|
||||
ideSettings: IdeSettings,
|
||||
llmLogger: ILLMLogger,
|
||||
|
|
@ -143,8 +144,10 @@ export async function llmFromDescription(
|
|||
baseChatSystemMessage += "\n\n";
|
||||
baseChatSystemMessage += await renderTemplatedString(
|
||||
desc.systemMessage,
|
||||
readFile,
|
||||
{},
|
||||
[],
|
||||
readFile,
|
||||
getUriFromPath,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { IDE } from "../..";
|
||||
import { GlobalContext } from "../../util/GlobalContext";
|
||||
import { joinPathsToUri } from "../../util/uri";
|
||||
import { IDE } from "..";
|
||||
import { GlobalContext } from "../util/GlobalContext";
|
||||
import { joinPathsToUri } from "../util/uri";
|
||||
|
||||
const FIRST_TIME_DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file
|
||||
# It is used to define and reuse prompts within Continue
|
||||
|
|
@ -1,10 +1,9 @@
|
|||
import { IDE } from "../..";
|
||||
import { walkDir } from "../../indexing/walkDir";
|
||||
import { readAllGlobalPromptFiles } from "../../util/paths";
|
||||
import { joinPathsToUri } from "../../util/uri";
|
||||
import { DEFAULT_PROMPTS_FOLDER_V1 } from "../v1";
|
||||
import { DEFAULT_PROMPTS_FOLDER_V1, DEFAULT_PROMPTS_FOLDER_V2 } from ".";
|
||||
import { IDE } from "..";
|
||||
import { walkDir } from "../indexing/walkDir";
|
||||
import { readAllGlobalPromptFiles } from "../util/paths";
|
||||
import { joinPathsToUri } from "../util/uri";
|
||||
|
||||
export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts";
|
||||
export async function getPromptFilesFromDir(
|
||||
ide: IDE,
|
||||
dir: string,
|
||||
19
core/promptFiles/index.ts
Normal file
19
core/promptFiles/index.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import { ContextProviderName } from "..";
|
||||
|
||||
export const DEFAULT_PROMPTS_FOLDER_V1 = ".prompts";
|
||||
export const DEFAULT_PROMPTS_FOLDER_V2 = ".continue/prompts";
|
||||
|
||||
export const SUPPORTED_PROMPT_CONTEXT_PROVIDERS: ContextProviderName[] = [
|
||||
"file",
|
||||
"clipboard",
|
||||
"repo-map",
|
||||
"currentFile",
|
||||
"os",
|
||||
"problems",
|
||||
"codebase",
|
||||
"tree",
|
||||
"open",
|
||||
"debugger",
|
||||
"terminal",
|
||||
"diff",
|
||||
];
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
import * as YAML from "yaml";
|
||||
|
||||
import { getLastNPathParts } from "../../util/uri";
|
||||
import { getLastNPathParts } from "../util/uri";
|
||||
|
||||
export function parsePromptFileV1V2(path: string, content: string) {
|
||||
export function parsePromptFile(path: string, content: string) {
|
||||
let [preambleRaw, prompt] = content.split("\n---\n");
|
||||
if (prompt === undefined) {
|
||||
prompt = preambleRaw;
|
||||
|
|
@ -1,16 +1,12 @@
|
|||
import { ContextProviderExtras, ILLM, RangeInFile } from "../..";
|
||||
import { testConfigHandler, testIde } from "../../test/fixtures";
|
||||
import {
|
||||
addToTestDir,
|
||||
setUpTestDir,
|
||||
tearDownTestDir,
|
||||
} from "../../test/testDir";
|
||||
import { renderPromptFileV2 } from "./renderPromptFile";
|
||||
import { ContextProviderExtras, ILLM, RangeInFile } from "..";
|
||||
import { testConfigHandler, testIde } from "../test/fixtures";
|
||||
import { addToTestDir, setUpTestDir, tearDownTestDir } from "../test/testDir";
|
||||
import { renderPromptFileV2 } from "./renderV2";
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock(
|
||||
import("../../context/providers/URLContextProvider"),
|
||||
import("../context/providers/URLContextProvider"),
|
||||
async (importOriginal) => {
|
||||
const actual = await importOriginal();
|
||||
return {
|
||||
|
|
@ -1,38 +0,0 @@
|
|||
import Handlebars from "handlebars";
|
||||
import { ContextItem, ContinueSDK, IContextProvider } from "../..";
|
||||
|
||||
function createContextItem(item: ContextItem, provider: IContextProvider) {
|
||||
return {
|
||||
...item,
|
||||
id: {
|
||||
itemId: item.description,
|
||||
providerTitle: provider.description.title,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function getContextProviderHelpers(
|
||||
context: ContinueSDK,
|
||||
): Array<[string, Handlebars.HelperDelegate]> | undefined {
|
||||
return context.config.contextProviders?.map((provider: IContextProvider) => [
|
||||
provider.description.title,
|
||||
async (helperContext: any) => {
|
||||
const items = await provider.getContextItems(helperContext, {
|
||||
config: context.config,
|
||||
embeddingsProvider: context.config.selectedModelByRole.embed,
|
||||
fetch: context.fetch,
|
||||
fullInput: context.input,
|
||||
ide: context.ide,
|
||||
llm: context.llm,
|
||||
reranker: context.config.selectedModelByRole.rerank,
|
||||
selectedCode: context.selectedCode,
|
||||
});
|
||||
|
||||
items.forEach((item) =>
|
||||
context.addContextItem(createContextItem(item, provider)),
|
||||
);
|
||||
|
||||
return items.map((item) => item.content).join("\n\n");
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
|
@ -1 +0,0 @@
|
|||
export const DEFAULT_PROMPTS_FOLDER_V1 = ".prompts";
|
||||
|
|
@ -1,64 +0,0 @@
|
|||
import { ChatMessage } from "../..";
|
||||
|
||||
export function replaceSlashCommandWithPromptInChatHistory(
|
||||
history: ChatMessage[],
|
||||
commandName: string,
|
||||
renderedPrompt: string,
|
||||
systemMessageOverride?: string,
|
||||
): ChatMessage[] {
|
||||
const messages = [...history];
|
||||
|
||||
for (let i = messages.length - 1; i >= 0; i--) {
|
||||
const { role, content } = messages[i];
|
||||
if (role !== "user") {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Array.isArray(content)) {
|
||||
if (
|
||||
content.some(
|
||||
(part) =>
|
||||
part.type === "text" && part.text?.startsWith(`/${commandName}`),
|
||||
)
|
||||
) {
|
||||
messages[i] = updateArrayContent(
|
||||
messages[i],
|
||||
commandName,
|
||||
renderedPrompt,
|
||||
);
|
||||
break;
|
||||
}
|
||||
} else if (
|
||||
typeof content === "string" &&
|
||||
content.startsWith(`/${commandName}`)
|
||||
) {
|
||||
messages[i] = { ...messages[i], content: renderedPrompt };
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (systemMessageOverride) {
|
||||
if (messages[0]?.role === "system") {
|
||||
messages[0].content = systemMessageOverride;
|
||||
} else {
|
||||
messages.unshift({ role: "system", content: systemMessageOverride });
|
||||
}
|
||||
}
|
||||
|
||||
return messages;
|
||||
}
|
||||
|
||||
function updateArrayContent(
|
||||
message: any,
|
||||
commandName: string,
|
||||
renderedPrompt: string,
|
||||
) {
|
||||
return {
|
||||
...message,
|
||||
content: message.content.map((part: any) =>
|
||||
part.text?.startsWith(`/${commandName}`)
|
||||
? { ...part, text: renderedPrompt }
|
||||
: part,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
|
@ -1,34 +0,0 @@
|
|||
import * as YAML from "yaml";
|
||||
|
||||
import { getLastNPathParts } from "../../util/uri";
|
||||
|
||||
export function extractName(preamble: { name?: string }, path: string): string {
|
||||
return preamble.name ?? getLastNPathParts(path, 1).split(".prompt")[0];
|
||||
}
|
||||
|
||||
export function getPreambleAndBody(content: string): [string, string] {
|
||||
let [preamble, body] = content.split("\n---\n");
|
||||
if (body === undefined) {
|
||||
// This means there is no preamble
|
||||
body = preamble;
|
||||
preamble = "";
|
||||
}
|
||||
return [preamble, body];
|
||||
}
|
||||
|
||||
export function parsePreamble(
|
||||
path: string,
|
||||
content: string,
|
||||
): { [key: string]: any; name: string; description: string } {
|
||||
const [preambleRaw, _] = getPreambleAndBody(content);
|
||||
|
||||
const preamble = YAML.parse(preambleRaw) ?? {};
|
||||
const name = extractName(preamble, path);
|
||||
const description = preamble.description ?? name;
|
||||
|
||||
return {
|
||||
...preamble,
|
||||
name,
|
||||
description,
|
||||
};
|
||||
}
|
||||
|
|
@ -1,84 +0,0 @@
|
|||
import { ContextItem, ContextProviderExtras } from "../..";
|
||||
import { contextProviderClassFromName } from "../../context/providers";
|
||||
import { getUrlContextItems } from "../../context/providers/URLContextProvider";
|
||||
import { resolveRelativePathInDir } from "../../util/ideUtils";
|
||||
import { getUriPathBasename } from "../../util/uri";
|
||||
|
||||
import { getPreambleAndBody } from "./parse";
|
||||
|
||||
async function resolveAttachment(
|
||||
name: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
// Context providers
|
||||
const contextProvider = extras.config.contextProviders?.find(
|
||||
(provider) => provider.description.title === name,
|
||||
);
|
||||
if (contextProvider) {
|
||||
const items = await contextProvider.getContextItems("", extras);
|
||||
return items;
|
||||
} else {
|
||||
// Just instantiate it here
|
||||
const providerClass = contextProviderClassFromName(name) as any;
|
||||
if (providerClass) {
|
||||
const providerInstance = new providerClass({});
|
||||
return providerInstance.getContextItems("", extras);
|
||||
}
|
||||
}
|
||||
|
||||
// Files
|
||||
const resolvedFileUri = await resolveRelativePathInDir(name, extras.ide);
|
||||
if (resolvedFileUri) {
|
||||
let subItems: ContextItem[] = [];
|
||||
if (name.endsWith(".prompt")) {
|
||||
// Recurse
|
||||
const [items, _] = await renderPromptFileV2(
|
||||
await extras.ide.readFile(resolvedFileUri),
|
||||
extras,
|
||||
);
|
||||
subItems.push(...items);
|
||||
}
|
||||
|
||||
const content = `\`\`\`${name}\n${await extras.ide.readFile(resolvedFileUri)}\n\`\`\``;
|
||||
return [
|
||||
...subItems,
|
||||
{
|
||||
name: getUriPathBasename(resolvedFileUri),
|
||||
content,
|
||||
description: resolvedFileUri,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
// URLs
|
||||
if (name.startsWith("http")) {
|
||||
const items = getUrlContextItems(name, extras.fetch);
|
||||
return items;
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
export async function renderPromptFileV2(
|
||||
rawContent: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<[ContextItem[], string]> {
|
||||
const [_, body] = getPreambleAndBody(rawContent);
|
||||
|
||||
const contextItemsPromises: Promise<ContextItem[]>[] = [];
|
||||
const renderedBody = body.replace(/@([^\s]+)/g, (match, name) => {
|
||||
contextItemsPromises.push(resolveAttachment(name, extras));
|
||||
return match;
|
||||
});
|
||||
|
||||
const contextItems = (await Promise.all(contextItemsPromises)).flat();
|
||||
const renderedPrompt = [
|
||||
...contextItems.map((item) => item.content),
|
||||
renderedBody,
|
||||
extras.fullInput,
|
||||
]
|
||||
.join("\n\n")
|
||||
.trim();
|
||||
|
||||
return [contextItems, renderedPrompt];
|
||||
}
|
||||
|
|
@ -18,6 +18,11 @@
|
|||
"noEmitOnError": false,
|
||||
"types": ["jest", "node"]
|
||||
},
|
||||
"include": ["./**/*.ts", "./**/*.js", "./**/*.d.ts"],
|
||||
"include": [
|
||||
"./**/*.ts",
|
||||
"./**/*.js",
|
||||
"./**/*.d.ts",
|
||||
"../gui/src/components/mainInput/TipTapEditor/utils/renderPromptv2.ts"
|
||||
],
|
||||
"exclude": ["dist"]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,45 +11,6 @@ function convertToLetter(num: number): string {
|
|||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* We replace filepaths with alphabetic characters to handle
|
||||
* escaping issues.
|
||||
*/
|
||||
const replaceFilepaths = (
|
||||
value: string,
|
||||
ctxProviderNames: string[],
|
||||
): [string, { [key: string]: string }] => {
|
||||
const ast = Handlebars.parse(value);
|
||||
|
||||
const keysToFilepath: { [key: string]: string } = {};
|
||||
|
||||
let keyIndex = 1;
|
||||
|
||||
for (const i in ast.body) {
|
||||
const node = ast.body[i] as any;
|
||||
|
||||
if (node.type === "MustacheStatement") {
|
||||
const originalNodeVal = node.path.original;
|
||||
const isFilepath = !ctxProviderNames.includes(originalNodeVal);
|
||||
|
||||
if (isFilepath) {
|
||||
const letter = convertToLetter(keyIndex);
|
||||
|
||||
keysToFilepath[letter] = originalNodeVal;
|
||||
|
||||
value = value.replace(
|
||||
new RegExp(`{{\\s*${originalNodeVal}\\s*}}`),
|
||||
`{{${letter}}}`,
|
||||
);
|
||||
|
||||
keyIndex++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [value, keysToFilepath];
|
||||
};
|
||||
|
||||
export function registerHelpers(
|
||||
helpers: Array<[string, Handlebars.HelperDelegate]>,
|
||||
): {
|
||||
|
|
@ -68,39 +29,66 @@ export function registerHelpers(
|
|||
return promises;
|
||||
}
|
||||
|
||||
export async function prepareTemplateAndData(
|
||||
export async function prepareTemplatedFilepaths(
|
||||
template: string,
|
||||
readFile: (filepath: string) => Promise<string>,
|
||||
inputData: Record<string, string>,
|
||||
ctxProviderNames: string[],
|
||||
): Promise<[string, any]> {
|
||||
const [newTemplate, vars] = replaceFilepaths(template, ctxProviderNames);
|
||||
readFile: (filepath: string) => Promise<string>,
|
||||
getUriFromPath: (path: string) => Promise<string | undefined>,
|
||||
) {
|
||||
// First, replace filepaths with letters to avoid escaping issues
|
||||
const ast = Handlebars.parse(template);
|
||||
|
||||
const data: any = { ...inputData };
|
||||
const filepathLetters: Map<string, string> = new Map();
|
||||
const requiredContextProviders: Set<string> = new Set();
|
||||
let withLetterKeys = template;
|
||||
|
||||
for (const [replacedName, originalCtxProviderName] of Object.entries(vars)) {
|
||||
data[replacedName] =
|
||||
inputData[originalCtxProviderName] ?? originalCtxProviderName;
|
||||
let letterIndex = 1;
|
||||
|
||||
// If it's not a context provider, assume it's a filepath.
|
||||
if (!ctxProviderNames.includes(originalCtxProviderName)) {
|
||||
const fileContents = await readFile(vars[replacedName]);
|
||||
for (const i in ast.body) {
|
||||
const node = ast.body[i] as any;
|
||||
|
||||
if (fileContents) {
|
||||
data[replacedName] = fileContents;
|
||||
if (node.type === "MustacheStatement") {
|
||||
const originalNodeVal = node.path.original;
|
||||
const isFilepath = !ctxProviderNames.includes(originalNodeVal);
|
||||
|
||||
if (isFilepath) {
|
||||
const letter = convertToLetter(letterIndex);
|
||||
|
||||
filepathLetters.set(letter, originalNodeVal);
|
||||
|
||||
withLetterKeys = withLetterKeys.replace(
|
||||
new RegExp(`{{\\s*${originalNodeVal}\\s*}}`),
|
||||
`{{${letter}}}`,
|
||||
);
|
||||
|
||||
letterIndex++;
|
||||
} else {
|
||||
requiredContextProviders.add(originalNodeVal);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [newTemplate, data];
|
||||
}
|
||||
// Then, resolve the filepaths to their actual content and add to template data
|
||||
// Fallback to simple error string if file read fails
|
||||
const templateData = { ...inputData };
|
||||
|
||||
export function compileAndRenderTemplate(
|
||||
template: string,
|
||||
data: Record<string, string>,
|
||||
): string {
|
||||
const templateFn = Handlebars.compile(template);
|
||||
return templateFn(data);
|
||||
for (const [letter, filepath] of filepathLetters.entries()) {
|
||||
try {
|
||||
const uri = await getUriFromPath(filepath);
|
||||
if (uri) {
|
||||
const fileContents = await readFile(uri);
|
||||
templateData[letter] = fileContents;
|
||||
} else {
|
||||
throw new Error(`File not found: ${filepath}`);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(`Error reading file in prompt file ${filepath}:`, e);
|
||||
templateData[letter] = `[Error reading file ${filepath}]`;
|
||||
}
|
||||
}
|
||||
|
||||
return { withLetterKeys, templateData, requiredContextProviders };
|
||||
}
|
||||
|
||||
export async function resolveHelperPromises(
|
||||
|
|
@ -1,15 +1,15 @@
|
|||
import {
|
||||
compileAndRenderTemplate,
|
||||
prepareTemplateAndData,
|
||||
prepareTemplatedFilepaths,
|
||||
registerHelpers,
|
||||
resolveHelperPromises,
|
||||
} from "./handlebarUtils";
|
||||
|
||||
export async function renderTemplatedString(
|
||||
template: string,
|
||||
readFile: (filepath: string) => Promise<string>,
|
||||
inputData: Record<string, string>,
|
||||
availableHelpers?: Array<[string, Handlebars.HelperDelegate]>,
|
||||
availableHelpers: Array<[string, Handlebars.HelperDelegate]>,
|
||||
readFile: (filepath: string) => Promise<string>,
|
||||
getUriFromPath: (path: string) => Promise<string | undefined>,
|
||||
): Promise<string> {
|
||||
const helperPromises = availableHelpers
|
||||
? registerHelpers(availableHelpers)
|
||||
|
|
@ -17,14 +17,16 @@ export async function renderTemplatedString(
|
|||
|
||||
const ctxProviderNames = availableHelpers?.map((h) => h[0]) ?? [];
|
||||
|
||||
const [newTemplate, data] = await prepareTemplateAndData(
|
||||
const { withLetterKeys, templateData } = await prepareTemplatedFilepaths(
|
||||
template,
|
||||
readFile,
|
||||
inputData,
|
||||
ctxProviderNames,
|
||||
readFile,
|
||||
getUriFromPath,
|
||||
);
|
||||
|
||||
let renderedString = compileAndRenderTemplate(newTemplate, data);
|
||||
const templateFn = Handlebars.compile(withLetterKeys);
|
||||
const renderedString = templateFn(templateData);
|
||||
|
||||
return resolveHelperPromises(renderedString, helperPromises);
|
||||
}
|
||||
|
|
@ -0,0 +1,49 @@
|
|||
import {
|
||||
ContextProviderName,
|
||||
RangeInFile,
|
||||
SlashCommandDescWithSource,
|
||||
} from "core";
|
||||
import { SUPPORTED_PROMPT_CONTEXT_PROVIDERS } from "core/promptFiles";
|
||||
import { renderTemplatedString } from "core/util/handlebars/renderTemplatedString";
|
||||
import { resolveRelativePathInDir } from "core/util/ideUtils";
|
||||
import { IIdeMessenger } from "../../../../context/IdeMessenger";
|
||||
|
||||
export async function getRenderedV1Prompt(
|
||||
ideMessenger: IIdeMessenger,
|
||||
command: SlashCommandDescWithSource,
|
||||
userInput: string,
|
||||
selectedCode: RangeInFile[],
|
||||
): Promise<string> {
|
||||
if (!command.prompt) {
|
||||
return "";
|
||||
}
|
||||
const handleBarHelpers = SUPPORTED_PROMPT_CONTEXT_PROVIDERS.map(
|
||||
(name: ContextProviderName): [string, Handlebars.HelperDelegate] => [
|
||||
name,
|
||||
async (helperContext: any) => {
|
||||
const response = await ideMessenger.request("context/getContextItems", {
|
||||
fullInput: userInput,
|
||||
name,
|
||||
query: "",
|
||||
selectedCode,
|
||||
});
|
||||
if (response.status === "success") {
|
||||
return response.content.join("\n\n");
|
||||
} else {
|
||||
throw new Error(`Failed to get context items from provider: ${name}`);
|
||||
}
|
||||
},
|
||||
],
|
||||
);
|
||||
const workspaceDirs = await ideMessenger.ide.getWorkspaceDirs();
|
||||
const getUriFromPath = (path: string) => {
|
||||
return resolveRelativePathInDir(path, ideMessenger.ide, workspaceDirs);
|
||||
};
|
||||
return await renderTemplatedString(
|
||||
command.prompt,
|
||||
{ input: userInput },
|
||||
handleBarHelpers,
|
||||
ideMessenger.ide.readFile.bind(ideMessenger.ide),
|
||||
getUriFromPath,
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,71 @@
|
|||
import { SlashCommandDescWithSource } from "core";
|
||||
import { SUPPORTED_PROMPT_CONTEXT_PROVIDERS } from "core/promptFiles";
|
||||
import { resolveRelativePathInDir } from "core/util/ideUtils";
|
||||
import { IIdeMessenger } from "../../../../context/IdeMessenger";
|
||||
import { MentionAttrs } from "./types";
|
||||
|
||||
export async function getPromptV2ContextAttrs(
|
||||
ideMessenger: IIdeMessenger,
|
||||
command: SlashCommandDescWithSource,
|
||||
): Promise<MentionAttrs[]> {
|
||||
if (!command.prompt) {
|
||||
return [];
|
||||
}
|
||||
const workspaceDirs = await ideMessenger.ide.getWorkspaceDirs();
|
||||
const visitedFiles = new Set<string>();
|
||||
if (command.promptFile) {
|
||||
visitedFiles.add(command.promptFile);
|
||||
}
|
||||
|
||||
const contextItemAttrs: MentionAttrs[] = [];
|
||||
const addItem = (item: MentionAttrs) => {
|
||||
contextItemAttrs.push(item);
|
||||
};
|
||||
|
||||
async function addContextAttrsRecursive(promptBody: string) {
|
||||
// Files
|
||||
for (const match of promptBody.matchAll(/@([^\s]+)/g)) {
|
||||
const name = match[0];
|
||||
const resolvedFileUri = await resolveRelativePathInDir(
|
||||
match[0],
|
||||
ideMessenger.ide,
|
||||
workspaceDirs,
|
||||
);
|
||||
if (resolvedFileUri) {
|
||||
const contents = await ideMessenger.ide.readFile(resolvedFileUri);
|
||||
if (name.endsWith(".prompt")) {
|
||||
if (visitedFiles.has(resolvedFileUri)) {
|
||||
return [];
|
||||
}
|
||||
visitedFiles.add(resolvedFileUri);
|
||||
await addContextAttrsRecursive(contents);
|
||||
}
|
||||
return addItem({
|
||||
label: name,
|
||||
id: "file",
|
||||
itemType: "contextProvider",
|
||||
query: resolvedFileUri,
|
||||
});
|
||||
}
|
||||
// URLs
|
||||
if (name.startsWith("http")) {
|
||||
return addItem({
|
||||
label: name,
|
||||
id: "url",
|
||||
itemType: "contextProvider",
|
||||
query: name,
|
||||
});
|
||||
}
|
||||
if (SUPPORTED_PROMPT_CONTEXT_PROVIDERS.includes(name)) {
|
||||
return addItem({
|
||||
label: name,
|
||||
id: name,
|
||||
itemType: "contextProvider",
|
||||
query: "",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
await addContextAttrsRecursive(command.prompt);
|
||||
return contextItemAttrs;
|
||||
}
|
||||
|
|
@ -14,20 +14,14 @@ import {
|
|||
TextMessagePart,
|
||||
} from "core";
|
||||
import { ctxItemToRifWithContents } from "core/commands/util";
|
||||
import { renderTemplatedString } from "core/promptFiles/v1/renderTemplatedString";
|
||||
import { parsePromptFileV1V2 } from "core/promptFiles/v2/parsePromptFileV1V2";
|
||||
import { renderChatMessage, stripImages } from "core/util/messageContent";
|
||||
import { stripImages } from "core/util/messageContent";
|
||||
import { getUriFileExtension } from "core/util/uri";
|
||||
import { IIdeMessenger } from "../../../../context/IdeMessenger";
|
||||
import { setIsGatheringContext } from "../../../../redux/slices/sessionSlice";
|
||||
import { CodeBlock, Mention, PromptBlock } from "../extensions";
|
||||
|
||||
interface MentionAttrs {
|
||||
label: string;
|
||||
id: string;
|
||||
itemType?: string;
|
||||
query?: string;
|
||||
}
|
||||
import { getRenderedV1Prompt } from "./renderPromptv1";
|
||||
import { getPromptV2ContextAttrs } from "./renderPromptv2";
|
||||
import { MentionAttrs } from "./types";
|
||||
|
||||
interface ResolveEditorContentInput {
|
||||
editorState: JSONContent;
|
||||
|
|
@ -70,20 +64,25 @@ export async function resolveEditorContent({
|
|||
} = processEditorContent(editorState);
|
||||
|
||||
const {
|
||||
parts: slashParts,
|
||||
slashedParts,
|
||||
contextAttrs: slashContextAttrs,
|
||||
legacyCommandWithInput,
|
||||
contextAttrs: slashContextAttrs = [],
|
||||
} = (await renderSlashCommandPrompt(
|
||||
} = await renderSlashCommandPrompt(
|
||||
ideMessenger,
|
||||
slashCommandName,
|
||||
availableSlashCommands,
|
||||
parts,
|
||||
)) ?? {};
|
||||
availableSlashCommands,
|
||||
selectedCode,
|
||||
);
|
||||
|
||||
const contextItemAttrs = [...editorContextAttrs, ...slashContextAttrs];
|
||||
|
||||
const shouldGatherContext =
|
||||
modifiers.useCodebase || contextItemAttrs.length > 0;
|
||||
defaultContextProviders.length > 0 ||
|
||||
modifiers.useCodebase ||
|
||||
!modifiers.noContext ||
|
||||
contextItemAttrs.length > 0;
|
||||
|
||||
if (shouldGatherContext) {
|
||||
dispatch(setIsGatheringContext(true));
|
||||
}
|
||||
|
|
@ -93,7 +92,7 @@ export async function resolveEditorContent({
|
|||
modifiers,
|
||||
ideMessenger,
|
||||
defaultContextProviders,
|
||||
parts: slashParts ?? parts,
|
||||
parts: slashedParts,
|
||||
selectedCode,
|
||||
});
|
||||
|
||||
|
|
@ -104,7 +103,7 @@ export async function resolveEditorContent({
|
|||
return {
|
||||
selectedContextItems,
|
||||
selectedCode,
|
||||
content: slashParts ?? parts,
|
||||
content: slashedParts,
|
||||
legacyCommandWithInput,
|
||||
};
|
||||
}
|
||||
|
|
@ -196,43 +195,42 @@ function processEditorContent(editorState: JSONContent) {
|
|||
|
||||
return { parts, contextItemAttrs, selectedCode, slashCommandName };
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes slash commands and prepares the command with input
|
||||
*/
|
||||
async function renderSlashCommandPrompt(
|
||||
ideMessenger: IIdeMessenger,
|
||||
slashCommandName: string | undefined,
|
||||
availableSlashCommands: SlashCommandDescWithSource[],
|
||||
commandName: string | undefined,
|
||||
parts: MessagePart[],
|
||||
): Promise<
|
||||
| {
|
||||
slashedParts: MessagePart[];
|
||||
legacyCommandWithInput?: {
|
||||
command: SlashCommandDescWithSource;
|
||||
input: string;
|
||||
};
|
||||
contextAttrs: MentionAttrs[];
|
||||
}
|
||||
| undefined
|
||||
> {
|
||||
if (!slashCommandName) return;
|
||||
|
||||
const command = availableSlashCommands.find(
|
||||
(c) => c.name === slashCommandName,
|
||||
);
|
||||
|
||||
if (!command) return;
|
||||
availableSlashCommands: SlashCommandDescWithSource[],
|
||||
selectedCode: RangeInFile[],
|
||||
): Promise<{
|
||||
slashedParts: MessagePart[];
|
||||
legacyCommandWithInput?: {
|
||||
command: SlashCommandDescWithSource;
|
||||
input: string;
|
||||
};
|
||||
contextAttrs: MentionAttrs[];
|
||||
}> {
|
||||
const NO_COMMAND = {
|
||||
slashedParts: parts,
|
||||
legacyCommandWithInput: undefined,
|
||||
contextAttrs: [],
|
||||
};
|
||||
if (!commandName) {
|
||||
return NO_COMMAND;
|
||||
}
|
||||
const command = availableSlashCommands.find((c) => c.name === commandName);
|
||||
if (!command) {
|
||||
return NO_COMMAND;
|
||||
}
|
||||
|
||||
const nonTextParts = parts.filter((part) => part.type !== "text");
|
||||
const slashedParts: MessagePart[] = [...nonTextParts];
|
||||
const textParts = parts.filter((part) => part.type === "text");
|
||||
|
||||
const userInput = textParts.length
|
||||
? renderChatMessage({
|
||||
role: "user",
|
||||
content: textParts,
|
||||
}).trimStart()
|
||||
: "";
|
||||
const userInput = stripImages(textParts).trimStart();
|
||||
|
||||
const legacyCommandWithInput = command.isLegacy
|
||||
? {
|
||||
|
|
@ -241,7 +239,7 @@ async function renderSlashCommandPrompt(
|
|||
}
|
||||
: undefined;
|
||||
|
||||
const contextItemAttrs: MentionAttrs[] = [];
|
||||
const contextAttrs: MentionAttrs[] = [];
|
||||
|
||||
switch (command.source) {
|
||||
case "built-in-legacy":
|
||||
|
|
@ -275,68 +273,53 @@ async function renderSlashCommandPrompt(
|
|||
});
|
||||
} else {
|
||||
throw new Error(
|
||||
`Failed to get MCP prompt for slash command ${slashCommandName}`,
|
||||
`Failed to get MCP prompt for slash command ${command.name}`,
|
||||
);
|
||||
}
|
||||
break;
|
||||
case ".prompt-file":
|
||||
if (!command.promptFile || !command.prompt) {
|
||||
case "prompt-file-v1":
|
||||
case "prompt-file-v2":
|
||||
if (!command.promptFile) {
|
||||
throw new Error(
|
||||
`Invalid prompt file from slash command ${command.name}`,
|
||||
);
|
||||
}
|
||||
case "yaml-prompt-block":
|
||||
if (!command.prompt) {
|
||||
throw new Error(
|
||||
`Invalid/empty prompt from slash command ${command.name}`,
|
||||
);
|
||||
}
|
||||
const { name, description, systemMessage, prompt } = parsePromptFileV1V2(
|
||||
command.promptFile,
|
||||
command.prompt,
|
||||
);
|
||||
case "yaml-prompt-block":
|
||||
const [_, renderedPrompt] = await renderPromptFileV2(prompt, {
|
||||
config: context.config,
|
||||
fullInput: context.input,
|
||||
embeddingsProvider: context.config.modelsByRole.embed[0],
|
||||
reranker: context.config.modelsByRole.rerank[0],
|
||||
llm: context.llm,
|
||||
ide: context.ide,
|
||||
selectedCode: context.selectedCode,
|
||||
fetch: context.fetch,
|
||||
});
|
||||
|
||||
// Render prompt template
|
||||
let renderedPrompt: string;
|
||||
if (customCommand.prompt.includes("{{{ input }}}")) {
|
||||
renderedPrompt = await renderTemplatedString(
|
||||
customCommand.prompt,
|
||||
ide.readFile.bind(ide),
|
||||
{ input },
|
||||
if (
|
||||
command.source === "prompt-file-v1" ||
|
||||
command.prompt.includes("{{{ input }}}")
|
||||
) {
|
||||
renderedPrompt = await getRenderedV1Prompt(
|
||||
ideMessenger,
|
||||
command,
|
||||
userInput,
|
||||
selectedCode,
|
||||
);
|
||||
} else {
|
||||
const renderedPromptFile = await renderPromptFileV2(
|
||||
customCommand.prompt,
|
||||
{
|
||||
config,
|
||||
llm,
|
||||
ide,
|
||||
selectedCode,
|
||||
fetch,
|
||||
fullInput: input,
|
||||
embeddingsProvider: config.selectedModelByRole.embed,
|
||||
reranker: config.selectedModelByRole.rerank,
|
||||
},
|
||||
const promptFileContextAttrs = await getPromptV2ContextAttrs(
|
||||
ideMessenger,
|
||||
command,
|
||||
);
|
||||
|
||||
renderedPrompt = renderedPromptFile[1];
|
||||
contextAttrs.push(...promptFileContextAttrs);
|
||||
renderedPrompt = [command.prompt, userInput].join("\n\n");
|
||||
}
|
||||
|
||||
const renderedPrompt = renderPromptFile();
|
||||
// const renderedPrompt = renderPromptFile();
|
||||
slashedParts.push({
|
||||
type: "text",
|
||||
text: renderedPrompt, // Includes user input
|
||||
text: renderedPrompt.trim(), // Includes user input
|
||||
});
|
||||
case "built-in":
|
||||
case "invokable-rule":
|
||||
case "json-custom-command":
|
||||
if (!command.prompt) {
|
||||
throw new Error(`Slash command ${slashCommandName} is missing prompt`);
|
||||
throw new Error(`Slash command ${command.name} is missing prompt`);
|
||||
}
|
||||
slashedParts.push({
|
||||
type: "text",
|
||||
|
|
@ -346,7 +329,7 @@ async function renderSlashCommandPrompt(
|
|||
return {
|
||||
slashedParts,
|
||||
legacyCommandWithInput,
|
||||
contextAttrs: [],
|
||||
contextAttrs,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -384,7 +367,10 @@ async function gatherContextItems({
|
|||
}
|
||||
|
||||
// cmd+enter to use codebase
|
||||
if (modifiers.useCodebase) {
|
||||
if (
|
||||
modifiers.useCodebase &&
|
||||
!contextItemAttrs.some((item) => item.id === "codebase")
|
||||
) {
|
||||
const result = await ideMessenger.request("context/getContextItems", {
|
||||
name: "codebase",
|
||||
query: "",
|
||||
|
|
@ -397,6 +383,32 @@ async function gatherContextItems({
|
|||
}
|
||||
}
|
||||
|
||||
// noContext modifier adds currently open file if it's not already present
|
||||
if (
|
||||
!modifiers.noContext &&
|
||||
!contextItemAttrs.some((item) => item.id === "currentFile")
|
||||
) {
|
||||
const currentFileResponse = await ideMessenger.request(
|
||||
"context/getContextItems",
|
||||
{
|
||||
name: "currentFile",
|
||||
query: "non-mention-usage",
|
||||
fullInput: "",
|
||||
selectedCode: [],
|
||||
},
|
||||
);
|
||||
if (currentFileResponse.status === "success") {
|
||||
const currentFile = currentFileResponse.content[0];
|
||||
if (currentFile.uri?.value) {
|
||||
currentFile.id = {
|
||||
providerTitle: "file",
|
||||
itemId: currentFile.uri.value,
|
||||
};
|
||||
contextItems.unshift(currentFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Include default context providers
|
||||
const defaultContextItems = await Promise.all(
|
||||
defaultContextProviders.map(async (provider) => {
|
||||
|
|
@ -418,18 +430,6 @@ async function gatherContextItems({
|
|||
return contextItems;
|
||||
}
|
||||
|
||||
function findLastIndex<T>(
|
||||
array: T[],
|
||||
predicate: (value: T, index: number, obj: T[]) => boolean,
|
||||
): number {
|
||||
for (let i = array.length - 1; i >= 0; i--) {
|
||||
if (predicate(array[i], i, array)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1; // if no element satisfies the predicate
|
||||
}
|
||||
|
||||
function resvolePromptBlock(p: JSONContent): string | undefined {
|
||||
return p.attrs?.item.name;
|
||||
}
|
||||
|
|
|
|||
6
gui/src/components/mainInput/TipTapEditor/utils/types.ts
Normal file
6
gui/src/components/mainInput/TipTapEditor/utils/types.ts
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
export interface MentionAttrs {
|
||||
label: string;
|
||||
id: string;
|
||||
itemType?: string;
|
||||
query?: string;
|
||||
}
|
||||
|
|
@ -1,116 +0,0 @@
|
|||
import { createAsyncThunk } from "@reduxjs/toolkit";
|
||||
import { JSONContent } from "@tiptap/core";
|
||||
import {
|
||||
ContextItemWithId,
|
||||
InputModifiers,
|
||||
MessageContent,
|
||||
RangeInFile,
|
||||
SlashCommandDescWithSource,
|
||||
} from "core";
|
||||
import * as URI from "uri-js";
|
||||
import { resolveEditorContent } from "../../components/mainInput/TipTapEditor";
|
||||
import { selectSelectedChatModel } from "../slices/configSlice";
|
||||
import { ThunkApiType } from "../store";
|
||||
|
||||
export const gatherContext = createAsyncThunk<
|
||||
{
|
||||
selectedContextItems: ContextItemWithId[];
|
||||
selectedCode: RangeInFile[];
|
||||
content: MessageContent;
|
||||
legacyCommandWithInput:
|
||||
| {
|
||||
command: SlashCommandDescWithSource;
|
||||
input: string;
|
||||
}
|
||||
| undefined;
|
||||
},
|
||||
{
|
||||
editorState: JSONContent;
|
||||
modifiers: InputModifiers;
|
||||
},
|
||||
ThunkApiType
|
||||
>(
|
||||
"chat/gatherContext",
|
||||
async ({ modifiers, editorState }, { dispatch, extra, getState }) => {
|
||||
const state = getState();
|
||||
const selectedChatModel = selectSelectedChatModel(state);
|
||||
|
||||
const defaultContextProviders =
|
||||
state.config.config.experimental?.defaultContext ?? [];
|
||||
|
||||
if (!selectedChatModel) {
|
||||
console.error(
|
||||
"gatherContext thunk: Cannot gather context, no model selected",
|
||||
);
|
||||
throw new Error("No chat model selected");
|
||||
}
|
||||
|
||||
// Resolve context providers and construct new history
|
||||
const {
|
||||
selectedContextItems,
|
||||
selectedCode,
|
||||
content,
|
||||
legacyCommandWithInput,
|
||||
} = await resolveEditorContent({
|
||||
editorState,
|
||||
modifiers,
|
||||
ideMessenger: extra.ideMessenger,
|
||||
defaultContextProviders,
|
||||
availableSlashCommands: state.config.config.slashCommands,
|
||||
dispatch,
|
||||
});
|
||||
|
||||
// Automatically use currently open file
|
||||
if (!modifiers.noContext) {
|
||||
const usingFreeTrial = false; // TODO no longer tracking free trial count, need to hook up to hub
|
||||
|
||||
const currentFileResponse = await extra.ideMessenger.request(
|
||||
"context/getContextItems",
|
||||
{
|
||||
name: "currentFile",
|
||||
query: "non-mention-usage",
|
||||
fullInput: "",
|
||||
selectedCode: [],
|
||||
},
|
||||
);
|
||||
if (currentFileResponse.status === "success") {
|
||||
const items = currentFileResponse.content;
|
||||
if (items.length > 0) {
|
||||
const currentFile = items[0];
|
||||
const uri = currentFile.uri?.value;
|
||||
|
||||
// don't add the file if it's already in the context items
|
||||
if (
|
||||
uri &&
|
||||
!selectedContextItems.find(
|
||||
(item) => item.uri?.value && URI.equal(item.uri.value, uri),
|
||||
)
|
||||
) {
|
||||
// Limit to 1000 lines if using free trial
|
||||
if (usingFreeTrial) {
|
||||
currentFile.content = currentFile.content
|
||||
.split("\n")
|
||||
.slice(0, 1000)
|
||||
.join("\n");
|
||||
if (!currentFile.content.endsWith("```")) {
|
||||
currentFile.content += "\n```";
|
||||
}
|
||||
}
|
||||
currentFile.id = {
|
||||
providerTitle: "file",
|
||||
itemId: uri,
|
||||
};
|
||||
selectedContextItems.unshift(currentFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
selectedContextItems,
|
||||
selectedCode,
|
||||
content,
|
||||
legacyCommandWithInput,
|
||||
};
|
||||
},
|
||||
);
|
||||
|
|
@ -5,6 +5,7 @@ import { constructMessages } from "core/llm/constructMessages";
|
|||
import { getApplicableRules } from "core/llm/rules/getSystemMessageWithRules";
|
||||
import posthog from "posthog-js";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent";
|
||||
import { getBaseSystemMessage } from "../../util";
|
||||
import { selectSelectedChatModel } from "../slices/configSlice";
|
||||
import {
|
||||
|
|
@ -13,7 +14,6 @@ import {
|
|||
updateHistoryItemAtIndex,
|
||||
} from "../slices/sessionSlice";
|
||||
import { ThunkApiType } from "../store";
|
||||
import { gatherContext } from "./gatherContext";
|
||||
import { resetStateForNewMessage } from "./resetStateForNewMessage";
|
||||
import { streamNormalInput } from "./streamNormalInput";
|
||||
import { streamThunkWrapper } from "./streamThunkWrapper";
|
||||
|
|
@ -45,18 +45,30 @@ export const streamResponseThunk = createAsyncThunk<
|
|||
);
|
||||
resetStateForNewMessage();
|
||||
|
||||
const result = await dispatch(
|
||||
gatherContext({
|
||||
editorState,
|
||||
modifiers,
|
||||
}),
|
||||
);
|
||||
const defaultContextProviders =
|
||||
state.config.config.experimental?.defaultContext ?? [];
|
||||
|
||||
if (!selectedChatModel) {
|
||||
console.error(
|
||||
"gatherContext thunk: Cannot gather context, no model selected",
|
||||
);
|
||||
throw new Error("No chat model selected");
|
||||
}
|
||||
|
||||
// Resolve context providers and construct new history
|
||||
const {
|
||||
selectedContextItems,
|
||||
selectedCode,
|
||||
content,
|
||||
legacyCommandWithInput,
|
||||
} = unwrapResult(result);
|
||||
} = await resolveEditorContent({
|
||||
editorState,
|
||||
modifiers,
|
||||
ideMessenger: extra.ideMessenger,
|
||||
defaultContextProviders,
|
||||
availableSlashCommands: state.config.config.slashCommands,
|
||||
dispatch,
|
||||
});
|
||||
|
||||
// symbols for both context items AND selected codeblocks
|
||||
const filesForSymbols = [
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue