Files
SillyTavern/public/scripts/macros/engine/MacroEngine.js
T
WolfsblvtandCohee e9bedadc0b Macros 2.0 (v0.4) - Add scoped macros (last arg can be scoped), {{if}} macro and macro flags (baseline implementation) (#4913)
* Macros: make category optional, default to UNCATEGORIZED

* Tests: Update macro tests to match new error handling behavior

- Change MacroRegistry tests from expecting thrown errors to capturing console.error logs
- Update MacroLexer tests to expect plaintext fallback instead of lexer errors for invalid tokens
- Fix MacroEngine test to use `char` macro instead of `newline` for arity validation
- Update MacroParser test with corrected expected error message for invalid identifiers
- Remove "[Error]" prefixes from test descriptions where lexer no longer errors

* Macros: Implement macro execution flags system

- Add MacroFlags module with flag parsing and validation (!, ?, ~, /, >, ., $, #)
- Update lexer to tokenize flags as separate tokens before macro identifier
- Modify parser to capture flags in CST under 'flags' label
- Update CST walker to parse flag tokens into MacroFlags object
- Pass parsed flags to macro handlers via MacroCall and MacroContext
- Update autocomplete parser to handle flags before identifier
- Add comprehensive tests for flag parsing,

* Macros: Fix autocomplete positioning for macros with flags and whitespace

- Add identifierStart to parseMacroContext to track where identifier begins in macro text
- Update autocomplete to use identifierStart for correct range calculation
- Simplify indexMacros regex to use global flag instead of manual loop
- Use parseMacroContext in indexMacros to extract identifier (handles flags/whitespace)
- Fix autocomplete range starting at wrong position when flags or whitespace present

* Macros: Add autocomplete support for macro execution flags

- Add MacroFlagAutoCompleteOption class for rendering flag options in autocomplete
- Extend parseMacroContext to track currentFlag (flag cursor is on) and isInFlagsArea
- Track flagEndPositions to determine which flag cursor is currently typing
- Update #buildEnhancedMacroOptions to show flag options when cursor is in flags area
- Show current flag first if cursor just typed it, then show remaining available flags
- Add renderItem and renderDetails methods to MacroFlag

* Macros: Implement scoped macro syntax with opening and closing tags

- Add scoped macro processing to MacroCstWalker to find and merge opening/closing pairs
- Parse closing block flag (/) to identify closing macros and match with opening tags
- Extract content between opening and closing tags as the last unnamed argument
- Add `isScoped` property to MacroCall and MacroContext to track scoped invocations
- Implement `#processScopedMacros` to find outermost matching pairs and handle nesting

* Macros: Add autocomplete warnings, scoped content info, and closing tag suggestions

- Add arity warning banners in autocomplete details for invalid argument counts
- Show warning when using space-separated args on multi-arg or no-arg macros
- Add scoped content info banner when cursor is inside unclosed scoped macro
- Implement MacroClosingTagAutoCompleteOption to suggest closing tags for scoped macros
- Add sortPriority property to AutoCompleteOption for controlling sort order

* SlashCommands: Disable unimplemented flags and closing flag when no unclosed scopes in autocomplete

- Set closing block flag as non-selectable when no unclosed scopes exist
- Set unimplemented flags as non-selectable with empty valueProvider
- Lower sort priority (12) for non-selectable flags vs selectable flags (10)

* Autocomplete: Show scoped content info and auto-close no-arg macros

- Show scoped content info when cursor is at closing }} of unclosed scoped macro
- Auto-complete no-arg macros with closing }} using valueProvider
- Trigger autocomplete on select (isSelect) to refresh after choosing an option
- Simplify MacroFlagAutoCompleteOption to use base makeItem for consistent styling
- Change closing tag icon from '{/}' to '{/' for better visual consistency

* Macros: Add scoped trim macro to trim content inside opening/closing tags

