Elffuss BraidHub

kikocis/continue public

08dbbc23cfc7 · 1.7 KiBRawPermalink
1import { minimatch } from "minimatch";
2import { RuleWithSource, ToolResultChatMessage, UserChatMessage } from "../..";
3import { renderChatMessage } from "../../util/messageContent";
4import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks";
5
6/**
7 * Checks if a path matches any of the provided globs
8 */
9const matchesGlobs = (
10 path: string,
11 globs: string | string[] | undefined,
12): boolean => {
13 if (!globs) return true;
14
15 if (typeof globs === "string") {
16 return minimatch(path, globs);
17 }
18
19 if (Array.isArray(globs)) {
20 return globs.some((glob) => minimatch(path, glob));
21 }
22
23 return false;
24};
25
26/**
27 * Filters rules that apply to the given message
28 */
29export const getApplicableRules = (
30 userMessage: UserChatMessage | ToolResultChatMessage | undefined,
31 rules: RuleWithSource[],
32): RuleWithSource[] => {
33 const filePathsFromMessage = userMessage
34 ? extractPathsFromCodeBlocks(renderChatMessage(userMessage))
35 : [];
36
37 return rules.filter((rule) => {
38 // A rule is active if it has no globs (applies to all files)
39 // or if at least one file path matches its globs
40 const hasNoGlobs = !rule.globs;
41 const matchesAnyFilePath = filePathsFromMessage.some((path) =>
42 matchesGlobs(path, rule.globs),
43 );
44
45 return hasNoGlobs || matchesAnyFilePath;
46 });
47};
48
49export const getSystemMessageWithRules = ({
50 baseSystemMessage,
51 userMessage,
52 rules,
53}: {
54 baseSystemMessage?: string;
55 userMessage: UserChatMessage | ToolResultChatMessage | undefined;
56 rules: RuleWithSource[];
57}) => {
58 const applicableRules = getApplicableRules(userMessage, rules);
59 let systemMessage = baseSystemMessage ?? "";
60
61 for (const rule of applicableRules) {
62 systemMessage += `\n\n${rule.rule}`;
63 }
64
65 return systemMessage;
66};