| 1 | import { minimatch } from "minimatch"; |
| 2 | import { RuleWithSource, ToolResultChatMessage, UserChatMessage } from "../.."; |
| 3 | import { renderChatMessage } from "../../util/messageContent"; |
| 4 | import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks"; |
| 5 | |
| 6 | /** |
| 7 | * Checks if a path matches any of the provided globs |
| 8 | */ |
| 9 | const 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 | export const getSystemMessageWithRules = ({ |
| 27 | baseSystemMessage, |
| 28 | userMessage, |
| 29 | rules, |
| 30 | }: { |
| 31 | baseSystemMessage?: string; |
| 32 | userMessage: UserChatMessage | ToolResultChatMessage | undefined; |
| 33 | rules: RuleWithSource[]; |
| 34 | }) => { |
| 35 | const filePathsFromMessage = userMessage |
| 36 | ? extractPathsFromCodeBlocks(renderChatMessage(userMessage)) |
| 37 | : []; |
| 38 | |
| 39 | let systemMessage = baseSystemMessage ?? ""; |
| 40 | |
| 41 | for (const rule of rules) { |
| 42 | // A rule is active if it has no globs (applies to all files) |
| 43 | // or if at least one file path matches its globs |
| 44 | const hasNoGlobs = !rule.globs; |
| 45 | const matchesAnyFilePath = filePathsFromMessage.some((path) => |
| 46 | matchesGlobs(path, rule.globs), |
| 47 | ); |
| 48 | |
| 49 | if (hasNoGlobs || matchesAnyFilePath) { |
| 50 | systemMessage += `\n\n${rule.rule}`; |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | return systemMessage; |
| 55 | }; |