### Usage Example: Install Extension Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/extension.md Provides an example of how to asynchronously install an extension and handle potential errors using a try-catch block. ```javascript try { await TavernHelper.installExtension('new-extension'); console.log('Installation complete'); } catch (error) { console.error('Installation failed:', error); } ``` -------------------------------- ### Example: Get Extension Status Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/extension.md Demonstrates how to retrieve and log the installation and enabled status of an extension using its ID. ```javascript const info = TavernHelper.getExtensionStatus('extension-name'); console.log('Installed:', info.installed); console.log('Enabled:', info.enabled); ``` -------------------------------- ### Example: Get SillyTavern Version Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/version.md Demonstrates how to call the getTavernVersion function and log the result to the console. ```javascript const tavernVersion = TavernHelper.getTavernVersion(); console.log('SillyTavern version:', tavernVersion); ``` -------------------------------- ### Install Extension Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/extension.md Initiates the installation process for a specified extension. This is an asynchronous operation. ```typescript async function installExtension(extension_id: string): Promise ``` -------------------------------- ### Example: Get Character Data and Log Properties Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/raw_character.md Demonstrates how to get character data using getCharData and log its description and creator. Ensure the character exists before accessing properties. ```javascript const charData = TavernHelper.getCharData('Alice'); if (charData) { console.log('Description:', charData.data.description); console.log('Creator:', charData.data.creator); } ``` -------------------------------- ### Usage Example: Check Extension Status Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/extension.md Shows how to check if an extension is installed and then retrieve its enabled status, logging the result. ```javascript const extId = 'example-extension'; if (TavernHelper.isInstalledExtension(extId)) { const status = TavernHelper.getExtensionStatus(extId); console.log('Installed, enabled:', status.enabled); } else { console.log('Extension not installed'); } ``` -------------------------------- ### Example: Get TavernHelper Version Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/version.md Demonstrates how to call the getTavernHelperVersion function and log the result to the console. ```javascript const version = TavernHelper.getTavernHelperVersion(); console.log('TavernHelper version:', version); ``` -------------------------------- ### Get Extension Installation Info Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/extension.md Retrieves detailed installation status for an extension, including whether it is installed and enabled. ```typescript function getExtensionInstallationInfo(extension_id: string): { installed: boolean; enabled: boolean; version?: string; } ``` -------------------------------- ### Example: Pre-process Message Sent Event Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/event.md This example demonstrates registering a listener with `_eventMakeFirst` to log a message before other handlers process a `MESSAGE_SENT` event. ```javascript // This will be called before other MESSAGE_SENT listeners TavernHelper._bind._eventMakeFirst( TavernHelper.tavern_events.MESSAGE_SENT, () => { console.log('First to handle message sent'); } ); ``` -------------------------------- ### Get and Display Entries Example Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/lorebook_entry.md Demonstrates how to retrieve all lorebook entries for a worldbook and iterate through them to display their names and a snippet of their content. ```javascript const entries = TavernHelper.getLorebookEntries('MainWorld'); for (const entry of entries) { console.log(`${entry.name}: ${entry.content.substring(0, 50)}...`); } ``` -------------------------------- ### installExtension Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/extension.md Initiates the installation process for a specified extension. This operation is asynchronous. ```APIDOC ## installExtension ### Description Installs an extension. ### Function Signature ```typescript async function installExtension(extension_id: string): Promise ``` ### Parameters #### Path Parameters * **extension_id** (string) - Required - The ID of the extension to install. ### Return * `Promise` - A promise that resolves when the installation is complete. ``` -------------------------------- ### getExtensionInstallationInfo Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/extension.md Retrieves detailed installation status for a given extension, including whether it is installed and enabled. ```APIDOC ## getExtensionInstallationInfo ### Description Gets the installation status and information for an extension. ### Function Signature ```typescript function getExtensionInstallationInfo(extension_id: string): { installed: boolean; enabled: boolean; version?: string; } ``` ### Parameters #### Path Parameters * **extension_id** (string) - Required - The ID of the extension. ### Return * `object` - An object containing installation details: * `installed` (boolean) - True if the extension is installed. * `enabled` (boolean) - True if the extension is enabled. * `version` (string, optional) - The installed version of the extension. ``` -------------------------------- ### List All Script Buttons Example Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/script.md Demonstrates how to retrieve all enabled script buttons and log their names and tooltips. This is a practical example of using `getAllEnabledScriptButtons`. ```javascript const buttons = TavernHelper.getAllEnabledScriptButtons(); for (const btn of buttons) { console.log(`${btn.name}: ${btn.tooltip}`); } ``` -------------------------------- ### Update Script Trees Example Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/script.md Shows how to fetch script trees for a specific character and then update them by enabling all trees. This example uses `getScriptTrees` and `updateScriptTreesWith`. ```javascript const trees = TavernHelper.getScriptTrees({ character_name: 'Alice' }); // Modify trees await TavernHelper.updateScriptTreesWith( { character_name: 'Alice' }, (trees) => { return trees.map(tree => ({ ...tree, enabled: true })); } ); ``` -------------------------------- ### JavaScript Example: Rename Preset Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/preset.md Provides an example of how to use the renamePreset function to change a preset's name from 'OldName' to 'NewName'. ```javascript await TavernHelper.renamePreset('OldName', 'NewName'); ``` -------------------------------- ### Example: Initialize Global State Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/global.md Demonstrates how to call the initializeGlobal function and log a confirmation message. ```javascript // Initialize global state TavernHelper.initializeGlobal(); console.log('Global state initialized'); ``` -------------------------------- ### Example: Emit Custom and Built-in Events Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/event.md These examples show how to emit a custom event with data and a built-in event with a specific argument using `_eventEmit`. ```javascript // Emit a custom event await TavernHelper._bind._eventEmit('my_custom_event', { data: 'value' }); // Emit built-in event await TavernHelper._bind._eventEmit( TavernHelper.tavern_events.MESSAGE_RECEIVED, 42 ); ``` -------------------------------- ### Example: Get and Display Character Avatar Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/raw_character.md Shows how to obtain a character's avatar path and use it to create an image element to display on the page. ```javascript const avatarPath = TavernHelper.getCharAvatarPath('Alice'); console.log('Avatar:', avatarPath); // Output: "characters/Alice.png" ``` -------------------------------- ### Example: Wait for Global Initialization Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/global.md Shows how to use await to pause execution until global state is ready, then logs a confirmation. ```javascript // Wait for global state await TavernHelper.waitGlobalInitialized(); console.log('Ready to use global features'); ``` -------------------------------- ### Example: Wait for First Message Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/event.md This example shows how to use `_eventOnce` to execute a callback only for the very first `MESSAGE_RECEIVED` event. This is useful for initialization or one-off tasks. ```javascript // Wait for the next message TavernHelper._bind._eventOnce( TavernHelper.tavern_events.MESSAGE_RECEIVED, (messageId) => { console.log('First message received:', messageId); } ); ``` -------------------------------- ### Get Installed Extension Types Source: https://github.com/n0vi028/js-slash-runner/blob/main/dist/@types.txt Returns the type of installed extensions, which can be 'local', 'global', or 'system'. ```typescript getExtensionTypes() ``` -------------------------------- ### Example: Post-process Message Sent Event Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/event.md This example shows how to use `_eventMakeLast` to log a message after all other handlers have processed a `MESSAGE_SENT` event. ```javascript // This will be called after other listeners TavernHelper._bind._eventMakeLast( TavernHelper.tavern_events.MESSAGE_SENT, () => { console.log('Last to handle message sent'); } ); ``` -------------------------------- ### Example Code Location Reference Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/INDEX.md Illustrates the format for referencing source file paths and line ranges for functions. ```plaintext src/function/audio.ts:29-44 ``` -------------------------------- ### JavaScript Example: Delete Preset Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/preset.md Demonstrates how to use the deletePreset function to remove a preset named 'OldPreset' and logs the result to the console. This example is useful for understanding the return value of the deletePreset function. ```javascript const deleted = await TavernHelper.deletePreset('OldPreset'); console.log('Deleted:', deleted); ``` -------------------------------- ### Custom Event System Example Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/events.md Demonstrates emitting and listening to custom events using a custom event naming convention (e.g., 'custom:user-action'). ```javascript // Emit custom events await TavernHelper._bind._eventEmit('custom:user-action', { action: 'clicked_button', timestamp: Date.now() }); // Listen to custom events TavernHelper._bind._eventOn('custom:user-action', (data) => { console.log('User action:', data.action); }); ``` -------------------------------- ### Check if Extension is Installed Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/extension.md Verifies whether a specific extension has been installed. ```typescript function isInstalledExtension(extension_id: string): boolean ``` -------------------------------- ### Trigger Slash Command and Get Result Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/slash.md This example demonstrates how to trigger a slash command and retrieve its result using `triggerSlash` with the `withResult` parameter set to true. The result is then logged to the console. ```javascript // Trigger a command await TavernHelper.triggerSlash('/help'); // Get result const result = await TavernHelper.triggerSlash('/getinfo', true); console.log('Info:', result); ``` -------------------------------- ### Example: Register and Remove Listener Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/event.md This example demonstrates registering a listener using `_eventOn` and then removing it later using `_eventRemoveListener`. It's important to keep a reference to the original listener function for removal. ```javascript const myListener = (messageId) => { console.log('Message:', messageId); }; // Register listener TavernHelper._bind._eventOn( TavernHelper.tavern_events.MESSAGE_RECEIVED, myListener ); // Later, remove it TavernHelper._bind._eventRemoveListener( TavernHelper.tavern_events.MESSAGE_RECEIVED, myListener ); ``` -------------------------------- ### Usage Example: Macro Substitution Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/util.md Provides examples of using substitudeMacros for replacing common macros in greetings and structured messages. It shows dynamic text formatting. ```javascript // Replace common macros const greeting = 'Hi {{user_name}}, talking to {{char_name}}'; const result = TavernHelper.substitudeMacros(greeting); console.log(result); // Use in message const message = { message: `User {{user_name}} says hello`, name: '{{char_name}}' }; const formatted = TavernHelper.substitudeMacros(JSON.stringify(message)); console.log(formatted); ``` -------------------------------- ### Example: Listen for Message Received Event Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/event.md This example demonstrates how to listen for a `MESSAGE_RECEIVED` event and log the received message ID. The `handle.stop()` call is crucial for unregistering the listener when it's no longer needed to prevent memory leaks. ```javascript // Listen for message received event const handle = TavernHelper._bind._eventOn( TavernHelper.tavern_events.MESSAGE_RECEIVED, (messageId) => { console.log('Message received:', messageId); } ); // Later, remove the listener handle.stop(); ``` -------------------------------- ### Check Versions Example Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/version.md Combines calls to getTavernHelperVersion and getTavernVersion to display both TavernHelper and SillyTavern versions. ```javascript const thVersion = TavernHelper.getTavernHelperVersion(); const stVersion = TavernHelper.getTavernVersion(); console.log(`TavernHelper: ${thVersion}`); console.log(`SillyTavern: ${stVersion}`); ``` -------------------------------- ### Register Macro-like Function Example Source: https://github.com/n0vi028/js-slash-runner/blob/main/dist/@types.txt Example of registering a macro-like function to count lines within a specific tag. The `context` and `substring` are provided to the replacement function. ```typescript /** * 注册一个新的助手宏 * * @param regex 匹配的正则表达式 * @param replace 针对匹配到的文本所要进行的替换 * * @example * // 注册一个统计行数的宏 * registerMacros( * /(.*?)/gi, * context => content.split('\n').length * ); * * @returns 后续操作 * - `unregister`: 取消注册 */ declare function registerMacroLike( regex: RegExp, replace: (context: MacroLikeContext, substring: string, ...args: any[]) => string, ): RegisterMacroLikeReturn; ``` -------------------------------- ### Trigger Slash Command with Result (Alias Example) Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/slash.md This example shows how to use the `triggerSlashWithResult` alias to execute a slash command and capture its result. ```javascript const result = await TavernHelper.triggerSlashWithResult('/status'); ``` -------------------------------- ### Example: Log Brief Chat History Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/raw_character.md Demonstrates fetching and logging the brief chat history for a specified character. ```javascript const chats = TavernHelper.getChatHistoryBrief('Alice'); console.log('Chat history:', chats); ``` -------------------------------- ### Example: Substitute Macros Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/util.md Demonstrates how to use the substitudeMacros function to replace placeholders in a string. The output will have the macros replaced with sample values. ```javascript const text = 'Hello {{char_name}}, your ID is {{user_id}}'; const result = TavernHelper.substitudeMacros(text); console.log(result); // Output: "Hello Alice, your ID is user123" ``` -------------------------------- ### isInstalledExtension Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/extension.md Checks if a specific extension is currently installed on the system. ```APIDOC ## isInstalledExtension ### Description Checks if an extension is installed. ### Function Signature ```typescript function isInstalledExtension(extension_id: string): boolean ``` ### Parameters #### Path Parameters * **extension_id** (string) - Required - The ID of the extension. ### Return * `boolean` - True if the extension is installed, false otherwise. ``` -------------------------------- ### Example: One-time Injection Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/inject.md Shows how to perform a one-time injection that is automatically removed after the next generation. This is useful for temporary modifications. ```javascript TavernHelper.injectPrompts( [ { id: 'temporary', position: 'in_chat', depth: 10, role: 'user', content: 'Remember to stay in character.', should_scan: false } ], { once: true } // Auto-removed after next generation ); ``` -------------------------------- ### Usage Example: Check Admin Status Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/extension.md Demonstrates how to use the `isAdmin` function to conditionally log messages based on user privileges. ```javascript if (TavernHelper.isAdmin()) { console.log('User is admin, can install extensions'); } else { console.log('User is not admin'); } ``` -------------------------------- ### Example: Simple Greeting Macro Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/macro_like.md Registers a simple macro that returns a greeting based on the current time of day. This macro takes no arguments. ```javascript TavernHelper.registerMacroLike('greeting', () => { const hour = new Date().getHours(); if (hour < 12) return 'Good morning'; if (hour < 18) return 'Good afternoon'; return 'Good evening'; }); // Use: "{{greeting}}" ``` -------------------------------- ### playAudio Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/audio.md Plays an audio file or adds it to the playlist and starts playback. It supports both background music ('bgm') and ambient sounds. ```APIDOC ## playAudio ### Description Plays an audio file or adds it to the playlist and starts playback. Supports background music ('bgm') and ambient sounds. ### Method `playAudio(type: 'bgm' | 'ambient', audio: AudioWithOptionalTitle): void` ### Parameters #### Path Parameters - **type** ('bgm' | 'ambient') - Required - Audio type: 'bgm' for background music or 'ambient' for sound effects. - **audio** (AudioWithOptionalTitle) - Required - Audio object with URL and optional title. - **audio.title** (string) - Optional - Title to display for the audio. Defaults to URL filename. - **audio.url** (string) - Required - URL or path to the audio file. ### Request Example ```javascript TavernHelper.playAudio('bgm', { title: 'Epic Battle Theme', url: 'https://example.com/music/battle.mp3' }); TavernHelper.playAudio('ambient', { url: 'https://example.com/sounds/rain.mp3' }); ``` ### Response `void` ``` -------------------------------- ### Start Development Server Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/configuration.md Launches the development server using pnpm watch. Enables features like inline source maps, disabled minification, and beautified output for easier debugging. ```bash pnpm watch ``` -------------------------------- ### Get All Preset Names Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/preset.md Retrieves a list of all available preset names. Use this to see which presets can be loaded or managed. ```typescript function getPresetNames(): string[] ``` ```javascript const presets = TavernHelper.getPresetNames(); console.log('Available presets:', presets); // Output: ['Default', 'Creative', 'Balanced', ...] ``` -------------------------------- ### Example: Reload Iframe Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/util.md Shows the usage of the _reloadIframe function within a script iframe context to refresh its content. ```javascript this._reloadIframe(); ``` -------------------------------- ### Example: Conditional Injection Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/inject.md Illustrates how to inject a prompt conditionally based on a filter function. The prompt is only included if the filter returns true. ```javascript TavernHelper.injectPrompts([ { id: 'conditional-prompt', position: 'in_chat', depth: 8, role: 'system', content: 'Focus on the current topic.', filter: async () => { // Only inject if condition is met const vars = TavernHelper.getVariables({ type: 'chat' }); return vars.focused === true; }, should_scan: false } ]); ``` -------------------------------- ### Example: Get Last Message ID Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/util.md Shows how to call getLastMessageId to obtain the ID of the last message and log it to the console. ```javascript const lastId = TavernHelper.getLastMessageId(); console.log('Last message:', lastId); ``` -------------------------------- ### Ensure Global State is Ready Before Access Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/global.md This example demonstrates the best practice of awaiting global initialization before accessing global features like variables. ```javascript // Always wait before accessing global features await TavernHelper.waitGlobalInitialized(); const globalVars = TavernHelper.getVariables({ type: 'global' }); console.log('Global variables:', globalVars); ``` -------------------------------- ### Get Current Displayed Message Example Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/displayed_message.md Retrieves and logs the currently displayed message text for a given message ID. ```javascript const current = TavernHelper.retrieveDisplayedMessage(0); console.log('Current display:', current); ``` -------------------------------- ### Refresh Message Display Example Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/displayed_message.md Updates the UI to reflect changes made to a message. This is necessary because message changes do not auto-refresh. ```javascript // Update display after modifying a message await TavernHelper.setChatMessage(0, { message: 'Updated' }); TavernHelper.refreshOneMessage(0); ``` -------------------------------- ### Update Lorebook Entries Example Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/lorebook_entry.md Illustrates how to update lorebook entries by providing an updater function that modifies entries based on a condition, such as disabling entries whose names start with an underscore. ```javascript await TavernHelper.updateLorebookEntriesWith('MainWorld', (entries) => { return entries.map(entry => ({ ...entry, enabled: entry.name.startsWith('_') ? false : entry.enabled })); }); ``` -------------------------------- ### Get Chat Messages (All Pages Included) Source: https://github.com/n0vi028/js-slash-runner/blob/main/dist/@types.txt Retrieves all chat messages for a given range, including those not directly used by the AI (e.g., initial setups, re-rolls). This provides a more complete view of the chat history. Requires `include_swipes: true`. ```typescript declare function getChatMessages( range: string | number, { role, hide_state, include_swipes }?: Omit & { include_swipes?: true }, ): ChatMessageSwiped[]; // Example: Get all messages for the 10th floor const chat_messages = getChatMessages(10, { include_swipes: true }); const chat_messages = getChatMessages('10', { include_swipes: true }); // Example: Get all messages for the latest floor const chat_message = getChatMessages(-1, { include_swipes: true })[0]; // Example: Get all messages across all floors const chat_messages = getChatMessages('0-{{lastMessageId}}', { include_swipes: true }); ``` -------------------------------- ### Example: Injecting a System Prompt Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/inject.md Demonstrates how to inject a system prompt with a specific ID, position, depth, role, and content. The injection can be removed later using the returned handle. ```javascript // Inject a system prompt const handle = TavernHelper.injectPrompts([ { id: 'my-prompt-1', position: 'in_chat', depth: 5, role: 'system', content: 'You are an expert in your field.', should_scan: false } ]); // Later, remove the injection handle.uninject(); ``` -------------------------------- ### Add Lorebook Entry Example Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/lorebook_entry.md Shows how to create a new lorebook entry with specified properties like name, content, and position within the worldbook. ```javascript await TavernHelper.createLorebookEntry('MainWorld', { name: 'New Location', enabled: true, strategy: { type: 'constant', keys: [] }, position: { type: 'before_character_definition' }, content: 'This is a new location in the world.' }); ``` -------------------------------- ### createPreset Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/preset.md Creates a new preset with specified initial configuration. An error is thrown if a preset with the same name already exists. ```APIDOC ## createPreset ### Description Create a new preset with initial configuration. ### Function Signature ```typescript async function createPreset( name: string, preset?: Partial ): Promise ``` ### Parameters #### Path Parameters - **name** (string) - Required - New preset name - **preset** (Partial) - Optional - Initial preset configuration ### Return `Promise` ### Throws Error if preset already exists ### Example ```javascript await TavernHelper.createPreset('MyPreset', { settings: { max_context: 4000, temperature: 0.7, top_p: 0.9 } }); ``` ``` -------------------------------- ### Usage Example: System Instructions Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/inject.md Adds system instructions to the generation pipeline without modifying presets. This is useful for setting the AI's behavior or persona. ```javascript // Add system instructions without modifying preset TavernHelper.injectPrompts([ { id: 'system-creative', position: 'in_chat', depth: 2, role: 'system', content: 'Be creative and imaginative in your responses.', should_scan: false } ]); ``` -------------------------------- ### Script Context Example Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/script.md Illustrates how to access script-specific information like ID, name, and info from within a script's execution context. It also shows how to append new buttons. ```javascript // Inside a script iframe const scriptId = this._getScriptId(); const scriptName = this._getScriptName(); const info = this._getScriptInfo(); console.log(`Script ${scriptName} (${scriptId})`); // Add a button this._appendInexistentScriptButtons([ { name: 'My Button', tooltip: 'Click me', display_text: 'Click' } ]); ``` -------------------------------- ### Get Button Event Trigger Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/script.md Retrieves the trigger for a specific button event type. This function is used to get the action associated with a given event. ```typescript function _getButtonEvent(this: Window, event_type: string): string ``` -------------------------------- ### Usage Example Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/README.md Demonstrates how to access and use the `TavernHelper` API to interact with SillyTavern functionalities like retrieving character information, listening to events, and generating AI responses. ```APIDOC ## Usage Example This example demonstrates how to access and use the `TavernHelper` API. ### Description Access the API, get the current character name, retrieve character data, listen to events, and generate an AI response. ### Method JavaScript ### Endpoint N/A (In-iframe execution) ### Parameters N/A ### Request Example ```javascript // Access the API const helper = window.TavernHelper; // Get current character name const charName = helper.getCurrentCharacterName(); console.log('Current character:', charName); // Get character data const character = await helper.getCharacter(charName); console.log('Character:', character); // Listen to events helper.tavern_events.MESSAGE_RECEIVED; helper._bind._eventOn(helper.tavern_events.MESSAGE_RECEIVED, (messageId) => { console.log('Message received:', messageId); }); // Generate AI response const response = await helper.generate({ user_input: 'Hello!', preset_name: 'in_use' }); console.log('AI response:', response); ``` ### Response N/A (Output is logged to console in the example) ``` -------------------------------- ### Get All Merged Variables Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/variables.md Retrieves all variables merged across global, character, chat, and message scopes. Use this to get a comprehensive view of all available variables. ```typescript function _getAllVariables(this: Window): Record ``` -------------------------------- ### Copy Preset Entries to Another Preset Using setPreset Source: https://github.com/n0vi028/js-slash-runner/blob/main/dist/@types.txt This example copies prompt entries from '预设A' to '预设B' using `setPreset`. It constructs a new preset object for '预设B' by concatenating the prompts from both presets. ```javascript await setPreset('预设B', { prompts: [...getPreset('预设A').prompts, ...getPreset('预设B').prompts], }); ``` -------------------------------- ### Copy Preset Entries to Another Preset Source: https://github.com/n0vi028/js-slash-runner/blob/main/dist/@types.txt This example shows how to copy all prompt entries from one preset ('预设A') to the beginning of another preset ('预设B'). It retrieves both presets, concatenates their prompt arrays, and updates '预设B'. ```javascript const preset_a = getPreset('预设A'); const preset_b = getPreset('预设B'); preset_b.prompts = [...preset_a.prompts, ...preset_b.prompts]; await replacePreset('预设B', preset_b); ``` -------------------------------- ### Get Chat Messages (AI Used Only) Source: https://github.com/n0vi028/js-slash-runner/blob/main/dist/@types.txt Retrieves chat messages that were actually used by the AI. Useful for getting a clean history of AI interactions. Supports filtering by role and hide state. ```typescript declare function getChatMessages( range: string | number, { role, hide_state, include_swipes }?: Omit & { include_swipes?: false }, ): ChatMessage[]; // Example: Get AI-used messages for the 10th floor const chat_messages = getChatMessages(10); const chat_messages = getChatMessages('10'); const chat_messages = getChatMessages('10', { include_swipes: false }); // Example: Get AI-used message for the latest floor const chat_message = getChatMessages(-1)[0]; // Example: Get all AI-used messages const chat_messages = getChatMessages('0-{{lastMessageId}}'); ``` -------------------------------- ### Delete Disabled Lorebook Entries Example Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/lorebook_entry.md Provides an example of how to delete multiple lorebook entries that are marked as disabled. It first retrieves all entries, filters for disabled ones, collects their IDs, and then calls the delete function. ```javascript // Delete all disabled entries const entries = TavernHelper.getLorebookEntries('MainWorld'); const disabledIds = entries .filter(e => !e.enabled) .map(e => e.uid); if (disabledIds.length > 0) { await TavernHelper.deleteLorebookEntries('MainWorld', disabledIds); } ``` -------------------------------- ### Copy Preset Entries to Another Preset Using updatePresetWith Source: https://github.com/n0vi028/js-slash-runner/blob/main/dist/@types.txt This example copies prompt entries from '预设A' to '预设B' using `updatePresetWith`. The updater function retrieves '预设A' and prepends its prompts to '预设B's prompts. ```javascript await updatePresetWith('预设B', preset => { const another_preset = getPreset('预设A'); preset.prompts = [...another_preset.prompts, ...preset.prompts]; return preset; }); ``` -------------------------------- ### getScriptName Source: https://github.com/n0vi028/js-slash-runner/blob/main/dist/@types.txt Gets the name of the current script. ```APIDOC ## getScriptName ### Description Gets the name of the current script. ### Method (Global function) ### Parameters None ### Response #### Success Response (200) - **string** - The name of the script. ``` -------------------------------- ### reinstallExtension Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/extension.md Initiates the reinstallation process for a specified extension. This operation is asynchronous. ```APIDOC ## reinstallExtension ### Description Reinstalls an extension. ### Function Signature ```typescript async function reinstallExtension(extension_id: string): Promise ``` ### Parameters #### Path Parameters * **extension_id** (string) - Required - The ID of the extension to reinstall. ### Return * `Promise` - A promise that resolves when the reinstallation is complete. ``` -------------------------------- ### getScriptInfo Source: https://github.com/n0vi028/js-slash-runner/blob/main/dist/@types.txt Gets the author information comment for the current script. ```APIDOC ## getScriptInfo ### Description Gets the author information comment for the current script. ### Method (Global function) ### Parameters None ### Response #### Success Response (200) - **string** - The author information comment. ``` -------------------------------- ### Adjust Lorebook Settings Example Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/lorebook.md Demonstrates adjusting specific lorebook settings like scan depth and budget cap. Use for performance tuning or increasing context limits. ```javascript // Lower scan depth for performance TavernHelper.setLorebookSettings({ scan_depth: 1, max_depth: 3 }); // Increase budget for more context TavernHelper.setLorebookSettings({ budget_cap: 8000 }); ``` -------------------------------- ### getLastMessageId(): number Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/util.md Get the ID of the last message in chat. ```APIDOC ## getLastMessageId ### Description Get the ID of the last message in chat. ### Function Signature ```typescript function getLastMessageId(): number ``` ### Parameters (None) ### Returns number - Last message index ### Example ```javascript const lastId = TavernHelper.getLastMessageId(); console.log('Last message:', lastId); ``` ``` -------------------------------- ### Update Check Example Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/version.md Demonstrates checking the current TavernHelper version and then attempting to update it, logging the outcome. Handles potential errors or cases where the software is already up to date. ```javascript const current = TavernHelper.getTavernHelperVersion(); console.log('Current version:', current); // Check for updates manually try { await TavernHelper.updateTavernHelper(); console.log('Updated successfully'); } catch (error) { console.log('Already up to date or error:', error); } ``` -------------------------------- ### Get All Lorebooks Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/lorebook.md Retrieves a list of all available worldbook names. ```typescript function getLorebooks(): string[] ``` -------------------------------- ### Example: Update TavernHelper Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/version.md Shows how to use the updateTavernHelper function within a try-catch block to handle potential errors during the update process. Logs success or failure messages. ```javascript try { await TavernHelper.updateTavernHelper(); console.log('Update complete, reload page'); } catch (error) { console.error('Update failed:', error); } ``` -------------------------------- ### Get Extension Type Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/extension.md Determines the type of a given extension based on its ID. ```typescript function getExtensionType(extension_id: string): string ``` -------------------------------- ### Get TavernHelper Extension ID Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/extension.md Retrieves the unique identifier for the TavernHelper extension. ```typescript function getTavernHelperExtensionId(): string ``` -------------------------------- ### Reinstall Extension Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/extension.md Initiates the reinstallation process for a specified extension. This is an asynchronous operation. ```typescript async function reinstallExtension(extension_id: string): Promise ``` -------------------------------- ### Get Last Message ID Source: https://github.com/n0vi028/js-slash-runner/blob/main/dist/@types.txt Retrieves the ID of the most recent message in the chat history. ```typescript declare function getLastMessageId(): number; ``` -------------------------------- ### SETTINGS_LOADED_BEFORE Source: https://github.com/n0vi028/js-slash-runner/blob/main/dist/@types.txt Fired just before settings are loaded. ```APIDOC ## SETTINGS_LOADED_BEFORE ### Description Called before the application settings are loaded. ### Event Signature `[tavern_events.SETTINGS_LOADED_BEFORE]: (settings: object) => void;` ### Parameters #### Event Payload - **settings** (object) - The settings object that is about to be loaded. ``` -------------------------------- ### Apply Regex to Text for a Character Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/tavern_regex.md Example demonstrating how to format a string with regex scripts applied for a specific character using JavaScript. Logs the original and formatted strings. ```javascript const original = 'Hello World'; const formatted = TavernHelper.formatAsTavernRegexedString( original, 'Alice' ); console.log('Formatted:', formatted); ``` -------------------------------- ### getMessageId(iframe_name: string): number Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/util.md Get message ID from iframe name string. ```APIDOC ## getMessageId ### Description Get message ID from iframe name string. ### Function Signature ```typescript function getMessageId(iframe_name: string): number ``` ### Parameters - **iframe_name** (string) - Required - Iframe element ID/name ### Returns number - Message index ``` -------------------------------- ### SETTINGS_LOADED_AFTER Source: https://github.com/n0vi028/js-slash-runner/blob/main/dist/@types.txt Fired after settings have been successfully loaded. ```APIDOC ## SETTINGS_LOADED_AFTER ### Description Called after the application settings have been loaded. ### Event Signature `[tavern_events.SETTINGS_LOADED_AFTER]: (settings: object) => void;` ### Parameters #### Event Payload - **settings** (object) - The settings object that was just loaded. ``` -------------------------------- ### Get SillyTavern Version Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/version.md Retrieves the current version string of SillyTavern. This is a read-only operation. ```typescript function getTavernVersion(): string ``` -------------------------------- ### loadPreset Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/preset.md Loads a specified preset, making it the active configuration for AI generation. An error is thrown if the preset does not exist. ```APIDOC ## loadPreset ### Description Load a preset to make it active. ### Function Signature ```typescript async function loadPreset(name: string): Promise ``` ### Parameters #### Path Parameters - **name** (string) - Required - Preset name to load ### Return `Promise` ### Throws Error if preset doesn't exist ### Example ```javascript await TavernHelper.loadPreset('Creative'); console.log('Loaded Creative preset'); ``` ``` -------------------------------- ### Get Frontend Version Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/version.md An alias for getTavernHelperVersion, used to retrieve the frontend version information. ```typescript function getFrontendVersion(): string ``` -------------------------------- ### Get TavernHelper Version Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/version.md Retrieves the current version string of TavernHelper. This is a read-only operation. ```typescript function getTavernHelperVersion(): string ``` -------------------------------- ### Get Chat Lorebook Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/lorebook.md Retrieves the name of the worldbook currently associated with the active chat. ```typescript function getChatLorebook(): string | null ``` -------------------------------- ### Combined Initialization and Waiting Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/global.md Shows a sequence where global state is initialized and then immediately awaited, ensuring all features are safe to use afterward. ```javascript // Initialize and wait TavernHelper.initializeGlobal(); await TavernHelper.waitGlobalInitialized(); // Now safe to use all features const characters = TavernHelper.getCharacterNames(); console.log('Characters loaded:', characters); ``` -------------------------------- ### getScriptButtons Source: https://github.com/n0vi028/js-slash-runner/blob/main/dist/@types.txt Gets the list of buttons for the current script. This function is intended for internal script use only. ```APIDOC ## getScriptButtons ### Description Gets the list of buttons for the current script. This function is intended for internal script use only. ### Method (Global function) ### Parameters None ### Response #### Success Response (200) - **ScriptButton[]** - An array of script buttons. ### Example ```javascript // 在脚本内获取当前脚本的按钮设置 const buttons = getScriptButtons(); ``` ``` -------------------------------- ### Example: Dynamic Macro with Arguments Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/macro_like.md Registers a macro that concatenates multiple string arguments provided to it. This demonstrates how macros can accept and process dynamic arguments. ```javascript TavernHelper.registerMacroLike('concat', (...args) => { return args.join(' '); }); // Use: "{{concat Hello World}}" ``` -------------------------------- ### Get Model List Source: https://github.com/n0vi028/js-slash-runner/blob/main/dist/@types.txt Retrieves a list of available AI models from a specified API endpoint. ```javascript const models = await getModelList({ apiurl: 'https://your-proxy-url.com', key: 'your-api-key' }); console.info('可用模型: ', models); ``` -------------------------------- ### Get Tavern Helper Extension ID Source: https://github.com/n0vi028/js-slash-runner/blob/main/dist/@types.txt Retrieves the unique identifier for the Tavern Helper extension. ```typescript getTavernHelperExtensionId() ``` -------------------------------- ### Example: Registering and Using a Dice Roll Macro Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/macro_like.md Demonstrates how to register a macro-like function named 'roll_dice' that simulates rolling a die. The registered macro can then be used in text templates. ```javascript const handle = TavernHelper.registerMacroLike( 'roll_dice', (sides = 20) => { return Math.floor(Math.random() * sides) + 1; } ); // Use in text via {{roll_dice 20}} ``` -------------------------------- ### View Regex Scripts for a Character Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/tavern_regex.md Example of how to retrieve and iterate through regex scripts for a character using JavaScript. Logs the name of each regex pattern found. ```javascript const regexes = TavernHelper.getTavernRegexes('Alice'); for (const regex of regexes) { console.log(`Pattern: ${regex.name}`); } ``` -------------------------------- ### Get Worldbook Data Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/worldbook.md Retrieves the complete data for a specified worldbook, including all its entries and settings. ```typescript async function getWorldbook(name: string): Promise ``` -------------------------------- ### getButtonEvent Source: https://github.com/n0vi028/js-slash-runner/blob/main/dist/@types.txt Gets the event type associated with a button name. This function is intended for internal script use only. ```APIDOC ## getButtonEvent ### Description Gets the event type associated with a button name. This function is intended for internal script use only. ### Method (Global function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **button_name** (string) - Required - The name of the button. ### Response #### Success Response (200) - **string** - The event type of the button. ### Example ```javascript const event_type = getButtonEvent('按钮名'); eventOn(event_type, () => { console.log('按钮被点击了'); }); ``` ``` -------------------------------- ### Initialize Chat-Scoped Variables Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/variables.md Sets up initial state for chat-specific variables like conversation topic and message count. Use this at the beginning of a conversation. ```javascript // Initialize conversation state TavernHelper.insertVariables( { type: 'chat' }, { conversationTopic: 'weather', messageCount: 0, sentiment: 'neutral' } ); ``` -------------------------------- ### TEXT_COMPLETION_SETTINGS_READY Source: https://github.com/n0vi028/js-slash-runner/blob/main/dist/@types.txt Indicates that settings for text completion are ready. ```APIDOC ## TEXT_COMPLETION_SETTINGS_READY ### Description Fired when all necessary settings for text completion have been loaded and are ready for use. ### Event Signature `[tavern_events.TEXT_COMPLETION_SETTINGS_READY]: () => void;` ``` -------------------------------- ### Get Script Name Source: https://github.com/n0vi028/js-slash-runner/blob/main/dist/@types.txt Retrieves the name of the current script. This function is intended for use within scripts. ```typescript /** 获取脚本名称 */ declare function getScriptName(): string; ``` -------------------------------- ### retrieveDisplayedMessage Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/displayed_message.md Retrieves the currently displayed version of a message. This is useful for getting the exact text shown to the user. ```APIDOC ## retrieveDisplayedMessage ### Description Gets the currently displayed version of a message. ### Method Signature ```typescript function retrieveDisplayedMessage(message_id: number): string ``` ### Parameters #### Path Parameters - **message_id** (number) - Required - Message index ### Return - **string** - Current displayed message text ### Example ```javascript const current = TavernHelper.retrieveDisplayedMessage(0); console.log('Current display:', current); ``` ``` -------------------------------- ### Project File Structure Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/INDEX.md Displays the directory and file organization of the JS-Slash-Runner project. ```plaintext /workspace/home/output/ ├── README.md # Project overview ├── INDEX.md # This file ├── types.md # Type definitions ├── events.md # Event reference ├── configuration.md # Configuration options └── api-reference/ # 20 module documentation files ├── audio.md ├── character.md ├── chat_message.md ├── displayed_message.md ├── event.md ├── extension.md ├── generate.md ├── global.md ├── inject.md ├── lorebook.md ├── lorebook_entry.md ├── macro_like.md ├── preset.md ├── raw_character.md ├── script.md ├── slash.md ├── tavern_regex.md ├── util.md ├── variables.md ├── version.md └── worldbook.md ``` -------------------------------- ### Get Lorebook Entries Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/lorebook_entry.md Retrieves all entries from a specified worldbook. Used to fetch existing lorebook data. ```typescript function getLorebookEntries(worldbook_name: string): WorldbookEntry[] ``` -------------------------------- ### Initialize Global State Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/global.md Call this function to start the initialization of global state and variables. It does not return any value. ```typescript function initializeGlobal(): void ``` -------------------------------- ### Common Slash Command Examples Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/slash.md This snippet illustrates the usage of various common slash commands, including saving chat, loading presets, generating content, and retrieving character information. Some commands are triggered without expecting a result, while others capture and log the result. ```javascript // Save chat await TavernHelper.triggerSlash('/save'); // Load preset await TavernHelper.triggerSlash('/loadpreset PresetName'); // Generate await TavernHelper.triggerSlash('/gen'); // Get character info const info = await TavernHelper.triggerSlashWithResult('/charinfo'); console.log(info); ``` -------------------------------- ### getPreset Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/preset.md Retrieves the full configuration details of a specific preset. If no name is provided, it returns the configuration of the currently active preset. ```APIDOC ## getPreset ### Description Get the full configuration of a preset. ### Function Signature ```typescript function getPreset(name?: string): Preset ``` ### Parameters #### Path Parameters - **name** (string) - Optional - Default: Current preset - Preset name to retrieve ### Return `Preset` object containing settings and prompts ### Example ```javascript const preset = TavernHelper.getPreset('Default'); console.log('Max context:', preset.settings.max_context); console.log('Temperature:', preset.settings.temperature); console.log('Prompts:', preset.prompts.length); ``` ``` -------------------------------- ### uninstallExtension Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/extension.md Initiates the uninstallation process for a specified extension. This operation is asynchronous. ```APIDOC ## uninstallExtension ### Description Uninstalls an extension. ### Function Signature ```typescript async function uninstallExtension(extension_id: string): Promise ``` ### Parameters #### Path Parameters * **extension_id** (string) - Required - The ID of the extension to uninstall. ### Return * `Promise` - A promise that resolves when the uninstallation is complete. ``` -------------------------------- ### Get Current Character Name Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/character.md Fetches the name of the character that is currently selected. Returns null if no character is active. ```typescript function getCurrentCharacterName(): string | null ``` ```javascript const currentChar = TavernHelper.getCurrentCharacterName(); if (currentChar) { console.log('Currently talking to:', currentChar); } else { console.log('No character selected'); } ``` -------------------------------- ### getLorebooks Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/lorebook.md Retrieves a list of all available worldbook names. This function can be used to get a list of all worldbooks that can be managed or bound. ```APIDOC ## getLorebooks ### Description Get all worldbooks. ### Method GET (Conceptual - SDK function call) ### Endpoint N/A (SDK Function) ### Parameters None ### Response #### Success Response - **string[]** - An array of strings, where each string is the name of a worldbook. ### Response Example ```json [ "Worldbook1", "Worldbook2" ] ``` ``` -------------------------------- ### showLoader Source: https://github.com/n0vi028/js-slash-runner/blob/main/dist/@types.txt Displays a loading indicator in the UI. ```APIDOC ## showLoader ### Description Displays a visual loading indicator to the user, typically used to signify that an operation is in progress. ### Method (Likely part of an SDK or library) ### Response * **void** ``` -------------------------------- ### Get or Create Chat Lorebook Source: https://github.com/n0vi028/js-slash-runner/blob/main/_autodocs/api-reference/lorebook.md Retrieves the worldbook for the current chat, creating it if it does not exist. An optional name can be provided. ```typescript async function getOrCreateChatLorebook(worldbook_name?: string): Promise ```