- Add scoped usage for {{trim}}content{{/trim}} to trim whitespace from content
- Keep non-scoped {{trim}} behavior (post-processing marker) for backward compatibility
- Add optional unnamed 'content' argument for scoped usage
- Update description to explain both scoped and non-scoped behavior
- Handler checks isScoped flag to determine which behavior to use

* Autocomplete: Fix closing tag parsing to prevent `/` being treated as flag

- Add special case in parseMacroContext to detect closing tags (`/` + identifier char)
- Stop flag parsing when `/` is followed by identifier character (closing tag syntax)
- Simplify MacroClosingTagAutoCompleteOption valueProvider to return full closing tag
- Remove input-based logic since autocomplete replaces entire identifier

* Macros: Add {{if}} conditional macro with auto-resolution of macro names

- Add {{if condition}}content{{/if}} macro to conditionally show content
- Auto-resolve condition if it matches a registered macro name (0 required args)
- Support both scoped content ({{if x}}...{{/if}}) and explicit args ({{if::x::content}})
- Treat empty string, "false", "off", "0" as falsy conditions
- Inherit environment context when resolving macro names
- Update autocomplete warning to allow space-separated syntax

* Macros: Add centralized identifier validation with pattern enforcement

- Export MACRO_IDENTIFIER_PATTERN from MacroLexer for reuse across modules
- Add isIdentifierValid() helper function to validate macro names and aliases
- Enforce identifier pattern: must start with letter, followed by word chars or hyphens
- Update macro registration to validate both primary names and alias identifiers
- Improve error messages to explain identifier requirements
- Add comprehensive e2e tests for valid/invalid identifier patterns

* Macros: Add tests for scoped {{trim}} macro functionality

* SlashCommands: Fix macro indexing to properly handle nested macros with brace depth tracking

- Replace regex-based macro detection with manual brace depth tracking
- Track opening/closing brace pairs to correctly identify macro boundaries
- Ensure nested macros like {{reverse::Hey {{user}}}} are properly indexed
- Index both outer and inner macros by scanning content recursively
- Handle unclosed macros by defaulting to end of text

* Macros: Add {{else}} branch support to {{if}} conditional macro

- Add {{else}} macro as marker to split then/else branches in {{if}} blocks
- Use control character sequence (\u0000\u001FELSE\u001F\u0000) as internal marker
- Split scoped content on else marker and trim both branches independently
- Return then-branch if condition is truthy, else-branch if falsy
- Auto-suggest {{else}} in autocomplete when inside scoped {{if}} block
- Make {{else}} non-selectable in autocomplete when outside {{if}} scope

* Macros: Add negation support to {{if}} conditional macro with ! prefix

- Add ! prefix support to invert condition evaluation in {{if}} macro
- Parse original macro text to detect ! prefix before macro resolution
- Strip ! from condition after detecting inversion to avoid double-negation
- Invert isFalsy result when ! prefix is detected in original condition
- Prevent ! in resolved values from triggering inversion (only original syntax)

* Autocomplete: Add {{if}} condition autocomplete with zero-arg macro suggestions

- Add EnhancedMacroAutoCompleteOptions typedef for noBraces/paddingAfter/closeWithBraces options
- Support options object in EnhancedMacroAutoCompleteOption constructor alongside context
- Add noBraces mode to display macro names without {{ }} braces (for use as values)
- Add paddingAfter option to match opening whitespace style before closing }}

* Autocomplete: Match opening whitespace padding when auto-closing macros

* Fix `{{if}}` example usages

* Macros: Hide `comment` alias from autocomplete suggestions for `//` macro

* Macros: Simplify {{trim}} handler with destructured parameters and clearer content check

* Macros: Use MacroEngine.evaluate for zero-arg macro resolution in {{if}} condition handler

* Macros: Add auto-trim for scoped content with # flag to preserve whitespace

