Merge pull request #3185 from SillyTavern/inject-filter Inject filter
Signed| @@ -2873,23 +2873,54 @@ function addPersonaDescriptionExtensionPrompt() { | |||
| 2873 | } | 2873 | } |
| 2874 | } | 2874 | } |
| 2875 | 2875 | ||
| 2876 | function getAllExtensionPrompts() { | 2876 | /** |
| 2877 | const value = Object | 2877 | * Returns all extension prompts combined. |
| 2878 | .values(extension_prompts) | 2878 | * @returns {Promise<string>} Combined extension prompts |
| 2879 | .filter(x => x.value) | 2879 | */ |
| 2880 | .map(x => x.value.trim()) | 2880 | async function getAllExtensionPrompts() { |
| 2881 | .join('\n'); | 2881 | const values = []; |
| 2882 | |||
| 2883 | for (const prompt of Object.values(extension_prompts)) { | ||
| 2884 | const value = prompt?.value?.trim(); | ||
| 2885 | |||
| 2886 | if (!value) { | ||
| 2887 | continue; | ||
| 2888 | } | ||
| 2882 | 2889 | ||
| 2883 | return value.length ? substituteParams(value) : ''; | 2890 | const hasFilter = typeof prompt.filter === 'function'; |
| 2891 | if (hasFilter && !await prompt.filter()) { | ||
| 2892 | continue; | ||
| 2893 | } | ||
| 2894 | |||
| 2895 | values.push(value); | ||
| 2896 | } | ||
| 2897 | |||
| 2898 | return substituteParams(values.join('\n')); | ||
| 2884 | } | 2899 | } |
| 2885 | 2900 | ||
| 2886 | // Wrapper to fetch extension prompts by module name | 2901 | /** |
| 2887 | export function getExtensionPromptByName(moduleName) { | 2902 | * Wrapper to fetch extension prompts by module name |
| 2888 | if (moduleName) { | 2903 | * @param {string} moduleName Module name |
| 2889 | return substituteParams(extension_prompts[moduleName]?.value); | 2904 | * @returns {Promise<string>} Extension prompt |
| 2890 | } else { | 2905 | */ |
| 2891 | return; | 2906 | export async function getExtensionPromptByName(moduleName) { |
| 2907 | if (!moduleName) { | ||
| 2908 | return ''; | ||
| 2909 | } | ||
| 2910 | |||
| 2911 | const prompt = extension_prompts[moduleName]; | ||
| 2912 | |||
| 2913 | if (!prompt) { | ||
| 2914 | return ''; | ||
| 2892 | } | 2915 | } |
| 2916 | |||
| 2917 | const hasFilter = typeof prompt.filter === 'function'; | ||
| 2918 | |||
| 2919 | if (hasFilter && !await prompt.filter()) { | ||
| 2920 | return ''; | ||
| 2921 | } | ||
| 2922 | |||
| 2923 | return substituteParams(prompt.value); | ||
| 2893 | } | 2924 | } |
| 2894 | 2925 | ||
| 2895 | /** | 2926 | /** |
| @@ -2900,27 +2931,36 @@ export function getExtensionPromptByName(moduleName) { | |||
| 2900 | * @param {string} [separator] Separator for joining multiple prompts | 2931 | * @param {string} [separator] Separator for joining multiple prompts |
| 2901 | * @param {number} [role] Role of the prompt | 2932 | * @param {number} [role] Role of the prompt |
| 2902 | * @param {boolean} [wrap] Wrap start and end with a separator | 2933 | * @param {boolean} [wrap] Wrap start and end with a separator |
| 2903 | * @returns {string} Extension prompt | 2934 | * @returns {Promise<string>} Extension prompt |
| 2904 | */ | 2935 | */ |
| 2905 | export function getExtensionPrompt(position = extension_prompt_types.IN_PROMPT, depth = undefined, separator = '\n', role = undefined, wrap = true) { | 2936 | export async function getExtensionPrompt(position = extension_prompt_types.IN_PROMPT, depth = undefined, separator = '\n', role = undefined, wrap = true) { |
| 2906 | let extension_prompt = Object.keys(extension_prompts) | 2937 | const filterByFunction = async (prompt) => { |
| 2938 | const hasFilter = typeof prompt.filter === 'function'; | ||
| 2939 | if (hasFilter && !await prompt.filter()) { | ||
| 2940 | return false; | ||
| 2941 | } | ||
| 2942 | return true; | ||
| 2943 | }; | ||
| 2944 | const promptPromises = Object.keys(extension_prompts) | ||
| 2907 | .sort() | 2945 | .sort() |
| 2908 | .map((x) => extension_prompts[x]) | 2946 | .map((x) => extension_prompts[x]) |
| 2909 | .filter(x => x.position == position && x.value) | 2947 | .filter(x => x.position == position && x.value) |
| 2910 | .filter(x => depth === undefined || x.depth === undefined || x.depth === depth) | 2948 | .filter(x => depth === undefined || x.depth === undefined || x.depth === depth) |
| 2911 | .filter(x => role === undefined || x.role === undefined || x.role === role) | 2949 | .filter(x => role === undefined || x.role === undefined || x.role === role) |
| 2912 | .map(x => x.value.trim()) | 2950 | .filter(filterByFunction); |
| 2913 | .join(separator); | 2951 | const prompts = await Promise.all(promptPromises); |
| 2914 | if (wrap && extension_prompt.length && !extension_prompt.startsWith(separator)) { | 2952 | |
| 2915 | extension_prompt = separator + extension_prompt; | 2953 | let values = prompts.map(x => x.value.trim()).join(separator); |
| 2954 | if (wrap && values.length && !values.startsWith(separator)) { | ||
| 2955 | values = separator + values; | ||
| 2916 | } | 2956 | } |
| 2917 | if (wrap && extension_prompt.length && !extension_prompt.endsWith(separator)) { | 2957 | if (wrap && values.length && !values.endsWith(separator)) { |
| 2918 | extension_prompt = extension_prompt + separator; | 2958 | values = values + separator; |
| 2919 | } | 2959 | } |
| 2920 | if (extension_prompt.length) { | 2960 | if (values.length) { |
| 2921 | extension_prompt = substituteParams(extension_prompt); | 2961 | values = substituteParams(values); |
| 2922 | } | 2962 | } |
| 2923 | return extension_prompt; | 2963 | return values; |
| 2924 | } | 2964 | } |
| 2925 | 2965 | ||
| 2926 | export function baseChatReplace(value, name1, name2) { | 2966 | export function baseChatReplace(value, name1, name2) { |
| @@ -3834,7 +3874,7 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro | |||
| 3834 | // Inject all Depth prompts. Chat Completion does it separately | 3874 | // Inject all Depth prompts. Chat Completion does it separately |
| 3835 | let injectedIndices = []; | 3875 | let injectedIndices = []; |
| 3836 | if (main_api !== 'openai') { | 3876 | if (main_api !== 'openai') { |
| 3837 | injectedIndices = doChatInject(coreChat, isContinue); | 3877 | injectedIndices = await doChatInject(coreChat, isContinue); |
| 3838 | } | 3878 | } |
| 3839 | 3879 | ||
| 3840 | // Insert character jailbreak as the last user message (if exists, allowed, preferred, and not using Chat Completion) | 3880 | // Insert character jailbreak as the last user message (if exists, allowed, preferred, and not using Chat Completion) |
| @@ -3907,8 +3947,8 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro | |||
| 3907 | } | 3947 | } |
| 3908 | 3948 | ||
| 3909 | // Call combined AN into Generate | 3949 | // Call combined AN into Generate |
| 3910 | const beforeScenarioAnchor = getExtensionPrompt(extension_prompt_types.BEFORE_PROMPT).trimStart(); | 3950 | const beforeScenarioAnchor = (await getExtensionPrompt(extension_prompt_types.BEFORE_PROMPT)).trimStart(); |
| 3911 | const afterScenarioAnchor = getExtensionPrompt(extension_prompt_types.IN_PROMPT); | 3951 | const afterScenarioAnchor = await getExtensionPrompt(extension_prompt_types.IN_PROMPT); |
| 3912 | 3952 | ||
| 3913 | const storyStringParams = { | 3953 | const storyStringParams = { |
| 3914 | description: description, | 3954 | description: description, |
| @@ -4471,7 +4511,7 @@ export async function Generate(type, { automatic_trigger, force_name2, quiet_pro | |||
| 4471 | ...thisPromptBits[currentArrayEntry], | 4511 | ...thisPromptBits[currentArrayEntry], |
| 4472 | rawPrompt: generate_data.prompt || generate_data.input, | 4512 | rawPrompt: generate_data.prompt || generate_data.input, |
| 4473 | mesId: getNextMessageId(type), | 4513 | mesId: getNextMessageId(type), |
| 4474 | allAnchors: getAllExtensionPrompts(), | 4514 | allAnchors: await getAllExtensionPrompts(), |
| 4475 | chatInjects: injectedIndices?.map(index => arrMes[arrMes.length - index - 1])?.join('') || '', | 4515 | chatInjects: injectedIndices?.map(index => arrMes[arrMes.length - index - 1])?.join('') || '', |
| 4476 | summarizeString: (extension_prompts['1_memory']?.value || ''), | 4516 | summarizeString: (extension_prompts['1_memory']?.value || ''), |
| 4477 | authorsNoteString: (extension_prompts['2_floating_prompt']?.value || ''), | 4517 | authorsNoteString: (extension_prompts['2_floating_prompt']?.value || ''), |
| @@ -4740,9 +4780,9 @@ export function stopGeneration() { | |||
| 4740 | * Injects extension prompts into chat messages. | 4780 | * Injects extension prompts into chat messages. |
| 4741 | * @param {object[]} messages Array of chat messages | 4781 | * @param {object[]} messages Array of chat messages |
| 4742 | * @param {boolean} isContinue Whether the generation is a continuation. If true, the extension prompts of depth 0 are injected at position 1. | 4782 | * @param {boolean} isContinue Whether the generation is a continuation. If true, the extension prompts of depth 0 are injected at position 1. |
| 4743 | * @returns {number[]} Array of indices where the extension prompts were injected | 4783 | * @returns {Promise<number[]>} Array of indices where the extension prompts were injected |
| 4744 | */ | 4784 | */ |
| 4745 | function doChatInject(messages, isContinue) { | 4785 | async function doChatInject(messages, isContinue) { |
| 4746 | const injectedIndices = []; | 4786 | const injectedIndices = []; |
| 4747 | let totalInsertedMessages = 0; | 4787 | let totalInsertedMessages = 0; |
| 4748 | messages.reverse(); | 4788 | messages.reverse(); |
| @@ -4760,7 +4800,7 @@ function doChatInject(messages, isContinue) { | |||
| 4760 | const wrap = false; | 4800 | const wrap = false; |
| 4761 | 4801 | ||
| 4762 | for (const role of roles) { | 4802 | for (const role of roles) { |
| 4763 | const extensionPrompt = String(getExtensionPrompt(extension_prompt_types.IN_CHAT, i, separator, role, wrap)).trimStart(); | 4803 | const extensionPrompt = String(await getExtensionPrompt(extension_prompt_types.IN_CHAT, i, separator, role, wrap)).trimStart(); |
| 4764 | const isNarrator = role === extension_prompt_roles.SYSTEM; | 4804 | const isNarrator = role === extension_prompt_roles.SYSTEM; |
| 4765 | const isUser = role === extension_prompt_roles.USER; | 4805 | const isUser = role === extension_prompt_roles.USER; |
| 4766 | const name = names[role]; | 4806 | const name = names[role]; |
| @@ -7453,14 +7493,16 @@ function select_rm_characters() { | |||
| 7453 | * @param {number} depth Insertion depth. 0 represets the last message in context. Expected values up to MAX_INJECTION_DEPTH. | 7493 | * @param {number} depth Insertion depth. 0 represets the last message in context. Expected values up to MAX_INJECTION_DEPTH. |
| 7454 | * @param {number} role Extension prompt role. Defaults to SYSTEM. | 7494 | * @param {number} role Extension prompt role. Defaults to SYSTEM. |
| 7455 | * @param {boolean} scan Should the prompt be included in the world info scan. | 7495 | * @param {boolean} scan Should the prompt be included in the world info scan. |
| 7496 | * @param {(function(): Promise<boolean>|boolean)} filter Filter function to determine if the prompt should be injected. | ||
| 7456 | */ | 7497 | */ |
| 7457 | export function setExtensionPrompt(key, value, position, depth, scan = false, role = extension_prompt_roles.SYSTEM) { | 7498 | export function setExtensionPrompt(key, value, position, depth, scan = false, role = extension_prompt_roles.SYSTEM, filter = null) { |
| 7458 | extension_prompts[key] = { | 7499 | extension_prompts[key] = { |
| 7459 | value: String(value), | 7500 | value: String(value), |
| 7460 | position: Number(position), | 7501 | position: Number(position), |
| 7461 | depth: Number(depth), | 7502 | depth: Number(depth), |
| 7462 | scan: !!scan, | 7503 | scan: !!scan, |
| 7463 | role: Number(role ?? extension_prompt_roles.SYSTEM), | 7504 | role: Number(role ?? extension_prompt_roles.SYSTEM), |
| 7505 | filter: filter, | ||
| 7464 | }; | 7506 | }; |
| 7465 | } | 7507 | } |
| 7466 | 7508 | ||
| @@ -611,8 +611,9 @@ function formatWorldInfo(value) { | |||
| 611 | * | 611 | * |
| 612 | * @param {Prompt[]} prompts - Array containing injection prompts. | 612 | * @param {Prompt[]} prompts - Array containing injection prompts. |
| 613 | * @param {Object[]} messages - Array containing all messages. | 613 | * @param {Object[]} messages - Array containing all messages. |
| 614 | * @returns {Promise<Object[]>} - Array containing all messages with injections. | ||
| 614 | */ | 615 | */ |
| 615 | function populationInjectionPrompts(prompts, messages) { | 616 | async function populationInjectionPrompts(prompts, messages) { |
| 616 | let totalInsertedMessages = 0; | 617 | let totalInsertedMessages = 0; |
| 617 | 618 | ||
| 618 | const roleTypes = { | 619 | const roleTypes = { |
| @@ -635,7 +636,7 @@ function populationInjectionPrompts(prompts, messages) { | |||
| 635 | // Get prompts for current role | 636 | // Get prompts for current role |
| 636 | const rolePrompts = depthPrompts.filter(prompt => prompt.role === role).map(x => x.content).join(separator); | 637 | const rolePrompts = depthPrompts.filter(prompt => prompt.role === role).map(x => x.content).join(separator); |
| 637 | // Get extension prompt | 638 | // Get extension prompt |
| 638 | const extensionPrompt = getExtensionPrompt(extension_prompt_types.IN_CHAT, i, separator, roleTypes[role], wrap); | 639 | const extensionPrompt = await getExtensionPrompt(extension_prompt_types.IN_CHAT, i, separator, roleTypes[role], wrap); |
| 639 | 640 | ||
| 640 | const jointPrompt = [rolePrompts, extensionPrompt].filter(x => x).map(x => x.trim()).join(separator); | 641 | const jointPrompt = [rolePrompts, extensionPrompt].filter(x => x).map(x => x.trim()).join(separator); |
| 641 | 642 | ||
| @@ -1020,7 +1021,7 @@ async function populateChatCompletion(prompts, chatCompletion, { bias, quietProm | |||
| 1020 | } | 1021 | } |
| 1021 | 1022 | ||
| 1022 | // Add in-chat injections | 1023 | // Add in-chat injections |
| 1023 | messages = populationInjectionPrompts(absolutePrompts, messages); | 1024 | messages = await populationInjectionPrompts(absolutePrompts, messages); |
| 1024 | 1025 | ||
| 1025 | // Decide whether dialogue examples should always be added | 1026 | // Decide whether dialogue examples should always be added |
| 1026 | if (power_user.pin_examples) { | 1027 | if (power_user.pin_examples) { |
| @@ -1051,9 +1052,9 @@ async function populateChatCompletion(prompts, chatCompletion, { bias, quietProm | |||
| 1051 | * @param {string} options.systemPromptOverride | 1052 | * @param {string} options.systemPromptOverride |
| 1052 | * @param {string} options.jailbreakPromptOverride | 1053 | * @param {string} options.jailbreakPromptOverride |
| 1053 | * @param {string} options.personaDescription | 1054 | * @param {string} options.personaDescription |
| 1054 | * @returns {Object} prompts - The prepared and merged system and user-defined prompts. | 1055 | * @returns {Promise<Object>} prompts - The prepared and merged system and user-defined prompts. |
| 1055 | */ | 1056 | */ |
| 1056 | function preparePromptsForChatCompletion({ Scenario, charPersonality, name2, worldInfoBefore, worldInfoAfter, charDescription, quietPrompt, bias, extensionPrompts, systemPromptOverride, jailbreakPromptOverride, personaDescription }) { | 1057 | async function preparePromptsForChatCompletion({ Scenario, charPersonality, name2, worldInfoBefore, worldInfoAfter, charDescription, quietPrompt, bias, extensionPrompts, systemPromptOverride, jailbreakPromptOverride, personaDescription }) { |
| 1057 | const scenarioText = Scenario && oai_settings.scenario_format ? substituteParams(oai_settings.scenario_format) : ''; | 1058 | const scenarioText = Scenario && oai_settings.scenario_format ? substituteParams(oai_settings.scenario_format) : ''; |
| 1058 | const charPersonalityText = charPersonality && oai_settings.personality_format ? substituteParams(oai_settings.personality_format) : ''; | 1059 | const charPersonalityText = charPersonality && oai_settings.personality_format ? substituteParams(oai_settings.personality_format) : ''; |
| 1059 | const groupNudge = substituteParams(oai_settings.group_nudge_prompt); | 1060 | const groupNudge = substituteParams(oai_settings.group_nudge_prompt); |
| @@ -1142,6 +1143,9 @@ function preparePromptsForChatCompletion({ Scenario, charPersonality, name2, wor | |||
| 1142 | if (!extensionPrompts[key].value) continue; | 1143 | if (!extensionPrompts[key].value) continue; |
| 1143 | if (![extension_prompt_types.BEFORE_PROMPT, extension_prompt_types.IN_PROMPT].includes(prompt.position)) continue; | 1144 | if (![extension_prompt_types.BEFORE_PROMPT, extension_prompt_types.IN_PROMPT].includes(prompt.position)) continue; |
| 1144 | 1145 | ||
| 1146 | const hasFilter = typeof prompt.filter === 'function'; | ||
| 1147 | if (hasFilter && !await prompt.filter()) continue; | ||
| 1148 | |||
| 1145 | systemPrompts.push({ | 1149 | systemPrompts.push({ |
| 1146 | identifier: key.replace(/\W/g, '_'), | 1150 | identifier: key.replace(/\W/g, '_'), |
| 1147 | position: getPromptPosition(prompt.position), | 1151 | position: getPromptPosition(prompt.position), |
| @@ -1254,7 +1258,7 @@ export async function prepareOpenAIMessages({ | |||
| 1254 | 1258 | ||
| 1255 | try { | 1259 | try { |
| 1256 | // Merge markers and ordered user prompts with system prompts | 1260 | // Merge markers and ordered user prompts with system prompts |
| 1257 | const prompts = preparePromptsForChatCompletion({ | 1261 | const prompts = await preparePromptsForChatCompletion({ |
| 1258 | Scenario, | 1262 | Scenario, |
| 1259 | charPersonality, | 1263 | charPersonality, |
| 1260 | name2, | 1264 | name2, |
| @@ -84,6 +84,25 @@ export const parser = new SlashCommandParser(); | |||
| 84 | const registerSlashCommand = SlashCommandParser.addCommand.bind(SlashCommandParser); | 84 | const registerSlashCommand = SlashCommandParser.addCommand.bind(SlashCommandParser); |
| 85 | const getSlashCommandsHelp = parser.getHelpString.bind(parser); | 85 | const getSlashCommandsHelp = parser.getHelpString.bind(parser); |
| 86 | 86 | ||
| 87 | /** | ||
| 88 | * Converts a SlashCommandClosure to a filter function that returns a boolean. | ||
| 89 | * @param {SlashCommandClosure} closure | ||
| 90 | * @returns {() => Promise<boolean>} | ||
| 91 | */ | ||
| 92 | function closureToFilter(closure) { | ||
| 93 | return async () => { | ||
| 94 | try { | ||
| 95 | const localClosure = closure.getCopy(); | ||
| 96 | localClosure.onProgress = () => { }; | ||
| 97 | const result = await localClosure.execute(); | ||
| 98 | return isTrueBoolean(result.pipe); | ||
| 99 | } catch (e) { | ||
| 100 | console.error('Error executing filter closure', e); | ||
| 101 | return false; | ||
| 102 | } | ||
| 103 | }; | ||
| 104 | } | ||
| 105 | |||
| 87 | export function initDefaultSlashCommands() { | 106 | export function initDefaultSlashCommands() { |
| 88 | SlashCommandParser.addCommandObject(SlashCommand.fromProps({ | 107 | SlashCommandParser.addCommandObject(SlashCommand.fromProps({ |
| 89 | name: '?', | 108 | name: '?', |
| @@ -1611,6 +1630,13 @@ export function initDefaultSlashCommands() { | |||
| 1611 | new SlashCommandNamedArgument( | 1630 | new SlashCommandNamedArgument( |
| 1612 | 'ephemeral', 'remove injection after generation', [ARGUMENT_TYPE.BOOLEAN], false, false, 'false', | 1631 | 'ephemeral', 'remove injection after generation', [ARGUMENT_TYPE.BOOLEAN], false, false, 'false', |
| 1613 | ), | 1632 | ), |
| 1633 | SlashCommandNamedArgument.fromProps({ | ||
| 1634 | name: 'filter', | ||
| 1635 | description: 'if a filter is defined, an injection will only be performed if the closure returns true', | ||
| 1636 | typeList: [ARGUMENT_TYPE.CLOSURE], | ||
| 1637 | isRequired: false, | ||
| 1638 | acceptsMultiple: false, | ||
| 1639 | }), | ||
| 1614 | ], | 1640 | ], |
| 1615 | unnamedArgumentList: [ | 1641 | unnamedArgumentList: [ |
| 1616 | new SlashCommandArgument( | 1642 | new SlashCommandArgument( |
| @@ -1901,6 +1927,11 @@ const NARRATOR_NAME_DEFAULT = 'System'; | |||
| 1901 | export const COMMENT_NAME_DEFAULT = 'Note'; | 1927 | export const COMMENT_NAME_DEFAULT = 'Note'; |
| 1902 | const SCRIPT_PROMPT_KEY = 'script_inject_'; | 1928 | const SCRIPT_PROMPT_KEY = 'script_inject_'; |
| 1903 | 1929 | ||
| 1930 | /** | ||
| 1931 | * Adds a new script injection to the chat. | ||
| 1932 | * @param {import('./slash-commands/SlashCommand.js').NamedArguments} args Named arguments | ||
| 1933 | * @param {import('./slash-commands/SlashCommand.js').UnnamedArguments} value Unnamed argument | ||
| 1934 | */ | ||
| 1904 | function injectCallback(args, value) { | 1935 | function injectCallback(args, value) { |
| 1905 | const positions = { | 1936 | const positions = { |
| 1906 | 'before': extension_prompt_types.BEFORE_PROMPT, | 1937 | 'before': extension_prompt_types.BEFORE_PROMPT, |
| @@ -1914,8 +1945,8 @@ function injectCallback(args, value) { | |||
| 1914 | 'assistant': extension_prompt_roles.ASSISTANT, | 1945 | 'assistant': extension_prompt_roles.ASSISTANT, |
| 1915 | }; | 1946 | }; |
| 1916 | 1947 | ||
| 1917 | const id = args?.id; | 1948 | const id = String(args?.id); |
| 1918 | const ephemeral = isTrueBoolean(args?.ephemeral); | 1949 | const ephemeral = isTrueBoolean(String(args?.ephemeral)); |
| 1919 | 1950 | ||
| 1920 | if (!id) { | 1951 | if (!id) { |
| 1921 | console.warn('WARN: No ID provided for /inject command'); | 1952 | console.warn('WARN: No ID provided for /inject command'); |
| @@ -1931,9 +1962,15 @@ function injectCallback(args, value) { | |||
| 1931 | const depth = isNaN(depthValue) ? defaultDepth : depthValue; | 1962 | const depth = isNaN(depthValue) ? defaultDepth : depthValue; |
| 1932 | const roleValue = typeof args?.role === 'string' ? args.role.toLowerCase().trim() : Number(args?.role ?? extension_prompt_roles.SYSTEM); | 1963 | const roleValue = typeof args?.role === 'string' ? args.role.toLowerCase().trim() : Number(args?.role ?? extension_prompt_roles.SYSTEM); |
| 1933 | const role = roles[roleValue] ?? roles[extension_prompt_roles.SYSTEM]; | 1964 | const role = roles[roleValue] ?? roles[extension_prompt_roles.SYSTEM]; |
| 1934 | const scan = isTrueBoolean(args?.scan); | 1965 | const scan = isTrueBoolean(String(args?.scan)); |
| 1966 | const filter = args?.filter instanceof SlashCommandClosure ? args.filter.rawText : null; | ||
| 1967 | const filterFunction = args?.filter instanceof SlashCommandClosure ? closureToFilter(args.filter) : null; | ||
| 1935 | value = value || ''; | 1968 | value = value || ''; |
| 1936 | 1969 | ||
| 1970 | if (args?.filter && !String(filter ?? '').trim()) { | ||
| 1971 | throw new Error('Failed to parse the filter argument. Make sure it is a valid non-empty closure.'); | ||
| 1972 | } | ||
| 1973 | |||
| 1937 | const prefixedId = `${SCRIPT_PROMPT_KEY}${id}`; | 1974 | const prefixedId = `${SCRIPT_PROMPT_KEY}${id}`; |
| 1938 | 1975 | ||
| 1939 | if (!chat_metadata.script_injects) { | 1976 | if (!chat_metadata.script_injects) { |
| @@ -1941,13 +1978,13 @@ function injectCallback(args, value) { | |||
| 1941 | } | 1978 | } |
| 1942 | 1979 | ||
| 1943 | if (value) { | 1980 | if (value) { |
| 1944 | const inject = { value, position, depth, scan, role }; | 1981 | const inject = { value, position, depth, scan, role, filter }; |
| 1945 | chat_metadata.script_injects[id] = inject; | 1982 | chat_metadata.script_injects[id] = inject; |
| 1946 | } else { | 1983 | } else { |
| 1947 | delete chat_metadata.script_injects[id]; | 1984 | delete chat_metadata.script_injects[id]; |
| 1948 | } | 1985 | } |
| 1949 | 1986 | ||
| 1950 | setExtensionPrompt(prefixedId, value, position, depth, scan, role); | 1987 | setExtensionPrompt(prefixedId, String(value), position, depth, scan, role, filterFunction); |
| 1951 | saveMetadataDebounced(); | 1988 | saveMetadataDebounced(); |
| 1952 | 1989 | ||
| 1953 | if (ephemeral) { | 1990 | if (ephemeral) { |
| @@ -1958,7 +1995,7 @@ function injectCallback(args, value) { | |||
| 1958 | } | 1995 | } |
| 1959 | console.log('Removing ephemeral script injection', id); | 1996 | console.log('Removing ephemeral script injection', id); |
| 1960 | delete chat_metadata.script_injects[id]; | 1997 | delete chat_metadata.script_injects[id]; |
| 1961 | setExtensionPrompt(prefixedId, '', position, depth, scan, role); | 1998 | setExtensionPrompt(prefixedId, '', position, depth, scan, role, filterFunction); |
| 1962 | saveMetadataDebounced(); | 1999 | saveMetadataDebounced(); |
| 1963 | deleted = true; | 2000 | deleted = true; |
| 1964 | }; | 2001 | }; |
| @@ -2053,9 +2090,28 @@ export function processChatSlashCommands() { | |||
| 2053 | } | 2090 | } |
| 2054 | 2091 | ||
| 2055 | for (const [id, inject] of Object.entries(context.chatMetadata.script_injects)) { | 2092 | for (const [id, inject] of Object.entries(context.chatMetadata.script_injects)) { |
| 2093 | /** | ||
| 2094 | * Rehydrates a filter closure from a string. | ||
| 2095 | * @returns {SlashCommandClosure | null} | ||
| 2096 | */ | ||
| 2097 | function reviveFilterClosure() { | ||
| 2098 | if (!inject.filter) { | ||
| 2099 | return null; | ||
| 2100 | } | ||
| 2101 | |||
| 2102 | try { | ||
| 2103 | return new SlashCommandParser().parse(inject.filter, true); | ||
| 2104 | } catch (error) { | ||
| 2105 | console.warn('Failed to revive filter closure for script injection', id, error); | ||
| 2106 | return null; | ||
| 2107 | } | ||
| 2108 | } | ||
| 2109 | |||
| 2056 | const prefixedId = `${SCRIPT_PROMPT_KEY}${id}`; | 2110 | const prefixedId = `${SCRIPT_PROMPT_KEY}${id}`; |
| 2111 | const filterClosure = reviveFilterClosure(); | ||
| 2112 | const filter = filterClosure ? closureToFilter(filterClosure) : null; | ||
| 2057 | console.log('Adding script injection', id); | 2113 | console.log('Adding script injection', id); |
| 2058 | setExtensionPrompt(prefixedId, inject.value, inject.position, inject.depth, inject.scan, inject.role); | 2114 | setExtensionPrompt(prefixedId, inject.value, inject.position, inject.depth, inject.scan, inject.role, filter); |
| 2059 | } | 2115 | } |
| 2060 | } | 2116 | } |
| 2061 | 2117 | ||
| @@ -3760,7 +3760,7 @@ export async function checkWorldInfo(chat, maxContext, isDryRun) { | |||
| 3760 | // Put this code here since otherwise, the chat reference is modified | 3760 | // Put this code here since otherwise, the chat reference is modified |
| 3761 | for (const key of Object.keys(context.extensionPrompts)) { | 3761 | for (const key of Object.keys(context.extensionPrompts)) { |
| 3762 | if (context.extensionPrompts[key]?.scan) { | 3762 | if (context.extensionPrompts[key]?.scan) { |
| 3763 | const prompt = getExtensionPromptByName(key); | 3763 | const prompt = await getExtensionPromptByName(key); |
| 3764 | if (prompt) { | 3764 | if (prompt) { |
| 3765 | buffer.addInject(prompt); | 3765 | buffer.addInject(prompt); |
| 3766 | } | 3766 | } |