Files
SillyTavern/public/scripts/st-context.js
T
Wolfsblvt f8c373f55a Macros 2.0 (v0.7.0) -Variable Shorthand: New Operators & Lazy Evaluation (#4997)
* Add new variable shorthand operators and new variable macros

- Add `{{hasvar}}` and `{{deletevar}}` macros for local variables
- Add `{{hasglobalvar}}` and `{{deleteglobalvar}}` macros for global variables
- Implement new variable shorthand operators: `-=`, `||`, `??`, `||=`, `??=`, `==`
- Refactor variable expression evaluation to use direct variable API calls instead of routing through macro registry
- Add comprehensive operator support in lexer with proper token ordering for multi-character operators

* Implement lazy evaluation for variable shorthand value expressions

- Replace eager value evaluation with lazy evaluation pattern for variable operators
- Add `#createLazyValue()` method that caches value expression result on first call
- Change `#executeVariableOperation()` to accept `lazyValue` function instead of pre-evaluated value
- Only evaluate value expressions when actually needed (e.g., when variable is falsy for `||`, when variable doesn't exist for `??`)
- Add comprehensive e2e tests

* Update variable shorthand autocomplete with new operators and add edge case tests

- Add new operators to autocomplete definitions: `-=`, `||`, `??`, `||=`, `??=`, `==`
- Update example lists in `VariableShorthandAutoCompleteOption` and `VariableNameAutoCompleteOption`
- Add operator definitions with descriptions and `needsValue` flags to `VariableOperatorDefinitions`
- Update `parseMacroContext()` to recognize new operators with proper ordering (longer operators checked first)

* Add not equals (!=) operator to variable shorthand expressions

- Add `!=` operator to variable shorthand definitions for local and global variables
- Implement `notEquals` operation in `MacroCstWalker` that returns inverted equality comparison
- Add `NotEquals` token to lexer with pattern `/!=`
- Update parser to handle `!=` operator with value expression
- Add `!=` operator to autocomplete examples and operator definitions
- Update `parseMacroContext()` to recognize `!=` operator and...

* Tiny code review fixes

- Fix typo: "insie" → "inside" in variable shorthand operators comment
- Remove extra space in `{{getglobalvar}}` example usage

* Fix missing closing braces in hasglobalvar macro example usage

* Fix isFalsy to normalize value before checking boolean state in variable shorthand operators

- Apply `normalize()` to value before passing to `isFalseBoolean()` in `isFalsy` helper
- Ensures consistent falsy evaluation for variable shorthand operators like `||`, `??`, `||=`, `??=`

* Fix pipe character inside macro braces being treated as command separator

- Add `isInsideMacroBraces()` method to track unclosed `{{}}` macro braces
- Modify `testCommandEnd()` to only treat `|` as command end when not inside macro braces
- Scan text behind current position to calculate macro brace depth
- Skip second character when detecting `{{` or `}}` pairs
- Ensure `depth` never goes below 0 using `Math.max(0, depth - 1)`

* Add aliases for variable existence and deletion macros

- Add `varexists` alias for `hasvar` macro
- Add `flushvar` alias for `deletevar` macro
- Add `globalvarexists` alias for `hasglobalvar` macro
- Add `flushglobalvar` alias for `deleteglobalvar` macro

* Update variable shorthand operator descriptions to clarify return behavior

- Add "returns nothing" clarification to `=`, `+=`, `-=` operators in examples and definitions
- Add "returns the new value" clarification to `++`, `--` operators in examples and definitions
- Update `VariableOperatorDefinitions` descriptions to match example text
- Ensures users understand which operators return values vs perform silent mutations
2026-01-13 13:32:18 +02:00

287 lines
9.7 KiB
JavaScript

import {
activateSendButtons,
addOneMessage,
appendMediaToMessage,
callPopup,
characters,
chat,
chat_metadata,
CONNECT_API_MAP,
create_save,
deactivateSendButtons,
event_types,
eventSource,
extension_prompts,
extractMessageFromData,
Generate,
generateQuietPrompt,
getCharacters,
getCurrentChatId,
getRequestHeaders,
getThumbnailUrl,
main_api,
max_context,
menu_type,
messageFormatting,
name1,
name2,
online_status,
openCharacterChat,
reloadCurrentChat,
renameChat,
saveChatConditional,
saveMetadata,
saveReply,
saveSettingsDebounced,
selectCharacterById,
sendGenerationRequest,
sendStreamingRequest,
sendSystemMessage,
setExtensionPrompt,
stopGeneration,
streamingProcessor,
substituteParams,
substituteParamsExtended,
this_chid,
updateChatMetadata,
updateMessageBlock,
printMessages,
clearChat,
unshallowCharacter,
deleteLastMessage,
getCharacterCardFields,
swipe_right,
swipe_left,
generateRaw,
showSwipeButtons,
hideSwipeButtons,
deleteMessage,
refreshSwipeButtons,
swipe,
isSwipingAllowed,
swipeState,
ensureMessageMediaIsArray,
getMediaDisplay,
getMediaIndex,
scrollChatToBottom,
scrollOnMediaLoad,
} from '../script.js';
import {
extension_settings,
ModuleWorkerWrapper,
openThirdPartyExtensionMenu,
renderExtensionTemplate,
renderExtensionTemplateAsync,
saveMetadataDebounced,
writeExtensionField,
} from './extensions.js';
import { groups, openGroupChat, selected_group, unshallowGroupMembers } from './group-chats.js';
import { addLocaleData, getCurrentLocale, t, translate } from './i18n.js';
import { hideLoader, showLoader } from './loader.js';
import { MacrosParser } from './macros.js';
import { getChatCompletionModel, oai_settings } from './openai.js';
import { callGenericPopup, Popup, POPUP_RESULT, POPUP_TYPE } from './popup.js';
import { power_user, registerDebugFunction } from './power-user.js';
import { getPresetManager } from './preset-manager.js';
import { humanizedDateTime, isMobile, shouldSendOnEnter } from './RossAscends-mods.js';
import { ScraperManager } from './scrapers.js';
import { executeSlashCommands, executeSlashCommandsWithOptions, registerSlashCommand } from './slash-commands.js';
import { SlashCommand } from './slash-commands/SlashCommand.js';
import { ARGUMENT_TYPE, SlashCommandArgument, SlashCommandNamedArgument } from './slash-commands/SlashCommandArgument.js';
import { SlashCommandParser } from './slash-commands/SlashCommandParser.js';
import { tag_map, tags } from './tags.js';
import { getTextGenServer, textgenerationwebui_settings } from './textgen-settings.js';
import { tokenizers, getTextTokens, getTokenCount, getTokenCountAsync, getTokenizerModel } from './tokenizers.js';
import { ToolManager } from './tool-calling.js';
import { accountStorage } from './util/AccountStorage.js';
import { timestampToMoment, uuidv4 } from './utils.js';
import { addGlobalVariable, addLocalVariable, decrementGlobalVariable, decrementLocalVariable, deleteGlobalVariable, deleteLocalVariable, existsGlobalVariable, existsLocalVariable, getGlobalVariable, getLocalVariable, incrementGlobalVariable, incrementLocalVariable, setGlobalVariable, setLocalVariable } from './variables.js';
import { convertCharacterBook, getWorldInfoPrompt, loadWorldInfo, reloadEditor, saveWorldInfo, updateWorldInfoList } from './world-info.js';
import { ChatCompletionService, TextCompletionService } from './custom-request.js';
import { ConnectionManagerRequestService } from './extensions/shared.js';
import { updateReasoningUI, parseReasoningFromString, getReasoningTemplateByName } from './reasoning.js';
import { IGNORE_SYMBOL } from './constants.js';
import { macros } from './macros/macro-system.js';
export function getContext() {
return {
accountStorage,
chat,
characters,
groups,
name1,
name2,
characterId: this_chid,
groupId: selected_group,
chatId: selected_group
? groups.find(x => x.id == selected_group)?.chat_id
: (characters[this_chid]?.chat),
getCurrentChatId,
getRequestHeaders,
reloadCurrentChat,
renameChat,
saveSettingsDebounced,
onlineStatus: online_status,
maxContext: Number(max_context),
chatMetadata: chat_metadata,
saveMetadataDebounced,
streamingProcessor,
eventSource,
eventTypes: event_types,
addOneMessage,
deleteLastMessage,
deleteMessage,
generate: Generate,
sendStreamingRequest,
sendGenerationRequest,
stopGeneration,
tokenizers,
getTextTokens,
/** @deprecated Use getTokenCountAsync instead */
getTokenCount,
getTokenCountAsync,
extensionPrompts: extension_prompts,
setExtensionPrompt,
updateChatMetadata,
saveChat: saveChatConditional,
openCharacterChat,
openGroupChat,
saveMetadata,
sendSystemMessage,
activateSendButtons,
deactivateSendButtons,
saveReply,
substituteParams,
substituteParamsExtended,
SlashCommandParser,
SlashCommand,
SlashCommandArgument,
SlashCommandNamedArgument,
ARGUMENT_TYPE,
executeSlashCommandsWithOptions,
/** @deprecated Use SlashCommandParser.addCommandObject() instead */
registerSlashCommand,
/** @deprecated Use executeSlashCommandWithOptions instead */
executeSlashCommands,
timestampToMoment,
/** @deprecated Handlebars for extensions are no longer supported. */
registerHelper: () => { },
/** @deprecated Use `macros.register(name, { handler, description })` from scripts/macros/macro-system.js instead. */
registerMacro: MacrosParser.registerMacro.bind(MacrosParser),
/** @deprecated Use `macros.registry.unregisterMacro(name)` from scripts/macros/macro-system.js instead. */
unregisterMacro: MacrosParser.unregisterMacro.bind(MacrosParser),
registerFunctionTool: ToolManager.registerFunctionTool.bind(ToolManager),
unregisterFunctionTool: ToolManager.unregisterFunctionTool.bind(ToolManager),
isToolCallingSupported: ToolManager.isToolCallingSupported.bind(ToolManager),
canPerformToolCalls: ToolManager.canPerformToolCalls.bind(ToolManager),
ToolManager,
registerDebugFunction,
/** @deprecated Use renderExtensionTemplateAsync instead. */
renderExtensionTemplate,
renderExtensionTemplateAsync,
registerDataBankScraper: ScraperManager.registerDataBankScraper.bind(ScraperManager),
/** @deprecated Use callGenericPopup or Popup instead. */
callPopup,
callGenericPopup,
showLoader,
hideLoader,
mainApi: main_api,
extensionSettings: extension_settings,
ModuleWorkerWrapper,
getTokenizerModel,
generateQuietPrompt,
generateRaw,
writeExtensionField,
getThumbnailUrl,
selectCharacterById,
messageFormatting,
shouldSendOnEnter,
isMobile,
t,
translate,
getCurrentLocale,
addLocaleData,
tags,
tagMap: tag_map,
menuType: menu_type,
createCharacterData: create_save,
/** @deprecated Legacy snake-case naming, compatibility with old extensions */
event_types: event_types,
Popup,
POPUP_TYPE,
POPUP_RESULT,
chatCompletionSettings: oai_settings,
textCompletionSettings: textgenerationwebui_settings,
powerUserSettings: power_user,
getCharacters,
getCharacterCardFields,
uuidv4,
humanizedDateTime,
updateMessageBlock,
appendMediaToMessage,
ensureMessageMediaIsArray,
getMediaDisplay,
getMediaIndex,
scrollChatToBottom,
scrollOnMediaLoad,
macros,
swipe: {
left: swipe_left,
right: swipe_right,
to: swipe,
show: showSwipeButtons,
hide: hideSwipeButtons,
refresh: refreshSwipeButtons,
isAllowed: isSwipingAllowed,
state: () => swipeState,
},
variables: {
local: {
get: getLocalVariable,
set: setLocalVariable,
del: deleteLocalVariable,
add: addLocalVariable,
inc: incrementLocalVariable,
dec: decrementLocalVariable,
has: existsLocalVariable,
},
global: {
get: getGlobalVariable,
set: setGlobalVariable,
del: deleteGlobalVariable,
add: addGlobalVariable,
inc: incrementGlobalVariable,
dec: decrementGlobalVariable,
has: existsGlobalVariable,
},
},
loadWorldInfo,
saveWorldInfo,
reloadWorldInfoEditor: reloadEditor,
updateWorldInfoList,
convertCharacterBook,
getWorldInfoPrompt,
CONNECT_API_MAP,
getTextGenServer,
extractMessageFromData,
getPresetManager,
getChatCompletionModel,
printMessages,
clearChat,
ChatCompletionService,
TextCompletionService,
ConnectionManagerRequestService,
updateReasoningUI,
parseReasoningFromString,
getReasoningTemplateByName,
unshallowCharacter,
unshallowGroupMembers,
openThirdPartyExtensionMenu,
symbols: {
ignore: IGNORE_SYMBOL,
},
};
}
export default getContext;