- Auto-trim scoped content by default in MacroCstWalker before passing to handlers
- Add preserveWhitespace flag (# symbol) to prevent auto-trimming when needed
- Rename legacyHash flag to preserveWhitespace across engine and definitions
- Update {{trim}} handler to rely on engine auto-trim for scoped content
- Update {{if}} handler to respect # flag when trimming branches around {{else}} marker

* Macros: Clarify macro name validation error message to use "alphanumeric characters" instead of "word chars"

* Add 'setspriteoverride' optional 'name' argument

* Refactor ElevenLabs TTS API key handling (#4906)

* Refactor ElevenLabs TTS API key handling #4483

* Remove unused connection button and related event handler from ElevenLabs TTS provider

* Add ElevenLabs STT endpoint

* Add caching system prompt feature for OpenRouter Gemini (#4903)

* feat: add caching system prompt for OpenRouter Gemini

* fix: resolve reviews

* Update GitHub links to llama.cpp

* Add model selection support for llama.cpp router mode (#4910)

* Add model selection support for llama.cpp router mode

- Add llamacpp_model setting to textgen-settings.js
- Implement loadLlamaCppModels() function to fetch and populate models
- Add onLlamaCppModelSelect() handler for model selection
- Update status check to load llama.cpp models when connecting
- Update getTextGenModel() to return selected llama.cpp model
- Add model dropdown to HTML UI in llama.cpp section
- Initialize event handlers and Select2 for better UX
- Add llamacpp_model to preset manager for save/load support
- Add llamacpp_model to slash commands support

This implements model selection for llama.cpp router mode, allowing
users to select from multiple models without restarting the server.
Follows the same pattern as Ollama, Tabby, and vLLM implementations.

* Correct spelling

* Fix clear selection position

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>

* Add glm-4.7 model option and context mapping for Z.AI

* Add select2 style for NanoGPT list
Closes #4911

* Disable macro engine init traces

* Update type annotations for instruct presets and context presets

* Fix test for new error text

* Add MacroStoryString tests

* Add trimContent utility for consistent indentation dedenting in scoped macros

- Add trimScopedContent method to MacroEngine that trims and dedents scoped content based on first non-empty line indentation
- Pass trimContent utility through evaluation context to all macro handlers
- Update {{if}} macro to use trimContent instead of direct trim() call
- Update auto-trim logic in MacroCstWalker to use trimContent for consistent dedenting
- Add trimContent to MacroExecutionContext type definitions

* Add ELSE_MARKER export and cleanup leftover markers in macro processing

* Update trimContent parameter to use options object pattern in JSDoc

* Add processor registration system to MacroEngine with priority-based execution

- Add MacroProcessor callback and RegisteredProcessor typedef for pre/post processors
- Add addPreProcessor/removePreProcessor and addPostProcessor/removePostProcessor methods with priority-based sorting
- Refactor core legacy syntax handling into registered processors with reserved priorities (0-50)
- Move legacy time syntax, marker replacements, brace unescaping, trim macro, and ELSE_MARKER cleanup to registered processors

* Split core processor registration into separate pre and post processor methods

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-12-28 21:36:13 +02:00

395 lines
14 KiB
JavaScript

import { MacroParser } from './MacroParser.js';
import { MacroCstWalker } from './MacroCstWalker.js';
import { MacroRegistry } from './MacroRegistry.js';
import { logMacroGeneralError, logMacroInternalError, logMacroRuntimeWarning, logMacroSyntaxWarning } from './MacroDiagnostics.js';
import { ELSE_MARKER } from '../definitions/core-macros.js';
/** @typedef {import('./MacroCstWalker.js').MacroCall} MacroCall */
/** @typedef {import('./MacroEnv.types.js').MacroEnv} MacroEnv */
/** @typedef {import('./MacroRegistry.js').MacroDefinition} MacroDefinition */
/**
* A processor function that transforms text before or after macro evaluation.
*
* @callback MacroProcessor
* @param {string} text - The text to process.
* @param {MacroEnv} env - The macro environment.
* @returns {string} The processed text.
*/
/**
* @typedef {Object} RegisteredProcessor
* @property {MacroProcessor} handler - The processor function.
* @property {number} priority - Execution priority (lower = earlier).
* @property {string} source - Identifier for debugging/tracking.
*/
/**
* The singleton instance of the MacroEngine.
*
* @type {MacroEngine}
*/
let instance;
export { instance as MacroEngine };
class MacroEngine {
/** @type {MacroEngine} */ static #instance;
/** @type {MacroEngine} */ static get instance() { return MacroEngine.#instance ?? (MacroEngine.#instance = new MacroEngine()); }
/** @type {RegisteredProcessor[]} */
#preProcessors = [];
/** @type {RegisteredProcessor[]} */
#postProcessors = [];
constructor() {
this.#registerCorePreProcessors();
this.#registerCorePostProcessors();
}
/**
* Registers a pre-processor to run before macro evaluation.
*
* @param {MacroProcessor} handler - The processor function.
* @param {Object} [options] - Configuration options.
* @param {number} [options.priority=100] - Execution priority (lower = earlier).
* @param {string} [options.source='unknown'] - Identifier for debugging.
*/
addPreProcessor(handler, { priority = 100, source = 'unknown' } = {}) {
this.#preProcessors.push({ handler, priority, source });
this.#preProcessors.sort((a, b) => a.priority - b.priority);
}
/**
* Removes a previously registered pre-processor.
*
* @param {MacroProcessor} handler - The processor function to remove.
* @returns {boolean} True if the processor was found and removed.
*/
removePreProcessor(handler) {
const index = this.#preProcessors.findIndex(p => p.handler === handler);
if (index !== -1) {
this.#preProcessors.splice(index, 1);
return true;
}
return false;
}
/**
* Registers a post-processor to run after macro evaluation.
*
* @param {MacroProcessor} handler - The processor function.
* @param {Object} [options] - Configuration options.
* @param {number} [options.priority=100] - Execution priority (lower = earlier).
* @param {string} [options.source='unknown'] - Identifier for debugging.
*/
addPostProcessor(handler, { priority = 100, source = 'unknown' } = {}) {
this.#postProcessors.push({ handler, priority, source });
this.#postProcessors.sort((a, b) => a.priority - b.priority);
}
/**
* Removes a previously registered post-processor.
*
* @param {MacroProcessor} handler - The processor function to remove.
* @returns {boolean} True if the processor was found and removed.
*/
removePostProcessor(handler) {
const index = this.#postProcessors.findIndex(p => p.handler === handler);
if (index !== -1) {
this.#postProcessors.splice(index, 1);
return true;
}
return false;
}
/**
* Evaluates a string containing macros and resolves them.
*
* @param {string} input - The input string to evaluate.
* @param {MacroEnv} env - The environment to pass to the macro handler.
* @returns {string} The resolved string.
*/
evaluate(input, env) {
if (!input) {
return '';
}
const safeEnv = Object.freeze({ ...env });
const preProcessed = this.#runPreProcessors(input, safeEnv);
const { cst, lexingErrors, parserErrors } = MacroParser.parseDocument(preProcessed);
// For now, we log and still try to process what we can.
if (lexingErrors && lexingErrors.length > 0) {
logMacroSyntaxWarning({ phase: 'lexing', input, errors: lexingErrors });
}
if (parserErrors && parserErrors.length > 0) {
logMacroSyntaxWarning({ phase: 'parsing', input, errors: parserErrors });
}
// If the parser did not produce a valid CST, fall back to the original input.
if (!cst || typeof cst !== 'object' || !cst.children) {
logMacroGeneralError({ message: 'Macro parser produced an invalid CST. Returning original input.', error: { input, lexingErrors, parserErrors } });
return input;
}
let evaluated;
try {
evaluated = MacroCstWalker.evaluateDocument({
text: preProcessed,
cst,
env: safeEnv,
resolveMacro: this.#resolveMacro.bind(this),
trimContent: this.trimScopedContent.bind(this),
});
} catch (error) {
logMacroGeneralError({ message: 'Macro evaluation failed. Returning original input.', error: { input, error } });
return input;
}
const result = this.#runPostProcessors(evaluated, safeEnv);
return result;
}
/**
* Resolves a macro call.
*
* @param {MacroCall} call - The macro call to resolve.
* @returns {string} The resolved macro.
*/
#resolveMacro(call) {
const { name, env } = call;
const raw = `{{${call.rawInner}}}`;
if (!name) return raw;
// First check if this is a dynamic macro to use. If so, we will create a temporary macro definition for it and use that over any registered macro.
/** @type {MacroDefinition?} */
let defOverride = null;
if (Object.hasOwn(env.dynamicMacros, name)) {
const impl = env.dynamicMacros[name];
defOverride = {
name,
aliases: [],
category: 'dynamic',
description: 'Dynamic macro',
minArgs: 0,
maxArgs: 0,
unnamedArgDefs: [],
list: null,
strictArgs: true, // Fail dynamic macros if they are called with arguments
returns: null,
returnType: 'string',
displayOverride: null,
exampleUsage: [],
source: { name: 'dynamic', isExtension: false, isThirdParty: false },
aliasOf: null,
aliasVisible: null,
handler: typeof impl === 'function' ? impl : () => impl,
};
}
// If not, check if the macro exists and is registered
if (!defOverride && !MacroRegistry.hasMacro(name)) {
return raw; // Unknown macro: keep macro syntax, but nested macros inside rawInner are already resolved.
}
try {
const result = MacroRegistry.executeMacro(call, { defOverride });
try {
return call.env.functions.postProcess(result);
} catch (error) {
logMacroInternalError({ message: `Macro "${name}" postProcess function failed.`, call, error });
return result;
}
} catch (error) {
const isRuntimeError = !!(error && (error.name === 'MacroRuntimeError' || error.isMacroRuntimeError));
if (isRuntimeError) {
logMacroRuntimeWarning({ message: (error.message || `Macro "${name}" execution failed.`), call, error });
} else {
logMacroInternalError({ message: `Macro "${name}" internal execution error.`, call, error });
}
return raw;
}
}
/**
* Runs pre-processors on the input text, before the engine processes the input.
*
* @param {string} text - The input text to process.
* @param {MacroEnv} env - The environment to pass to the macro handler.
* @returns {string} The processed text.
*/
#runPreProcessors(text, env) {
let result = text;
for (const { handler } of this.#preProcessors) {
result = handler(result, env);
}
return result;
}
/**
* Runs post-processors on the input text, after the engine finished processing the input.
*
* @param {string} text - The input text to process.
* @param {MacroEnv} env - The environment to pass to the macro handler.
* @returns {string} The processed text.
*/
#runPostProcessors(text, env) {
let result = text;
for (const { handler } of this.#postProcessors) {
result = handler(result, env);
}
return result;
}
/**
* Registers the core pre/post processors that handle legacy syntax and cleanup.
*/
#registerCorePreProcessors() {
// Pre-processors (priority 0-50 reserved for core)
// This legacy macro will not be supported by the new macro parser, but rather regex-replaced beforehand
// {{time_UTC-10}} => {{time::UTC-10}}
this.addPreProcessor(
text => text.replace(/{{time_(UTC[+-]\d+)}}/gi, (_match, utcOffset) => `{{time::${utcOffset}}}`),
{ priority: 10, source: 'core:legacy-time-syntax' },
);
// Legacy non-curly markers like <USER>, <BOT>, <GROUP>, etc.
// These are rewritten into their equivalent macro forms so they go through the normal engine pipeline.
this.addPreProcessor(
text => text
.replace(/<USER>/gi, '{{user}}')
.replace(/<BOT>/gi, '{{char}}')
.replace(/<CHAR>/gi, '{{char}}')
.replace(/<GROUP>/gi, '{{group}}')
.replace(/<CHARIFNOTGROUP>/gi, '{{charIfNotGroup}}'),
{ priority: 20, source: 'core:legacy-markers' },
);
}
/**
* Registers the core post-processors that handle legacy syntax and cleanup.
*/
#registerCorePostProcessors() {
// Post-processors (priority 0-50 reserved for core)
// Unescape braces: \{ → { and \} → }
// Since \{\{ doesn't match {{ (MacroStart), it passes through as plain text.
// We only need to remove the backslashes in post-processing.
this.addPostProcessor(
text => text.replace(/\\([{}])/g, '$1'),
{ priority: 10, source: 'core:unescape-braces' },
);
// The original trim macro is reaching over the boundaries of the defined macro. This is not something the engine supports.
// To treat {{trim}} as it was before, we won't process it by the engine itself,
// but doing a regex replace on {{trim}} and the surrounding area, after all other macros have been processed.
this.addPostProcessor(
text => text.replace(/(?:\r?\n)*{{trim}}(?:\r?\n)*/gi, ''),
{ priority: 20, source: 'core:legacy-trim' },
);
// Remove any wrongly placed leftover ELSE_MARKER that might have been inserted during processing
this.addPostProcessor(
text => text.replaceAll(ELSE_MARKER, ''),
{ priority: 30, source: 'core:cleanup-else-marker' },
);
}
/**
* Normalizes macro results into a string.
* This mirrors the behavior of the legacy macro system in a simplified way.
*
* @param {any} value
* @returns {string}
*/
normalizeMacroResult(value) {
if (value === null || value === undefined) {
return '';
}
if (value instanceof Date) {
return value.toISOString();
}
if (typeof value === 'object' || Array.isArray(value)) {
try {
return JSON.stringify(value);
} catch (_error) {
return String(value);
}
}
return String(value);
}
/**
* Trims scoped content with optional indentation dedent.
*
* When trimIndent is true (default), this function:
* 1. Trims leading and trailing whitespace (like String.trim())
* 2. Finds the indentation of the first non-empty line
* 3. Removes that amount of leading whitespace from all subsequent lines
*
* This allows neatly formatted scoped macros like:
* ```
* {{if condition}}
* # Heading
* Content here
* {{/if}}
* ```
* To produce "# Heading\nContent here" instead of "# Heading\n Content here"
*
* @param {string} content - The content to trim
* @param {Object} options - Configuration options
* @param {boolean} [options.trimIndent=true] - Whether to also dedent consistent indentation
* @returns {string} The trimmed content
*/
trimScopedContent(content, { trimIndent = true } = {}) {
if (!content) return '';
// If not dedenting, just do a basic trim
if (!trimIndent) {
return content.trim();
}
// Split into lines BEFORE trimming to preserve indentation info
const lines = content.split('\n');
// Find the first non-empty line (has non-whitespace characters)
let baseIndent = 0;
for (const line of lines) {
if (line.trim() !== '') {
// Found first non-empty line - get its indentation
const match = line.match(/^[ \t]*/);
baseIndent = match ? match[0].length : 0;
break;
}
}
// If no indentation to remove, just trim and return
if (baseIndent === 0) {
return content.trim();
}
// Remove the base indentation from ALL lines
const dedentedLines = lines.map(line => {
// Only remove indentation if the line has enough leading whitespace
const match = line.match(/^[ \t]*/);
const lineIndent = match ? match[0].length : 0;
if (lineIndent >= baseIndent) {
return line.slice(baseIndent);
}
// Line has less indentation than base - just trim its leading whitespace
return line.trimStart();
});
// Join and trim the final result
return dedentedLines.join('\n').trim();
}
}
instance = MacroEngine.instance;