Compare commits

...
450 Commits
Author SHA1 Message Date
Cohee 9a191c41e8 Merge pull request #4316 from SillyTavern/staging
Staging
2025-07-26 22:16:05 +03:00
Cohee e8247ca8e9 Remove ⌛ from readmes 2025-07-26 21:27:22 +03:00
Cohee ce1b5ba91c Fix header level nesting 2025-07-26 21:23:07 +03:00
Cohee 24ec287fa5 Cull down the repo readme to bare minimum (#4315)
* Cull down the repo readme to bare minimum

* Return some fluff sections

* Update localized readmes

* Fix image url
2025-07-26 21:20:10 +03:00
Cohee 2c0d8d71bc Browser launch: Add support for Brave browser 2025-07-26 18:29:15 +03:00
Cohee def315eb98 Bump version to 1.13.2 2025-07-26 18:26:47 +03:00
Cohee a8bb8a6703 Add hint popup on string length overflow 2025-07-26 18:20:45 +03:00
Cohee 27487f1f2a MistralAI: new magistral subversions 2025-07-26 01:52:35 +03:00
Cohee 82d9fa79e8 Add vectorization via Vertex AI (#4311)
* Add vectorization via Vertex AI

* Enable batching for Google vectors

* Add batch embeddings for Vertex

* Split embed methods for Vertex/AI Studio
2025-07-25 23:59:30 +03:00
Cohee c094e5d8ef Fix type errors in variables.js 2025-07-25 22:37:09 +03:00
IceFog72 8948d9773e Adding unique galleryImageDraggable class to draggable div with gallery Image inside (#4310) 2025-07-25 22:32:59 +03:00
Cohee 2a971a517c Adjust tags list to use screen size relative units 2025-07-25 22:31:30 +03:00
Cohee fdc51a1211 Claude model deprecations (#4306)
* Claude: deprecate Claude 2 models

* Claude: flatten tool call schema

* Remove deprecated Sonnet 3 from captioning list
2025-07-25 22:06:12 +03:00
Cohee 6224e20cbe Merge pull request #4305 from SillyTavern/feat/allow-empty-setvar
Allow empty values in {{setvar/setglobalvar}}
2025-07-25 22:04:56 +03:00
Cohee 29702a3f1b Merge pull request #4302 from cloudskytian/staging
Console access log output is now controlled by enableAccessLog
2025-07-25 22:02:27 +03:00
cloudskytian 9cd7910aff Update config.yaml for Console access log output is now controlled by enableAccessLog 2025-07-25 10:18:42 +08:00
Coheeandzonde306 90adf2f104 Allow extensions to add or exclude WI entries (#4304)
* Allows control of Lore books entries by extensions

* WORLDINFO_SORTING changed to WORLDINFO_ENTRIES_LOADED

---------

Co-authored-by: zonde306 <anonymous@localhost>
2025-07-24 23:21:48 +03:00
zonde306 53d96deaff WORLDINFO_SORTING changed to WORLDINFO_ENTRIES_LOADED 2025-07-25 04:09:33 +08:00
zonde306 ac759e5b7e Allows control of Lore books entries by extensions 2025-07-25 03:36:01 +08:00
Cohee d641cbecc4 Remove Scale Spellbook from CC sources (#4293) 2025-07-24 22:02:45 +03:00
Cohee d3818244e6 Merge branch 'release' into staging 2025-07-24 21:34:00 +03:00
Cohee bcf5f65759 Fix audit in tests 2025-07-24 21:33:54 +03:00
Cohee 487c7fa120 Fix npm audit 2025-07-24 21:33:15 +03:00
Cohee 38a5e4a4f2 Refactor BYAF parsing (#4303)
* Refactor BYAF parsing

* Refactor ByafParser to use private field for data and improve type annotations
2025-07-24 21:31:45 +03:00
cloudskytian d1a82c85a5 Console access log output is now controlled by enableAccessLog 2025-07-24 19:16:21 +08:00
Cohee 7edd81f183 Remove legacy key from config extras.promptExpansionModel 2025-07-24 00:58:12 +03:00
Cohee c627d77c46 Add toggle and user agent filter for CacheBuster middleware (#4301)
* Add toggle and user agent filter for CacheBuster middleware
Closes #4290 [BUG] SillyTavern takes ~45 seconds to load initially

* Use single instance of CacheBuster class

* Cache config values

* Consistent log header

* Remove unnecessary empty line at the beginning of byaf.js
2025-07-24 00:45:42 +03:00
CoheeandCopilot e0b020f211 Import BYAF (#4300)
* allow byaf import format

* Add byaf import converters

* Fix import of image and scenario

* Update src/byaf.js

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Log JSON parsing errors

* Use fsPromises for file acces

* Fix callback variable name

* Clear file input value after file upload to allow re-uploading

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-07-23 23:05:14 +03:00
Cohee 87ece15faf Fix phantom scroll in WI entry editor 2025-07-23 21:15:02 +03:00
RossAscends e18cde0095 tweak margins on rm_tag_controls to account for collapsed tag lists. 2025-07-23 13:10:57 +09:00
RossAscends b2cae4032c Make charlist tag filter list scrollable 2025-07-23 13:01:53 +09:00
afa3261746 Redesign Creator's Note block (#4298)
* Restyle creator's notes block

* Creator Notes to standoutHeader styling, allows for viewing Note without hiding chardefs

* Fix closing tag

* Remove stray close tag

* Adjust spoiler-free mode toggle

* Make the whole toggle area clickable

* Remove redundant comment

* Add empty state for creator's notes

* Adjust paddings

* Update public/index.html

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>

---------

Co-authored-by: RossAscends <124905043+RossAscends@users.noreply.github.com>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2025-07-23 00:08:56 +03:00
Cohee 0bfb5e1302 Update config.yaml 2025-07-22 23:34:41 +03:00
Cohee 9698c78725 Fix index.html formatting 2025-07-22 20:00:50 +03:00
Cohee 7429726eb1 Remove Window AI from CC sources (#4294) 2025-07-22 19:45:54 +03:00
Cohee 6217ea9888 Navbar: Do not wait for animation duration if it's zero 2025-07-21 21:11:16 +03:00
Cohee d070982ad7 Bump multer field size limit
Closes #4291
2025-07-21 20:26:18 +03:00
Cohee bec05909eb STscript: fix REPLACE_GETVAR with non-lowercase {{getvar}} 2025-07-21 04:02:09 +03:00
Cohee 4177c829d1 Add default global scan data for checkWorldInfo 2025-07-21 01:58:26 +03:00
Coheeandgemini-code-assist[bot] 5d56992ea8 Feat/global install (#4289)
* Update npm dependencies

* Add global paths mode
Closes #4209

* Update src/command-line.js

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>

* Async => Promise.resolve

* Remove unnecessary Promise.resolve()

---------

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2025-07-21 00:24:49 +03:00
Cohee 5f32fba499 Increase padding of rm fixed top 2025-07-20 00:25:13 +03:00
Cohee c292f64163 Add generation type triggers to world info (#4286)
* Add generation type triggers to world info

* Simplify includes check

* Refactor getEntryField validation and default value handling

* Remove invalid attribute

* Check for a valid trigger
2025-07-20 00:22:54 +03:00
Cohee 786d8f43db Merge branch 'release' into staging 2025-07-19 21:07:36 +03:00
Cohee 8f2a194617 [chore] Only HIGH priority comments 2025-07-19 21:05:22 +03:00
Cohee 192236f8dd Add config for jeremy code assist 2025-07-19 21:02:16 +03:00
Cohee fb86dedf29 Show controls when editing compact messages 2025-07-18 22:10:09 +03:00
Cohee 4fd39e8ad3 Improve right menu kbd nav when no char is selected 2025-07-18 22:03:43 +03:00
Cohee c6fe918556 Update .text_muted styles for improved readability and theme consistency 2025-07-18 21:18:00 +03:00
Cohee 043e3bfc50 Make rm_button_bar wrap 2025-07-18 20:55:57 +03:00
CoheeandCopilot ba12b32a1f Characters list top panel touchup (#4282)
* Move search bar under buttons
Closes #4275

* Remove horizontal rules from right menu

* Add toggle for search form

* Add container for extension rm buttons

* Be square or be there

* Adjust font sizes

* Square enlargement program

* Adjust margins

* Remove margin from pagination outlet buttons

* Adjust margin on tag controls

* Collapse 1px margins

* Update public/script.js

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Remove variable assignment

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-07-18 20:01:44 +03:00
kallewoof c3e3fdb0ca chat templates: add Kimi K2 (Moonshot AI) chat template derivation (#4283)
* chat templates: add Kimi K2 (Moonshot AI) chat template derivation

* tweak chatml substring derivation
2025-07-18 11:04:57 +03:00
Cohee 4a8ef76d6f Merge branch 'release' into staging 2025-07-18 01:37:20 +03:00
Cohee f1d6a2e6c9 Fix npm audit 2025-07-18 01:35:46 +03:00
Cohee 808f3ac174 Replace NanoGPT logo 2025-07-18 01:32:04 +03:00
Cohee 13ed0d3ad9 Add height limit to global WI picker
Closes #4278
2025-07-17 21:47:59 +03:00
Cohee d9f4028952 CC/PM: Add generation type trigger prompt filter (#4281)
* CC/PM: Add generation type trigger prompt filter
Closes #4276

* Fix element cast type

* Narrower element types

* Change trigger to multiple select

* Extract class scope function

* Fix control name

* Add 'enabled' property to Prompt class and update type annotations in PromptManager methods

* Clarify placeholder of multiselect
2025-07-17 21:27:26 +03:00
Cohee e7ad36a758 Merge branch 'release' into staging 2025-07-17 13:49:35 +00:00
Cohee a64aae3edf Fix recover.js script 2025-07-17 13:49:15 +00:00
Cohee fddfbc5529 Fix CC import 2025-07-16 00:58:55 +03:00
Cohee 7894e4d361 Google: Fix video inlining with PPP
Fixes #4268
2025-07-15 23:28:26 +03:00
Cohee 0e1d29acfe Bump request payload limits 2025-07-15 23:23:07 +03:00
Cohee 1a92157643 Refactor generateRaw/generateQuietPrompt calls (#4277)
* generateQuietPrompt: Update to object arguments

* generateRaw: Update to object arguments

* Fix jsdoc

* Fix lint

* Unwrap JSON schema options

* Remove default args from gen call
2025-07-15 23:11:31 +03:00
Cohee f8f9ee8a0e NanoGPT: Add backend web search 2025-07-15 22:47:10 +03:00
bmen25124andCohee cd176039ef Added structured output for common APIs (#4272)
* Added structured output for common APIs

* eslint

* Added frontend impl

* Type name change

* Unprefix json_schema, apply review suggestions

* Add schema to generateQuietPrompt, add comments

* Prettify diff

* Extract JSON from Claude response

* Add structured gen for Mistral

* Hack to support schema for DeepSeek

* Hack JSON schema for AI21

* Add Groq structured gen

* Add JSON mode for pollinations

* Add JSON schema for perplexity

* Add JSON schema for AIML

* Using extractJsonFromData in custom-request, added google rules for flattenSchema

* Fix response parsing

* Fix Google

* Fixed json parse

* Expose generateRaw to getContext

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-07-15 21:54:36 +03:00
cloak1505andCohee 87f8a3eb2c Add Moonshot AI instruct template (#4270)
* Add Moonshot AI instruct template

* This is not needed anymore

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-07-15 00:17:12 +03:00
Cohee a4ec66f230 Pollinations: write voice request URL to console 2025-07-14 22:45:01 +03:00
Cohee d3a19f795e Fix type error in falai response handler 2025-07-14 22:42:27 +03:00
Cohee 4607132576 Pollinations: add as TTS provider 2025-07-14 22:29:30 +03:00
Cohee 9a86f8a6bb NovelAI: Fix TTS preview 2025-07-14 22:26:39 +03:00
Frédéric BolvinandCohee 71a3ad0edb apply gemini safety settings as extra_body in OpenRouter requests (#4256)
* apply gemini safety settings as extra_body in OpenRouter requests

* revert adding new gemini safety category

* Make it actually work

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-07-14 21:03:46 +03:00
556fb4ba08 adding prefill parameter to generateRaw() (#4266)
* adding prefill parameter to generateRaw()

* additional comments

* Substitute params in prefill

* Add prefill prompt for /genraw command

* Fix param comment

* fixing generateRaw param comment

* fixing param comment

---------

Co-authored-by: qvink <qvink@users.noreply.github.com>
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-07-14 20:51:53 +03:00
Cohee 3edb5a5616 Add Moonshot AI to OpenRouter providers (#4269) 2025-07-14 10:19:34 +03:00
cloak1505 0c2e2f90a8 Add Moonshot AI to OpenRouter providers 2025-07-14 01:56:55 -05:00
db318cd75c Ability to specify multiple messages and roles in generateRaw() (#4264)
* adding capability for generateRaw() to specify roles of messages for chat completion

* linting

* additional comments

* Apply review comments, fix type errors

* Fix joiner for non-instruct prompts

* Format joint prompt for novel, fix prefix for non-instruct

* Fix role for string prompts

* Do not trim sysprompt for instruct

* Do not prefix names for CC

* Append newline to systemPrompt in instruct

---------

Co-authored-by: qvink <qvink@users.noreply.github.com>
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-07-13 22:04:44 +03:00
Cohee 9a392afee3 Fix type checks 2025-07-13 16:58:34 +03:00
Cohee c9111596c0 Prefer node-fetch instead of native 2025-07-13 16:57:22 +03:00
Cohee 9197527c13 Sync OpenRouter providers 2025-07-13 15:51:57 +03:00
Forkoz c4b5236ed4 Fix nsigma in sampler order value (#4259) 2025-07-12 01:26:06 +03:00
Cohee 4f3eb7417e Fix oai_settings assignment in getPresetList 2025-07-11 22:31:51 +03:00
Forkoz b233402ac9 Ooba nsigma support. (#4258)
* nsigma index.html

* nsigma textgen-settings.js
2025-07-11 22:27:49 +03:00
Cohee 19a8a8625c Move event types + new events (#4257)
* Move app events to separate module

* Add event emission for preset changes and deletions

* Remove unnecessary blank line at the beginning of events.js

* Add await to selectPreset call in initTextGenSettings

* Emit events for preset deletion and change in initPresetManager

* Move event emit out of PRESET_CHANGED
2025-07-11 22:00:04 +03:00
Cohee febb02ffcb /inject: auto-generate ID and fix argument description (#4253)
* /inject: auto-generate ID and fix argument description

* Fix default depth and role handling

* Return ID of the new inject
2025-07-11 13:25:29 +03:00
equal-l2 9842598325 Add vision support for Grok 4 (#4254) 2025-07-10 23:35:30 +03:00
Cohee 13e1d3190e gork-4 2025-07-10 19:44:36 +03:00
Cohee 0ae171985d MistralAI: Add new devstral models 2025-07-10 19:30:04 +03:00
Cohee f8b0e8f2ad Move system messages init into separate module (#4251)
* Move system messages init into separate module

* getSystemMessages => initSystemMessages
2025-07-10 19:22:16 +03:00
Cohee d785e7a7ce Makes sense that a new temp chat starts if you were already on a temp chat 2025-07-10 09:21:10 +00:00
Cohee f477ed1d74 Move CHAT_CHANGED injects revive listener to initDefaultSlashCommands 2025-07-10 00:11:00 +03:00
Cohee ea5181af08 Preset Manager: Add methods for reading/writing custom data (#4246)
* Preset Manager: Add methods for reading/writing custom data

* Fix loading novel extensions on load

* Move ensurePlainObject to utils

* Init empty object in convertNovelPreset
2025-07-09 23:55:08 +03:00
Cohee 489d46b9a0 Perplexity: unlock reasoning effort 2025-07-09 20:51:21 +03:00
Cohee dd7dbaea5e Perplexity: Add sonar-deep-research to the list 2025-07-09 20:38:56 +03:00
Cohee 0567cdc473 Perplexity: Fix frequency_penalty normalization 2025-07-09 20:36:19 +03:00
Cohee 6ee5d7ff9c MistralAI: Add small-2506 to the list 2025-07-09 20:30:43 +03:00
Cohee 86bac00a81 Groq: Pull models list from endpoint 2025-07-09 20:25:20 +03:00
Cohee 5be2323e23 AI21: Add Jamba 1.7 models 2025-07-09 20:09:34 +03:00
Cohee b737af47b5 Refactor OpenAI preset API endpoints to unify save and delete operations 2025-07-08 21:32:58 +03:00
Cohee 5a6d93fc03 Vectors: Fix passing model id to AI Studio 2025-07-08 09:41:28 +00:00
Cohee de3d91670a Fix add max height and scroll overflow to hamburger and wand menus
Fixes #4242
2025-07-07 21:55:45 +03:00
Cohee a029a6e1f1 Fix convertTextToBase64 for large files
Reference: https://github.com/google/closure-library/blob/b312823ec5f84239ff1db7526f4a75cba0420a33/closure/goog/crypt/crypt.js#L104-L123
2025-07-07 12:57:48 +00:00
Cohee 96bdc13937 Replace ajax with fetch (#4241)
* Replace ajax with fetch
Fix type errors in power-user / group-chats modules

* Fix single sprite upload

* Return empty object on failed upload
2025-07-06 23:27:53 +03:00
Cohee 55ca4c89b6 Disallow message edits while in delete mode 2025-07-06 20:55:16 +03:00
CoheeandCopilot 28189bb1c7 Move default slash commands to respective module (#4240)
* Move default slash commands to respective module

* Update public/scripts/slash-commands.js

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-07-06 17:17:19 +03:00
Cohee 8449b4bb27 Move Horde status check to respective module 2025-07-06 16:38:52 +03:00
Cohee c51ce1d018 Move text completion settings to respective module (#4239) 2025-07-06 16:32:48 +03:00
Cohee 3d488a5e7b Move DOMPurify hooks to chats module 2025-07-06 16:13:22 +03:00
CoheeandCopilot 2f56a73368 Move NovelAI settings to respective module (#4238)
* Move NovelAI settings to respective module

* Update public/scripts/nai-settings.js

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-07-06 16:05:26 +03:00
Cohee 88ef9ca0de Properly save chat QR metadata in groups
Fixes #4121
2025-07-06 15:11:00 +03:00
Jenner La Fave b45477578f Fix FAL.AI models list endpoint (#4236)
The FAL.AI endpoint seems to have switched to a paginated format where the
results are nested under an `items` key. This updates the endpoint handler to
fetch all pages and extract the model options correctly.
2025-07-06 14:53:41 +03:00
CoheeandCopilot e1a55408b6 OpenRouter: match both id/text in select2 (#4237)
* OpenRouter: match both id/text in select2

* Update public/scripts/utils.js

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-07-06 14:41:25 +03:00
Marcela Petra Ferraz de NovaesandCohee 38a7668535 Feature/add character tags to message div option (#4225)
* Adding toggle.

* Adding events for the new toggle. Reloading chat when toggled.

* Adding chat reload when tags are added or removed to char.

* Adding main applyCharacterTagsToMessageDivs function to add tags to divs.

* Adding information that the class name is normalized and lowercased to the tooltip.

* Correcting console.traces to console.debug for minimal console printing.

* Lint indentation fix.

* Adding simple cache.

* Adding reload event when a new message is added to chat.

* Changing tags applied from classes to HTML data API.

* Adding guide showing how to select data attributes with CSS.

* Fixing trailing comma pointed out by lint.

* Simplifying re-rendering by deleting previous attributes.

* Adding the feature as default behavior, removing toggles. Will add docs to ST docs.

* Removing code that is no longer needed.

* Re-rendering divs after other tag operations.

* Filtering message ids to only re-render specific divs. Adding suggested changes.

* After testing, it seems to add all messages by one, so it appears it's not needed call this in the printMessages function.

* Lint fixes.

* Cache jquery selector

* Fix local variables assignment

* Move new functions to tags module

* Normalizing tag names before adding them as data-*

* Replace commas with spaces to avoid issues with tag names containing commas.

* Correcting where the comma replacing should go.

* Add error handling for applyCharacterTagsToMessageDivs

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-07-05 22:37:43 +03:00
CoheeandCopilot e0469b4808 Move Kobold Classic settings into related module (#4234)
* Move Kobold Classic settings into related module

* Update public/scripts/kai-settings.js

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-07-05 21:00:06 +03:00
Cohee fad1fa3a33 Hide prompt cost block for non-TC APIs 2025-07-05 20:52:29 +03:00
CoheeandCopilot 8a6e6503f5 Move itemized prompts into separate module (#4229)
* Move itemized prompts into separate module

* Update public/scripts/itemized-prompts.js

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update public/scripts/itemized-prompts.js

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-07-05 16:21:17 +03:00
Cohee 85f38542b6 Improve sanitation of CSS pseudo-classes (#4230) 2025-07-05 16:13:35 +03:00
Cohee a68d31b1b9 Non-streaming narrate by paragraphs setting now actually works automatically regardless of streaming-related settings. Resolves #4228. (#4232) 2025-07-05 12:22:17 +03:00
Gness Erquint 9aab4ea648 Non-streaming narrate by paragraphs setting now actually works automatically regardless of streaming-related settings. Resolves #4228. 2025-07-05 08:25:03 +03:00
Cohee 257883a5f9 Fix creation of characters with additional WI files assigned 2025-07-04 20:33:17 +03:00
GregW6andCohee 1547a53d7c Refactor: Replace Deprecated Code (#4221)
* refactor: ♻️ Replace deprecated code defined within this repository

- Replace ““/public/scripts.js” > `callPopup`” with ““/public/scripts/popup.js” > `callGenericPopup`”.
- Replace ““/public/scripts/tokenizers.js” > `getTokenCount`” with ““/public/scripts/tokenizers.js” > `getTokenCountAsync`”.
- Replace ““/public/scripts/extensions/assets/index.js” > `executeSlashCommands`” with ““/public/scripts/extensions/assets/index.js” > `executeSlashCommandsWithOptions`”.

* refactor: ♻️ Replace deprecated code from standard library

1. Replace set of deprecated `escape` and deprecated `unescape` functions with `encodeURIComponent` and `decodeURIComponent` functions.
2. Replace set of `encodeURIComponent` and deprecated `unescape` functions with a custom `convertTextToBinaryString` function.

* refactor: ♻️ Replace deprecated code imported from external library

All of them is from jQuery.
1. Replace `$(document).ready(() => { ... })` → `jQuery(() => { ... })`.
2. Replace event type direct calls.
    1) Change
        - `$('...').change(function () { ... })` → `$('...').on('change', function () { ... })`.
    2) Click
        - `$('...').click(function () { ... })` → `$('...').on('click', function () { ... })`.
        - `$('...').click()` → `$('...').trigger('click')`.
    3) Focus
        - `$('...').focus(function () { ... })` → `$('...').on('focus', function () { ... })`.
        - `$('...').focus()` → `$('...').trigger('focus')`.
    4) Blur
        - `$('...').blur(function () { ... })` → `$('...').on('blur', function () { ... })`.
    5) Keyup
        - `$('...').keyup(function () { ... })` → `$('...').on('keyup', function () { ... })`.

* refactor(Attachment): ♻️ Merge `convertTextToBinaryString` and `convertTextToBase64`

`convertTextToBase64` function use `Uint8Array.prototype.toBase64` if supported by the Browser and use a combination of `Window.btoa` and `String.fromCharCode` as fallback.

* fix: 🐛 Fix Bind World Info to Character Card

Using the new `Popup` class.

* fix: 🐛 Fix Bind World Info to Character Card

Using the new `Popup` class.

* refactor: 🐛 Refactor and fix Character World Info popup

Add singleton back and some optimization.

-   **🛡️ Singleton Pattern:** Implemented a singleton pattern using the `characterWorldPopup` variable. This prevents multiple instances of the popup from being created, ensuring a clean and predictable UI. If the popup is already open, it will be brought into focus instead of creating a duplicate.
-   **♻️ Improved Readability:** The event handling logic has been extracted into clearly named functions (`handlePrimaryWorldSelect`, `handleExtrasWorldSelect`), making the `Popup` constructor cleaner and the overall code more readable and maintainable.
-   **⚙️ Optimized Performance:** The new implementation caches frequently accessed values and jQuery selectors, reducing redundant DOM lookups and improving performance.

---

* refactor(Chat): ♻️ Modernize chat deletion confirmation

Replaces the deprecated `callPopup` with the modern `callGenericPopup` for the chat deletion confirmation dialog.

* Fix /delchat command

* Remove unused code

* Fix type. Change value to debug log

* Remove value logs

* Remove singleton pattern for openCharacterWorldPopup

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-07-04 19:42:51 +03:00
Cohee 649a4b19f4 Revert old logic of zoomed img resolve 2025-07-04 01:33:08 +03:00
Cohee 46eb01d8be Fix clickable avatar 2025-07-04 01:29:08 +03:00
Cohee 1e63fdd4b3 Clean-up console.trace calls 2025-07-04 01:25:47 +03:00
Cohee 9cdfb8b596 Remove console.debug from tags colorize handler 2025-07-04 01:24:36 +03:00
Marcela Petra Ferraz de Novaes 3f842d2049 Bugfix - Clicking on tag view list toggles checkbox (#4227)
* Adding event.preventDefault() to prevent checkbox toggle when clicking to open pop-up.

* Adjusting comment.
2025-07-04 01:23:51 +03:00
VhalloandCohee 61b12ec657 Current Mistral Small 24B Instruct Format (#4226)
* Current Mistral Small 24B Instruct Format

* Current Mistral Small 24B Instruct Format

* Add new files to index

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-07-03 21:59:16 +03:00
Cohee 51904c2f10 Add persona titles (#4224)
* Add persona titles

* Refactor persona title editing
2025-07-03 19:28:09 +03:00
Cohee d41725cd4f Fix thumbnails for backgrounds containing a single quote 2025-06-30 23:07:50 +03:00
Cohee fbb6180bc1 Adjust scoped variable naming, format comments 2025-06-29 18:09:47 +03:00
kallewoofandCohee 1b2976ae1d feature: customizable mappings for presets per model name / chat template (#4153)
* feature: customizable mappings for presets per chat template

This adds the ability to assign custom context/instruct presets on a per-chat-template(-hash) basis. Users using custom templates may use this feature to auto-enable the preset of their choice, rather than the built-in defaults.

* fix: do not use chat tempate based instruct preset derivation if a preset was auto-selected already

This fixes issues where regex matched presets are overridden.

* reset chat template hash on connect

* handle derive_mappings being null

* unorthodox eslint requirement adherence

* button styling

* un-nest derivation related properties

* Migrate setting

* add bind model to preset button to the miscellaneous section

* switch to unified button for model preset mappings

* fix bind UI

* eslint

* do not include koboldcpp/ggml-model-xxx.gguf in preset saving

* review fixes

* stray console.log / eslint

* Update checkbox state if no model map exists

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-06-29 18:04:00 +03:00
Cohee 380c88d401 Stop click propagation on copy from code blocks
Fixes #4214
2025-06-29 17:26:42 +03:00
Vin AstralisandCohee a7783b62a8 Add Speed Control to ElevenLabs TTS Provider (#4213)
* add speed

* Adjust speed range

* More granular step

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-06-29 02:30:24 +03:00
Cohee 4efed978f0 Enhance file name validation by allowing objects with toString method 2025-06-28 22:36:21 +03:00
Cohee 1e3fada8d7 Prefer sanitize filename with extension 2025-06-28 22:25:14 +03:00
Cohee cdefddef6c Implement persona thumbnails (#4210)
* Implement persona thumbnails

* Dear Firefox, fix your overzealous image cache

* Add cache busting for avatar uploads when overwriting existing files
2025-06-28 21:39:32 +03:00
Cohee 37528c81b3 Caption: Add 'Show captions in chat' setting 2025-06-28 20:00:38 +03:00
Cohee a6b9fffbf7 Merge branch 'release' into staging 2025-06-28 16:29:54 +03:00
Cohee 31e7c65397 Downgrade webpack to 5.98.0 2025-06-28 16:29:24 +03:00
Marcela Petra Ferraz de NovaesandCohee 34118bbdc2 Feature/Perchance AI Character Chat import (#4211)
* Adding ZLib and Jimp imports.

* Adding checks to see if UUID or URL are from Perchance.

* Adding conversion for Perchance cards and avatar.

* Adding label and example for Perchance character import.

* Adding localization of Perchance import option.

* Lint dangling comma fix.

* Simplifying one liner arrow function.

* Checking .gz at the end of Perchance url.

* Refactoring.

* Handling Base64 avatars.

* Fixing issue with UUID and refactoring.

* Adding char name to Perchance UUID example.

* Undoing unwanted variable name change of avatarBuffer to defaultAvatarBuffer

* Adding null check.

* Minor adjustments: renaming variable and organizing imports.

* Simple refactoring and reducing level of console messages.

* Add character source for perchance

* Add null check

* Use slug for source

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-06-28 16:18:26 +03:00
Vin Astralis 363192dd39 feat(elevenlabs): add new models and deprecate old ones (#4212)
* feat(elevenlabs): add new models and deprecate old ones

* feat(elevenlabs): update default model to eleven_turbo_v2_5 and enhance extended settings check
2025-06-28 15:58:09 +03:00
Cohee d91c6c28cb Translate: Update API key management 2025-06-28 15:32:29 +03:00
Cohee 579ef1e86c Refactor API key management in extensions 2025-06-26 21:24:51 +03:00
Cohee 0f73e361df Remove nomicai from secrets input map 2025-06-26 20:53:36 +03:00
Cohee b618f7e4ce select2: Replace line-height with vertical padding 2025-06-26 20:50:44 +03:00
Cohee 780bd1fc65 Add backfill for missing WI entries fields (#4203)
* Add backfill for missing WI entries fields
Fixes #4202

* Backfill before filter/sorting

* Fix array wrapping

* Check if characterFilter is array

* Add console debug for isArray check

* Add isArray check for entry
2025-06-26 20:48:24 +03:00
Cohee 1ad7662f10 select2: adjust single selection placeholder override 2025-06-26 20:31:30 +03:00
qvinkandqvink b3bc065713 Select2 visual bug fix (#4207)
* attempt at fixing select2 spacing issue across browsers

* found the actual problem

* fixing placeholder text

* fixing placeholder text again

* removing references to the select2_multi_sameline

---------

Co-authored-by: qvink <qvink@users.noreply.github.com>
2025-06-26 20:24:21 +03:00
Wolfsblvt b1887a0cc2 Fix default emojis expression setting resetting (#4206)
Adjusts conditions to properly enforce mutual exclusivity between fallback expression and default emoji settings

- Ensures "[ No fallback ]" option only appears when both settings are inactive
- Updates migration logic to ONLY reset default emoji setting when fallback is active

Fixes #4205
2025-06-26 09:47:16 +03:00
Cohee 6f5f945eb2 Merge pull request #4208 from qvink/staging
Removing zh-tw translations for specific extension
2025-06-26 09:45:54 +03:00
Cohee 28f5b74cc7 OpenRouter: Use display name for options on text completion 2025-06-25 22:05:16 +03:00
Cohee 7bf1da7384 Perform save if fixing placement 2025-06-25 22:03:25 +03:00
Cohee 7d7f1b1e29 Check if regex script placement is an array 2025-06-25 22:01:45 +03:00
Cohee 17511c444f Hide image models from Together textgen select 2025-06-25 21:39:24 +03:00
Cohee dbe0111034 Refactor saveBase64AsFile uploads (#4200)
* Refactor saveBase64AsFile uploads

* Add request body check

* Extract server-side constants

* Allow .jfif media attachments

* Allow .bmp uploads

* Enhance image prompt handling: support additional MIME types and prevent upscaling in thumbnails

* Convert file extension to lowercase

* Enhance thumbnail creation: improve image quality and add white background

* Add toast for error in media upload
2025-06-25 21:34:08 +03:00
Cohee 7755fc50a5 Image Generation: Support video outputs for ComfyUI (#4194)
* ImgGen: ComfyUI support video outputs

* Fix video format check to handle undefined and case sensitivity

* Fix error handling and add output debug log in comfy workflows

* Refactor Comfy generation result

* Add video file extensions constant
2025-06-25 20:11:09 +03:00
Cohee 9e6fbde3cf Webpack: Use cache version scoping in Docker 2025-06-25 10:52:04 +00:00
Cohee 66adbea12b Merge branch 'release' into staging 2025-06-25 10:39:14 +00:00
Cohee 12a54d901e WI: exclude characterFilter fields from new entry template 2025-06-25 10:38:08 +00:00
Cohee d641089107 Merge pull request #4199 from GregW6/fix/file-attachment-1
Fix attachment file extension extraction
2025-06-25 00:21:04 +03:00
Cohee f8d7a3e853 Verify if passed a jimp instance to applyAvatarCropResize 2025-06-24 23:38:25 +03:00
GregW6 9bfb4163d3 refactor(Attachment): ♻️ Simplify extension extraction to one line
Removing temporary variable.
2025-06-25 02:27:00 +07:00
GregW6 4785d7580c fix(Attachment): 🐛 Extract file attachment extension through file name 2025-06-24 22:03:11 +07:00
Cohee f30cc04e9e Fix npm audit in tests 2025-06-24 12:59:54 +00:00
Cohee dc533b5ae8 Merge branch 'release' into staging 2025-06-24 12:59:18 +00:00
Cohee 06db0c15db Scope webpack cache by version 2025-06-24 12:58:43 +00:00
Cohee 5b96dc3547 Scope webpack cache by version 2025-06-24 12:54:39 +00:00
qvink b37b4d0357 removing zh-tw translations specific to the qvink memory extension 2025-06-23 15:12:01 -06:00
02lokaandCohee e3923a7be3 Fixed minor avatar cropping bug in avatars.js (#4192)
* Fixed avatar cropping bug in avatars.js

Persona icons/profile pictures were forced to a 2:3 ratio despite "Never resize avatars" being enabled.

Moved a misplaced line of code inside the crop condition to fix this behavior.

* Fix indentation for ESLint compliance

**Attempted** to correct indentation on line 49 of avatars.js to pass ESLint check.

* Update avatars.js

Gave my best to fix it :(

At the very least the issue is known now.

* Update avatars.js

Removed empty characters (formatting)

* Fixed avatars.js

Fixed the issue of avatar's not changing after my recent revision.

* Update avatars.js

Accidentally left a duplicate line; removed it now

* Extract reusable function for avatar resize

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-06-23 23:09:54 +03:00
Cohee 2b7c0a3d37 Extensions: Check if directory is a repo root before updating/getting status 2025-06-23 22:03:41 +03:00
Cohee f84d5a037e Merge pull request #4193 from henk717/staging
KoboldAI Instruct format preset
2025-06-23 20:47:34 +03:00
Henk 42eb25dcd0 KoboldAI Instruct format preset 2025-06-23 18:56:08 +02:00
Cohee 0fa1b26fa4 Add deletion control for attached videos 2025-06-23 01:01:44 +03:00
Cohee b357e5d25e Add video preview to clean-up dialog 2025-06-23 00:39:21 +03:00
Cohee 2a1d07c46a Don't treat attached videos as unused files 2025-06-23 00:16:44 +03:00
Cohee 0599b91609 Pass yaml library to frontend 2025-06-22 23:37:44 +03:00
Cohee ebfd8a2256 Fix "Test Message" font size 2025-06-22 23:36:21 +03:00
Cohee 5ea2c48bf8 Allow message swipe gens with image attachments (#4184)
* Allow message swipe gens with image attachments

* Replace JSON.parse with structuredClone
2025-06-22 20:55:54 +03:00
Cohee 9481f9989a Closes #4187 [FEATURE_REQUEST] Allow wildcards in Banned Strings List 2025-06-22 20:35:46 +03:00
Cohee 50cd88c5dc Ollama: deprecate Mirostat params
Closes #4188
2025-06-22 18:39:28 +03:00
Cohee a2efd8792c Merge pull request #4189 from SillyTavern/staging
Staging
2025-06-22 18:15:27 +03:00
Cohee fb46343b85 Clarify title for WEBP bg anims toggle 2025-06-22 17:01:52 +03:00
Cohee 4376d66b33 Add timeout to extensions auto-update 2025-06-22 16:28:29 +03:00
Cohee 9014a2e3d3 1.13.0 => 1.13.1 2025-06-22 16:13:16 +03:00
Cohee 5605265862 Google: Fix image generation on deprecated models 2025-06-21 23:54:36 +03:00
Cohee 0677777a74 Fix AI Studio image generation params 2025-06-21 23:38:26 +03:00
Wandering MouseandCohee 116bef6c9f Add support for characterFilter to getEntryField and setEntryField (#4185)
* Add support for characterFilter to getEntryField and setEntryField

* No more conflicts between lint and autoformat

* Fix array type default values hint

* Properly capitalize name

* Fix search by name

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-06-21 22:10:56 +03:00
Cohee 40f10d7d38 TTS: Add registerTtsProvider function export 2025-06-20 23:37:36 +03:00
Cohee 1786e641f7 Image Generation: save modified prompt on image swipe gen 2025-06-20 20:56:58 +03:00
Cohee 2d28f5cdaf Google: Add Imagen image generation 2025-06-20 20:44:21 +03:00
Cohee 14831ac5df Display local TZ name 2025-06-20 15:38:53 +00:00
Cohee 7a84563add Display local date of git HEAD 2025-06-20 08:20:42 +00:00
Cohee f78be0897e Merge pull request #4178 from imesha10/staging
Make back to parent chat button faster (PR for #4177)
2025-06-18 21:58:18 +03:00
Cohee def10929d2 Optimize performance of getExistingChatNames 2025-06-18 20:08:07 +03:00
Cohee 1ee3081b5d Docker: Update Alpine version 2025-06-18 08:40:54 +00:00
I 224a961c1c back to parent chat fix eslint fix 2025-06-18 08:27:51 +00:00
I fa38543b1a back to parent chat speed up by not checking for file and if there is an error or no file then send a warning. 2025-06-18 02:56:18 -05:00
Cohee e657b61df7 New Jeremy 2.5 2025-06-18 00:09:50 +03:00
Cohee ec428fd82f Export resolveSecretKey 2025-06-17 23:37:39 +03:00
Cohee c228de06a8 Copium for old Node 18 2025-06-17 22:01:57 +03:00
Cohee dfe1cdee21 Fix type errors in regex extension 2025-06-16 23:06:58 +03:00
Cohee 195034637f Fix browser launch on android 2025-06-16 22:56:01 +03:00
Cohee 3155de1886 Add section on common Docker issues and SELinux permissions 2025-06-16 22:45:13 +03:00
Cohee c9d8a0ad44 Merge pull request #4170 from imesha10/staging
Regex bulkedit select all toggle button add
2025-06-16 22:22:52 +03:00
Cohee 7614e5e9fe Reset toggle icon on render list 2025-06-16 22:20:42 +03:00
Cohee 412b0fce0f Change icon on individual checkbox toggle 2025-06-16 22:19:58 +03:00
coffeegrind123andCohee 0a136cbb2a Add Extension Hook for Stable Diffusion Prompt Processing (#4167)
* Update index.js

* Update index.js

* Update script.js

* Use a named constant in event emit

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-06-16 21:48:38 +03:00
Cohee 3e03b9f0a2 Sort post-processing types into optgroups 2025-06-16 09:59:50 +00:00
Cohee 703e67399c JSDoc types can be deceiving 2025-06-16 08:28:06 +00:00
powercaller f302916b57 disabled vertexAI for now (#4168) 2025-06-16 10:26:20 +03:00
I 8cf30fd519 regex bulkedit select all button add 2025-06-15 23:04:33 -05:00
Cohee 51431b1a75 Include persona name in delete confirmation
Closes #4119
2025-06-15 23:09:09 +03:00
Cohee 13416dba7f STscript: parse number operands with Number 2025-06-15 22:52:20 +03:00
powercallerandCohee 48f18cb74a Feature: Google Native TTS (#4163)
* google native tts impl

* Refactor getting google auth data

* Bring back status json

* Native TTS => Gemini TTS

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-06-15 16:58:01 +03:00
Cohee 8c8e4f032f VertexAI: Deduplicate models list 2025-06-15 15:27:27 +03:00
CompassandCohee 083f92b2b2 Add region option for vertex express mode to access more models (#4155)
* add region option for vertex express mode to access more models

* add region option for vertex express mode to access more models

* fix: Consolidate duplicate 'vertexai_region' input

* feat: add vertex region suggestion datalist & update caption endpoint to correctly handle region

* Adjust global projectless Vertex endpoint

* Remove pointless slash trim

* Skill issue

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-06-15 15:26:12 +03:00
Cohee 441dffc0da Vectors: Allow chunk overlap when forced chunking on delimiter 2025-06-15 01:48:17 +03:00
Cohee cb8fd4f663 Merge pull request #4162 from kingbri1/staging
More expression fixes for main API
2025-06-15 01:46:00 +03:00
kingbri 525b46daa0 Expressions: Change tooltip for LLM prompt
JSON schemas might need coercion from the user, so indicate that the
LLM prompt is appended in addition to the JSON schema.

Signed-off-by: kingbri <8082010+kingbri1@users.noreply.github.com>
2025-06-14 18:24:12 -04:00
kingbri cc9f095aa7 Expressions: Set additionalProperties to false in JSON schema
Some backends use grammar constraints that allow additional properties
with the generated JSON schema, resulting in an incoherent and extremely
long JSON.

Set this to false so the model can generate what we need and nothing else.

Signed-off-by: kingbri <8082010+kingbri1@users.noreply.github.com>
2025-06-14 18:17:55 -04:00
Cohee 6445c8fec2 DeepSeek: Add tool calls for reasoner model
Fixes #4161
2025-06-15 00:12:03 +03:00
Cohee 34873024b0 xAI: Enable backend web search
Closes #4160
2025-06-14 23:46:08 +03:00
Cohee 363b07ab0b Add try-catch to rename chat endpoint 2025-06-14 22:56:42 +03:00
Cohee eced082571 Merge pull request #4157 from kingbri1/staging
Emotions: Use the full context for main API
2025-06-14 20:46:23 +03:00
Cohee 9efd40980f Add prompt type selection for LLM expressions in settings 2025-06-14 20:01:59 +03:00
kingbri e43e771cc5 Emotions: Use the full context for main API
To prevent prompt reprocessing per turn, use the full context
when prompting with the main API. Doing so keeps the preserved
prefix while adding an extra sentence rather than providing two
different prompts for each turn.

In addition, JSON schemas might need a prompt to coerce a proper
schema return from the model.

Signed-off-by: kingbri <8082010+kingbri1@users.noreply.github.com>
2025-06-13 21:55:02 -04:00
Cohee e1130e7077 Fix npm audit 2025-06-13 22:59:40 +03:00
Cohee fdf881d074 Increase slider number input width 2025-06-13 22:37:13 +03:00
Cohee 982dca58ba Enable reasoning parsing for Pollinations and AIML 2025-06-13 21:46:41 +03:00
Dmitry fece612f09 Merge pull request #4135 from D1m7asis/release
feat: Added AI/ML API Provider Support
2025-06-13 20:59:18 +03:00
Cohee 33b9370675 Merge pull request #4156 from RivelleDays/staging
Improve and Add Traditional Chinese Translations
2025-06-13 20:54:11 +03:00
Rivelle 5a62fc29f1 Update zh-tw.json 2025-06-14 01:13:35 +08:00
Rivelle 0af655b2f7 Improve and Add Traditional Chinese Translations
- Added missing Traditional Chinese translations for the latest version
- Improved existing Traditional Chinese translations for clarity, professionalism, and neutrality
- Also fixed an obvious error in the Simplified Chinese translation
2025-06-14 01:10:53 +08:00
RossAscends de1b4a3770 range slider knobs match theme 2025-06-13 21:21:19 +09:00
RossAscends 603cbb5fb3 range sliders also respect theme colors 2025-06-13 15:53:16 +09:00
RossAscends dd03724eb4 CSS: .right_menu_button respects theme colors, no longer forces greyscale 2025-06-13 15:36:47 +09:00
Cohee 87f618d15c Rework browser launch functionality (#4143)
* Add browser selection to auto-launch

* Update readmes

* Update readme

* Display browser name in a console
2025-06-12 22:17:34 +03:00
Cohee addfcade32 MistralAI: fix selection of endpoint provided models 2025-06-12 21:55:56 +03:00
Cohee 70eb34086e AI Studio: fix saving null model id when selecting from Others list 2025-06-12 21:47:57 +03:00
Cohee af3906e243 Change selector of chat-scoped <hr> #4144 2025-06-12 21:37:40 +03:00
Cohee 19d1bd29d4 Merge pull request #4150 from Yokayo/staging
Update ru-ru locale
2025-06-12 21:36:03 +03:00
Yokayo f1720be017 Merge branch 'SillyTavern:staging' into staging 2025-06-13 01:13:17 +07:00
Cohee 8b82325d30 Localization improvements 2025-06-12 20:54:55 +03:00
Cohee 5e5ec679d7 Merge pull request #4145 from Boof2015/staging
Support for chatterbox api
2025-06-12 20:43:24 +03:00
Cohee 022b0d8d62 Fix seed in preview generation 2025-06-12 20:41:24 +03:00
Yokayo 5b4198957a Work on tl 2025-06-13 00:37:21 +07:00
Cohee 81ab2ab953 Fix styles and logic 2025-06-12 20:21:16 +03:00
Cohee 274c7ef82c Add input class 2025-06-12 20:12:17 +03:00
Cohee 87ac4b37e4 Increase <hr> opacity in chat from 0.2 to 0.4 2025-06-12 19:33:01 +03:00
Cohee 46f109618e Increase <hr>'s opacity from 0.2 to 0.4 (#4144) 2025-06-12 19:25:34 +03:00
Cohee c0f2a62b33 Merge pull request #4149 from Culpeo/release
Added new slash command member-count
2025-06-12 19:24:17 +03:00
Cohee b226081469 Allow getting group count during generation 2025-06-12 19:23:28 +03:00
Culpeo 9cfb913b3d Added new slash command member-count 2025-06-12 16:36:23 +02:00
Boof2015 bce6f3eef0 Fix ESLint errors 2025-06-12 01:48:38 -04:00
Boof2015 b9b0d054f9 Update index.js 2025-06-12 00:54:32 -04:00
Boof2015 e2b1e14ee1 Add files via upload 2025-06-12 00:53:40 -04:00
cloak1505 b3be989e24 Increase <hr>'s opacity from 0.2 to 0.4 2025-06-11 20:40:45 -05:00
Cohee 5008b4223a Downgrade types/node package 2025-06-12 01:57:15 +03:00
Cohee d785d38144 MistralAI: add magistral models to the list 2025-06-12 00:56:31 +03:00
Cohee 097845b163 Merge pull request #4142 from SillyTavern/feat/update-deps-jun-25
Update npm dependencies
2025-06-11 23:17:12 +03:00
Cohee ac339f7368 Update helmet 2025-06-11 23:09:54 +03:00
Cohee 57ab347448 Run npm audit 2025-06-11 23:00:00 +03:00
Cohee f7746d9485 Update yauzl 2025-06-11 22:50:34 +03:00
Cohee 1e115d68ab Update simple-git 2025-06-11 22:45:11 +03:00
Cohee 695218303d Update mime-types 2025-06-11 22:41:12 +03:00
Cohee 68f90485d3 Update types packages 2025-06-11 22:39:41 +03:00
Cohee a4333a519e Update ws 2025-06-11 22:37:37 +03:00
Cohee 7d328271db Update webpack 2025-06-11 22:37:06 +03:00
Cohee 533701b069 Update tiktoken 2025-06-11 22:36:30 +03:00
Cohee b3d399b71c Update html-entities 2025-06-11 22:35:31 +03:00
Cohee 3afbbee382 Update form-data 2025-06-11 22:34:57 +03:00
Cohee affb2b5811 Update morphdom 2025-06-11 22:34:26 +03:00
Cohee bfeb67d09b Update csrf-sync 2025-06-11 22:33:50 +03:00
Cohee c77cbf715c Update yaml 2025-06-11 22:32:26 +03:00
Cohee b489817cf8 Update dompurify 2025-06-11 22:31:56 +03:00
Cohee b386ec38c5 Update @adobe/css-tools 2025-06-11 22:31:22 +03:00
Cohee 8d2b9d2dab Secrets manager (#4131)
* Secret manager (now for real)

* Refactor secret manager dialog

* Add error handling to secrets migration

* Adjust default value

* Add secret-id slash command

* Add secret management slash commands

* Improve type definitions

* Improve compatibility of UUID generator

* Add copy buttons to manager view

* Improve compatibility with Vertex AI service account
- Changed to input since textarea can't be used with datalist
- Unblock regular key placeholder
- Save email as a key label
- Interrupt validation if the input is a UUID (autocompleted)

* Add optional label input for secret values in key manager dialog

* Update masking rules

* /secret-id: make the arg "required" (it's not)
2025-06-11 21:26:19 +03:00
InterestingDarkness 8b5a8914b1 Solve the issue where selecting an unofficial Gemini model and then clicking 'Connect' causes the selection to be reset (#4139) 2025-06-11 15:17:44 +03:00
Cohee 320b7b1450 Write /edit endpoint error to console 2025-06-11 10:53:15 +00:00
Cohee b6c5fac59b Merge pull request #4140 from leopardracer/release
Fix Typo in Error Message
2025-06-11 13:52:16 +03:00
Cohee 4777a7ca20 Prompt Manager: fool-proof personality / scenario formats 2025-06-11 10:34:07 +00:00
leopardracer 2e52f34262 Update characters.js 2025-06-11 12:42:18 +03:00
Cohee 2376e6f4f6 Remove dead button, sort providers 2025-06-11 01:03:46 +03:00
Roberts SlisansandCohee 0fc82432ac TTS WebUI provider (#4097)
* initial version

* volume and additional parameters for chatterbox

* add voice fetch

* deduplicate code

* fix eslint

* add all parameters

* use own secret

* remove (Unofficial) tag

* use only client side requests, fix voice discovery

* enable streaming by default

* change openai_compatible to tts_webui in inputs

* remove unused volume helpers

* extract PCM processor

* eslint fix

* remove unused secrets

* Remove obsolete secret IDs

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-06-11 01:00:58 +03:00
MAX-TAB 350de3d969 Update outdated readme-zh_cn.md (#4134)
* update readme-zh_cn.md

* Update readme-zh_cn.md
2025-06-10 18:23:59 +03:00
Cohee 6e58f08f3c Use CSS variable monospace font for slash commands in send textarea 2025-06-09 23:37:25 +03:00
Cohee 14212fb761 Fix type errors 2025-06-09 23:35:10 +03:00
Cohee 4fa7de9c93 Add typing for QR API global 2025-06-09 22:53:34 +03:00
Cohee a5127a58e6 Add PPP types allowing tool calls (#4125) 2025-06-09 22:17:54 +03:00
Cohee b46cc46139 Merge pull request #4128 from LumiWasTaken/release
add dots1 templates
2025-06-09 19:59:05 +03:00
Cohee eb1cd95b03 Remove obsolete field 2025-06-09 19:57:49 +03:00
LumiWasTaken 29bfaf6927 add dots1 to index.json 2025-06-09 11:36:09 +02:00
LumiWasTaken 23a313ab23 add dots1 templates 2025-06-09 10:52:56 +02:00
CoheeandRossAscends b3c636fe91 Refactor and fix type errors in WI and script modules (#4123)
* remove unnecessary arg passage from WI helper funcs

* remove some typescript red from script.js

* hide in shame

* Add JSDoc to helper functions

* Fix fav_ch_checked not updating

* Move PWA mode match to firstLoadInit

* Fix more type errors and deprecations

* Fix the rest of type errors in script.js

---------

Co-authored-by: RossAscends <124905043+RossAscends@users.noreply.github.com>
2025-06-08 19:14:03 +03:00
InterestingDarkness 358bbf8622 Replace url.origin with trimTrailingSlash (#4118)
* Replace url.origin with trimV1

* Replace url.origin with trimTrailingSlash
2025-06-08 19:09:15 +03:00
RossAscends fd80474d47 Merge pull request #4117 from SillyTavern/goodbye-isSaveWorldInfoDisabled
Add skip save checks to all on-init event handlers
2025-06-08 17:04:17 +09:00
Cohee 70141aa565 Get rid of isSaveWorldInfoDisabled 2025-06-08 03:20:41 +03:00
Cohee d0b4eb2abb Allow bypass AI Studio status check 2025-06-08 02:49:58 +03:00
Cohee 44c73354fd Stop mass WI open if the page was unloaded 2025-06-08 02:36:22 +03:00
Cohee 732ca6c4e0 Don't toggle drawer if elements not found 2025-06-08 01:55:02 +03:00
Cohee 6eee5122b3 Hide autocomplete divider 2025-06-08 01:54:11 +03:00
Cohee dc1d20cca0 Fix typo
Thanks @TsunamicBug
2025-06-08 00:14:29 +03:00
Cohee e39eec2c6f Enhance lazy loading for backgrounds 2025-06-08 00:10:14 +03:00
Cohee dfc1688eb5 Load bg thumbnail config from backend 2025-06-08 00:01:10 +03:00
e75da14563 Implement lazy loading for background menu (#4110)
* debug: Enhance logging for IntersectionObserver and root element

This commit adds more detailed console logging to `backgrounds.js`
to help you diagnose issues with the lazy loading mechanism.

Key changes:
- Added logs to trace calls to `activateLazyLoader` from
  `getBackgrounds` and `getChatBackgroundsList`.
- Added a log at the start of `activateLazyLoader`.
- Added a check and log for the existence of the `#Backgrounds`
  element, which is intended as the `root` for the
  IntersectionObserver.
- Logged the options being passed to the IntersectionObserver.
- Ensured the IntersectionObserver can handle a null rootElement
  (which would default to the viewport).

* feat: Implement lazy loading for background image thumbnails

This commit introduces lazy loading for background image thumbnails to improve initial load performance and reduce unnecessary data transfer.

Key changes:
- Modified `getBackgroundFromTemplate` to store image URLs in a `data-bg-src` attribute instead of directly setting the `background-image` style. A `lazy-load-background` class is added to these elements.
- Introduced a new `activateLazyLoader` function that uses the `IntersectionObserver` API. This function monitors elements with the `lazy-load-background` class and only loads their `background-image` (from `data-bg-src`) when they are about to become visible in the viewport.
- Integrated `activateLazyLoader` into `getBackgrounds` and `getChatBackgroundsList` so that it's activated after background placeholder elements are created.
- Added checks at the beginning of `getBackgrounds` and `getChatBackgroundsList` to prevent them from re-populating the thumbnail lists if they already contain elements, avoiding redundant processing.

This ensures that:
1. No background thumbnails are downloaded when the application first loads.
2. When the background selection menu is opened, the list of thumbnails is generated as placeholders, but the actual images are not downloaded.
3. Thumbnail images are only downloaded from the server as they scroll into view.

* I've made some updates to help diagnose why background images may not be loading.

Specifically, I've:
- Added logging to see when the lazy loader is activated and how many elements it's working with.
- Included logs to track when the IntersectionObserver is triggered for an element and its status.
- Added logging for the image URL being applied.
- Included a warning if an image URL isn't found for an element that should be loading.

Additionally, I've configured the IntersectionObserver to use the '#Backgrounds' element as the reference point for its calculations, with a 10% threshold.

* Optimize background menu loading and add toggleable logging

This PR addresses UI lag caused by the background selection menu.

Changes:

- Optimized Background Loading:
    - The background selection menu (`#Backgrounds`) now unloads non-selected and non-locked background images when it's closed. This is achieved by setting `style.backgroundImage = 'none'` for the respective elements.
    - When the menu is reopened, the background images are repopulated by calling the existing `getBackgrounds()` and `getChatBackgroundsList()` functions, which also re-initialize the lazy loader.
    - A `MutationObserver` is used to detect when the `#Backgrounds` menu drawer is opened or closed by observing changes to its `classList` (specifically the `closedDrawer` class).

- Toggleable Debug Logging:
    - Added a `DEBUG_BACKGROUND_LOADING` constant at the top of `public/scripts/backgrounds.js`.
    - All `console.log`, `console.warn`, and `console.error` statements related to the background loading/unloading logic and the lazy loader are now conditional on this flag. Set `DEBUG_BACKGROUND_LOADING = true` to enable these logs for debugging purposes.

Benefits:

- Improves UI performance by reducing the number of images actively loaded in the DOM when the background menu is not in use.
- Reduces main background playback lag that was exacerbated by having many backgrounds loaded.
- Provides a way to enable detailed logging for troubleshooting background loading issues without cluttering the console during normal operation.

* I can optimize the background menu loading.

I'll detect when the background select menu is opened and closed.
When the menu is closed, I will remove non-selected and non-locked backgrounds from the DOM to improve performance.
When the menu is opened, I will repopulate the backgrounds.
This will prevent UI lag caused by too many background images being loaded simultaneously.

* lint syntax and spacing fix

* add url check back in

* Post-merge clean-up

* Disconnecting previous observer on lazy load init

---------

Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-06-07 23:12:22 +03:00
a1ed83a1ba animated bg thumb toggle (#4109)
* Feat: Add toggle for animated background thumbnails

This commit introduces a new toggle in the User Settings UI: "Load Animated Background Thumbnails".

- When checked (default), animated background thumbnails (.gif, .mp4, animated .webp) load and display as usual in the background selection menu.
- When unchecked, these animated thumbnails are replaced with a transparent PNG (`__transparent.png`) in the selection menu. This is intended to reduce UI and network lag for you if you have a large number of animated backgrounds.

The actual functionality of setting any background (animated or static) remains unchanged; clicking a thumbnail will always apply the original background file.

Changes include:
- Added `loadAnimatedBackgroundThumbnails` (boolean, defaults to true) to `settings.json` under the `power_user` object.
- Added the toggle HTML to `public/index.html`.
- Modified `public/scripts/backgrounds.js` to conditionally replace animated thumbnails based on the new setting.
- Modified `public/script.js` to handle the toggle's event listener and save its state.
- Modified `public/scripts/power-user.js` to initialize the toggle's state upon loading settings.

* Fix: Resolve issues with animated background thumbnail toggle

This commit addresses two issues with the "Load Animated Background Thumbnails" feature:
1.  Toggle state was not persisting correctly across page loads.
2.  Animated media files were still being loaded even when the toggle was set to hide their thumbnails.

Fixes:
-   Corrected the variable scope in `applyPowerUserSettings` within `public/scripts/power-user.js` to ensure the toggle's checked state is properly initialized from the global `power_user.loadAnimatedBackgroundThumbnails` setting. This resolves the persistence issue.
-   Refined the logic in `getBackgroundFromTemplate` within `public/scripts/backgrounds.js`. When the toggle is off and a background is an animated type (.gif, .mp4, .webp), the `background-image` CSS property for its thumbnail now directly uses the path to `__transparent.png`. This prevents the browser from potentially pre-fetching or the server from processing the original animated file via the `/thumbnail` endpoint for display purposes.
-   Added console logging in `getBackgroundFromTemplate` to help debug the toggle state and file being processed.

The core functionality of applying backgrounds by clicking on thumbnails (whether transparent or regular) remains unchanged, as the `bgfile` attribute correctly stores the original media path.

* Fix: Resolve page load error and animated thumbnail toggle issues

This commit addresses a critical page loading error (`power_user is not defined`
in `backgrounds.js`) and ensures the "Load Animated Background Thumbnails"
toggle functions as intended.

The page load error was caused by `getBackgrounds()` (and subsequently
`getBackgroundFromTemplate()`) in `backgrounds.js` attempting to access
`power_user.loadAnimatedBackgroundThumbnails` before the `power_user` object
was fully initialized and its properties reliably accessible during the
application's `firstLoadInit` sequence.

Fixes:
1.  **Explicit Setting Passing for Initial Load**:
    *   Modified `getBackgrounds()` in `public/scripts/backgrounds.js` to accept
        `loadAnimatedThumbnailsSetting` as a parameter.
    *   Modified `getBackgroundFromTemplate()` in `public/scripts/backgrounds.js`
        to accept and prioritize this passed parameter. It includes fallback
        logic to use the global `power_user.loadAnimatedBackgroundThumbnails`
        (primarily for event-driven updates like chat changes, which happen later)
        and then to a default of `true` if the setting is somehow unavailable.
    *   Updated the call to `getBackgrounds()` in `public/script.js` during
        `firstLoadInit` to pass `power_user.loadAnimatedBackgroundThumbnails`
        explicitly after `power_user` settings are loaded.
    *   Updated the toggle's `change` event listener in `public/script.js` to also
        pass the new setting state to `getBackgrounds()` for immediate refresh
        of system backgrounds.

2.  **Toggle Persistence**:
    *   Ensured the toggle's state in `public/scripts/power-user.js`
        (within `applyPowerUserSettings`) is correctly initialized using the
        global `power_user.loadAnimatedBackgroundThumbnails`.

3.  **Media Loading for Thumbnails**:
    *   The logic in `getBackgroundFromTemplate` now ensures that if animated
        thumbnails are toggled off, the `background-image` CSS directly uses
        `url("backgrounds/__transparent.png")`, avoiding calls to `getThumbnailUrl()`
        with original animated file paths, which might have caused unintended
        pre-fetching or server-side processing.

This set of changes should resolve the page loading blockage and ensure the
animated background thumbnail toggle works correctly for both display and
network loading, while maintaining the functionality of applying original
backgrounds.

* Fix: Ensure correct initial state and first-toggle behavior for animated thumbnail toggle

This commit addresses issues where the "Load Animated Background Thumbnails"
toggle might not correctly display its default 'on' state (checked) on
a clean install, and ensures the first toggle action takes immediate effect.

Changes:
- In `public/scripts/power-user.js`:
    - `loadPowerUserSettings`: Ensured that `power_user.loadAnimatedBackgroundThumbnails`
      is robustly defaulted to `true` if the key is missing or not a boolean
      (e.g., from an older settings file) *before* `applyPowerUserSettings` is called.
    - `applyPowerUserSettings`: Added console logging to trace the value of
      `power_user.loadAnimatedBackgroundThumbnails` just before setting the
      checkbox state. Ensured the checkbox `checked` property is set using
      `!!power_user.loadAnimatedBackgroundThumbnails` for explicit boolean conversion.
      The function already correctly referenced the global `power_user` object.

- In `public/scripts/backgrounds.js`:
    - `getBackgroundFromTemplate`: This function's logic for determining the
      `loadSetting` (which decides if a transparent thumbnail is used) was
      previously refined to prioritize a passed parameter, then fall back to the
      global `power_user.loadAnimatedBackgroundThumbnails`, and then to `true`.
      Console logs were added to trace the resolved setting and file details.

- In `public/script.js`:
    - `firstLoadInit`: The call to `getBackgrounds` already correctly passes the
      `power_user.loadAnimatedBackgroundThumbnails` after settings are loaded.
    - Event listener for `#loadAnimatedBackgroundThumbnails`: The logic to update
      the global `power_user` state and then call refresh functions
      (`getBackgrounds` and emitting `CHAT_CHANGED` for `getChatBackgroundsList`)
      appears to be in the correct synchronous order.

These changes should ensure the toggle initializes to its correct visual state (checked)
and that the first toggle from ON to OFF (and back) correctly and immediately
updates both the visual display of thumbnails and the network loading behavior.

* Fix: Address ESLint issues in background thumbnail toggle feature

This commit resolves ESLint errors that were present in
`public/scripts/backgrounds.js` and `public/scripts/power-user.js`
related to the "Load Animated Background Thumbnails" feature.

Changes:
- I corrected indentation errors in `public/scripts/backgrounds.js`
  as reported by the linter.
- I replaced direct use of `object.hasOwnProperty()` with
  `Object.prototype.hasOwnProperty.call(object, ...)` in both
  `backgrounds.js` and `power-user.js` to resolve the
  `no-prototype-builtins` ESLint error.
- I ensured `power_user` is correctly imported and/or checked for
  definition (using `typeof power_user !== 'undefined'`) in
  `backgrounds.js` before accessing its properties, to satisfy
  linter concerns around `no-undef` for `power_user` in the
  context of the `getBackgroundFromTemplate` fallback logic.

These changes primarily address code style and linting rules and
are not intended to alter the functional behavior of the animated
background thumbnail toggle, which was addressed in previous commits.

* fix weird spacing for lint

* Refactor animated background thumbnail settings and functionality

* Remove comments

* Add missing awaits

---------

Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-06-07 22:55:48 +03:00
Cohee 65dcf9d341 Only play hide-scroll animation for webkit scrollbar 2025-06-07 22:51:17 +03:00
Cohee c22d70793d Refactor /status endpoint 2025-06-07 22:40:52 +03:00
Cohee 88cd8bbbf3 Merge pull request #4113 from InterestingDarknessII/google-dynamic-model
Implement Google AI Studio model list dynamic fetching
2025-06-07 22:29:47 +03:00
Cohee 63b4896d56 Dedupe fillRight, fillLeft styles 2025-06-07 21:53:48 +03:00
Cohee 4361559aa1 Are we there yet? 2025-06-07 21:36:43 +03:00
InterestingDarkness a106602f25 Add static model list for Google AI Studio 2025-06-08 02:36:01 +08:00
Cohee c90f1d7f86 Adjust create form paddings 2025-06-07 21:09:37 +03:00
Cohee e456c0bb21 🔥🦊 👎 2 2025-06-07 21:04:42 +03:00
Cohee f8006530d4 🔥🦊 👎 2025-06-07 20:37:34 +03:00
InterestingDarkness ff4a98a939 Implement Google AI Studio model list dynamic fetching 2025-06-08 01:10:31 +08:00
Cohee 6fe03d655f Increase global scan depth limit to 1000
Closes #4098
2025-06-07 19:33:11 +03:00
Cohee f33db29e76 Merge pull request #4096 from SillyTavern/TopbarFadeMUIAndGetWorldEntryRefactors
UI performance optimizations and refactoring
2025-06-07 18:53:02 +03:00
Cohee 2ee6bb76b3 Fix summary popout fade in 2025-06-07 18:41:26 +03:00
Cohee bc35856ed0 Clean-up comments 2025-06-07 18:38:57 +03:00
Cohee 90f58bb553 Fix mobile QR popout style 2025-06-07 18:37:26 +03:00
Cohee 9bcbe957af Refactor transition durations to use CSS variables 2025-06-07 16:40:30 +03:00
Cohee cb8e82db2f Add delay for drawer animation when open drawers exist 2025-06-07 15:55:52 +03:00
Cohee 2fe12ed0cf Animate gallery block 2025-06-07 15:46:14 +03:00
Cohee d83f926269 Unset height of movingDivs descendants 2025-06-07 15:06:23 +03:00
Cohee be65f31d40 Fix mobile animations 2025-06-07 15:05:19 +03:00
Cohee 2e2a4661ce Remove height from drawer-content (handled by starting-style) 2025-06-07 14:12:24 +03:00
Cohee 5eb4e9ee05 Replace with named constants 2025-06-07 14:10:35 +03:00
RossAscends 0c6cf14097 two birds with one line instead 2025-06-07 19:07:45 +09:00
RossAscends 8109b98081 make AN open properly, random typescript fixes 2025-06-07 19:00:45 +09:00
Cohee b85d026a74 Fix neo-slider position in Firefox 2025-06-06 23:54:44 +03:00
Cohee 2205d5b2f1 Add delay to mass WI drawer toggle 2025-06-06 23:44:42 +03:00
Cohee 6a190abc80 Comment-out scroll delay 2025-06-06 23:28:08 +03:00
Cohee 0c28623592 Hide overflow of rm_characters_block 2025-06-06 23:26:32 +03:00
Cohee a1c387e02a Remove early return 2025-06-06 22:03:02 +03:00
Cohee b0d6bba5a7 Add generic class for scroll delay 2025-06-06 10:55:48 +00:00
Cohee 02187bfcd0 Delay right menu scrolls until animation 2025-06-06 10:44:20 +00:00
Cohee d33b21282e Fix eslint 2025-06-06 09:55:18 +00:00
Cohee 302761482b Merge pull request #4102 from cloak1505/gemma
Add gemma-3n-e4b-it
2025-06-06 12:52:05 +03:00
Cohee aa81b0c5a3 Init key scroll heights immediately 2025-06-06 09:45:55 +00:00
Cohee 6dc2077507 Fix expand/collapse all entries 2025-06-06 09:40:59 +00:00
Cohee db59b19d41 Hide drawer scrollbar until the animation finishes 2025-06-06 09:15:20 +00:00
Cohee 4bb5f8daa9 Wrap right menu in scrollableInner 2025-06-06 08:59:56 +00:00
Cohee 7719fe7162 Merge pull request #4101 from cloak1505/staging
Sync OpenRouter providers list
2025-06-06 11:00:16 +03:00
cloak1505 d7e0f539f4 Add gemma-3n-e4b-it 2025-06-06 02:53:39 -05:00
cloak1505 3a439ecf77 Sync OpenRouter providers list 2025-06-06 02:08:06 -05:00
RossAscends 506e2f2c6f - fix charPanel div heights
- fix noHotswap area height & flex dir
2025-06-06 13:57:22 +09:00
Cohee 192d50afb0 Fix non-recursable and prevent recursion flags 2025-06-06 02:17:27 +03:00
Cohee e7db61f664 Remove opacity transition 2025-06-06 02:14:33 +03:00
Cohee 9a82b688ba WI: Split entry header and editor 2025-06-06 02:10:49 +03:00
Cohee a10ded9785 Lint fix 2025-06-06 01:11:30 +03:00
Cohee 2a70086ef1 Fix right/left drawers animations 2025-06-06 00:58:49 +03:00
Cohee 8c384a03bb Pure CSS drawer animations 2025-06-06 00:44:44 +03:00
RossAscends edbc257e81 - replace top bar toggle animations with opacity fades
- refactor MovingUI
- refactor getWorldEntry
2025-06-06 05:29:18 +09:00
Cohee d55676d6d5 New Jeremy 2.5 Pro 2025-06-05 20:14:46 +03:00
Cohee e08d1b522c Don't destroy sortable manually 2025-06-05 08:45:31 +00:00
Cohee 62fdce8cad Replace select2 detection 2025-06-05 08:44:55 +00:00
Cohee bbe62527d2 Remove pointless DOM call 2025-06-05 08:40:01 +00:00
Cohee b7323715b2 Prevent saveWorldInfo calls while rendering the list 2025-06-05 08:33:38 +00:00
Cohee 0f9cd5f48d Remove debug logs with DOM queries 2025-06-05 08:25:50 +00:00
Cohee 1c499df9da Merge branch 'release' into staging 2025-06-05 08:21:34 +00:00
Cohee f12c523fcd Merge pull request #4093 from SillyTavern/dependabot/npm_and_yarn/multer-2.0.1
Bump multer from 2.0.0 to 2.0.1
2025-06-05 11:17:57 +03:00
dependabot[bot] ba74e4f126 Bump multer from 2.0.0 to 2.0.1
Bumps [multer](https://github.com/expressjs/multer) from 2.0.0 to 2.0.1.
- [Release notes](https://github.com/expressjs/multer/releases)
- [Changelog](https://github.com/expressjs/multer/blob/main/CHANGELOG.md)
- [Commits](https://github.com/expressjs/multer/compare/v2.0.0...v2.0.1)

---
updated-dependencies:
- dependency-name: multer
  dependency-version: 2.0.1
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-06-05 07:35:19 +00:00
RossAscends e1a1fdb0da dont reload editor list on world list tag click if that world is already displayed and open in the editor 2025-06-05 16:13:27 +09:00
RossAscends 42b2637707 await the fade in.. 2025-06-05 15:51:11 +09:00
RossAscends b55de85243 Removes memory heap bloat by improving DOM and JQUI datacache clearing when swapping WI in the editor, and all other 'reloadEditor' calls via slashcommands etc.
Results in a slight delay depending on entries visible via pagination (about 2s for 50 visible entries), but I added a pleasant fade transition to make it feel organic.
2025-06-05 15:32:33 +09:00
Cohee 96fb85457f Gallery: add delete functionality for gallery items 2025-06-04 23:53:18 +03:00
Cohee f646c9416a fix: handle enhance parameter in pollinations generate endpoint 2025-06-04 23:25:13 +03:00
Cohee 0eff634bd0 OpenRouter: add cache TTL control for Claude 2025-06-04 20:30:20 +03:00
Cohee 555c5be8d1 Fix horizontal stretching of HTML img embeds in mobile layout 2025-06-04 11:59:51 +00:00
Cohee 8eb56355df Merge pull request #4088 from SillyTavern/dependabot/npm_and_yarn/tests/tar-fs-3.0.9
Bump tar-fs from 3.0.8 to 3.0.9 in /tests
2025-06-03 20:30:55 +03:00
dependabot[bot] 1211493404 Bump tar-fs from 3.0.8 to 3.0.9 in /tests
Bumps [tar-fs](https://github.com/mafintosh/tar-fs) from 3.0.8 to 3.0.9.
- [Commits](https://github.com/mafintosh/tar-fs/compare/v3.0.8...v3.0.9)

---
updated-dependencies:
- dependency-name: tar-fs
  dependency-version: 3.0.9
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-06-03 17:30:31 +00:00
Cohee 229def21cd Fix npm audit in tests 2025-06-03 13:06:38 +00:00
Cohee c4a44bc08d rename chat: update to new popup 2025-06-03 00:19:31 +03:00
Cohee 13b3f61e82 slash-commands.js: update for new popup 2025-06-03 00:16:00 +03:00
Cohee b6d282b4ee Fix for eslint 2025-06-03 00:11:06 +03:00
Cohee 8d143a81c3 bulk edit: update for new popup 2025-06-03 00:11:01 +03:00
Cohee 8cf11bccde horde.js: update for new popup 2025-06-03 00:06:34 +03:00
Cohee b72d7f37d7 regex: update for new popup 2025-06-03 00:05:33 +03:00
Cohee b901ed1be7 caption: update for new popup 2025-06-03 00:02:05 +03:00
Cohee 5e4c570eb0 textgen-models.js: update for new popup 2025-06-02 23:58:19 +03:00
Cohee 45ef4b60c9 stats.js: update for new popup 2025-06-02 23:57:11 +03:00
Cohee 8c7dbedaa1 samplerSelect.js: update for new popup 2025-06-02 23:55:16 +03:00
Cohee def23eb359 Fix for eslint 2025-06-02 23:50:12 +03:00
Cohee 134ade0951 secret.js: update for new popup 2025-06-02 23:49:56 +03:00
Cohee 52e7df970f backgrounds.js: update for new poup 2025-06-02 23:44:59 +03:00
Cohee 55b3016985 openai.js: update for new popup 2025-06-02 23:44:50 +03:00
Cohee d7c938a294 WI: increase budget cap max value 8k -> 64k 2025-06-02 14:33:03 +00:00
Cohee 1ae4c22ebc Merge pull request #4086 from NicodeSS/release
fix: lowercase remote-user header in authelia auto-login procedure
2025-06-02 17:27:54 +03:00
Nicode cfa9ef4726 fix: lowercase remote-user header in authelia auto-login procedure
Ensure the remote-user header is lowercased to fix case-sensitivity issues in the authelia auto-login process, improving compatibility.
2025-06-02 20:53:39 +08:00
Cohee 281ce10040 Update placeholder for empty message 2025-06-02 11:44:56 +03:00
Rebecca Turner 7ef296d43a Feature: Allow tools to accept arrays of values as an array (#4085)
Previously, a tool that that registered itself as having an array parameter
had each element of the array registered as a variable, but it did not
register the array parameter itself.  This meant that it was only really
useful with fixed length arrays.

This patch adds a variable for the array itself that lives alongside the
existing args.  I don't expect this to have any backward compatiblity
concerns.

Repro:

```stscript
// this requires lalib to function |
/let key=schema {
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "string",
    "properties": {
        "example": {
            "type": "array",
            "contains": {
                "type": "string"
            }
        }
    },
    "required": [
        "example"
    ]
} ||
/tools-register name=YourFunc description="filler" parameters={{var::schema}} {:
    /let ex {: /try {: /return {{var::arg.example}} :} :}() | /= ex.isException | /if rule=not left={{pipe}} else={:
        /console-log {{var::ex}}
    :} {:
        /console-log "arg.example: {{var::arg.example}}" |
        /foreach {{var::arg.example}} {: /console-log "#{{var::index}}: {{var::item}}" :}
    :} |
    /try {: /return {{var::arg.example.0}} :}  | /console-log "arg.example.0: {{pipe}}" |
    /try {: /return {{var::arg.example.1}} :}  | /console-log "arg.example.1: {{pipe}}" |
    /try {: /return {{var::arg.example.2}} :}  | /console-log "arg.example.2: {{pipe}}" |
    /try {: /return {{var::arg.example.3}} :}  | /console-log "arg.example.3: {{pipe}}" |
:} ||
/let key=params {
    "example": [
    	"test1", "test2", "test3"
    ]
} |
/tools-invoke parameters={{var::params}} YourFunc
```
Currently produces:

```
[/console-log] arg.example: {"isException":true,"exception":"No such variable: \"arg.example\""}
[/console-log] arg.example.0: {"isException":false,"result":"test1"}
[/console-log] arg.example.1: {"isException":false,"result":"test2"}
[/console-log] arg.example.2: {"isException":false,"result":"test3"}
[/console-log] arg.example.3: {"isException":true,"exception":"No such variable: \"arg.example.3\""}
```

With this patch it produces:

```
[/console-log] arg.example: ["test1","test2","test3"]
[/console-log] #0: test1
[/console-log] #1: test2
[/console-log] #2: test3
[/console-log] arg.example.0: {"isException":false,"result":"test1"}
[/console-log] arg.example.1: {"isException":false,"result":"test2"}
[/console-log] arg.example.2: {"isException":false,"result":"test3"}
[/console-log] arg.example.3: {"isException":true,"exception":"No such variable: \"arg.example.3\""}
```
2025-06-02 10:54:10 +03:00
Rebecca TurnerandCohee 6bb07370f4 Fix #4083 JSON parse error when tool does not accept parameters (#4084)
* Fix #4083: JSON parse error when tool does not accept parameters

* Reformat for visual coolness

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-06-02 10:18:04 +03:00
RossAscendsandCohee fa10833e52 add minimum requirement of 2 [A-za-z] for slashcommand autocomplete to show up (#4080)
* add minimum requirement of 2 [A-za-z] for slashcommand autocomplete to show up

* Migrate to dedicated AC toggle

* Replace state checkbox with select

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-06-01 20:07:33 +03:00
Cohee 4c3bb1aede PPP command and connection profiles (#4079)
* Add PPP command

* Add PPP to connection profiles
2025-06-01 18:15:06 +03:00
Nikolas BrownandCohee c4d89b2067 Gemini inline video (#4078)
* Add inline video attachment support for Gemini 2.5 Pro

* file formatting

* removed redundant function for saving video to message

* removed other redundant function for saving video to message

* Seperate inlining check for video

* Edit video token cost to be a conservative estimate of 10000 tokens

* fixed missing semicolon

* Adds seperate ui toggle for video inlining.

* Move mes_video out of img_container

* Remove title from video element for now

* Better visibilty of video with controls

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-06-01 15:04:16 +03:00
Cohee 3ec9b1a099 Implement data clean-up dialog (#4072)
* [wip] Add user data cleanup service

* Add clean-up report viewer

* Fix review comments

* Add function comments

* Implement item actions

* Fix UI styles

* Add placeholder for empty results, update category description view

* Add displayEmptyPlaceholder method to show message when results list is empty

* Adjust menu buttons row

* Delete char-scoped data bank attachments on character deletion

* Data Bank: Handle character attachments on rename

* Remove line breaks in description strings

* Drop the category when the last item is deleted

* Skip invalid hashes instead of bailing
2025-06-01 13:56:34 +03:00
Cohee 7f47f84c9f Merge branch 'release' into staging 2025-06-01 01:17:59 +03:00
Cohee 303c1dcf14 Caption: fix displaying secondary endpoint for unsupported sources 2025-06-01 01:17:42 +03:00
Cohee ecbe8d38c5 Merge branch 'release' into staging 2025-06-01 01:11:51 +03:00
Cohee 5b7483af14 Add filename validation middleware to create endpoint 2025-06-01 01:11:26 +03:00
Cohee b7444a0fd2 Add filename validation middleware to upload endpoint
#4065
2025-06-01 01:09:53 +03:00
Cohee a17d0c2293 Merge pull request #4077 from SillyTavern/fix-mes0-right-swipe
Allow swipe right to generate first message in non-pristine chats
2025-05-31 21:27:21 +03:00
Cohee 7ca8c4591f Allow swipe right to generate first message in non-pristine chats
Fixes #4074
2025-05-31 19:02:35 +03:00
Cohee 8b44bf1e55 Merge pull request #4071 from closuretext/patch-1
Added NAI Diffusion V4.5 Full and V4.5 Curated
2025-05-31 02:01:08 +03:00
closure 26f717ac45 Added NAI Diffusion V4.5 Full and V4.5 Curated 2025-05-30 17:48:39 -03:00
Cohee 89ef54f286 Do not replace inline HTML img with image embed (#4063) 2025-05-29 21:44:16 +03:00
Cohee 1cbc4ac65b Fix HTML syntax errors by @Dakraid
Original commit: https://github.com/SillyTavern/SillyTavern/commit/fd4babab31c420e94df7d355db2d32c478b853c7
2025-05-29 21:38:55 +03:00
Cohee e1e2d3e726 Recent chats: add delete and rename buttons (#4051)
* [wip] Add rename/delete for recent chats

* Implement deleteCharacterChatByName

* Fix character name usage in deleteCharacterChatByName function
2025-05-29 21:21:53 +03:00
Radovenchyk 71de864a5e docs: edited the link to the forks badge (#4059)
* Update readme.md

* Update readme.md
2025-05-29 21:02:21 +03:00
Cohee 0b1e3828aa Merge pull request #4060 from leandrojofre/relieve-group-chat-console
Clean console debugs for group chats
2025-05-29 19:30:52 +03:00
leandrojofre 34b8b48b52 Update - Clean console debugs for group chats
Those two debugs always floods the console in group chats, making it imposible to debug anything else, like extensions or activated wi entries.
2025-05-29 12:05:57 -03:00
Cohee 8ccbbe8cdc Merge pull request #4057 from omahs/patch-2
Fix typos
2025-05-29 16:40:53 +03:00
Cohee 1dc7415cdb Merge pull request #4058 from rsxdalv/patch-1
refresh voices upon checkReady in openai-compatible TTS
2025-05-29 15:51:09 +03:00
Roberts Slisans 8db879d9f2 refresh voices upon checkReady in openai-compatible TTS 2025-05-29 14:40:52 +03:00
omahs d7d20a67fa Fix typos 2025-05-29 11:56:59 +02:00
Cohee 87df4db1a4 Add vertexai.svg image file 2025-05-29 01:48:42 +03:00
Cohee 853a80a428 Unblock Request model reasoning for Vertex 2025-05-28 20:55:40 +03:00
Cohee b61269445d Merge pull request #4046 from InterestingDarknessII/vertexfull
Add Vertex AI Full Version support
2025-05-28 20:52:24 +03:00
Cohee 4e75f2fa4d Change no neutral warning text to align with other inputs 2025-05-28 20:45:35 +03:00
Cohee 1921036666 Move account status block higher 2025-05-28 20:42:40 +03:00
Cohee 0559fd7e8b Fix alignment of Region controls 2025-05-28 20:40:13 +03:00
Cohee 250bf5249a Remove unnecessary blank lines in chat-completions.js 2025-05-28 20:38:09 +03:00
Cohee 5c2cfed18b Implement auto-connect for VertexAI full 2025-05-28 20:37:50 +03:00
Cohee a0dda44ff9 Fix model options hiding on Chrome 2025-05-28 20:37:34 +03:00
InterestingDarkness 75e3f599e6 Derive Vertex AI Project ID from Service Account JSON
This commit refactors the Vertex AI integration to automatically derive the
Project ID from the provided Service Account JSON. This simplifies the
configuration process for users in "Full" (service account) authentication
mode by removing the need to specify the Project ID separately.
2025-05-28 21:57:17 +08:00
InterestingDarkness 9f698dd6e3 Updated the placeholder text for the region input field in index.html to include 'global' as an option.
- Added a help link to provide users with information on available regions and models, improving user guidance.
2025-05-28 21:32:39 +08:00
InterestingDarkness 55af19e70b Reduced the number of rows in the textarea for Service Account JSON input in index.html 2025-05-28 21:26:10 +08:00
InterestingDarkness c9f90a2bd3 Update Gemini model options in Vertex AI section
- Removed outdated model options from the Gemini 2.0 optgroup in index.html.
- Added 'gemini-2.0-flash-preview-image-generation' to the image generation models in chat-completions.js for improved functionality.
2025-05-28 09:26:06 +08:00
Cohee b3077c4635 Use shared constant for default avatar path 2025-05-27 22:34:22 +03:00
Cohee 817ae20c3b Allow vertical scroll in import menu 2025-05-27 22:31:16 +03:00
buzz 4bec90abb5 Import character card from Soulkyn (#4042) 2025-05-27 22:30:15 +03:00
InterestingDarkness 1e2bec1751 Removed direct references to 'vertexai_project_id' from openai.js and related files, ensuring it is now managed through backend secrets for enhanced security. 2025-05-27 21:25:53 +08:00
InterestingDarkness a9d4988fc0 Remove vertexai_service_account_json from oai_settings. And google.js. 2025-05-27 08:59:13 +08:00
Cohee 2c7f2e2014 Pollinations: fix headers, add samplers 2025-05-26 23:18:51 +03:00
Cohee e2222ac40a Pollinations: fix headers, add samplers 2025-05-26 23:18:14 +03:00
Cohee 1b5a11206f Merge pull request #3967 from gakada/regex
Regex: allow multiple definitions in a single file
2025-05-26 22:26:06 +03:00
Cohee 523cc36b46 Implement bulk operations for regex 2025-05-26 22:21:48 +03:00
Cohee 52c3b83f96 Merge branch 'staging' into regex 2025-05-26 21:13:13 +03:00
InterestingDarkness df36b60e9b Add vertex AI configuration fields to sensitiveFields in openai.js
- Included 'vertexai_project_id', 'vertexai_region', and 'vertexai_service_account_json' to the sensitiveFields array for enhanced configuration management.
2025-05-27 00:45:33 +08:00
InterestingDarkness 453c177a8e Enhance Vertex AI model selection by adding data-mode attributes
- Updated index.html to include data-mode attributes for model optgroups, distinguishing between express and full modes.
- Modified openai.js to show/hide model groups based on the selected authentication mode, improving user experience and functionality.
2025-05-27 00:43:31 +08:00
InterestingDarkness 9e71b70f75 Updated toastr messages in openai.js to use translation function for better internationalization support. 2025-05-27 00:38:06 +08:00
InterestingDarkness 1c048a6c79 Refactor Google authentication functions for Vertex AI
- Exported `getVertexAIAuth`, `generateJWTToken`, and `getAccessToken` functions from google.js for better modularity.
- Removed redundant JWT token generation and access token retrieval logic from chat-completions.js, utilizing the newly exported functions instead.
- Improved code organization and maintainability by centralizing authentication logic.
2025-05-27 00:31:43 +08:00
InterestingDarkness 7fcd40c829 fix ESLint 2025-05-26 22:18:54 +08:00
InterestingDarkness 5656c7950d Implement Vertex AI authentication modes and configuration in UI
- Updated index.html to include options for Vertex AI authentication modes (Express and Full).
- Enhanced openai.js to manage Vertex AI settings, including project ID, region, and service account JSON.
- Added validation and handling for service account JSON in the backend.
- Modified API request handling in google.js to support both authentication modes for Vertex AI.
- Updated secrets.js to include a key for storing Vertex AI service account JSON.
- Improved error handling and user feedback for authentication issues.
2025-05-26 22:09:59 +08:00
Cohee a6928289b3 Clear extension load errors before activating extensions 2025-05-26 11:10:47 +00:00
Cohee a8a133b6c2 Merge branch 'release' into staging 2025-05-26 08:08:47 +00:00
Cohee 51c5783eb3 Add referrer for Pollinations requests 2025-05-26 08:08:38 +00:00
RossAscendsandCohee 57882c80e5 add ability for exts to req other exts (#4023)
* add ability for exts to req other exts

* Get rid of toasts. Collect errors on load, display in manager

* Remove unused variable

* Only show missing modules/dependencies

* Prefer display names in validation messages

* Prefer internal name for console warn

---------

Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>
2025-05-26 01:38:32 +03:00
Cohee e12e0ccd84 Support ISO 8601 timestamps 2025-05-26 01:20:28 +03:00
Cohee 61a1078e1d Display a greeting for custom welcome assistants 2025-05-26 01:09:57 +03:00
gk 6df95b98ec Regex: add export buttons for global and scoped scripts 2025-05-08 01:27:03 +09:00
gk 2650d88606 Regex: allow multiple definitions in a single file 2025-05-07 18:48:18 +09:00
213 changed files with 18325 additions and 9719 deletions
+1
View File
@@ -14,3 +14,4 @@ access.log
.DS_Store
/public/scripts/extensions/third-party
/colab
.gemini
+10
View File
@@ -0,0 +1,10 @@
have_fun: true
code_review:
disable: false
comment_severity_threshold: HIGH
max_review_comments: -1
pull_request_opened:
help: false
summary: false
code_review: false
ignore_patterns: []
+12 -301
View File
@@ -1,6 +1,5 @@
> [!IMPORTANT]
> Die hier veröffentlichten Informationen sind möglicherweise veraltet oder unvollständig. Für aktuelle Informationen nutzen Sie bitte die englische Version.
> Letztes Update dieser README: 28.9.2024
<a name="readme-top"></a>
@@ -11,7 +10,7 @@
[English](readme.md) | German | [中文](readme-zh_cn.md) | [繁體中文](readme-zh_tw.md) | [日本語](readme-ja_jp.md) | [Русский](readme-ru_ru.md) | [한국어](readme-ko_kr.md)
[![GitHub Stars](https://img.shields.io/github/stars/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/stargazers)
[![GitHub Forks](https://img.shields.io/github/forks/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/network)
[![GitHub Forks](https://img.shields.io/github/forks/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/forks)
[![GitHub Issues](https://img.shields.io/github/issues/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/issues)
[![GitHub Pull Requests](https://img.shields.io/github/issues-pr/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/pulls)
@@ -27,7 +26,7 @@ Wir haben eine [Dokumentationswebsite](https://docs.sillytavern.app/), um die me
SillyTavern (oder ST abgekürtz) ist eine lokal installierte Benutzeroberfläche, die es dir ermöglicht, mit Textgenerations-LLMs, Bildgenerierungsmaschinen und TTS-Sprachmodellen zu interagieren.
Angefangen im Februar 2023 als Fork von TavernAI 1.2.8 hat SillyTavern nun über 100 Mitwirkende und 2 Jahre unabhängiger Entwicklung hinter sich und dient weiterhin als führende Software für versierte KI-Hobbyisten.
Angefangen im Februar 2023 als Fork von TavernAI 1.2.8 hat SillyTavern nun über 200 Mitwirkende und 2 Jahre unabhängiger Entwicklung hinter sich und dient weiterhin als führende Software für versierte KI-Hobbyisten.
## Unsere Vision
@@ -35,29 +34,9 @@ Angefangen im Februar 2023 als Fork von TavernAI 1.2.8 hat SillyTavern nun über
2. Wir bieten weder Online- oder gehosteten Dienste an, noch verfolgen wir programmgesteuert Benutzerdaten.
3. SillyTavern ist ein Herzensprojekt, das von einer engagierten Community von LLM-Enthusiasten unterstützt wird, und wird immer kostenlos und Open Source sein.
## Branches
## Brauche ich einen leistungsstarken PC, um SillyTavern auszuführen?
SillyTavern wird mit einem Branchsystem entwickelt, um ein reibungsloses Erlebnis für alle Nutzer zu gewährleisten.
* `release` -🌟 **Empfohlen für die meisten Nutzer.** Dies ist der stabilste und empfohlene Branch, der nur aktualisiert wird, wenn wichtige Versionen veröffentlicht werden. Er ist für die Mehrheit der Nutzer geeignet. Typischerweise einmal im Monat aktualisiert.
* `staging` - ⚠️ **Nicht für den gelegentlichen Gebrauch empfohlen.** Dieser Branch enthält die neuesten Funktionen, kann jedoch jederzeit instabil sein. Nur für Power-User und Enthusiasten. Mehrmals täglich aktualisiert.
Wenn du nicht vertraut mit der Verwendung der git CLI bist oder nicht verstehst, was ein Branch ist, mach dir keine Sorgen! Der Release-Branch ist immer die bevorzugte Option für dich.
## Was brauche ich zusätzlich zu SillyTavern?
Da SillyTavern nur eine Benutzeroberfläche ist, benötigst du Zugriff auf ein LLM-Backend, um Inferenz bereitzustellen. Du kannst AI Horde für sofortiges Chatten ohne weitere Einrichtung verwenden. Darüber hinaus unterstützen wir viele andere lokale und cloudbasierte LLM-Backends: OpenAI-kompatible API, KoboldAI, Tabby und viele mehr. Du kannst mehr über unsere unterstützten APIs in [der FAQ](https://docs.sillytavern.app/usage/api-connections/) lesen.
### Brauche ich einen leistungsstarken PC, um SillyTavern auszuführen?
Die Hardwareanforderungen sind minimal: Es läuft auf allem, was NodeJS 18 oder höher ausführen kann. Wenn du LLM-Inferenz auf deinem lokalen Rechner durchführen möchtest, empfehlen wir eine NVIDIA-Grafikkarte der 3000er-Serie mit mindestens 6 GB VRAM. Überprüfe die Dokumentation deines Backends für weitere Einzelheiten.
### Vorgeschlagene Backends (keine Partnerschaft oder Werbebeziehung)
* [AI Horde](https://aihorde.net/) - verwende Modelle, die von Freiwilligen gehostet werden. Erfordert keine weitere Einrichtung
* [KoboldCpp](https://github.com/LostRuins/koboldcpp) - ein Favorit der Community, um GGUF-Modelle lokal auszuführen
* [tabbyAPI](https://github.com/theroyallab/tabbyAPI) - eine beliebte, portable, speicherplatzoptimierte und lokal gehostete exl2 Inferenz-API
* [OpenRouter](https://openrouter.ai) - eine einzige API für viele Cloud-Anbieter (OpenAI, Claude, Meta Llama usw.) sowie beliebte Community-Modelle.
Die Hardwareanforderungen sind minimal: Es läuft auf allem, was NodeJS 18 oder höher ausführen kann. Wenn du LLM-Inferenz auf deinem lokalen Rechner durchführen möchtest, empfehlen wir eine NVIDIA-Grafikkarte der 3000er-Serie mit mindestens 6 GB VRAM, aber die tatsächlichen Anforderungen können je nach Modell und Backend, das du verwendest, variieren.
## Fragen oder Vorschläge?
@@ -83,287 +62,18 @@ Oder nimm direkt Kontakt mit den Entwicklern auf:
<img width="500" alt="image" src="https://github.com/user-attachments/assets/9b5f32f0-c3b3-4102-b3f5-0e9213c0f50f">
<img width="500" alt="image" src="https://github.com/user-attachments/assets/913fdbaa-7d33-42f1-ae2c-89dca41c53d1">
## Charakterkarten
## Installation
SillyTavern basiert auf dem Konzept der "Charakterkarten". Eine Charakterkarte ist eine Sammlung von Prompts, die das Verhalten des LLM festlegen und erforderlich sind, um persistente Gespräche in SillyTavern zu führen. Sie funktionieren ähnlich wie ChatGPT's GPTs oder Poe's Bots. Der Inhalt einer Charakterkarte kann alles sein: ein abstraktes Szenario, ein Assistent, der für eine bestimmte Aufgabe maßgeschneidert ist, eine berühmte Persönlichkeit oder ein fiktiver Charakter.
Für detaillierte Installationsanweisungen besuche bitte unsere Dokumentation:
Das Namensfeld ist der einzige erforderliche Eingabewert für die Charakterkarte. Um ein neutrales Gespräch mit dem LLM zu beginnen, erstelle eine neue Karte, die einfach "Assistent" genannt wird, und lasse die restlichen Felder leer. Für einen thematischeren Chat kannst du dem LLM verschiedene Hintergrundinformationen, Verhaltensweisen und Schreibmuster sowie ein Szenario geben, um das Gespräch zu beginnen.
Um ein schnelles Gespräch zu führen, ohne eine Charakterkarte auszuwählen, oder um einfach die LLM-Verbindung zu testen, gib einfach dein Prompt in die Eingabezeile auf dem Willkommensbildschirm ein, nachdem du SillyTavern geöffnet hast. Bitte beachte, dass solche Chats vorübergehend sind und nicht gespeichert werden.
Um eine allgemeine Vorstellung davon zu bekommen, wie man Charakterkarten definiert, sieh dir die mitgelieferte Charakterkarte (Seraphina) an oder lade ausgewählte von der Community erstellte Karten im Menü "Erweiterungen & Assets herunterladen" herunter.
## Wichtigste Features
* Erweiterte Text-Generierungs-Einstellungen mit vielen von der Community erstellten mitgelieferten Einstellungen (Presets)
* Unterstützung für World Info: Erstelle reichhaltige Lore oder reduziere die Tokens in deiner Charakterkarte
* Gruppenchats: Multi-Bot-Räume für Charaktere, die mit dir und/oder untereinander sprechen
* Reichhaltige UI-Anpassungsoptionen: Themes zur Farbenwahl, Hintergrundbilder, benutzerdefiniertes CSS und mehr
* Benutzer-Personas: Lass die KI ein wenig über dich wissen, um die Immersion zu erhöhen
* Eingebaute RAG-Unterstützung: Füge Dokumente zu deinen Chats hinzu, auf die die KI verweisen kann
* Umfangreiches "Chat-Befehle"-System und eigene [Scripting-Engine](https://docs.sillytavern.app/usage/st-script/)
## Erweiterungen
SillyTavern unterstützt Erweiterungen.
* Emotionale Ausdrucksformen von Charakteren (Sprites)
* Automatische Zusammenfassung des Chatverlaufs
* Automatische UI- und Chat-Übersetzung
* Bildgenerierung mit Stable Diffusion/FLUX/DALL-E
* Text-to-Speech für KI-Antwortnachrichten (über ElevenLabs, Silero oder die TTS-Funktion des Betriebssystems)
* Websuchfunktionen zum Hinzufügen zusätzlicher realer Kontexte zu deinen Eingabeaufforderungen
* Viele weitere sind im Menü "Erweiterungen & Assets herunterladen" verfügbar.
Tutorials zur Nutzung findest du in der [Dokumentation](https://docs.sillytavern.app/).
# ⌛ Installation
> \[!WARNING]
>
> * INSTALLIERE NICHT IN EINEM VON WINDOWS KONTROLLIERTEN ORDNER (Programme, System32 usw.).
> * FÜHRE START.BAT NICHT MIT ADMIN-BERECHTIGUNGEN AUS.
> * DIE INSTALLATION AUF WINDOWS 7 IST UNMÖGLICH, DA ES NODEJS 18.16 NICHT AUSFÜHREN KANN.
## 🪟 Windows
### Installation über Git
1. Installiere [NodeJS](https://nodejs.org/en) (die neueste LTS-Version wird empfohlen).
2. Installiere [Git für Windows](https://gitforwindows.org/).
3. Öffne den Windows-Explorer (`Win+E`).
4. Gehe zu oder erstelle einen Ordner, der nicht von Windows kontrolliert oder überwacht wird. (z.B.: C:\MySpecialFolder\)
5. Öffne ein Eingabeaufforderungsfenster in diesem Ordner, indem du in die 'Adressleiste' oben klickst, `cmd` eingibst und Enter drückst.
6. Sobald das schwarze Fenster (Eingabeaufforderung) erscheint, gib EINE der folgenden Optionen ein und drücke Enter:
* für den Release-Branch: `git clone https://github.com/SillyTavern/SillyTavern -b release`
* für den Staging-Branch: `git clone https://github.com/SillyTavern/SillyTavern -b staging`
7. Sobald alles geklont ist, doppelklicke auf `Start.bat`, damit NodeJS seine Anforderungen installiert.
8. Der Server wird dann gestartet, und SillyTavern wird in deinem Browser geöffnet.
### Installation über GitHub Desktop
(Dies ermöglicht die Nutzung von git **nur** in GitHub Desktop. Wenn du `git` auch in der Eingabeaufforderung verwenden möchtest, musst du auch [Git für Windows](https://gitforwindows.org/) installieren.)
1. Installiere [NodeJS](https://nodejs.org/en) (die neueste LTS-Version wird empfohlen).
2. Installiere [GitHub Desktop](https://central.github.com/deployments/desktop/desktop/latest/win32).
3. Klicke nach der Installation von GitHub Desktop auf `Ein Repository aus dem Internet klonen....` (Hinweis: Du **musst kein** GitHub-Konto für diesen Schritt erstellen).
4. Klicke im Menü auf den Tab URL, gib diese URL ein `https://github.com/SillyTavern/SillyTavern` und klicke auf Klonen. Du kannst den lokalen Pfad ändern, um festzulegen, wohin SillyTavern heruntergeladen werden soll.
5. Um SillyTavern zu öffnen, durchsuche mit dem Windows-Explorer den Ordner, in den du das Repository geklont hast. Standardmäßig wird das Repository hier hin geklont: `C:\Users\[Dein Windows-Benutzername]\Documents\GitHub\SillyTavern`.
6. Doppelklicke auf die Datei `start.bat`. (Hinweis: Der Teil `.bat` des Dateinamens könnte von deinem Betriebssystem verborgen sein. In diesem Fall sieht es aus wie eine Datei namens "`Start`". Dies ist die Datei, auf die du doppelklickst, um SillyTavern auszuführen.)
7. Nach dem Doppelklicken sollte ein großes schwarzes Konsolenfenster erscheinen, und SillyTavern beginnt, das zu installieren, was es zum Betrieb benötigt.
8. Nach dem Installationsprozess sollte das Konsolenfenster so aussehen, und ein SillyTavern-Tab sollte in deinem Browser geöffnet sein.
9. Verbinde dich mit einer der [unterstützten APIs](https://docs.sillytavern.app/usage/api-connections/) und beginne zu chatten!
## 🐧 Linux & 🍎 MacOS
Für MacOS/Linux werden all diese Schritte in einem Terminal durchgeführt.
1. Installiere git und nodeJS (die Methode zur Durchführung hängt von deinem Betriebssystem ab).
2. Klone das Repository.
* für den Release-Branch: `git clone https://github.com/SillyTavern/SillyTavern -b release`
* für den Staging-Branch: `git clone https://github.com/SillyTavern/SillyTavern -b staging`
3. `cd SillyTavern`, um in den Installationsordner zu navigieren.
4. Führe das Skript `start.sh` mit einem dieser Befehle aus:
* `./start.sh`
* `bash start.sh`
## ⚡ Installation über SillyTavern Launcher
Der SillyTavern Launcher ist ein Installationsassistent, der dir bei der Einrichtung mit vielen Optionen helfen wird, einschließlich der Installation eines Backends für lokale Inferenz.
### Für Windows-Nutzer
1. Drücke auf deiner Tastatur **`WINDOWS + R`**, um das Ausführen-Dialogfeld zu öffnen. Führe dann den folgenden Befehl aus, um git zu installieren:
```shell
cmd /c winget install -e --id Git.Git
```
2. Drücke auf deiner Tastatur **`WINDOWS + E`**, um den Datei-Explorer zu öffnen, und navigiere dann zu dem Ordner, in dem du den Launcher installieren möchtest. Gib im gewünschten Ordner in die Adressleiste `cmd` ein und drücke Enter. Führe dann den folgenden Befehl aus:
```shell
git clone https://github.com/SillyTavern/SillyTavern-Launcher.git && cd SillyTavern-Launcher && start installer.bat
```
### Für Linux-Nutzer
1. Öffne dein bevorzugtes Terminal und installiere git.
2. Klone den SillyTavern-Launcher mit:
```shell
git clone https://github.com/SillyTavern/SillyTavern-Launcher.git && cd SillyTavern-Launcher
```
3. Starte die installer.sh mit:
```shell
chmod +x install.sh && ./install.sh
```
4. Nach der Installation starte die launcher.sh mit:
```shell
chmod +x launcher.sh && ./launcher.sh
```
### Für Mac-Nutzer
1. Öffne ein Terminal und installiere brew mit:
```shell
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
```
2. Installiere git mit:
```shell
brew install git
```
3. Klone den SillyTavern-Launcher mit:
```shell
git clone https://github.com/SillyTavern/SillyTavern-Launcher.git && cd SillyTavern-Launcher
```
4. Starte die installer.sh mit:
```shell
chmod +x install.sh && ./install.sh
```
5. Nach der Installation starte die launcher.sh mit:
```shell
chmod +x launcher.sh && ./launcher.sh
```
## 🐋 Installation über Docker
Diese Anweisungen setzen voraus, dass du Docker installiert hast, auf deine Befehlszeile für die Installation von Containern zugreifen kannst und mit deren allgemeiner Funktionsweise vertraut bist.
### Image selbst bauen
Wir haben einen umfassenden Leitfaden zur Nutzung von SillyTavern in Docker [hier](http://docs.sillytavern.app/installation/docker/) der die Installationen auf Windows, macOS und Linux abdeckt! Lies ihn, wenn du das Image selbst bauen möchtest.
### Verwendung der GitHub Container Registry (am einfachsten)
Du benötigst zwei zwingende Verzeichniszuordnungen und eine Portzuordnung, um SillyTavern funktionsfähig zu machen. Ersetze in dem Befehl deine Auswahl an den folgenden Stellen:
#### Container-Variablen
##### Volumen-Zuordnungen
* [config] - Das Verzeichnis, in dem die SillyTavern-Konfigurationsdateien auf deinem Host-Computer gespeichert werden
* [data] - Das Verzeichnis, in dem die Benutzerdaten von SillyTavern (einschließlich Charaktere) auf deinem Host-Computer gespeichert werden
* [plugins] - (optional) Das Verzeichnis, in dem die SillyTavern-Server-Plugins auf deinem Host-Computer gespeichert werden
##### Port-Zuordnungen
* [PublicPort] - Der Port, über den der Datenverkehr ausgegeben werden soll. Dies ist zwingend erforderlich, da du auf die Instanz von außerhalb des virtuellen Maschinencontainers zugreifst. EXPOSIERE DIES NICHT IM INTERNET, OHNE EINEN GETRENNTEN SERVICE FÜR DIE SICHERHEIT ZU IMPLEMENTIEREN.
##### Zusätzliche Einstellungen
* [DockerNet] - Das Docker-Netzwerk, mit dem der Container erstellt werden soll. Wenn du nicht weißt, was das ist, sieh dir die [offizielle Docker-Dokumentation](https://docs.docker.com/reference/cli/docker/network/) an.
* [version] - Auf der rechten Seite dieser GitHub-Seite siehst du "Packages". Wähle das Paket "sillytavern" und du siehst die Imageversionen. Das Image-Tag "latest" hält dich auf dem Laufenden mit dem aktuellen Release. Du kannst auch "staging" und "release" Tags nutzen, die auf die nightly images der jeweiligen Branche verweisen, aber das könnte unangemessen sein, wenn du Erweiterungen verwendest, die möglicherweise kaputt sind und Zeit benötigen, um aktualisiert zu werden.
#### Installationsbefehl
1. Öffne deine Befehlszeile.
2. Führe den folgenden Befehl aus:
`docker create --name='sillytavern' --net='[DockerNet]' -p '8000:8000/tcp' -v '[plugins]':'/home/node/app/plugins':'rw' -v '[config]':'/home/node/app/config':'rw' -v '[data]':'/home/node/app/data':'rw' 'ghcr.io/sillytavern/sillytavern:[version]'`
> Beachte, dass 8000 ein Standard-Listening-Port ist. Vergiss nicht, einen geeigneten Port zu verwenden, wenn du ihn in der Konfiguration änderst.
## 📱 Installation über Termux auf Android OS
> \[!HINWEIS]
> **SillyTavern kann nativ auf Android-Geräten über Termux ausgeführt werden, aber wir bieten keine offizielle Unterstützung für diesen Anwendungsfall.**
>
> **Bitte beziehe dich auf diesen Leitfaden von ArroganceComplex#2659:**
>
> * <https://rentry.org/STAI-Termux>
**Nicht unterstützte Plattform: android arm LEtime-web.** 32-Bit-Android benötigt eine externe Abhängigkeit, die nicht mit npm installiert werden kann. Verwende den folgenden Befehl, um sie zu installieren: `pkg install esbuild`. Führe dann die üblichen Installationsschritte aus.
## API-Schlüsselverwaltung
SillyTavern speichert deine API-Schlüssel in einer Datei `secrets.json` im Benutzerdatenverzeichnis (`/data/default-user/secrets.json` ist der Standardpfad).
Standardmäßig sind API-Schlüssel nach dem Speichern und Aktualisieren der Seite nicht mehr über die Benutzeroberfläche sichtbar.
Um die Ansicht deiner Schlüssel zu aktivieren:
1. Setze den Wert von `allowKeysExposure` auf `true` in der Datei `config.yaml`.
2. Starte den SillyTavern-Server neu.
3. Klicke auf den Link 'Verborgene API-Schlüssel anzeigen' in der unteren rechten Ecke des API-Verbindungsfeldes.
## Befehlszeilenargumente
Sie können Befehlszeilenargumente an den Start des SillyTavern-Servers übergeben, um einige Einstellungen in `config.yaml` zu überschreiben.
### Beispiele
```shell
node server.js --port 8000 --listen false
# oder
npm run start -- --port 8000 --listen false
# oder (nur Windows)
Start.bat --port 8000 --listen false
```
### Unterstützte Argumente
| Option | Beschreibung | Typ |
|-------------------------|----------------------------------------------------------------------------------------------------|----------|
| `--version` | Versionsnummer anzeigen | boolean |
| `--enableIPv6` | Aktiviert IPv6. | boolean |
| `--enableIPv4` | Aktiviert IPv4. | boolean |
| `--port` | Legt den Port fest, unter dem SillyTavern ausgeführt wird. Wenn nicht angegeben, wird auf YAML-Konfiguration „Port“ zurückgegriffen. | number |
| „--dnsPreferIPv6“ | Bevorzugt IPv6 für DNS. Wenn nicht angegeben, wird auf YAML-Konfiguration „preferIPv6“ zurückgegriffen. | boolean |
| „--autorun“ | Startet SillyTavern automatisch im Browser. Wenn nicht angegeben, wird auf YAML-Konfiguration „autorun“ zurückgegriffen.| boolean |
| „--autorunHostname“ | Der Autorun-Hostname, am besten auf „auto“ belassen. | string |
| „--autorunPortOverride“ | Überschreibt den Port für Autorun. | string |
| „--listen“ | SillyTavern lauscht auf allen Netzwerkschnittstellen. Wenn nicht angegeben, wird auf YAML-Konfiguration „listen“ zurückgegriffen.| boolean |
| „--corsProxy“ | Aktiviert CORS-Proxy. Wenn nicht angegeben, wird auf YAML-Konfiguration „enableCorsProxy“ zurückgegriffen. | boolean |
| `--disableCsrf` | Deaktiviert CSRF-Schutz | boolean |
| `--ssl` | Aktiviert SSL | boolean |
| `--certPath` | Pfad zu Ihrer Zertifikatsdatei. | string |
| `--keyPath` | Pfad zu Ihrer privaten Schlüsseldatei. | string |
| `--whitelist` | Aktiviert den Whitelist-Modus | boolean |
| `--dataRoot` | Stammverzeichnis für Datenspeicherung | string |
| `--avoidLocalhost` | Vermeidet die Verwendung von „localhost“ für Autorun im Auto-Modus. | boolean |
| `--basicAuthMode` | Aktiviert die grundlegende Authentifizierung | boolean |
| `--requestProxyEnabled` | Aktiviert die Verwendung eines Proxys für ausgehende Anfragen | boolean |
| `--requestProxyUrl` | Proxy-URL anfordern (HTTP- oder SOCKS-Protokolle) | string |
| `--requestProxyBypass` | Proxy-Bypass-Liste anfordern (durch Leerzeichen getrennte Liste von Hosts) | Array |
## Remoteverbindungen
Dies ist in den meisten Fällen für Personen gedacht, die SillyTavern auf ihren Mobiltelefonen verwenden möchten, während ihr PC den ST-Server im selben WLAN-Netzwerk betreibt. Es kann jedoch auch verwendet werden, um Remoteverbindungen von überall her zu ermöglichen.
Lies die ausführliche Anleitung zum Einrichten von Remoteverbindungen in den [Docs](https://docs.sillytavern.app/usage/remoteconnections/).
Möglicherweise möchtest du SillyTavern-Benutzerprofile auch mit (optionalem) Kennwortschutz konfigurieren: [Benutzer](https://docs.sillytavern.app/installation/st-1.12.0-migration-guide/#users).
## Leistungsprobleme?
1. Deaktiviere den Unschärfeeffekt und aktiviere "Verringerte Bewegung" im Bedienfeld "Benutzereinstellungen" (UI-Design schaltet Kategorie um).
2. Wenn du Response Streaming verwendest, stelle die Streaming-FPS auf einen niedrigeren Wert ein (10-15 FPS werden empfohlen).
3. Stelle sicher, dass der Browser die GPU-Beschleunigung zum Rendern verwenden kann.
* **[Windows Installationsanleitung](https://docs.sillytavern.app/installation/windows/)**
* **[MacOS/Linux Installationsanleitung](https://docs.sillytavern.app/installation/linuxmacos/)**
* **[Android (Termux) Installationsanleitung](https://docs.sillytavern.app/installation/android-(termux)/)**
* **[Docker Installationsanleitung](https://docs.sillytavern.app/installation/docker/)**
## Lizenz und Danksagungen
**Dieses Programm wird in der Hoffnung verbreitet, dass es nützlich ist,
aber OHNE JEGLICHE GARANTIE; nicht einmal die stillschweigende Garantie der
MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die
GNU Affero General Public License für weitere Details.**
**Dieses Programm wird in der Hoffnung verbreitet, dass es nützlich ist, aber OHNE JEGLICHE GARANTIE; nicht einmal die stillschweigende Garantie der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. Siehe die GNU Affero General Public License für weitere Details.**
* [TavernAI](https://github.com/TavernAI/TavernAI) 1.2.8 von Humi: MIT-Lizenz
* Teile von CncAnons TavernAITurbo-Mod werden mit Genehmigung verwendet
@@ -372,6 +82,7 @@ GNU Affero General Public License für weitere Details.**
* Symboldesign von Font Awesome <https://fontawesome.com> (Symbole: CC BY 4.0, Schriftarten: SIL OFL 1.1, Code: MIT-Lizenz)
* Standardinhalt von @OtisAlejandro (Seraphina-Charakter und Lorebook) und @kallmeflocc (10.000 Discord-Benutzer-Feierhintergrund)
* Docker-Anleitung von [@mrguymiah](https://github.com/mrguymiah) und [@Bronya-Rand](https://github.com/Bronya-Rand)
* kokoro-js library by [@hexgrad](https://github.com/hexgrad) (Apache-2.0 License)
## Top Contributors
+50 -286
View File
@@ -1,6 +1,8 @@
> [!IMPORTANT]
> ここに掲載されている情報は、古かったり不完全であったりする可能性があります。最新の情報は英語版をご利用ください。
<a name="readme-top"></a>
![][cover]
<div align="center">
@@ -8,7 +10,7 @@
[English](readme.md) | [German](readme-de_de.md) | [中文](readme-zh_cn.md) | [繁體中文](readme-zh_tw.md) | 日本語 | [Русский](readme-ru_ru.md) | [한국어](readme-ko_kr.md)
[![GitHub Stars](https://img.shields.io/github/stars/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/stargazers)
[![GitHub Forks](https://img.shields.io/github/forks/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/network)
[![GitHub Forks](https://img.shields.io/github/forks/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/forks)
[![GitHub Issues](https://img.shields.io/github/issues/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/issues)
[![GitHub Pull Requests](https://img.shields.io/github/issues-pr/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/pulls)
@@ -16,315 +18,77 @@
---
モバイルデバイスにも適したレイアウト・マルチAPI(KoboldAI/CPP、Horde、NovelAI、Ooba、OpenAI、OpenRouter、Claude、Scale)、VN ライクな Waifu モード、Stable Diffusion、TTS、WorldInfo(伝承本)、カスタマイズ可能なUI、自動翻訳、大量のプロンプトオプション+サードパーティの拡張機能をインストールする機能
SillyTavernは、多くのLLM API(KoboldAI/CPP、Horde、NovelAI、Ooba、Tabby、OpenAI、OpenRouter、Claude、Mistralなど)に対応した統一インターフェース、モバイルフレンドリーなレイアウト、ビジュアルノベルモード、Automatic1111 & ComfyUI API画像生成連携、TTS、WorldInfo(伝承本)、カスタマイズ可能なUI、自動翻訳、必要以上に豊富なプロンプトオプション、そしてサードパーティ製拡張機能による無限の成長可能性を提供します。
[TavernAI](https://github.com/TavernAI/TavernAI) v.1.2.8 のフォークに基づいています。
私たちは[ドキュメントウェブサイト](https://docs.sillytavern.app/)を用意しており、ほとんどの質問に答え、入門の手助けをします。
## 重要事項
## SillyTavernとは?
1. 私たちは[ドキュメントウェブサイト](https://docs.sillytavern.app/) を作成し、ほとんどの質問にお答えしています。
SillyTavern(略してST)は、テキスト生成LLM、画像生成エンジン、TTS音声モデルと対話するための、ローカルにインストールされるユーザーインターフェースです。
2. アップデートしたら使っていた拡張機能を見失いましたか?リリースバージョン 1.10.6 以降、これまで内蔵されていた拡張機能のほとんどがダウンロード可能なアドオンに変更されました。ダウンロードは、拡張機能パネル(トップバーのスタックドブロックアイコン)にある内蔵の "Download Extensions and Assets" メニューから行えます。
2023年2月にTavernAI 1.2.8のフォークとして始まり、SillyTavernは現在200人以上の貢献者と2年間の独立した開発を経て、知識豊富なAI愛好家のための主要なソフトウェアとして機能し続けています。
### Cohee、RossAscends、SillyTavern コミュニティがお届けします
## 私たちのビジョン
### SillyTavern または TavernAI とは何ですか?
1. 私たちは、ユーザーにできるだけ多くの実用性とLLMプロンプトの制御権限を与えることを目指しています。急な学習曲線も楽しみの一部です!
2. 私たちはオンラインサービスやホストされたサービスを提供せず、プログラム的にユーザーデータを追跡することもありません。
3. SillyTavernは、熱心なLLM愛好家のコミュニティによってもたらされた情熱的なプロジェクトであり、常に無料でオープンソースです。
SillyTavern は、あなたのコンピュータ(および Android スマホ)にインストールできるユーザーインターフェイスで、テキスト生成 AI と対話したり、あなたやコミュニティが作成したキャラクターとチャットやロールプレイをすることができます。
## SillyTavernを実行するには強力なPCが必要ですか?
SillyTavern は TavernAI 1.2.8 のフォークで、より活発な開発が行われており、多くの主要な機能が追加されています。現時点では、これらは完全に独立したプログラムと考えることができます。
ハードウェア要件は最小限です。NodeJS 18以上を実行できるものであれば何でも動作します。ローカルマシンでLLM推論を行う場合は、少なくとも6GBのVRAMを搭載した3000シリーズのNVIDIAグラフィックスカードを推奨しますが、実際の要件は使用するモデルやバックエンドによって異なる場合があります。
### ブランチ
## 質問や提案はありますか?
SillyTavern は、すべてのユーザーにスムーズな体験を保証するために、2 つのブランチシステムを使用して開発されています。
### Discordサーバー
* release -🌟 **ほとんどのユーザーにお勧め。** これは最も安定した推奨ブランチで、メジャーリリースがプッシュされた時のみ更新されます。大半のユーザーに適しています。
* staging - ⚠️ **カジュアルな使用にはお勧めしない。** このブランチには最新の機能がありますが、いつ壊れるかわからないので注意してください。パワーユーザーとマニア向けです。
| [![][discord-shield-badge]][discord-link] | [私たちのDiscordコミュニティに参加してください!](https://discord.gg/sillytavern) サポートを受けたり、お気に入りのキャラクターやプロンプトを共有したりできます。 |
| :---------------------------------------- | :----------------------------------------------------------------------------------------------------------------- |
git CLI の使い方に慣れていなかったり、ブランチが何なのかわからなかったりしても、心配はいりません!releaseブランチが良い選択肢となります。
または、開発者に直接連絡してください:
### Tavern 以外に何が必要ですか?
* Discord: cohee, rossascends, wolfsblvt
* Reddit: [/u/RossAscends](https://www.reddit.com/user/RossAscends/), [/u/sillylossy](https://www.reddit.com/user/sillylossy/), [u/Wolfsblvt](https://www.reddit.com/user/Wolfsblvt/)
* [GitHub issueを投稿](https://github.com/SillyTavern/SillyTavern/issues)
Tavern は単なるユーザーインターフェイスなので、それだけでは何もできません。ロールプレイキャラクターとして機能する AI システムのバックエンドにアクセスする必要があります。様々なバックエンドがサポートされています。リストはこちらです: OpenAPI API (GPT)、KoboldAI (ローカルまたは Google Colab 上で動作)、その他。詳しくは [FAQ](https://docs.sillytavern.app/usage/faq/) をご覧ください。
### このプロジェクトが気に入りました!どうすれば貢献できますか?
### Tavern を実行するには、ハイスペックなPCが必要ですか?
Tavern は単なるフロントエンドのUIであり、必要なハードウェアはごくわずかです。パワフルである必要があるのは、AI システムのバックエンドです。
## モバイルサポート
> **注**
> **このフォークは Termux を使って Android スマホで実行できます。ArroganceComplex#2659 のガイドを参照してください:**
<https://rentry.org/STAI-Termux>
## ご質問やご提案
### コミュニティ Discord サーバーを開設しました
サポートを受けたり、作成したキャラを共有したり、コミュニティの作ったキャラと遊びたいですか?:
### [参加](https://discord.gg/RZdyAEUPvj)
***
開発者と直接連絡:
* Discord: cohee または rossascends
* Reddit: /u/RossAscends または /u/sillylossy
* [GitHub issue を投稿](https://github.com/SillyTavern/SillyTavern/issues)
## このバージョンには以下のコードが含まれます
* 大幅に修正された TavernAI 1.2.8 (コードの 50% 以上が書き換えまたは最適化されています)
* スワイプ
* グループチャット: キャラクター同士が会話できるマルチボットルーム
* チャットチェックポイント / ブランチ
* 高度なKoboldAI / TextGen生成設定と、コミュニティが作成した多くのプリセット
* ワールド情報サポート: 豊富な伝承を作成したり、キャラクターカードにトークンを保存したりできます
* [OpenRouter](https://openrouter.ai) 各種 API(Claude、GPT-4/3.5 など)の接続
* [Oobabooga's TextGen WebUI](https://github.com/oobabooga/text-generation-webui) API 接続
* [AI Horde](https://aihorde.net/) 接続
* プロンプト生成フォーマットの調整
## 拡張機能
SillyTavern は拡張できるようになっており。
* キャラクターの感情表現(スプライト)
* チャット履歴の自動サマリー
* チャットに画像を送り、AI が内容を解釈する
* Stable Diffusion 画像生成 (5 つのチャット関連プリセットと 'free mode')
* AI 応答メッセージの音声合成(ElevenLabs、Silero、または OS のシステム TTS 経由)
含まれている拡張機能の完全なリストとその使い方のチュートリアルは [Docs](https://docs.sillytavern.app/) にあります。
## RossAscends による UI/CSS/クオリティオブライフの調整
* iOS 用に最適化されたモバイル UI で、ホーム画面へのショートカット保存とフルスクリーンモードでの起動をサポート。
* ホットキー
* Up = チャットの最後のメッセージを編集する
* Ctrl+Up = チャットで最後のユーザーメッセージを編集する
* Left = 左スワイプ
* Right = 右スワイプ (注: チャットバーに何か入力されている場合、スワイプホットキーが無効になります)
* Ctrl+Left = ローカルに保存された変数を見る(ブラウザのコンソールウィンドウにて)
* Enter (チャットバー選択時) = AI にメッセージを送る
* Ctrl+Enter = 最後の AIのレスポンスを再生成する
* ユーザー名の変更と文字の削除でページが更新されなくなりました。
* ページロード時に API に自動的に接続するかどうかを切り替えます。
* ページの読み込み時に、最近見た文字を自動的に読み込むかどうかを切り替えます。
* より良いトークンカウンター - 保存されていないキャラクターに対して機能し、永続的なトークンと一時的なトークンの両方を表示する。
* より良い過去のチャット
* 新しいチャットのファイル名は、"(文字) - (作成日)" という読みやすい形式で保存されます
* チャットのプレビューが 40 文字から 300 文字に増加。
* 文字リストの並べ替えに複数のオプション(名前順、作成日順、チャットサイズ順)があります。
* デフォルトでは、左右の設定パネルはクリックすると閉じます。
* ナビパネルのロックをクリックすると、パネルが開いたままになり、この設定はセッションをまたいで記憶されます。
* ナビパネルの開閉状態もセッションをまたいで保存されます。
* カスタマイズ可能なチャット UI:
* 新しいメッセージが届いたときにサウンドを再生する
* 丸型、長方形のアバタースタイルの切り替え
* デスクトップのチャットウィンドウを広くする
* オプションの半透明ガラス風パネル
* 'メインテキスト'、'引用テキスト'、'斜体テキスト'のページカラーをカスタマイズ可能。
* カスタマイズ可能な UI 背景色とぼかし量
## インストール
*注: このソフトウェアはローカルにインストールすることを目的としており、colab や他のクラウドノートブックサービス上では十分にテストされていません。*
> **警告**
> WINDOWS が管理しているフォルダ(Program Files、System32 など)にはインストールしないでください
> START.BAT を管理者権限で実行しないでください
### Windows
Git 経由でのインストール(更新を容易にするため推奨)
写真付きのわかりやすいガイドはこちらです:
<https://docs.sillytavern.app/installation/windows/>
1. [NodeJS](https://nodejs.org/en) をインストール(最新の LTS 版を推奨)
2. [GitHub Desktop](https://central.github.com/deployments/desktop/desktop/latest/win32) をインストールする
3. Windows エクスプローラーを開く (`Win+E`)
4. Windows によって制御または監視されていないフォルダを参照または作成する。(例: C:\MySpecialFolder\)
5. 上部のアドレスバーをクリックし、`cmd` と入力して Enter キーを押し、そのフォルダーの中にコマンドプロンプトを開きます。
6. 黒いボックス(コマンドプロンプト)がポップアップしたら、そこに以下のいずれかを入力し、Enter を押します:
* Release ブランチの場合: `git clone https://github.com/SillyTavern/SillyTavern -b release`
* Staging ブランチの場合: `git clone https://github.com/SillyTavern/SillyTavern -b staging`
7. すべてをクローンしたら、`Start.bat` をダブルクリックして、NodeJS に要件をインストールさせる。
8. サーバーが起動し、SillyTavern がブラウザにポップアップ表示されます。
ZIP ダウンロードによるインストール(推奨しない)
1. [NodeJS](https://nodejs.org/en) をインストールする(最新の LTS 版を推奨)
2. GitHub のリポジトリから zip をダウンロードする。(`ソースコード(zip)` は [Releases](https://github.com/SillyTavern/SillyTavern/releases/latest) から入手)
3. お好きなフォルダに解凍してください
4. `Start.bat` をダブルクリックまたはコマンドラインで実行する。
5. サーバーが準備できれば、ブラウザのタブを開きます。
### Linux
1. `node -v` を実行して、Node.js v18 以上(最新の [LTS バージョン](https://nodejs.org/en/download/) を推奨)がインストールされていることを確認してください。
または、[Node Version Manager](https://github.com/nvm-sh/nvm#installing-and-updating) スクリプトを使用して、迅速かつ簡単に Node のインストールを管理します。
2. `start.sh` スクリプトを実行する。
3. お楽しみください。
## API キー管理
SillyTavern は API キーをサーバーディレクトリの `secrets.json` ファイルに保存します。
デフォルトでは、入力後にページをリロードしても、フロントエンドには表示されません。
API ブロックのボタンをクリックして、キーを閲覧できるようにする:
1. ファイル `config.yaml` で `allowKeysExposure` の値を `true` に設定する。
2. SillyTavern サーバを再起動します。
## リモート接続
SillyTavern をスマホで使用しながら、同じ Wifi ネットワーク上で ST サーバーを PC で実行したい場合に使用します。
しかし、これはどこからでもリモート接続を許可するために使用することができます。
**重要: SillyTavern はシングルユーザーのプログラムなので、ログインすれば誰でもすべてのキャラクターとチャットを見ることができ、UI 内で設定を変更することができます。**
### 1. ホワイトリスト IP の管理
* SillyTavern のベースインストールフォルダ内に `whitelist.txt` という新しいテキストファイルを作成します。
* テキストエディタでこのファイルを開き、接続を許可したい IP のリストを追加します。
*個々の IP とワイルドカード IP 範囲の両方が受け入れられる。例:*
```txt
192.168.0.1
192.168.0.20
```
または
```txt
192.168.0.*
```
(上記のワイルドカード IP 範囲は、ローカルネットワーク上のどのデバイスでも)
CIDR マスクも受け付ける(例:10.0.0.0/24)。
* `whitelist.txt` ファイルを保存する。
* TAI サーバーを再起動する。
これでファイルに指定された IP を持つデバイスが接続できるようになります。
*注: `config.yaml` にも `whitelist` 配列があり、同じように使うことができるが、`whitelist.txt` が存在する場合、この配列は無視される。*
### 2. ST ホストマシンの IP の取得
ホワイトリストの設定後、ST ホストデバイスの IP が必要になります。
ST ホストデバイスが同じ無線 LAN ネットワーク上にある場合、ST ホストの内部無線 LAN IP を使用します:
* Windows の場合: ウィンドウズボタン > 検索バーに `cmd.exe` と入力 > コンソールに `ipconfig` と入力して Enter > `IPv4` のリストを探す。
同じネットワーク上にいない状態で、ホストしているSTに接続したい場合は、STホスト機器のパブリックIPが必要です。
* ST ホストデバイスを使用中に、[このページ](https://whatismyipaddress.com/)にアクセスし、`IPv4` を探してください。これはリモートデバイスからの接続に使用するものです。
### 3. リモートデバイスを ST ホストマシンに接続します。
最終的に使用する IP が何であれ、その IP アドレスとポート番号をリモートデバイスのウェブブラウザに入力します。
同じ無線 LAN ネットワーク上の ST ホストの典型的なアドレスは以下のようになります:
`http://192.168.0.5:8000`
http:// を使用し、https:// は使用しないでください
### ST をすべての IP に開放する
これはお勧めしませんが、`config.yaml` を開き、`whitelistMode` を `false` に変更してください。
SillyTavern のベースインストールフォルダにある `whitelist.txt` が存在する場合は削除(または名前の変更)する必要があります。
これは通常安全ではないので、これを行う際にはユーザー名とパスワードを設定する必要があります。
ユーザー名とパスワードは `config.yaml` で設定します。
ST サーバを再起動すると、ユーザ名とパスワードさえ知っていれば、IP に関係なくどのデバイスでも ST サーバに接続できるようになる。
### まだ接続できませんか?
* `config.yaml` で見つかったポートに対して、インバウンド/アウトバウンドのファイアウォールルールを作成します。これをルーターのポートフォワーディングと間違えないでください。そうしないと、誰かがあなたのチャットログを見つける可能性があり、それはマジで止めましょう。
* 設定 > ネットワークとインターネット > イーサネットで、プライベートネットワークのプロファイルタイプを有効にします。そうしないと、前述のファイアウォールルールを使っても接続できません。
## パフォーマンスに問題がありますか?
ユーザー設定パネルでブラー効果なし(高速 UI)モードを有効にしてみてください。
## このプロジェクトが気に入りました!どうすれば貢献できますか?
### やるべきこと
1. プルリクエストを送る
2. 確立されたテンプレートを使って機能提案と課題レポートを送る
3. 何か質問する前に、readme ファイルや組み込みのドキュメントを読んでください
### やるべきではないこと
1. 金銭の寄付を申し出る
2. 何の脈絡もなくバグ報告を送る
3. すでに何度も回答されている質問をする
## 古い背景画像はどこにありますか?
100% オリジナルコンテンツのみのポリシーに移行しているため、古い背景画像はこのリポジトリから削除されました。
アーカイブはこちら:
<https://files.catbox.moe/1xevnc.zip>
1. プルリクエストを送ってください。貢献する方法については、[CONTRIBUTING.md](../CONTRIBUTING.md)をご覧ください。
2. 提供されたテンプレートを使用して、機能の提案や問題の報告を送ってください。
3. 重複した問題を避けるために、まずこのreadmeファイル全体とドキュメントウェブサイトを確認してください。
## スクリーンショット
<img width="500" alt="image" src="https://github.com/user-attachments/assets/9b5f32f0-c3b3-4102-b3f5-0e9213c0f50f">
<img width="500" alt="image" src="https://github.com/user-attachments/assets/913fdbaa-7d33-42f1-ae2c-89dca41c53d1">
## インストール
詳細なインストール手順については、私たちのドキュメントをご覧ください:
* **[Windowsインストールガイド](https://docs.sillytavern.app/installation/windows/)**
* **[MacOS/Linuxインストールガイド](https://docs.sillytavern.app/installation/linuxmacos/)**
* **[Android (Termux)インストールガイド](https://docs.sillytavern.app/installation/android-(termux)/)**
* **[Dockerインストールガイド](https://docs.sillytavern.app/installation/docker/)**
## ライセンスとクレジット
**このプログラムは有用であることを願って配布されていますが、いかなる保証もありません;
また、商品性または特定目的への適合性についての黙示の保証もありません。
詳細は GNU Affero General Public License をご覧ください。**
**このプログラムは有用であることを期待して配布されていますが、いかなる保証もありません。商品性または特定目的への適合性の黙示の保証さえもありません。詳細はGNU Affero General Public Licenseをご覧ください。**
* Humi によるTAI Base: 不明ライセンス
* Cohee の修正と派生コード: AGPL v3
* RossAscends の追加: AGPL v3
* CncAnon の TavernAITurbo 改造の一部: 不明ライセンス
* kingbri のさまざまなコミットと提案 (<https://github.com/bdashore3>)
* city_unit の拡張機能と様々な QoL 機能 (<https://github.com/city-unit>)
* StefanDanielSchwarz のさまざまなコミットとバグ報告 (<https://github.com/StefanDanielSchwarz>)
* PepperTaco の作品にインスパイアされた Waifu モード (<https:/fugithub.com/peppertaco/Tavern/>)
* ピグマリオン大学の皆さん、素晴らしいテスターとしてクールな機能を提案してくれてありがとう!
* TextGen のプリセットをコンパイルしてくれた obabooga に感謝
* KAI Lite の KoboldAI プリセット: <https://lite.koboldai.net/>
* Google による Noto Sans フォント(OFLライセンス)
* Font Awesome によるアイコンテーマ <https://fontawesome.com> (アイコン: CC BY 4.0、フォント: SIL OFL 1.1、コード: MIT License)
* ZeldaFan0225 による AI Horde クライアントライブラリ: <https://github.com/ZeldaFan0225/ai_horde>
* AlpinDale による Linux 起動スクリプト
* FAQ を提供してくれた paniphons に感謝
* 10K ディスコード・ユーザー記念背景 by @kallmeflocc
* デフォルトコンテンツ(キャラクターと伝承書)の提供: @OtisAlejandro、@RossAscends、@kallmeflocc
* @doloroushyeonse による韓国語翻訳
* k_euler_a による Horde のサポート <https://github.com/Teashrock>
* [@XXpE3](https://github.com/XXpE3) による中国語翻訳、中国語 ISSUES の連絡先は @XXpE3
* [TavernAI](https://github.com/TavernAI/TavernAI) 1.2.8 by Humi: MITライセンス
* CncAnonのTavernAITurbo modの一部を許可を得て使用
* PepperTacoの作品に触発されたビジュアルノベルモード (<https://github.com/peppertaco/Tavern/>)
* GoogleによるNoto Sansフォント (OFLライセンス)
* Font Awesomeによるアイコンテーマ <https://fontawesome.com> (アイコン: CC BY 4.0, フォント: SIL OFL 1.1, コード: MITライセンス)
* @OtisAlejandroによるデフォルトコンテンツ(Seraphinaキャラクターと伝承本)と@kallmefloccによる10K Discordユーザー記念背景
* [@mrguymiah](https://github.com/mrguymiah)と[@Bronya-Rand](https://github.com/Bronya-Rand)によるDockerガイド
* [@hexgrad](https://github.com/hexgrad)によるkokoro-jsライブラリ (Apache-2.0ライセンス)
## トップコントリビューター
[![Contributors](https://contrib.rocks/image?repo=SillyTavern/SillyTavern)](https://github.com/SillyTavern/SillyTavern/graphs/contributors)
<!-- LINK GROUP -->
[cover]: https://github.com/user-attachments/assets/01a6ae9a-16aa-45f2-8bff-32b5dc587e44
[discord-link]: https://discord.gg/sillytavern
[discord-shield-badge]: https://img.shields.io/discord/1100685673633153084?color=5865F2&label=discord&labelColor=black&logo=discord&logoColor=white&style=for-the-badge
+11 -311
View File
@@ -10,7 +10,7 @@
[English](readme.md) | [German](readme-de_de.md) | [中文](readme-zh_cn.md) | [繁體中文](readme-zh_tw.md) | [日本語](readme-ja_jp.md) | [Русский](readme-ru_ru.md) | 한국어
[![GitHub Stars](https://img.shields.io/github/stars/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/stargazers)
[![GitHub Forks](https://img.shields.io/github/forks/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/network)
[![GitHub Forks](https://img.shields.io/github/forks/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/forks)
[![GitHub Issues](https://img.shields.io/github/issues/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/issues)
[![GitHub Pull Requests](https://img.shields.io/github/issues-pr/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/pulls)
@@ -26,8 +26,7 @@ SillyTavern은 많은 LLM API(KoboldAI/CPP, Horde, NovelAI, Ooba, Tabby, OpenAI,
SillyTavern(짧게는 ST)은 텍스트 생성 LLM, 이미지 생성 엔진, TTS 음성 모델 등과 상호작할 수 있는 로컬 설치형 UI 입니다.
2023년 2월, TavernAI 1.2.8의 포크로 시작한 SillyTavern은 현재 100명이 넘는 기여자를 보유하고 있으며, 2년간의 독자적인 개발을 거쳐 숙련된 AI 애호가들을 위한 선도적인 소프트웨어로 자리매김하고 있습니다.
2023년 2월, TavernAI 1.2.8의 포크로 시작한 SillyTavern은 현재 200명이 넘는 기여자를 보유하고 있으며, 2년간의 독자적인 개발을 거쳐 숙련된 AI 애호가들을 위한 선도적인 소프트웨어로 자리매김하고 있습니다.
## 우리의 비전
@@ -35,30 +34,9 @@ SillyTavern(짧게는 ST)은 텍스트 생성 LLM, 이미지 생성 엔진, TTS
2. 저희는 어떠한 온라인 및 호스팅 서브시도 제공하지 않으며, 프로그래밍으로 사용자의 데이터를 추적하지 않습니다.
3. SillyTavern은 헌신적인 LLM 커뮤니티가 여러분에게 제공하는 열정적인 프로젝트이며, 언제나 무료이며 오픈소스로 제공될 것입니다.
## 브랜치
## SillyTavern을 위해서 좋은 성능의 PC가 필요한가요?
SillyTavern은 모든 사용자가 원활한 경험을 할 수 있도록 두 개의 브랜치를 활용하여 개발되고 있습니다.
* `release` -🌟 **대부분의 사용자에게 추천됨.** 가장 안정적이고 권장되는 브랜치이며, 주요 릴리스가 배포될 때만 업데이트됩니다. 대부분의 사용자에게 적합합니다. 일반적으로 한달에 한번 업데이트됩니다.
* `staging` - ⚠️ **일반적인 사용에 추천되지 않음.** 최신 기능을 가지고 있지만, 언제든지 문제가 발생할 수 있습니다. 고급 사용자 및 숙련자 전용입니다. 하루에 여러번 업데이트됩니다.
만약 git CLI 사용에 익숙하지 않거나 브랜치가 무엇인지 모르겠다면 release 브랜치가 더 나은 선택입니다.
## SillyTavern 외에 무엇이 필요한가요?
SillyTavern은 인터페이스 역할만 하기 때문에, 실제로 채팅하려면 LLM 백엔드에 대한 액세스 권한이 필요합니다. 즉시 사용 가능한 채팅을 위해 AI Horde를 사용할 수 있습니다. 그 외에도 OpenAI 호환 API, KoboldAI, Tabby 등 많은 로컬 및 클라우드 기반 LLM 백엔드를 지원합니다. 지원되는 API에 대한 자세한 내용은 [FAQ](https://docs.sillytavern.app/usage/api-connections/)에서 확인할 수 있습니다.
### SillyTavern을 위해서 좋은 성능의 PC가 필요한가요?
하드웨어 요구 사항은 거의 없습니다: NodeJS 18 이상을 실행할 수 있는 모든 환경에서 작동합니다. 다만 로컬 LLM 모델을 사용할 경우, 최소 6GB VRAM 이상의 3000번대 NVIDIA 그래픽 카드를 권장합니다. 자세한 내용은 백엔드 문서를 참고하세요.
### 추천되는 백엔드 (제휴 없음)
* [AI Horde](https://aihorde.net/) - 자원 봉사자들이 호스팅하는 모델을 사용합니다. 추가 설정이 필요하지 않습니다.
* [KoboldCpp](https://github.com/LostRuins/koboldcpp) - 로컬에서 GGUF 모델을 실행하기 위한 커뮤니티에서 선호하는 옵션입니다.
* [tabbyAPI](https://github.com/theroyallab/tabbyAPI) - 인기 있는 경량 로컬 exl2 추론 API입니다.
* [OpenRouter](https://openrouter.ai) - OpenAI, Claude, Meta Llama 등 다양한 클라우드 제공업체와 인기 있는 커뮤니티 모델을 위한 단일 API입니다.
하드웨어 요구 사항은 거의 없습니다: NodeJS 18 이상을 실행할 수 있는 모든 환경에서 작동합니다. 다만 로컬 LLM 모델을 사용할 경우, 최소 6GB VRAM 이상의 3000번대 NVIDIA 그래픽 카드를 권장하지만, 실제 요구 사항은 사용하는 모델과 백엔드에 따라 달라질 수 있습니다.
## 질문이나 제안이 있으신가요?
@@ -84,293 +62,14 @@ SillyTavern은 인터페이스 역할만 하기 때문에, 실제로 채팅하
<img width="500" alt="image" src="https://github.com/user-attachments/assets/9b5f32f0-c3b3-4102-b3f5-0e9213c0f50f">
<img width="500" alt="image" src="https://github.com/user-attachments/assets/913fdbaa-7d33-42f1-ae2c-89dca41c53d1">
## 설치
## 캐릭터 카드
자세한 설치 방법은 저희의 문서를 확인하세요:
SillyTavern은 "캐릭터 카드"라는 개념을 중심으로 구축되었습니다. 캐릭터 카드는 LLM의 동작을 설정하는 프롬프트 모음이며, SillyTavern에서 지속적인 대화를 하려면 필수적입니다. 이는 ChatGPT의 GPT 또는 Poe의 봇과 유사하게 작동합니다. 캐릭터 카드의 내용은 추상적인 시나리오, 특정 작업에 맞춰진 도우미, 유명 인사 또는 가상 인물 등 무엇이든 될 수 있습니다.
이름 필드는 유일한 필수 캐릭터 카드 입력 항목입니다. 언어 모델과 중립적인 대화를 시작하려면 "도우미"라고 간단히 이름 지은 새 카드를 만들고 나머지 상자는 비워 두세요. 더 주제가 있는 채팅을 원한다면 언어 모델에 다양한 배경 정보, 행동 및 작문 패턴, 그리고 채팅을 바로 시작할 시나리오를 제공할 수 있습니다.
캐릭터 카드를 선택하지 않고 빠른 대화를 하거나 LLM 연결을 테스트하려면 SillyTavern을 연 후 시작 화면의 입력 창에 프롬프트 입력을 입력하기만 하면 됩니다. 이러한 채팅은 임시적이며 저장되지 않습니다.
캐릭터 카드를 정의하는 방법에 대한 일반적인 아이디어를 얻으려면 기본 캐릭터(Seraphina)를 보거나 "확장 프로그램 및 에셋 다운로드" 메뉴에서 선택된 커뮤니티 제작 카드를 다운로드하세요.
## 핵심 기능
* 고급 텍스트 생성 설정과 다양한 커뮤니티 제작 프리셋
* 월드 인포 지원: 풍부한 설정을 만들거나 캐릭터 카드에 토큰 저장
* 그룹 채팅: 캐릭터가 사용자 혹은 다른 캐릭터와 대화할 수 있는 방
* 다양한 UI 커스텀 옵션: 테마 색, 뱌경 이미지, 커스텀 CSS 등
* 유저 페르소나: AI에게 사용자에 대한 정보를 주어 더욱 몰입감을 높임
* 내장 RAG 지원: AI가 참조할 수 있도록 채팅에 문서를 추가
* 광범위한 채팅 명령어 시스템 및 자체 [스크립트](https://docs.sillytavern.app/usage/st-script/)
## 확장
SillyTavern은 확장(익스텐션)을 지원합니다.
* 캐릭터 감정 표현 (스프라이트)
* 채팅 기록 자동 요약
* 자동 UI 및 채팅 번역
* Stable Diffusion/FLUX/DALL-E 이미지 생성
* AI 응답 메시지 텍스트 음성 변환 (ElevenLabs, Silero 또는 OS 시스템 TTS 사용)
* 프롬프트에 추가적인 현실 세계 맥락을 추가하기 위한 웹 검색 기능
* "확장 프로그램 및 에셋 다운로드" 메뉴에서 더 많은 기능을 다운로드할 수 있습니다.
사용 방법에 대한 튜토리얼은 [Docs](https://docs.sillytavern.app/)에서 확인할 수 있습니다.
# ⌛ Installation
> \[!WARNING]
>
> * **윈도우 제어 폴더에는 설치하지 마십시오 (Program Files, System32 등).**
> * **권리자 권한으로 START.BAT을 실행하지 마십시오.**
> * **Windows 7에서는 NodeJS 18.16을 실행할 수 없으므로 설치가 불가능합니다.**
## 🪟 Windows
### Git을 통해 설치하기
1. [NodeJS](https://nodejs.org/ko) 설치 (최신 LTS 버전 권장)
2. [Git for Windows](https://gitforwindows.org/) 설치
3. 파일 탐색기 열기 (`Win+E`)
4. Windows에서 제어하거나 모니터하지 않는 폴더를 찾거나 만드세요. (ex: C:\MySpecialFolder\)
5. 상단의 주소 표시줄을 클릭하고 `cmd`를 입력한 후 Enter 키를 눌러 해당 폴더 내에서 명령 프롬프트를 여세요.
6. 검은색 창(명령 프롬프트)이 나타나면 다음 중 하나를 입력하고 Enter 키를 누르세요.
* Release 브랜치: `git clone https://github.com/SillyTavern/SillyTavern -b release`
* Staging 브랜치: `git clone https://github.com/SillyTavern/SillyTavern -b staging`
7. clone이 완료되면, `Start.bat`을 더블 클릭하여 NodeJS가 필요한 구성요소를 설치하도록 하세요.
8. 그러면 서버가 시작하고, SillyTavern이 브라우저에 나타납니다.
### GitHub Desktop을 통해 설치하기
(이 방법은 **오직** GitHub Desktop에서만 git 사용이 가능합니다. 명령 프롬프트에서 git을 사용하려면 [Git for Windows](https://gitforwindows.org/)를 설치해야 합니다.)
1. [NodeJS](https://nodejs.org/ko) 설치 (최신 LTS 버전 권장)
2. [GitHub Desktop](https://central.github.com/deployments/desktop/desktop/latest/win32) 설치
3. GitHub Desktop을 설치했으면, `Clone a repository from the internet....`를 클릭하세요. (참고: 이 과정에서는 Github 계정이 **필요하지 않습니다**.)
4. 메뉴에서 URL 탭을 클릭하고, 다음 URL을 입력한 후 복제를 클릭합니다: `https://github.com/SillyTavern/SillyTavern` 리포지토리가 다운로드될 위치를 변경하려면 로컬 경로를 변경할 수 있습니다.
5. SillyTavern을 열려면 파일 탐색기를 사용하여 리포지토리를 복제한 폴더로 이동합니다. 기본적으로 리포지토리는 다음 위치에 복제됩니다: `C:\Users\[사용자 Windows 사용자 이름]\Documents\GitHub\SillyTavern`
6. `start.bat` 파일을 더블 클릭 하세요. (참고: `.bat` 확장자 명은 OS 설정에 따라 보이지 않을 수 있습니다, 그럴 때는 파일 이름이 "`Start`" 처럼 보일 수 있습니다. 이 파일을 더블 클릭해 SillyTavern을 실행하세요.)
7. 더블 클릭하면, 검고 큰 명령 프롬프트 창이 열리고 SillyTavern이 작동하는데 필요한 항목을 설치하기 시작합니다.
8. 설치 과정이 끝나고 모든 것이 잘 작동한다면, 브라우저에 SillyTavern 탭이 열려 있어야 하고, 명령 프롬프트 창에 다음과 같이 표시되어야 합니다:
9. Connect to any of the [supported APIs](https://docs.sillytavern.app/usage/api-connections/) and start chatting!
## 🐧 Linux & 🍎 MacOS
MacOS / Linux 에서는 이 모든 작업이 터미널에서 수행됩니다.
1. git과 nodeJS 설치 (이 작업은 OS에 따라 달라집니다.)
2. 리포지토리 clone하기
* Release 브랜치: `git clone https://github.com/SillyTavern/SillyTavern -b release`
* Staging 브랜치: `git clone https://github.com/SillyTavern/SillyTavern -b staging`
3. `cd SillyTavern` 를 입력해 설치 폴더로 이동하기
4. `start.sh` 스크립트를 아래의 명령어 중 하나로 실행하기:
* `./start.sh`
* `bash start.sh`
## ⚡ SillyTavern Launcher를 통해 설치하기
SillyTavern 런처는 로컬 LLM 사용을 위한 백엔드 설치를 포함하여 다양한 설정을 도와주는 설치 마법사입니다.
### Windows 사용자
1. 키보드에서 **`WINDOWS + R`** 키를 눌러 실행 창을 여세요. 그리고 아래의 명령어를 입력해 git을 설치하세요.
```shell
cmd /c winget install -e --id Git.Git
```
2. 키보드에서 **`WINDOWS + E`** 키를 눌러 파일 탐색기를 열고 런처를 설치할 폴더로 이동합니다. 원하는 폴더에 도착하면 주소 표시줄에 `cmd`를 입력하고 Enter 키를 누릅니다. 그 후 아래의 명령어를 입력합니다.
```shell
git clone https://github.com/SillyTavern/SillyTavern-Launcher.git && cd SillyTavern-Launcher && start installer.bat
```
### Linux 사용자
1. 선호하는 터미널을 열고 git을 설치하세요.
2. SillyTavern-Launcher를 clone 하세요:
```shell
git clone https://github.com/SillyTavern/SillyTavern-Launcher.git && cd SillyTavern-Launcher
```
3. installer.sh를 실행하세요:
```shell
chmod +x install.sh && ./install.sh
```
4. 설치가 끝나면 launcher.sh를 실행하세요:
```shell
chmod +x launcher.sh && ./launcher.sh
```
### Mac 사용자
1. 터미널을 열고 Brew를 설치하세요:
```shell
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
```
2. git을 설치하세요:
```shell
brew install git
```
3. SillyTavern-Launcher를 clone 하세요:
```shell
git clone https://github.com/SillyTavern/SillyTavern-Launcher.git && cd SillyTavern-Launcher
```
4. installer.sh를 실행하세요:
```shell
chmod +x install.sh && ./install.sh
```
5. 설치가 끝나면 launcher.sh를 실행하세요:
```shell
chmod +x launcher.sh && ./launcher.sh
```
## 🐋 Docker를 통해 설치하기
이 방법은 Docker가 설치되어 있고, Docker 설치를 위해 커맨드 라인에 접근할 수 있으며, Docker의 일반적인 작동 방식에 익숙하다고 가정합니다.
### 이미지 직접 빌드하기
SillyTavern을 Docker에서 사용하는 방법에 대한 포괄적인 가이드는 [여기서](http://docs.sillytavern.app/installation/docker/) 확인할 수 있습니다. 이 가이드는 Windows, macOS 및 Linux에서의 설치를 다룹니다! 직접 이미지를 빌드하려면 이 가이드를 읽어보세요.
### GitHub Container Registry 사용하기 (가장 쉬움)
SillyTavern이 작동하려면 두 개의 필수 디렉터리 매핑과 하나의 포트 매핑이 필요합니다. 명령에서 다음 위치의 선택 항목을 바꿔주세요.
#### Container Variables
##### Volume Mappings
* [config] - SillyTavern 구성 파일이 호스트 컴퓨터에 저장될 디렉터리
* [data] - 캐릭터를 포함한 SillyTavern 사용자 데이터가 호스트 컴퓨터에 저장될 디렉터리
* [plugins] - (선택 사항) SillyTavern 서버 플러그인이 호스트 컴퓨터에 저장될 디렉터리
##### Port Mappings
* [PublicPort] - 트래픽을 노출할 포트입니다. 가상 머신 컨테이너 외부에서 인스턴스에 접근하므로 필수 사항입니다. 보안을 위한 별도의 서비스를 구현하지 않고는 인터넷에 노출하지 마십시오.
##### Additional Settings
* [DockerNet] - 컨테이너가 연결되어 생성되어야 하는 Docker 네트워크입니다. 해당 내용을 모르는 경우 [공식 Docker 문서](https://docs.docker.com/reference/cli/docker/network/)를 참조하세요.
* [version] - 이 GitHub 페이지의 오른쪽에서 "Packages"를 선택하면 "sillytavern" 패키지를 볼 수 있습니다. "latest" 이미지 태그는 현재 릴리스와 함께 최신 상태를 유지합니다. 각 브랜치의 야간 이미지를 가리키는 "staging" 및 "release" 태그를 사용할 수도 있지만, 업데이트에 시간이 걸릴 수 있고 중단될 수 있는 확장 프로그램을 사용하는 경우에는 적합하지 않을 수 있습니다.
#### 설치 명령어
1. 커맨드 라인 열기
2. 아래의 명령어 실행
`docker create --name='sillytavern' --net='[DockerNet]' -p '8000:8000/tcp' -v '[plugins]':'/home/node/app/plugins':'rw' -v '[config]':'/home/node/app/config':'rw' -v '[data]':'/home/node/app/data':'rw' 'ghcr.io/sillytavern/sillytavern:[version]'`
> 8000은 기본 리스닝 포트입니다. 구성에서 포트를 변경한 경우 적절한 포트를 사용하는 것을 잊지 마세요.
## 📱 Termux를 통해 Android OS에 설치하기
> \[!NOTE]
> **SillyTavern은 Termux를 사용하여 Android 기기에서 기본적으로 실행할 수 있지만, 이러한 사용 사례에 대한 공식적인 지원은 제공하지 않습니다.**
>
> **ArroganceComplex#2659의 가이드를 참조하세요:**
>
> * <https://rentry.org/STAI-Termux>
**지원되지 않는 플랫폼: android arm LEtime-web.** 32비트 Android는 npm으로 설치할 수 없는 외부 종속성이 필요합니다. 다음 명령어를 사용하여 설치하세요: pkg install esbuild. 그런 다음 일반적인 설치 단계를 진행하세요.
## API 키 관리
SillyTavern은 API 키를 사용자 데이터 디렉터리의 `secrets.json` 파일에 저장합니다 (`/data/default-user/secrets.json`이 기본 경로입니다).
기본적으로 API 키는 저장하고 페이지를 새로 고침한 후에는 인터페이스에서 보이지 않습니다.
키 보기 기능을 활성화하려면 다음 단계를 따르세요:
1. `config.yaml` 파일에서 `allowKeysExposure` 값을 `true로` 설정합니다.
2. SillyTavern 서버를 다시 시작합니다.
3. API 연결 패널 오른쪽 하단에 있는 '숨겨진 API 키 보기' 링크를 클릭합니다.
## 커맨드 라인 인수
`config.yaml`의 일부 설정을 덮어쓰기 위해 SillyTavern 서버 시작 시 커맨드 라인 인수를 전달할 수 있습니다.
### 예시
```shell
node server.js --port 8000 --listen false
# 혹은
npm run start -- --port 8000 --listen false
# 혹은 (Windows 전용)
Start.bat --port 8000 --listen false
```
### 지원되는 인수
| 옵션 | 설명 | 타입 |
|-------------------------|------------------------------------------------------------------------------------------------------|----------|
| `--version` | 버전 표시 | boolean |
| `--enableIPv6` | IPv6 활성화 | boolean |
| `--enableIPv4` | IPv4 활성화 | boolean |
| `--port` | SillyTavern이 실행될 포트를 설정합니다. 설정되지 않은 경우 yaml config 'port'를 불러옵니다. | number |
| `--dnsPreferIPv6` | DNS에 IPv6를 우선으로 할당합니다. 설정되지 않은 경우 yaml config를 불러옵니다. | boolean |
| `--autorun` | 브라우저에서 SillyTavern을 자동으로 실행합니다. 설정되지 않은 경우 yaml config 'autorun'를 불러옵니다. | boolean |
| `--autorunHostname` | 자동 실행 호스트 이름, 'auto'가 최적의 설정일 것입니다. | string |
| `--autorunPortOverride` | 자동 실행 포트 덮어쓰기 | string |
| `--listen` | SillyTavern이 모든 네트워크 인터페이스에서 수신 대기합니다. 설정되지 않은 경우 yaml 구성 'listen'을 불러옵니다. | boolean |
| `--corsProxy` | CORS 프록시 활성화. 설정되지 않은 경우 yaml 구성 'enableCorsProxy'을 불러옵니다. | boolean |
| `--disableCsrf` | CSRF 보호 비활성화 | boolean |
| `--ssl` | SSL 활성화 | boolean |
| `--certPath` | 인증서 파일 경로 | string |
| `--keyPath` | 프라이빗 키 파일 경로 | string |
| `--whitelist` | 화이트리스트 모드 활성화 | boolean |
| `--dataRoot` | 데이터 스토리지의 루트 디렉토리 | string |
| `--avoidLocalhost` | 자동 모드에서 자동 실행 시 'localhost' 사용 방지 | boolean |
| `--basicAuthMode` | 기본 인증 활성화 | boolean |
| `--requestProxyEnabled` | 외부 리퀘스트 프록시 활성화 | boolean |
| `--requestProxyUrl` | 프록시 URL 리퀘스트 (HTTP 혹은 SOCKS 프로토콜) | string |
| `--requestProxyBypass` | 프록시 바이패스 리스트 리퀘스트 (공백으로 구분된 호스트 목록) | array |
## 원격 연결
대부분의 경우 이는 PC에서 ST 서버를 실행하는 동안 모바일 장치에서 SillyTavern을 사용하려는 사람들을 위한 것입니다. 그러나 원격 연결을 다른 곳에서도 허용하도록 사용할 수 있습니다.
원격 연결 설정 방법에 대한 자세한 가이드는 [Docs](https://docs.sillytavern.app/usage/remoteconnections/)에서 확인할 수 있습니다.
또한 암호 보호 기능이 포함된 SillyTavern 사용자 프로필을 구성할 수 있습니다 (선택 사항): [Users](https://docs.sillytavern.app/installation/st-1.12.0-migration-guide/#users).
## 성능 이슈가 발생하나요?
1. 사용자 설정 패널(UI 테마 전환 카테고리)에서 흐림 효과를 비활성화하고 동작 줄이기를 활성화합니다.
2. 응답 스트리밍을 사용하는 경우 스트리밍 FPS를 더 낮은 값(10-15 FPS 권장)으로 설정합니다.
3. 브라우저에서 렌더링에 GPU 가속을 사용하도록 설정되어 있는지 확인합니다.
* **[Windows 설치 가이드](https://docs.sillytavern.app/installation/windows/)**
* **[MacOS/Linux 설치 가이드](https://docs.sillytavern.app/installation/linuxmacos/)**
* **[Android (Termux) 설치 가이드](https://docs.sillytavern.app/installation/android-(termux)/)**
* **[Docker 설치 가이드](https://docs.sillytavern.app/installation/docker/)**
## 라이센스 및 크레딧
@@ -383,6 +82,7 @@ Start.bat --port 8000 --listen false
* Font Awesome의 아이콘 테마 <https://fontawesome.com> (아이콘: CC BY 4.0, 폰트: SIL OFL 1.1, 코드: MIT 라이선스)
* 기본 콘텐츠는 @OtisAlejandro (Seraphina 캐릭터 및 로어북)와 @kallmeflocc (10K 디스코드 사용자 축전 배경화면)가 제공함
* [@mrguymiah](https://github.com/mrguymiah)와 [@Bronya-Rand](https://github.com/Bronya-Rand)의 Docker 가이드
* [@hexgrad](https://github.com/hexgrad)의 kokoro-js 라이브러리 (Apache-2.0 라이선스)
## 상위 기여자
+48 -404
View File
@@ -10,7 +10,7 @@
[English](readme.md) | [German](readme-de_de.md) | [中文](readme-zh_cn.md) | [繁體中文](readme-zh_tw.md) | [日本語](readme-ja_jp.md) | Русский | [한국어](readme-ko_kr.md)
[![GitHub Stars](https://img.shields.io/github/stars/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/stargazers)
[![GitHub Forks](https://img.shields.io/github/forks/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/network)
[![GitHub Forks](https://img.shields.io/github/forks/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/forks)
[![GitHub Issues](https://img.shields.io/github/issues/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/issues)
[![GitHub Pull Requests](https://img.shields.io/github/issues-pr/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/pulls)
@@ -18,433 +18,77 @@
---
Мобайл-френдли интерфейс, поддержка множества API (KoboldAI/CPP, Horde, NovelAI, Ooba, OpenAI, OpenRouter, Claude, Scale), ВН-образный режим Вайфу, Stable Diffusion, TTS, поддержка миров (лорбуков), кастомизируемый UI, автоперевод, тончайшая настройка промптов + возможность устанавливать расширения.
SillyTavern предоставляет единый интерфейс для многих LLM API (KoboldAI/CPP, Horde, NovelAI, Ooba, Tabby, OpenAI, OpenRouter, Claude, Mistral и других), мобайл-френдли макет, режим визуальной новеллы, интеграцию с генерацией изображений через API Automatic1111 и ComfyUI, TTS, WorldInfo (лорбуки), кастомизируемый UI, автоперевод, тончайшую настройку промптов, и возможность устанавливать расширения.
Основано на форке [TavernAI](https://github.com/TavernAI/TavernAI) версии 1.2.8
Чтобы помочь вам быстрее разобраться в SillyTavern, мы создали [сайт с документацией](https://docs.sillytavern.app/). Ответы на большинство вопросов можно найти там.
## Важные новости!
## Что такое SillyTavern?
1. Чтобы помочь вам быстрее разобраться в SillyTavern, мы создали [сайт с документацией](https://docs.sillytavern.app/). Ответы на большинство вопросов можно найти там.
SillyTavern (или сокращенно ST) - это локально устанавливаемый пользовательский интерфейс, который позволяет вам взаимодействовать с LLM для генерации текста, движками для генерации изображений и моделями голоса TTS.
2. Почему пропали расширения после апдейта? Начиная с версии 1.10.6, большинство встроенных расширений были конвертированы в формат загружаемых аддонов. Их можно установить обратно через меню "Download Extensions and Assets" на панели расширений (значок с тремя кубиками сверху).
Начавшись в феврале 2023 года как форк TavernAI 1.2.8, SillyTavern теперь насчитывает более 200 контрибьюторов и 2 года независимой разработки, и продолжает служить ведущим программным обеспечением для опытных энтузиастов ИИ.
3. Не поддерживается следующая платформа: android arm LEtime-web. 32-битный Android требует внешнюю зависимость, которую нельзя установить посредством npm. Для её установки потребуется следующая команда: `pkg install esbuild`. После этого продолжайте установку по общей инструкции.
## Наше видение
### Разрабатывается Cohee, RossAscends и всем сообществом SillyTavern
1. Мы стремимся предоставить пользователям как можно больше полезности и контроля над их промптами LLM. Крутая кривая обучения - это часть веселья!
2. Мы не предоставляем никаких онлайн или хостинговых услуг, а также программно не отслеживаем данные пользователей.
3. SillyTavern - это проект, созданный преданным сообществом энтузиастов LLM, и он всегда будет бесплатным и с открытым исходным кодом.
### Что такое SillyTavern и TavernAI?
## Нужен ли мне мощный компьютер для запуска SillyTavern?
SillyTavern — это интерфейс, который устанавливается на ПК (и на Android), который даёт возможность общаться с генеративным ИИ и чатиться/ролеплеить с вашими собственными персонажами или персонажами других пользователей.
Требования к оборудованию минимальны: он будет работать на всем, что может запустить NodeJS 18 или выше. Если вы собираетесь выполнять инференс LLM на своем локальном компьютере, мы рекомендуем видеокарту NVIDIA 3000-й серии с не менее чем 6 ГБ видеопамяти, но фактические требования могут варьироваться в зависимости от модели и используемого вами бэкенда.
SillyTavern — это форк версии TavernAI 1.2.8, который разрабатывается более активно и имеет множество новых функций. Сейчас уже можно сказать, что это две отдельные и абсолютно самостоятельные программы.
## Вопросы или предложения?
### Сервер в Discord
| [![][discord-shield-badge]][discord-link] | [Вступайте в наше Discord-сообщество!](https://discord.gg/sillytavern) Получайте поддержку, делитесь любимыми персонажами и промптами. |
| :---------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------- |
Или свяжитесь с разработчиками напрямую:
* Discord: cohee, rossascends, wolfsblvt
* Reddit: [/u/RossAscends](https://www.reddit.com/user/RossAscends/), [/u/sillylossy](https://www.reddit.com/user/sillylossy/), [u/Wolfsblvt](https://www.reddit.com/user/Wolfsblvt/)
* [Опубликовать issue на GitHub](https://github.com/SillyTavern/SillyTavern/issues)
### Мне нравится ваш проект! Как я могу внести свой вклад?
1. Отправляйте пулл-реквесты. Узнайте, как внести свой вклад: [CONTRIBUTING.md](../CONTRIBUTING.md)
2. Отправляйте предложения по функциям и отчеты о проблемах, используя предоставленные шаблоны.
3. Прочтите весь этот файл readme и сайт документации, чтобы избежать отправки дублирующихся проблем.
## Скриншоты
<img width="500" alt="image" src="https://github.com/user-attachments/assets/9b5f32f0-c3b3-4102-b3f5-0e9213c0f50f">
<img width="500" alt="image" src="https://github.com/user-attachments/assets/913fdbaa-7d33-42f1-ae2c-89dca41c53d1">
### Ветки
## Установка
SillyTavern разрабатывается в двух ветках, чтобы всем категориям пользователей было удобно.
Для получения подробных инструкций по установке, пожалуйста, посетите нашу документацию:
* release -🌟 **Рекомендовано для большинства пользователей.** Самая стабильная ветка, рекомендуем именно её. Обновляется только в момент крупных релизов. Подходит для большей части пользователей.
* staging - ⚠️ **Не рекомендуется для повседневного использования.** В этой ветке весь самый свежий и новый функционал, но будьте аккуратны, поскольку сломаться может в любом месте и в любое время. Только для продвинутых пользователей и энтузиастов.
* **[Руководство по установке для Windows](https://docs.sillytavern.app/installation/windows/)**
* **[Руководство по установке для MacOS/Linux](https://docs.sillytavern.app/installation/linuxmacos/)**
* **[Руководство по установке для Android (Termux)](https://docs.sillytavern.app/installation/android-(termux)/)**
* **[Руководство по установке Docker](https://docs.sillytavern.app/installation/docker/)**
Если вы не умеете обращаться с git через командную строку, или не знаете, что такое ветка, то не переживайте! Наилучшим вариантом всегда остаётся ветка release.
## Лицензия и благодарности
### Что ещё нужно, кроме SillyTavern?
**Эта программа распространяется в надежде, что она будет полезна, но БЕЗ КАКИХ-ЛИБО ГАРАНТИЙ; даже без подразумеваемой гарантии ТОВАРНОЙ ПРИГОДНОСТИ или ПРИГОДНОСТИ ДЛЯ ОПРЕДЕЛЕННОЙ ЦЕЛИ. Смотрите GNU Affero General Public License для получения более подробной информации.**
Сама по себе SillyTavern бесполезна, ведь это просто интерфейс. Вам потребуется доступ к бэкенду с ИИ, который и будет отыгрывать выбранного вами персонажа. Поддерживаются разные виды бэкендов: OpenAPI API (GPT), KoboldAI (локально или на Google Colab), и многое другое. Больше информации в [FAQ](https://docs.sillytavern.app/usage/faq/).
* [TavernAI](https://github.com/TavernAI/TavernAI) 1.2.8 от Humi: лицензия MIT
* Части мода CncAnon TavernAITurbo используются с разрешения
* Режим визуальной новеллы вдохновлен работой PepperTaco (<https://github.com/peppertaco/Tavern/>)
* Шрифт Noto Sans от Google (лицензия OFL)
* Тема иконок от Font Awesome <https://fontawesome.com> (Иконки: CC BY 4.0, Шрифты: SIL OFL 1.1, Код: лицензия MIT)
* Стандартный контент от @OtisAlejandro (персонаж Seraphina и лорбук) и @kallmeflocc (фон в честь 10 тысяч пользователей Discord)
* Руководство по Docker от [@mrguymiah](https://github.com/mrguymiah) и [@Bronya-Rand](https://github.com/Bronya-Rand)
* Библиотека kokoro-js от [@hexgrad](https://github.com/hexgrad) (лицензия Apache-2.0)
### Требуется ли для SillyTavern мощный ПК?
## Ведущие контрибьюторы
SillyTavern — это просто интерфейс, поэтому запустить его можно на любой картошке. Мощным должен быть бэкенд с ИИ.
## Есть вопросы или предложения?
### У нас появился сервер в Discord
| [![][discord-shield-badge]][discord-link] | [Вступайте в наше Discord-сообщество!](https://discord.gg/sillytavern) Задавайте вопросы, делитесь любимыми персонажами и промптами. |
| :---------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------- |
Также можно написать разработчикам напрямую:
* Discord: cohee или rossascends
* Reddit: [/u/RossAscends](https://www.reddit.com/user/RossAscends/) или [/u/sillylossy](https://www.reddit.com/user/sillylossy/)
* [Запостить issue на GitHub](https://github.com/SillyTavern/SillyTavern/issues)
## Эта версия включает
* Глубоко переработанную TavernAI 1.2.8 (переписано и оптимизировано более 50% кода)
* Свайпы
* Групповые чаты: комнаты для нескольких ботов, где персонажи могут говорить друг с другом и с вами
* Чекпоинты и ветки для чатов
* Продвинутые настройки для KoboldAI / TextGen со множеством созданных сообществом пресетов
* Поддержка миров (функция "Информация о мире" / WorldInfo): создавайте свой богатый лор, или экономьте токены для карточек персонажей
* Соединение через [OpenRouter](https://openrouter.ai) для разных API (Claude, GPT-4/3.5 и других)
* Соединение с API [Oobabooga's TextGen WebUI](https://github.com/oobabooga/text-generation-webui)
* Соединение с [AI Horde](https://aihorde.net/)
* Настройку форматирования промптов
## Расширения
SillyTavern поддерживает расширения.
* Эмоции для персонажей (спрайты)
* Автоматический саммарайз (краткий пересказ) истории чата
* Возможность отправить в чат картинку, которую ИИ сможет рассмотреть и понять
* Генерация картинок в Stable Diffusion (5 пресетов для чата, плюс свободный режим)
* Text-to-speech для сообщений ИИ (с помощью ElevenLabs, Silero, или родной TTS вашей ОС)
Полный список расширений и инструкций к ним можно найти в [документации](https://docs.sillytavern.app/).
## Улучшения от RossAscends для UI/CSS/общего удобства
* Мобильный интерфейс адаптирован для iOS, добавлена возможность сохранить ярлык на главный экран и открыть приложение в полноэкранном режиме.
* Горячие клавиши
* Up = Редактировать последнее сообщение в чате
* Ctrl+Up = Редактировать ВАШЕ последнее сообщение в чате
* Left = свайп влево
* Right = свайп вправо (ОБРАТИТЕ ВНИМАНИЕ: когда в окне ввода что-то напечатано, клавиши для свайпа не работают)
* Ctrl+Left = посмотреть локальные переменные (в консоли браузера)
* Enter (при нахождении внутри окна ввода) = отправить ваше сообщение ИИ
* Ctrl+Enter = Повторная генерация последнего ответа ИИ
* Страница больше не перезагружается при смене имени пользователя или удалении персонажа
* Отключаемая возможность автоматически соединяться с API при загрузке страницы.
* Отключаемая возможность автоматически загружать последнего открытого персонажа при загрузке страницы.
* Улучшенный счётчик токенов - работает с несохранёнными персонажами, отображает и перманентные, и временные токены
* Улучшенный менеджер чатов
* Файлы с новыми чатами получают читабельные названия вида "(персонаж) - (когда создано)"
* Увеличен размер превью чата с 40 символов до 300.
* Несколько вариантов сортировки списка персонажей (по имени, дате создания, размеру чата).
* Панели настроек слева и справа автоматически скрываются, если щёлкнуть за их пределы.
* При нажатии на значок замка навигационная панель будет закреплена на экране, и эта настройка сохранится между сессиями
* Сам статус панели (открыта или закрыта) также сохраняется между сессиями
* Кастомизируемый интерфейс чата:
* Настройте звук при получении нового ответа
* Переключайтесь между круглыми и прямоугольными аватарками
* Увеличенное вширь окно чата для стационарных ПК
* Возможность включать полупрозрачные панели, стилизованные под стекло
* Настраиваемые цвета для обычного текста, курсива, цитат
* Настраиваемый цвет фона и интенсивность размытия
# ⌛ Установка
> **Внимание!**
> * НЕ УСТАНАВЛИВАЙТЕ В ПАПКИ, КОТОРЫЕ КОНТРОЛИРУЕТ WINDOWS (Program Files, System32 и т.п.).
> * НЕ ЗАПУСКАЙТЕ START.BAT С ПРАВАМИ АДМИНИСТРАТОРА
> * УСТАНОВКА НА WINDOWS 7 НЕВОЗМОЖНА ИЗ-ЗА ОТСУТСТВИЯ NODEJS 18.16
## 🪟 Windows
## Установка через Git
1. Установите [NodeJS](https://nodejs.org/en) (рекомендуется последняя LTS-версия)
2. Установите [Git for Windows](https://gitforwindows.org/)
3. Откройте Проводник (`Win+E`)
4. Перейдите в папку, которую не контролирует Windows, или создайте её. (пример: C:\MySpecialFolder\)
5. Откройте командную строку. Для этого нажмите на адресную строку (сверху), введите `cmd` и нажмите Enter.
6. Когда появится чёрное окошко (командная строка), введите ОДНУ из перечисленных ниже команд:
- для ветки release: `git clone https://github.com/SillyTavern/SillyTavern -b release`
- для ветки staging: `git clone https://github.com/SillyTavern/SillyTavern -b staging`
7. Когда клонирование закончится, дважды щёлкните по `Start.bat`, чтобы установить зависимости для NodeJS.
8. После этого сервер запустится, и SillyTavern откроется в вашем браузере.
## Установка с помощью SillyTavern Launcher
1. Установите [Git for Windows](https://gitforwindows.org/)
2. Откройте Проводник (`Win+E`) и создайте или выберите папку, в которую будет установлен лаунчер
3. Откройте командную строку. Для этого нажмите на адресную строку (сверху), введите `cmd` и нажмите Enter.
4. Когда появится чёрное окошко, введите следующую команду: `git clone https://github.com/SillyTavern/SillyTavern-Launcher.git`
5. Дважды щёлкните по `installer.bat` и выберите, что именно хотите установить
6. После завершения установки дважды щёлкните по `launcher.bat`
## Установка с помощью GitHub Desktop
(Тут речь про git **только** в рамках GitHub Desktop, если хотите использовать `git` в командной строке, вам также понадобится [Git for Windows](https://gitforwindows.org/))
1. Установите [NodeJS](https://nodejs.org/en) (latest LTS version is recommended)
2. Установите [GitHub Desktop](https://central.github.com/deployments/desktop/desktop/latest/win32)
3. После завершения установки GitHub Desktop, нажмите `Clone a repository from the internet....` (обратите внимание: для этого шага **НЕ требуется** аккаунт на GitHub)
4. В меню перейдите на вкладку URL, введите адрес `https://github.com/SillyTavern/SillyTavern`, и нажмите Clone. В поле Local path можно изменить директорию, в которую будет загружена SillyTavern.
6. Чтобы запустить SillyTavern, откройте Проводник и перейдите в выбранную на предыдущем шаге папку. По умолчанию репозиторий будет склонирован сюда: `C:\Users\[Имя пользователя]\Documents\GitHub\SillyTavern`
7. Дважды щёлкните по файлу `start.bat`. (обратите внимание: окончание `.bat` может быть скрыто настройками вашей ОС. Таким образом, имя файла будет выглядеть как "`Start`". Дважды щёлкните по нему, чтобы запустить SillyTavern)
8. После того, как вы дважды щёлкнули по файлу, должно открыться чёрное окошко, и SillyTavern начнёт устанавливать свои зависимости.
9. Если установка прошла успешно, то в командной строке будет вот такое, а в браузере откроется вкладка с SillyTavern:
10. Подключайтесь к любому из [поддерживаемых API](https://docs.sillytavern.app/usage/api-connections/) и начинайте переписку!
## 🐧 Linux и 🍎 MacOS
В MacOS и Linux всё это делается через Терминал.
1. Установите git и nodeJS (как именно - зависит от вашей ОС)
2. Клонируйте репозиторий
- для ветки release: `git clone https://github.com/SillyTavern/SillyTavern -b release`
- для ветки staging: `git clone https://github.com/SillyTavern/SillyTavern -b staging`
3. Перейдите в папку установки с помощью `cd SillyTavern`.
4. Запустите скрипт `start.sh` с помощью одной из команд:
- `./start.sh`
- `bash start.sh`
## Установка с помощью SillyTavern Launcher
### Для пользователей Linux
1. Откройте любимый терминал и установите git
2. Загрузите Sillytavern Launcher с помощью команды: `git clone https://github.com/SillyTavern/SillyTavern-Launcher.git`
3. Перейдите в SillyTavern-Launcher: `cd SillyTavern-Launcher`
4. Запустите лаунчер установки: `chmod +x install.sh && ./install.sh`, затем выберите, что конкретно хотите установить
5. После завершения установки, запустите лаунчер следующей командой: `chmod +x launcher.sh && ./launcher.sh`
### Для пользователей Mac
1. Откройте терминал и установите brew: `/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"`
2. Затем установите git: `brew install git`
3. Загрузите Sillytavern Launcher: `git clone https://github.com/SillyTavern/SillyTavern-Launcher.git`
4. Перейдите в SillyTavern-Launcher: `cd SillyTavern-Launcher`
5. Запустите лаунчер установки: `chmod +x install.sh && ./install.sh` and choose what you wanna install
6. После завершения установки, запустите лаунчер следующей командой: `chmod +x launcher.sh && ./launcher.sh`
## 🐋 Установка с помощью Docker
Предполагается, что вы уже установили Docker, имеете доступ к командной строке для установки контейнеров и знакомы с их базовым управлением.
### Сборка образа самостоятельно
У нас есть подробное руководство по использованию SillyTavern в Docker [здесь](http://docs.sillytavern.app/installation/docker/), которое охватывает установку на Windows, macOS и Linux! Ознакомьтесь с ним, если хотите создать образ самостоятельно.
### Использование реестра контейнеров GitHub (самый простой способ)
Для работы SillyTavern вам понадобятся две обязательные настройки каталогов и одна настройка порта. В команде замените указанные значения на свои:
#### Переменные контейнера
##### Маппинг томов
* [config] - директория, где на вашем хосте будут храниться файлы конфигурации SillyTavern.
* [data] - директория, где на вашем хосте будут храниться пользовательские данные SillyTavern (включая персонажей).
* [plugins] - (необязательно) директория, где на вашем хосте будут храниться плагины сервера SillyTavern.
##### Маппинг портов
* [PublicPort] - Порт, через который будет передаваться трафик. Это обязательно, так как вы будете обращаться к контейнеру извне его виртуальной машины. НЕ ОТКРЫВАЙТЕ этот порт в интернет без реализации дополнительного уровня безопасности.
##### Дополнительные настройки
* [DockerNet] - Docker сеть, к которой контейнер должен быть подключен. Если вы не знаете, что это, обратитесь к [официальной документации Docker](https://docs.docker.com/reference/cli/docker/network/).
* [version] - на правой части этой страницы GitHub вы найдете раздел "Packages". Выберите пакет "sillytavern", чтобы увидеть версии образов. Тег "latest" позволит вам обновляться до текущего релиза. Также доступны теги "staging" и "release", которые соответствуют ночным сборкам соответствующих веток. Однако это может быть нецелесообразно, если вы используете расширения, которые могут ломаться и требуют времени для обновления.
#### Команда установки
1. Откройте командную строку
2. Выполните следующую команду
`docker create --name='sillytavern' --net='[DockerNet]' -p '8000:8000/tcp' -v '[plugins]':'/home/node/app/plugins':'rw' -v '[config]':'/home/node/app/config':'rw' -v '[data]':'/home/node/app/data':'rw' 'ghcr.io/sillytavern/sillytavern:[version]'`
> Заметьте, что 8000 является портом по умолчанию. Не забудьте использовать соответствующий порт, если вы измените его в конфиге.
## 📱 Мобильные устройства - Установка при помощи termux
> **ОБРАТИТЕ ВНИМАНИЕ!**
>
> **На Android-телефонах SillyTavern можно запускать нативно посредством Termux. Обратитесь к гайду, написанному ArroganceComplex#2659:**
>
> * <https://rentry.org/STAI-Termux>
## Управление ключами от API
SillyTavern сохраняет ключи от ваших API в файле `secrets.json` в папке на сервере.
По умолчанию, ключи не будут отображаться на фронте после их ввода и перезагрузки страницы.
Чтобы включить возможность отображения ключей путём нажатия кнопки в блоке API:
1. Зайдите в файл `config.yaml` и установите `allowKeysExposure` в положение `true`.
2. Перезапустите сервер SillyTavern.
## Аргументы командной строки
Вы можете передавать аргументы командной строки при запуске сервера SillyTavern, чтобы переопределять настройки из `config.yaml`.
### Примеры
```shell
node server.js --port 8000 --listen false
# или
npm run start -- --port 8000 --listen false
# или (только на Windows)
Start.bat --port 8000 --listen false
```
### Поддерживаемые аргументы
| Аргумент | Описание | Тип |
|-------------------------|----------------------------------------------------------------------------------------------------------------|----------|
| `--version` | Показывает номер версии. | boolean |
| `--enableIPv6` | Включает IPv6. | boolean |
| `--enableIPv4` | Включает IPv4. | boolean |
| `--port` | Устанавливает порт, котрый будет использовать SillyTavern. Если не указан, то используется yaml-конфиг 'port'. | number |
| `--dnsPreferIPv6` | Отдает предпочтение IPv6 для dns. Если не указан, то используется yaml-конфиг 'preferIPv6'. | boolean |
| `--autorun` | Автоматический запуск SillyTavern в браузере. Если не указан, то используется yaml-конфиг 'autorun'. | boolean |
| `--autorunHostname` | Имя хоста автозапуска, лучше оставить на 'auto'. | string |
| `--autorunPortOverride` | Переопределяет порт для автозапуска. | string |
| `--listen` | SillyTavern будет прослушивать все сетевые интерфейсы. Если не указан, то используется yaml-конфиг 'listen'. | boolean |
| `--corsProxy` | Включает CORS-прокси. Если не указан, то используется yaml-конфиг 'enableCorsProxy'. | boolean |
| `--disableCsrf` | Отключает защиту от CSRF. | boolean |
| `--ssl` | Включает SSL. | boolean |
| `--certPath` | Путь к файлу c сертификатом. | string |
| `--keyPath` | Путь к файлу с закрытым ключом. | string |
| `--whitelist` | Включает режим белого списка. | boolean |
| `--dataRoot` | Корневой каталог для хранения данных. | string |
| `--avoidLocalhost` | Избегает использования 'localhost' для автозапуска в режиме 'auto'. | boolean |
| `--basicAuthMode` | Включает простую аутентификацию. | boolean |
| `--requestProxyEnabled` | Разрешает использование прокси для исходящих запросов. | boolean |
| `--requestProxyUrl` | URL-адрес прокси (протоколы HTTP или SOCKS). | string |
| `--requestProxyBypass` | Bypass список прокси (список хостов, разделенных пробелами). | array |
## Удалённое подключение
В основном этим пользуются тогда, когда хотят использовать SillyTavern с телефона, запустив сервер SillyTavern на стационарном ПК в той же Wi-Fi-сети.
Однако это позволит подключаться откуда угодно, а не только вам.
**ВАЖНО: в SillyTavern не предусмотрена возможность использования программы несколькими людьми. Поэтому любой, кто подключится к вашему серверу, получит доступ ко всем вашим персонажам и чатам, а также сможет менять настройки через UI.**
### 1. Заведение "белого списка" IP-адресов
* Создайте в корневой папке SillyTavern файл с названием `whitelist.txt`.
* Откройте файл в текстовом редакторе и внесите список IP-адресов, с которых хотите разрешить подключение.
*Принимаются как обычные IP-адреса, так и целые диапазоны, размеченные с помощью астериска. Примеры:*
```txt
192.168.0.1
192.168.0.20
```
или
```txt
192.168.0.*
```
(диапазон из примера сверху позволит подключаться всем устройствам в локальной сети)
Также принимаются маски CIDR (вида 10.0.0.0/24).
* Сохраните файл `whitelist.txt`.
* Перезапустите сервер ST.
После этого устройства из белого списка смогут подключаться к вашему серверу.
*Обратите внимание: в файле `config.yaml` также имеется массив `whitelist`, который работает по тому же принципу. Однако если существует файл `whitelist.txt`, то этот массив игнорируется.*
### 2. Получение IP хост-машины с ST
После настройки белого списка адресов, следующим шагом будет получение IP-адреса хост-машины, на которой запущена SillyTavern.
Если хост-машина находится в той же Wi-Fi-сети, то можно воспользоваться её внутренним Wi-Fi-IP-адресом:
* На Windows: нажмите Пуск > введите `cmd.exe` в поиске > в консоли введите команду `ipconfig` и нажмите Enter > найдите пункт `IPv4-адрес`.
Если вы (или кто-то другой) хотите подключаться к хост-машине из другой сети, то вам понадобится ваш публичный IP-адрес.
* Откройте [эту страницу](https://whatismyipaddress.com/) с вашей хост-машины и найдите пункт `IPv4`. На этот адрес и будет подключаться удалённое устройство.
### 3. Соединить удалённое устройство с хост-машиной ST
Какой бы IP-адрес вы ни выбрали, вам нужно будет вводить его в адресной строке браузера вашего удалённого устройства.
Обычный адрес хост-машины, находящейся в той же Wi-Fi-сети, выглядит примерно так:
`http://192.168.0.5:8000`
НЕ используйте https://
Только http://
### Открытие доступа до ST для всех IP-адресов
Мы не рекомендуем так делать, но вы можете открыть файл `config.yaml` и изменить `whitelistMode` на `false`.
Обязательно нужно удалить (или переименовать) файл `whitelist.txt`, если такой файл есть в корневой директории SillyTavern.
Эта практика считается небезопасной, поэтому, если вы решите так сделать, мы попросим вас установить логин и пароль.
Оба этих параметра настраиваются в `config.yaml` (username и password).
Останется только перезапустить сервер ST, и после этого к вам сможет подключиться любой пользователь вне зависимости от IP-адреса его устройства. Главное, чтобы он знал логин и пароль.
### Не получается соединиться?
* Создайте входящее/исходящее правило в вашем фаерволле для порта, указанного в `config.yaml`. НЕ ПУТАЙТЕ этот процесс с пробросом портов на роутере. Если по ошибке перепутаете, то на ваш сервер сможет забраться посторонний человек и украсть ваши логи, этого следует избегать.
* Переключите Сетевой профиль на значение "Частные". Для этого зайдите в Параметры > Сеть и Интернет > Ethernet. КРАЙНЕ важно для Windows 11, без этого не получится подключиться даже с правилом фаервола.
## Проблемы с производительностью?
Попробуйте включить опцию "Отключить эффект размытия" в меню "Пользовательские настройки".
## Нравится ваш проект! Как помочь?
### ЧТО ДЕЛАТЬ
1. Присылайте пулл реквесты
2. Присылайте идеи и баг-репорты, оформленные по установленным шаблонам
3. Прежде чем задавать вопросы, прочтите readme и документацию
### ЧЕГО НЕ ДЕЛАТЬ
1. Предлагать донаты
2. Присылать баг-репорты безо всякого контекста
3. Задавать вопросы, на которые уже отвечали
## Где найти старые фоны?
Мы двигаемся в сторону 100% уникальности всего используемого контента, поэтому старые фоны были убраны из репозитория.
Они отправлены в архив, скачать их можно здесь:
<https://files.catbox.moe/1xevnc.zip>
## Авторы и лицензии
**Мы надеемся, что эта программа принесёт людям пользу,
но мы не даём НИКАКИХ ГАРАНТИЙ; мы ни в коем случае не гарантируем того,
что программа СООТВЕТСТВУЕТ КАКИМ-ЛИБО КРИТЕРИЯМ или ПРИГОДНА ДЛЯ КАКОЙ-ЛИБО ЦЕЛИ.
Подробнее можно узнать в GNU Affero General Public License.**
* Базовая TAI от Humi: Лицензия неизвестна
* Модификации от Cohee и производная кодовая база: AGPL v3
* Дополнения RossAscends: AGPL v3
* Кусочки TavernAITurbo мода от CncAnon: Лицензия неизвестна
* Различные коммиты и предложения от kingbri (<https://github.com/bdashore3>)
* Расширения и внедрение разного рода удобств - city_unit (<https://github.com/city-unit>)
* Различные коммиты и баг-репорты от StefanDanielSchwarz (<https://github.com/StefanDanielSchwarz>)
* Режим Вайфу вдохновлён работой PepperTaco (<https://github.com/peppertaco/Tavern/>)
* Благодарность Pygmalion University за прекрасную работу по тестированию и за все предлагаемые крутые фичи!
* Благодарность oobabooga за компиляцию пресетов для TextGen
* Пресеты для KoboldAI из KAI Lite: <https://lite.koboldai.net/>
* Шрифт Noto Sans от Google (OFL license)
* Тема Font Awesome <https://fontawesome.com> (Иконки: CC BY 4.0, Шрифты: SIL OFL 1.1, Код: MIT License)
* Клиентская библиотека для AI Horde от ZeldaFan0225: <https://github.com/ZeldaFan0225/ai_horde>
* Пусковой скрипт для Linux от AlpinDale
* Благодарность paniphons за оформление документа с FAQ
* Фон в честь 10 тысяч пользователей в Discord от @kallmeflocc
* Стандартный контент (персонажи и лорбуки) предоставлен пользователями @OtisAlejandro, @RossAscends и @kallmeflocc
* Корейский перевод от @doloroushyeonse
* Поддержка k_euler_a для Horde от <https://github.com/Teashrock>
* Китайский перевод от [@XXpE3](https://github.com/XXpE3), 中文 ISSUES 可以联系 @XXpE3
[![Contributors](https://contrib.rocks/image?repo=SillyTavern/SillyTavern)](https://github.com/SillyTavern/SillyTavern/graphs/contributors)
<!-- LINK GROUP -->
[back-to-top]: https://img.shields.io/badge/-BACK_TO_TOP-151515?style=flat-square
[cover]: https://github.com/user-attachments/assets/01a6ae9a-16aa-45f2-8bff-32b5dc587e44
[discord-link]: https://discord.gg/sillytavern
[discord-shield]: https://img.shields.io/discord/1100685673633153084?color=5865F2&label=discord&labelColor=black&logo=discord&logoColor=white&style=flat-square
[discord-shield-badge]: https://img.shields.io/discord/1100685673633153084?color=5865F2&label=discord&labelColor=black&logo=discord&logoColor=white&style=for-the-badge
+49 -277
View File
@@ -1,6 +1,8 @@
> [!IMPORTANT]
> 这里的信息可能已经过时或不完整,仅供您参考。请使用英文版本获取最新信息。
<a name="readme-top"></a>
![][cover]
<div align="center">
@@ -8,7 +10,7 @@
[English](readme.md) | [German](readme-de_de.md) | 中文 | [繁體中文](readme-zh_tw.md) | [日本語](readme-ja_jp.md) | [Русский](readme-ru_ru.md) | [한국어](readme-ko_kr.md)
[![GitHub Stars](https://img.shields.io/github/stars/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/stargazers)
[![GitHub Forks](https://img.shields.io/github/forks/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/network)
[![GitHub Forks](https://img.shields.io/github/forks/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/forks)
[![GitHub Issues](https://img.shields.io/github/issues/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/issues)
[![GitHub Pull Requests](https://img.shields.io/github/issues-pr/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/pulls)
@@ -16,307 +18,77 @@
---
移动设备界面友好,多种人工智能服务或模型支持(KoboldAI/CPP, Horde, NovelAI, Ooba, OpenAI, OpenRouter, Claude, Scale),类似 Galgame 的 老 婆 模 式,Horde SD,文本系统语音生成,世界信息(Lorebooks),可定制的界面,自动翻译,和比你所需要的更多的 Prompt。附带扩展服务,支持文本绘画生成与语音生成和基于向量数据库 的聊天信息总结。
SillyTavern 为众多 LLM API(KoboldAI/CPP、Horde、NovelAI、Ooba、Tabby、OpenAI、OpenRouter、Claude、Mistral 等)提供统一界面,拥有移动设备友好的布局、视觉小说模式、Automatic1111 & ComfyUI API 图像生成集成、TTS、世界书(lorebooks)、可自定义的 UI、自动翻译、超乎您想象的丰富 Prompt 选项,以及通过第三方扩展实现的无限增长潜力。
基于 TavernAI 1.2.8 的分叉版本
我们有一个[文档网站](https://docs.sillytavern.app/)来回答您的大部分问题并帮助您入门。
### 由 Cohee、RossAscends 和 SillyTavern 社区为您呈现
## SillyTavern 是什么?
注意:我们创建了一个 [帮助文档](https://docs.sillytavern.app/) 网站来回答各类问题与帮助您开始使用。
SillyTavern(简称 ST)是一个本地安装的用户界面,允许您与文本生成 LLM、图像生成引擎和 TTS 语音模型进行交互。
### SillyTavern 或 TavernAI 是什么?
SillyTavern 于 2023 年 2 月作为 TavernAI 1.2.8 的一个分支开始,如今已拥有超过 200 名贡献者和 2 年的独立开发经验,并继续作为资深 AI 爱好者领先的软件。
SillyTavern 是一个可以安装在电脑(和安卓手机)上的用户界面,让您可以与文本生成的人工智能互动,并与您或社区创建的角色聊天/玩角色扮演游戏。
## 我们的愿景
SillyTavern 是 TavernAI 1.2.8 的一个分支,正在进行更积极地开发,并添加了许多重要功能。在这一点上,它可以被视为完全独立的程序。
1. 我们的目标是尽可能为用户提供 LLM Prompt 的最大效用和控制权。陡峭的学习曲线是乐趣的一部分!
2. 我们不提供任何在线或托管服务,也不会以编程方式跟踪任何用户数据。
3. SillyTavern 是一个由专注的 LLM 爱好者社区为您带来的充满激情的项目,并且将永远是免费和开源的。
### 分支
## 我需要一台性能强大的电脑来运行 SillyTavern 吗?
SillyTavern 采用双分支进行开发,以确保所有用户都能获得流畅的使用体验。
* release -🌟 **推荐给大多数用户。** 这是最稳定、最推荐的分支,只有在重大版本推送时才会更新。适合大多数用户使用。
* staging - ⚠️ **不建议随意使用。** 该分支拥有最新功能,但要谨慎,因为它随时可能崩溃。仅适用于高级用户和爱好者。
如果你不熟悉使用 Git 命令,或者不了解什么是分支,别担心!release 分支始终是您的首选。
### 除了 SillyTavern,我还需要什么?
SillyTavern 本身并无用处,因为它只是一个用户聊天界面。你必须接入一个能充当角色扮演的人工智能系统。支持的人工智能系统有多种:OpenAPI API (GPT)、KoboldAI(可在本地或 Google Colab 上运行)等。您可以在 [常见问题](https://docs.sillytavern.app/usage/faq/) 中阅读更多相关信息。
### 我需要一台性能强大的电脑来运行 SillyTavern 吗?
由于 SillyTavern 只是一个用户聊天界面,它对硬件性能的要求很低,可以在任何电脑上运行。需要强大性能的是人工智能系统。
### 移动设备支持
> 注意
> **此分叉可使用 Termux 在安卓手机上原生运行。请参考 ArroganceComplex#2659 编写的指南:**
<https://rentry.org/STAI-Termux>
硬件要求很低:任何可以运行 NodeJS 18 或更高版本的设备都可以运行它。如果您打算在本地计算机上进行 LLM 推理,我们建议使用至少具有 6GB VRAM 的 3000 系列 NVIDIA 显卡,但实际要求可能会根据模型和您使用的后端而有所不同。
## 有问题或建议?
### 我们现在有了 Discord 社区
### Discord 服务器
获取支持,或分享喜爱的角色和 Prompt:
| [![][discord-shield-badge]][discord-link] | [加入我们的 Discord 社区!](https://discord.gg/sillytavern) 获取支持,分享喜爱的角色和 Prompt。 |
| :---------------------------------------- | :---------------------------------------------------------------------------------------------- |
### [加入 Discord 社区](https://discord.gg/sillytavern)
或者直接与开发人员联系:
***
* Discord: cohee, rossascends, wolfsblvt
* Reddit: [/u/RossAscends](https://www.reddit.com/user/RossAscends/), [/u/sillylossy](https://www.reddit.com/user/sillylossy/), [u/Wolfsblvt](https://www.reddit.com/user/Wolfsblvt/)
* [提交 GitHub 问题](https://github.com/SillyTavern/SillyTavern/issues)
直接与开发人员联系:
### 我喜欢你的项目!我该如何贡献自己的力量?
* Discord: cohee 或 rossascends
* Reddit:/u/RossAscends 或 /u/sillylossy
* [发布 GitHub 问题](https://github.com/SillyTavern/SillyTavern/issues)
## 此版本包括
* 经过大量修改的 TavernAI 1.2.8(超过 50% 的代码经过重写或优化)
* 根据自定义规则自动重新生成消息
* 群聊:多机器人房间,供角色与你或彼此交谈
* 聊天书签/分支(复制当前状态下的对话)
* 先进的 KoboldAI / TextGen 生成设置,包含大量社区预设
* 支持世界信息(Lorebooks):创建丰富的传说
* 支持 Window AI 浏览器扩展(运行 Claude、GPT 4 等模型):<https://windowai.io/>
* [Oobabooga's TextGen WebUI](https://github.com/oobabooga/text-generation-webui) API 连接
* 连接 [AI Horde](https://aihorde.net/)
* Prompt 生成格式调整
* Webp 角色卡支持(PNG 仍是内部格式)
## 扩展
SillyTavern 支持扩展服务。
* 角色情绪识别
* 聊天记录自动摘要
* 在聊天窗口发送图片,并由人工智能解释图片内容
* 文本图像生成(5 预设,以及 "自由模式")
* 聊天信息的文字转语音(通过 ElevenLabs、Silero 或操作系统的语音生成)
扩展服务的完整功能介绍和使用教程,请参阅 [Docs](https://docs.sillytavern.app/)。
## 界面/CSS/性能,由 RossAscends 调整并优化
* 针对 iOS 系统优化了界面,并支持将快捷方式保存到主屏幕,在全屏模式下打开。
* 热键
* 上 = 编辑聊天中的最后一条信息
* Ctrl+P = 编辑聊天中最后一条用户信息
* 左 = 向左滑动
* 右 = 向右滑动(注意:当聊天窗口输入内容时,轻扫快捷键将被禁用)
* Ctrl+左 = 查看本地存储的变量(在浏览器控制台窗口中)
* 回车(选择聊天栏)= 向人工智能发送信息
* Ctrl+Enter = 重新生成人工智能最后的回复
* 用户名更改和角色删除不再强制重新刷新页面。
* 增加在页面加载时自动连接 API 的选项。
* 增加选项,在页面加载时自动加载最近的聊天信息。
* 更好的 Tokens 计算器 - 适用于未保存的文字,并显示永久和临时 Tokens 数量
* 更好的聊天历史查询窗口
* 聊天的文件名以"(角色卡名称)+(创建时间)"的可读格式保存
* 聊天历史预览从 40 个字符增加到 300 个字符。
* 聊天历史排序有多种选择(按名称、创建日期、聊天记录大小)。
* 默认情况下,左侧和右侧弹出的设置面板会在点击其他区域时自动关闭。
* 点击导航面板上的 "锁按钮" 将保持弹出面板打开,并在不同聊天中记住此设置。
* 导航面板的打开或关闭状态也会跨聊天保存。
* 自定义聊天界面:
* 收到新消息时播放提示音
* 切换圆形或长方形头像样式
* 在台式电脑上拥有更宽的聊天窗口
* 可选的半透明玻璃效果聊天窗口
* 可定制 "主文本"、"引用文本 "和 "斜体文本 "的字体颜色。
* 可定制聊天界面的背景颜色和透明模糊程度
## 安装
*注意:SillyTavern 用于本地安装,尚未在 Colab 或其他云服务上进行全面测试。
> **警告**
> 切勿安装到任何受 Windows 控制的系统文件夹(Program Files, System32, etc)中。
> 不要以管理员权限运行 start.bat
### Windows
通过 Git 安装(推荐使用,便于更新)
附有精美图片示例的简易指南:
<https://docs.sillytavern.app/installation/windows/>
1. 安装 [NodeJS](https://nodejs.org/en)(建议使用最新的 LTS 版本)
2. 安装 [GitHub 客户端](https://central.github.com/deployments/desktop/desktop/latest/win32)
3. 打开 Windows 资源管理器 (`Win+E`)
4. 浏览或创建一个不受 Windows 控制或监控的文件夹。(例如:C:\MySpecialFolder\)
5. 点击顶部的 "地址栏",在该文件夹内打开命令提示符,输入 `cmd`,然后按回车。
6. 弹出黑框(CMD 命令提示符)后,键入以下其中一项并按 Enter:
* 稳定分支:`git clone https://github.com/SillyTavern/SillyTavern -b release`
* 开发分支: `git clone https://github.com/SillyTavern/SillyTavern -b staging`
7. 等待 Git 克隆完成后,双击文件夹中的 `Start.bat` 将启动 NodeJS 并开始自动安装需要的软件包。
8. 然后 SillyTavern 服务就会自动启动,同时在浏览器新标签页中自动打开。
通过压缩包下载安装(不推荐)
1. 安装 [NodeJS](https://nodejs.org/en)(建议使用最新的 LTS 版本)
2. 从该 GitHub 仓库下载压缩包。(从 [Releases](https://github.com/SillyTavern/SillyTavern/releases/latest) 获取 "Source code(zip)")。
3. 将压缩包解压到您选择的文件夹中
4. 双击或在命令行中运行 `Start.bat`。
5. SillyTavern 服务自动为你准备好一切后,会在你的浏览器中打开一个新标签页。
### Linux
1.运行 `start.sh` 脚本。
2.等待自动完成,然后开始享受
## API 密钥管理
SillyTavern 会将 API 密钥保存在目录中的 `secrets.json` 文件内。
默认情况下,输入密钥并重新加载页面后,密钥会自动隐藏以保证安全。
如果要想通过点击 API 输入框旁边的按钮来查看密钥,请按照以下设置:
1. 打开 `config.yaml` 文件,将里面的 `allowKeysExposure` 设置为 `true`。
2. 然后重启 SillyTavern 服务。
## 远程访问
这通常是为那些想在手机上使用 SillyTavern 的人准备的,而他们的电脑和手机在同一个局域网中。
不过,SillyTavern 也可以被设置为允许从任何地方进行远程访问。
**重要提示:SillyTavern 是单用户程序,因此任何人登录后都能看到所有的角色卡和聊天内容,并能更改任何设置。
### 1.管理白名单 IP
* 在你的 SillyTavern 文件夹中新建一个文本文件,名为 `whitelist.txt`。
* 用文本编辑器打开该文件,添加你希望允许连接的 IP 地址列表。
* 接受单个 IP 地址和 IP 范围,示例:
```
192.168.0.1
192.168.0.20
```
或者
```
192.168.0.*
```
(上述 IP 范围将允许局域网中的任何设备连接)
也接受子网掩码设置(如 10.0.0.0/24)。
* 保存`whitelist.txt`文件。
* 重启 SillyTavern 服务。
然后,文件中设置的 IP 就可以访问 SillyTavern 了。
*注意:"config.yaml" 文件内也有一个 "whitelist" 设置,你可以用同样的方法设置它,但如果 "whitelist.txt" 文件存在,这个设置将被忽略。
### 2.获取 SillyTavern 服务的 IP 地址
白名单设置完成后,您需要 SillyTavern 服务的 IP 地址。
如果 SillyTavern 服务设备在同一个局域网上,则使用安装 SillyTavern 服务的电脑的局域网 IP 地址:
* Windows:Windows 按钮 > 在搜索栏中输入 `cmd.exe` > 在打开的控制台中输入 `ipconfig`,回车 > 然后在输出中查找 `IPv4` 地址。
如果您(或其他人)想在互联网中访问你自己的 SillyTavern 服务,则需要运行 SillyTavern 服务的设备的互联网 IP 地址。
* 使用运行 SillyTavern 的设备,访问 [this page](https://whatismyipaddress.com/) 并查找 `IPv4`。这是您从互联网访问时要用到的。
### 3. 使用其他设备访问 SillyTavern 服务
无论你最终使用的是什么 IP 地址,都要将该 IP 地址和端口号输入其他设备网络浏览器。
同一局域网中的 SillyTavern 服务的典型默认地址如下:
`http://192.168.0.5:8000`
使用 http:// 而不是 https://
### 向所有 IP 开放您的 SillyTavern 服务
我们不建议这样做,但您可以打开 `config.yaml` 并将里面的 `whitelistMode` 设置改为 `false`。
你必须删除(或重命名)SillyTavern 文件夹中的 `whitelist.txt` 文件(如果有的话)。
这通常是不安全的做法,所以我们要求在这样做时必须设置用户名和密码。
用户名和密码在`config.yaml`文件中设置。
重启 SillyTavern 服务后,只要知道用户名和密码,任何设备都可以访问。
### 还是无法访问?
* 为 `config.yaml` 文件中的端口创建一条入站/出站防火墙规则。切勿将此误认为是路由器上的端口转发,否则,有人可能会发现你的聊天隐私,那就大错特错了。
* 在 "设置" > "网络和 Internet" > "以太网" 中启用 "专用网络" 配置。这对 Windows 11 非常重要,否则即使添加了上述防火墙规则也无法连接。
### 性能问题?
尝试在用户设置面板上关闭模糊效果(快速用户界面)模式。
## 我喜欢你的项目!我该如何贡献自己的力量?
### 应该
1. 发送 Fork 请求
2. 使用规定的模板发送功能建议和问题报告
3. 在提出任何问题之前,请先阅读 Readme 文件和文档
#### 不应该
1. 提供金钱捐赠
2. 发送错误报告而不提供任何详细信息
3. 提出已经回答过无数次的问题
## 我在哪里可以找到以前的聊天背景图片?
我们正在实行 100% 原创内容的政策,因此旧的背景图片已从该资源库中删除。
不过你可以在这里找到它们的存档:
<https://files.catbox.moe/1xevnc.zip>
1. 发送 Pull Request。学习如何贡献:[CONTRIBUTING.md](../CONTRIBUTING.md)
2. 使用提供的模板发送功能建议和问题报告。
3. 请先阅读整个 readme 文件并查看文档网站,以避免提交重复的问题。
## 屏幕截图
<img width="500" alt="image" src="https://github.com/user-attachments/assets/9b5f32f0-c3b3-4102-b3f5-0e9213c0f50f">
<img width="500" alt="image" src="https://github.com/user-attachments/assets/913fdbaa-7d33-42f1-ae2c-89dca41c53d1">
## 许可证和贡献
## 安装
**发布本程序是希望它能有所帮助,但不做任何保证;甚至没有明示的性能、稳定性和其他任何特定用途的可用性保证。更多详情,请参阅 GNU Affero 通用公共许可证。**
有关详细的安装说明,请访问我们的文档:
**This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.**
* **[Windows 安装指南](https://docs.sillytavern.app/installation/windows/)**
* **[MacOS/Linux 安装指南](https://docs.sillytavern.app/installation/linuxmacos/)**
* **[Android (Termux) 安装指南](https://docs.sillytavern.app/installation/android-(termux)/)**
* **[Docker 安装指南](https://docs.sillytavern.app/installation/docker/)**
* TAI Base by Humi: Unknown license
* Cohee's modifications and derived code: AGPL v3
* RossAscends' additions: AGPL v3
* Portions of CncAnon's TavernAITurbo mod: Unknown license
* kingbri's various commits and suggestions (<https://github.com/bdashore3>)
* StefanDanielSchwarz's various commits and bug reports (<https://github.com/StefanDanielSchwarz>)
* Waifu mode inspired by the work of PepperTaco (<https://github.com/peppertaco/Tavern/>)
* Thanks Pygmalion University for being awesome testers and suggesting cool features!
* Thanks oobabooga for compiling presets for TextGen
* KoboldAI Presets from KAI Lite: <https://lite.koboldai.net/>
* Noto Sans font by Google (OFL license)
* Icon theme by Font Awesome <https://fontawesome.com> (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
* AI Horde client library by ZeldaFan0225: <https://github.com/ZeldaFan0225/ai_horde>
* Linux startup script by AlpinDale
* Thanks paniphons for providing a FAQ document
* 10K Discord Users Celebratory Background by @kallmeflocc
* Default content (characters and lore books) provided by @OtisAlejandro, @RossAscends and @kallmeflocc
* Korean translation by @doloroushyeonse
* 中文翻译由 [@XXpE3](https://github.com/XXpE3) 完成,中文 ISSUES 可以联系 @XXpE3
## 许可证和致谢
**本程序的分发是希望它能有用,但不提供任何保证;甚至没有对适销性或特定用途适用性的默示保证。有关更多详细信息,请参阅 GNU Affero 通用公共许可证。**
* [TavernAI](https://github.com/TavernAI/TavernAI) 1.2.8 by Humi: MIT 许可证
* CncAnon 的 TavernAITurbo mod 的部分内容经许可使用
* 视觉小说模式的灵感来自 PepperTaco 的工作 (<https://github.com/peppertaco/Tavern/>)
* Noto Sans 字体 by Google (OFL 许可证)
* 图标主题 by Font Awesome <https://fontawesome.com> (图标: CC BY 4.0, 字体: SIL OFL 1.1, 代码: MIT 许可证)
* 默认内容由 @OtisAlejandro (Seraphina 角色和世界书) 和 @kallmeflocc (10K Discord 用户庆祝背景) 提供
* Docker 指南由 [@mrguymiah](https://github.com/mrguymiah) 和 [@Bronya-Rand](https://github.com/Bronya-Rand) 提供
* kokoro-js 库由 [@hexgrad](https://github.com/hexgrad) 提供 (Apache-2.0 许可证)
## 主要贡献者
[![Contributors](https://contrib.rocks/image?repo=SillyTavern/SillyTavern)](https://github.com/SillyTavern/SillyTavern/graphs/contributors)
<!-- LINK GROUP -->
[cover]: https://github.com/user-attachments/assets/01a6ae9a-16aa-45f2-8bff-32b5dc587e44
[discord-link]: https://discord.gg/sillytavern
[discord-shield-badge]: https://img.shields.io/discord/1100685673633153084?color=5865F2&label=discord&labelColor=black&logo=discord&logoColor=white&style=for-the-badge
+11 -298
View File
@@ -10,7 +10,7 @@
[English](readme.md) | [German](readme-de_de.md) | [中文](readme-zh_cn.md) | 繁體中文 | [日本語](readme-ja_jp.md) | [Русский](readme-ru_ru.md) | [한국어](readme-ko_kr.md)
[![GitHub 星標](https://img.shields.io/github/stars/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/stargazers)
[![GitHub 分支](https://img.shields.io/github/forks/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/network)
[![GitHub 分支](https://img.shields.io/github/forks/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/forks)
[![GitHub 問題](https://img.shields.io/github/issues/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/issues)
[![GitHub 拉取請求](https://img.shields.io/github/issues-pr/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/pulls)
@@ -26,7 +26,7 @@ SillyTavern 提供一個統一的前端介面,整合多種大型語言模型
SillyTavern(簡稱 ST)是一款本地安裝的使用者介面,讓您能與大型語言模型(LLM)、影像生成引擎以及語音合成模型互動的前端。
SillyTavern 起源於 2023 年 2 月,作為 TavernAI 1.2.8 的分支版本發展至今。目前已有超過 100 位貢獻者,並擁有超過兩年的獨立開發歷史。如今,它已成為 AI 愛好者中備受推崇的軟體之一。
SillyTavern 起源於 2023 年 2 月,作為 TavernAI 1.2.8 的分支版本發展至今。目前已有超過 200 位貢獻者,並擁有超過兩年的獨立開發歷史。如今,它已成為 AI 愛好者中備受推崇的軟體之一。
## 我們的願景
@@ -34,29 +34,9 @@ SillyTavern 起源於 2023 年 2 月,作為 TavernAI 1.2.8 的分支版本發
2. 我們不提供任何線上或託管服務,也不會程式化追蹤任何使用者數據。
3. SillyTavern 是由一群熱衷於 LLM 的開發者社群所打造的專案,並將永遠保持免費與開源。
## 分支介紹
## 我需要高效能電腦才能運行 SillyTavern 嗎?
SillyTavern 採用雙分支開發模式,確保為所有使用者提供流暢的體驗。
* `release`(穩定版):🌟 **推薦給大部分的使用者使用。** 此分支最為穩定,僅在主要版本發布時更新。適合大多數人,通常每月更新一次。
* `staging`(開發版):⚠️ **不建議普通使用者使用。** 此分支包含最新功能,但可能隨時出現問題。適合進階使用者與愛好者,每日多次更新。
如果您不熟悉 git CLI 或對分支概念不清楚,請放心,對您來說,`release`(穩定版)分支永遠是首選。
## 使用 SillyTavern 需要什麼?
由於 SillyTavern 僅是一個介面,您需要一個 LLM 後端來提供推理能力。您可以使用 AI Horde 以立即開始聊天。此外,我們支持許多其他本地和雲端 LLM 後端,例如 OpenAI 兼容 API、KoboldAI、Tabby 等。更多支持的 API 資訊,請參閱 [常見問題](https://docs.sillytavern.app/usage/api-connections/)。
### 我需要高效能電腦才能運行 SillyTavern 嗎?
SillyTavern 的硬體需求相當低。任何能夠運行 NodeJS 18 或更高版本的設備都可以執行。若您打算在本地機器上進行 LLM 推理,我們建議使用擁有至少 6GB VRAM 的 3000 系列 NVIDIA 顯示卡。更多詳細資訊,請參考您使用的後端文檔。
### 推薦後端(僅為推薦,非官方合作和隸屬關係)
* [AI Horde](https://aihorde.net/):使用志願者託管的模型,無需進一步設定
* [KoboldCpp](https://github.com/LostRuins/koboldcpp):社群推崇的選擇,可在本地運行 GGUF 模型
* [tabbyAPI](https://github.com/theroyallab/tabbyAPI):一個流行且輕量的本地託管 exl2 推理 API
* [OpenRouter](https://openrouter.ai):提供多個雲端 LLM 提供商(如 OpenAI、Claude、Meta Llama 等)及熱門社群模型的單一 API
SillyTavern 的硬體需求相當低。任何能夠運行 NodeJS 18 或更高版本的設備都可以執行。若您打算在本地機器上進行 LLM 推理,我們建議使用擁有至少 6GB VRAM 的 3000 系列 NVIDIA 顯示卡,但實際需求可能因模型和您使用的後端而異。
## 有任何問題或建議?
@@ -82,287 +62,19 @@ SillyTavern 的硬體需求相當低。任何能夠運行 NodeJS 18 或更高版
<img width="500" alt="image" src="https://github.com/user-attachments/assets/9b5f32f0-c3b3-4102-b3f5-0e9213c0f50f">
<img width="500" alt="image" src="https://github.com/user-attachments/assets/913fdbaa-7d33-42f1-ae2c-89dca41c53d1">
## 角色卡
## 安裝指南
SillyTavern 的核心概念是「角色卡」(Character Cards)。角色卡是一組設定 LLM 行為的提示詞,用於 SillyTavern 中進行持續性對話。功能類似於 ChatGPT 的 GPT 或 Poe 的聊天機器人。角色卡的內容可以是任何形式:抽象場景、針對特定任務設計的助手、知名人物,或者虛構角色。
有關詳細的安裝說明,請訪問我們的文檔:
角色卡中唯一必填的項目是名稱欄位。若想與語言模型開始一般對話,您只需創建一個名稱為「Assistant」的新卡片,其餘欄位皆可保持空白。若希望進行更具主題性的對話,則可以提供語言模型背景資訊、行為模式、寫作風格以及特定情境來啟動聊天。
如果僅想進行快速對話而不選擇角色卡片,或想測試 LLM 的連線,則可在開啟 SillyTavern 後,於歡迎頁面的輸入欄位中直接輸入您的提示內容。請注意,這類對話是暫時的,不會被永久保存。
若想了解如何設定角色卡,可參考預設角色(如 Seraphina)或從「下載擴充功能 & 資源」(Download Extensions & Assets)選單中下載社群製作的角色卡。
## 核心功能
* 進階文本生成設定:內含許多社群製作的預設設定
* 支援世界資訊(World Info):創建豐富的背景故事,或節省角色卡中的 Token(符元)使用
* 群組聊天:多角色聊天室,可讓角色與您或彼此對話
* 豐富的 UI 自定義選項:主題顏色、背景圖片、自定義 CSS 等
* 使用者設定:讓 AI 更了解您並提升沉浸感
* 內建 RAG 支持:可將文檔加入對話,供 AI 參考
* 強大的聊天指令子系統:內含 [腳本引擎(Scripting Engine)](https://docs.sillytavern.app/usage/st-script/)
## 擴充功能
SillyTavern 支持多種擴充功能。
* 角色情感表達:使用視覺圖片(立繪)呈現情緒表達
* 聊天記錄自動摘要
* 自動化介面與聊天翻譯
* 穩定擴散(Stable Diffusion)、FLUX 和 DALL-E 的影像生成整合
* 語音合成:AI 回應的訊息可使用 ElevenLabs、Silero 或系統 TTS 語音合成
* 網頁搜尋功能:為提示詞添加真實世界的上下文資訊
* 更多擴展:可從「下載擴充功能 & 資源」(Download Extensions & Assets)選單中下載
想了解如何使用這些擴充功能,請參考:[官方說明文件](https://docs.sillytavern.app/)
# ⌛ 安裝指南
> \[!WARNING]
>
> * 請勿將程式安裝到 Windows 的系統控制資料夾(如 Program Files、System32 等)
> * 請勿以管理員權限執行 Start.bat
> * 無法在 Windows 7 系統上安裝,因為它無法執行 NodeJS 18.16
## 🪟 Windows
### 使用 Git 安裝
1. 安裝 [NodeJS](https://nodejs.org/en)(建議使用最新的 LTS 版本)
2. 安裝 [Git for Windows](https://gitforwindows.org/)
3. 打開 Windows 檔案總管(`Win+E`)
4. 創建/使用一個不受 Windows 系統控制或監控的資料夾(例如:C:\MySpecialFolder\)
5. 在該資料夾內開啟命令提示字元(Command Prompt):點擊地址欄,輸入 `cmd` 並按下 Enter
6. 當命令提示字元黑框彈出時,輸入以下其中一條指令後,按下 Enter:
* 安裝 Release(穩定版)分支:`git clone https://github.com/SillyTavern/SillyTavern -b release`
* 安裝 Staging(開發板)分支:`git clone https://github.com/SillyTavern/SillyTavern -b staging`
7. 當程式碼下載完成後,雙擊 `Start.bat`,NodeJS 將自動安裝所需的依賴項
8. 本地伺服器啟動後,SillyTavern 將自動在您的瀏覽器中打開
### 使用 GitHub Desktop 安裝
(此方式僅允許通過 GitHub Desktop 使用 git。如果您也希望在命令列中使用 `git`,則需額外安裝 [Git for Windows](https://gitforwindows.org/))
1. 安裝 [NodeJS](https://nodejs.org/en)(建議使用最新的 LTS 版本)
2. 安裝 [GitHub Desktop](https://central.github.com/deployments/desktop/desktop/latest/win32)
3. 安裝完成後,打開 GitHub Desktop,點擊 `Clone a repository from the internet....` (注意:此步驟 **無需創建 GitHub 帳號**。)
4. 在彈出選單中,點擊「URL」選項,輸入此網址:`https://github.com/SillyTavern/SillyTavern`,然後點擊「Clone」。您可以更改「Local path」來選擇 SillyTavern 的下載位置
6. 若想開啟 SillyTavern,需使用 Windows 檔案總管以進入您複製儲存庫的資料夾。預設位置為:`C:\Users\[您的 Windows 使用者名稱]\Documents\GitHub\SillyTavern`
7. 雙擊 `start.bat` 文件。(請注意:若您的作業系統隱藏了 `.bat` 副檔名,該文件可能顯示為「`Start`」。這就是您需要雙擊運行的文件。)
8. 雙擊後,將會彈出一個大型黑色的命令提示字元視窗,SillyTavern 會開始安裝其運行所需的文件與依賴
9. 安裝完成後,若一切正常,命令提示字元視窗應顯示運行中的訊息,且您的瀏覽器會自動打開 SillyTavern 頁籤
10. 連接到任何 SillyTavern [支援的 APIs](https://docs.sillytavern.app/usage/api-connections/) 並開始聊天吧!
## 🐧 Linux & 🍎 MacOS
對於 MacOS 和 Linux 系統,所有操作都將在終端機(Terminal)中完成。
1. 安裝 git 和 NodeJS(具體方法因操作系統而異)
2. 複製儲存庫(Clone the repo):
* 安裝 Release(穩定版)分支:`git clone https://github.com/SillyTavern/SillyTavern -b release`
* 安裝 Staging(開發板)分支:`git clone https://github.com/SillyTavern/SillyTavern -b staging`
3. 使用命令 `cd SillyTavern` 以進入安裝資料夾
4. 使用以下其中一條命令,以執行 `start.sh` 腳本:
* `./start.sh`
* `bash start.sh`
## ⚡ 使用 SillyTavern Launcher 安裝
SillyTavern Launcher 是一個安裝嚮導,協助您設定多種選項,包括安裝本地推理(inference)的後端。
### 對於 Windows 使用者
1. 在鍵盤上按下 **`WINDOWS + R`** 打開「執行」對話框,然後輸入以下指令以安裝 git:
```shell
cmd /c winget install -e --id Git.Git
```
2. 在鍵盤上按下 **`WINDOWS + E`** 打開檔案總管,導航至您想要安裝 Launcher 的資料夾。在目標資料夾的地址欄輸入 `cmd` 並按下 Enter。接著執行以下命令:
```shell
git clone https://github.com/SillyTavern/SillyTavern-Launcher.git && cd SillyTavern-Launcher && start installer.bat
```
### 對於 Linux 使用者
1. 打開您喜歡的終端機(Terminal),安裝 git
2. 使用以下指令以複製 Sillytavern-Launcher:
```shell
git clone https://github.com/SillyTavern/SillyTavern-Launcher.git && cd SillyTavern-Launcher
```
3. 執行安裝腳本(installer.sh):
```shell
chmod +x install.sh && ./install.sh
```
4. 安裝完成後,執行啟動腳本(launcher.sh):
```shell
chmod +x launcher.sh && ./launcher.sh
```
### 對於 Mac 使用者
1. 打開終端機(Terminal),並使用以下指令安裝 Homebrew:
```shell
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
```
2. 使用 Homebrew 以安裝 git:
```shell
brew install git
```
3. 使用以下指令以複製 Sillytavern-Launcher:
```shell
git clone https://github.com/SillyTavern/SillyTavern-Launcher.git && cd SillyTavern-Launcher
```
4. 執行安裝腳本(installer.sh):
```shell
chmod +x install.sh && ./install.sh
```
5. 安裝完成後,執行啟動腳本(launcher.sh):
```shell
chmod +x launcher.sh && ./launcher.sh
```
## 🐋 使用 Docker 安裝
以下指南已假設您安裝 Docker,能夠訪問命令列進行容器安裝,並熟悉 Docker 的基本使用。
### 自行構建映像
我們提供了一份完整的 [SillyTavern Docker 使用指南](http://docs.sillytavern.app/installation/docker/)。該指南涵蓋了 Windows、macOS 和 Linux 的安裝過程。若您希望自行構建映像,建議先閱讀該文檔。
### 使用 GitHub 容器註冊表(最簡易的方式)
您需要設定兩個必要的目錄映射(directory mappings)和一個端口映射(port mapping)來使 SillyTavern 正常運行。在執行指令時,請將以下佔位符替換為您的實際配置:
#### 容器變數
##### 目錄映射(Volume Mappings)
* [config]:用於存放 SillyTavern 設定文件的本地資料夾
* [data]:用於存放 SillyTavern 使用者數據(包括角色)的本地資料夾
* [plugins](可選):用於存放 SillyTavern 擴充功能的本地資料夾
##### 端口映射(Port Mappings)
* [PublicPort]:對外流量的訪問端口。這是必需的,因為您將從虛擬機容器外部訪問實例。除非實施了額外的安全服務,否則請勿將此端口暴露於網路
##### 其他設定(Additional Settings)
* [DockerNet]:容器應連接的 Docker 網路。如果您不熟悉此概念,請參閱 [Docker 官方說明文件](https://docs.docker.com/reference/cli/docker/network/)
* [version]:在 GitHub 頁面的右側,您可以找到「Packages」。選擇「sillytavern」包,然後查看映像版本。「latest」標籤會使您保持與當前版本同步。您也可以選擇「staging」或「release」標籤,但這可能不適用於依賴擴充功能的使用者,因為擴充功能可能需要時間進行更新
#### 安裝命令
1. 打開命令列(Command Line)
2. 執行以下指令:
`docker create --name='sillytavern' --net='[DockerNet]' -p '8000:8000/tcp' -v '[plugins]':'/home/node/app/plugins':'rw' -v '[config]':'/home/node/app/config':'rw' -v '[data]':'/home/node/app/data':'rw' 'ghcr.io/sillytavern/sillytavern:[version]'`
> 請注意:默認的監聽端口為 8000。如果您在設定文件中更改了此端口,請務必使用適當的端口號
## 📱 於 Android 系統中使用 Termux 安裝
> \[!NOTE]
> **雖然您可以在 Android 設備上使用 Termux 直接運行 SillyTavern,但這不在我們的官方支持範圍內。**
>
> **請參閱 ArroganceComplex#2659 所提供的指南:**
>
> * <https://rentry.org/STAI-Termux>
**不支援:Android ARM LEtime-web。** 32 位 Android 系統需要額外的依賴項,這無法通過 npm 安裝。請使用以下命令安裝:`pkg install esbuild`。完成後,請按照普通的安裝步驟進行操作
## API 金鑰管理
SillyTavern 將您的 API 金鑰(Keys)保存在使用者數據目錄中的 `secrets.json` 文件內(默認路徑為`/data/default-user/secrets.json`)
默認情況下,API 金鑰在您保存並重新載入頁面後,將不會自介面中顯示
如需啟用查看金鑰功能:
1. 在 `config.yaml` 文件中,將 `allowKeysExposure` 的「值」設為 `true`
2. 重新啟動 SillyTavern 伺服器
3. 點擊 API 連線頁面右下角的「查看隱藏的 API 金鑰(View hidden API keys)」超連結
## 命令列參數(Command-line Arguments)
您可以在啟動 SillyTavern 伺服器時傳遞命令列參數,以覆蓋 `config.yaml` 文件中的某些設定。
### 範例
```shell
node server.js --port 8000 --listen false
# or
npm run start -- --port 8000 --listen false
# or(僅適用於 Windows)
Start.bat --port 8000 --listen false
```
### Supported arguments
| Option | Description | Type |
|-------------------------|------------------------------------------------------------------------------------------------------|----------|
| `--version` | 顯示版本序號 | boolean |
| `--enableIPv6` | 啟用 IPv6 | boolean |
| `--enableIPv4` | 啟用 IPv4 | boolean |
| `--port` | 設定 SillyTavern 運行的端口。若未提供,則預設使用 `config.yaml` 中的 'port' | number
| `--dnsPreferIPv6` | 偏好使用 IPv6 解析 DNS。未提供則默認使用 `config.yaml` 中的 'preferIPv6' | boolean |
| `--autorun` | 自動在瀏覽器中啟動 SillyTavern。未提供則默認使用 `config.yaml` 中的 'autorun' | boolean |
| `--autorunHostname` | 自動啟動時的主機名稱,通常建議保持為 'auto' | string |
| `--autorunPortOverride` | 覆蓋自動啟動的端口設定 | string |
| `--listen` | SillyTavern 是否可監聽所有網路接口。若未提供,則默認使用 `config.yaml` 中的 'listen' | boolean |
| `--corsProxy` | 啟用 CORS 代理。若未提供,則默認使用 `config.yaml` 中的 'enableCorsProxy' | boolean |
| `--disableCsrf` | 停用 CSRF 保護 | boolean |
| `--ssl` | 啟用 SSL | boolean |
| `--certPath` | 設定您證書文件的路徑 | string |
| `--keyPath` | 設定您私人金鑰文件的路徑 | string |
| `--whitelist` | 啟用白名單模式 | boolean |
| `--dataRoot` | 設定數據儲存的根目錄 | string |
| `--avoidLocalhost` | 在自動模式下避免使用 'localhost' | boolean |
| `--basicAuthMode` | 啟用基本身份驗證模式 | boolean |
| `--requestProxyEnabled` | 啟用代理以處理外部請求 | boolean |
| `--requestProxyUrl` | 設定請求代理的 URL(支持 HTTP 或 SOCKS 協議) | string |
| `--requestProxyBypass` | 請求代理的例外主機清單(主機列表需以空格分隔) | array |
## 遠端連線
遠端連線功能最常用於希望在手機上使用 SillyTavern 的使用者。此時伺服器將由同一 Wi-Fi 網路上的 PC 運行。不過,您也可以設定來自其他網路的遠端連線。
詳細設定指南請參閱 [官方說明文件](https://docs.sillytavern.app/usage/remoteconnections/)。
您還可以選擇設定 SillyTavern 的使用者檔案,並開啟密碼保護(可選):[使用者設定指南](https://docs.sillytavern.app/installation/st-1.12.0-migration-guide/#users)。
## 遇到任何效能問題?
1. 在「使用者設定」選單(設定介面主題)中,禁用模糊效果(Blur Effect),並開啟「減少動畫效果」(Reduced Motion)
2. 若使用響應串流傳輸,請將串流的 FPS 設定為較低的值(建議設定為 10-15 FPS)
3. 確保瀏覽器已啟用 GPU 加速以進行渲染
* **[Windows 安裝指南](https://docs.sillytavern.app/installation/windows/)**
* **[MacOS/Linux 安裝指南](https://docs.sillytavern.app/installation/linuxmacos/)**
* **[Android (Termux) 安裝指南](https://docs.sillytavern.app/installation/android-(termux)/)**
* **[Docker 安裝指南](https://docs.sillytavern.app/installation/docker/)**
## 授權與致謝
**本程式(SillyTavern)的發布是基於其可能對使用者有所幫助的期許,但不提供任何形式的保證;包括但不限於對可銷售性(marketability)或特定用途適用性的隱含保證。如需更多詳情,請參閱 GNU Affero 通用公共許可證。**
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
* [TavernAI](https://github.com/TavernAI/TavernAI) 1.2.8 由 Humi 提供:MIT 許可
* 經授權使用部分來自 CncAnon 的 TavernAITurbo 模組
* 視覺小說模式(Visual Novel Mode)的靈感,來源於 PepperTaco 的貢獻(<https://github.com/peppertaco/Tavern/>)
@@ -370,6 +82,7 @@ This program is distributed in the hope that it will be useful, but WITHOUT ANY
* 主題圖示由 Font Awesome <https://fontawesome.com> 提供(圖示:CC BY 4.0,字體:SIL OFL 1.1,程式碼:MIT 許可)
* 預設資源來源於 @OtisAlejandro(包含角色 Seraphina 與知識書)與 @kallmeflocc(SillyTavern 官方 Discord 伺服器成員突破 10K 的慶祝背景)
* Docker 安裝指南由 [@mrguymiah](https://github.com/mrguymiah) 和 [@Bronya-Rand](https://github.com/Bronya-Rand) 編寫
* kokoro-js 函式庫由 [@hexgrad](https://github.com/hexgrad) 提供 (Apache-2.0 許可)
## 主要貢獻者
+9 -309
View File
@@ -7,7 +7,7 @@
English | [German](readme-de_de.md) | [中文](readme-zh_cn.md) | [繁體中文](readme-zh_tw.md) | [日本語](readme-ja_jp.md) | [Русский](readme-ru_ru.md) | [한국어](readme-ko_kr.md)
[![GitHub Stars](https://img.shields.io/github/stars/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/stargazers)
[![GitHub Forks](https://img.shields.io/github/forks/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/network)
[![GitHub Forks](https://img.shields.io/github/forks/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/forks)
[![GitHub Issues](https://img.shields.io/github/issues/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/issues)
[![GitHub Pull Requests](https://img.shields.io/github/issues-pr/SillyTavern/SillyTavern.svg)](https://github.com/SillyTavern/SillyTavern/pulls)
@@ -31,29 +31,9 @@ Beginning in February 2023 as a fork of TavernAI 1.2.8, SillyTavern now has over
2. We do not provide any online or hosted services, nor programmatically track any user data.
3. SillyTavern is a passion project brought to you by a dedicated community of LLM enthusiasts, and will always be free and open sourced.
## Branches
## Do I need a powerful PC to run SillyTavern?
SillyTavern is being developed using a two-branch system to ensure a smooth experience for all users.
* `release` -🌟 **Recommended for most users.** This is the most stable and recommended branch, updated only when major releases are pushed. It's suitable for the majority of users. Typically updated once a month.
* `staging` - ⚠️ **Not recommended for casual use.** This branch has the latest features, but be cautious as it may break at any time. Only for power users and enthusiasts. Updates several times daily.
If you're not familiar with using the git CLI or don't understand what a branch is, don't worry! The release branch is always the preferable option for you.
## What do I need other than SillyTavern?
Since SillyTavern is only an interface, you will need access to an LLM backend to provide inference. You can use AI Horde for instant out-of-the-box chatting. Aside from that, we support many other local and cloud-based LLM backends: OpenAI-compatible API, KoboldAI, Tabby, and many more. You can read more about our supported APIs in [the Docs](https://docs.sillytavern.app/usage/api-connections/).
### Do I need a powerful PC to run SillyTavern?
The hardware requirements are minimal: it will run on anything that can run NodeJS 18 or higher. If you intend to do LLM inference on your local machine, we recommend a 3000-series NVIDIA graphics card with at least 6GB of VRAM. Check your backend's documentation for more details.
### Suggested Backends (not affiliated)
* [AI Horde](https://aihorde.net/) - use models hosted by volunteers. Requires no further setup
* [KoboldCpp](https://github.com/LostRuins/koboldcpp) - a community's favorite for running GGUF models locally
* [tabbyAPI](https://github.com/theroyallab/tabbyAPI) - a popular, lightweight, locally-hosted exl2 inference API
* [OpenRouter](https://openrouter.ai) - a single API for many cloud providers (OpenAI, Claude, Meta Llama, etc.) as well as popular community models.
The hardware requirements are minimal: it will run on anything that can run NodeJS 18 or higher. If you intend to do LLM inference on your local machine, we recommend a 3000-series NVIDIA graphics card with at least 6GB of VRAM, but actual requirements may vary depending on the model and backend you choose to use.
## Questions or suggestions?
@@ -79,294 +59,14 @@ Or get in touch with the developers directly:
<img width="500" alt="image" src="https://github.com/user-attachments/assets/9b5f32f0-c3b3-4102-b3f5-0e9213c0f50f">
<img width="500" alt="image" src="https://github.com/user-attachments/assets/913fdbaa-7d33-42f1-ae2c-89dca41c53d1">
## Character Cards
## Installation
SillyTavern is built around the concept of "character cards". A character card is a collection of prompts that set the behavior of the LLM and is required to have persistent conversations in SillyTavern. They function similarly to ChatGPT's GPTs or Poe's bots. The content of a character card can be anything: an abstract scenario, an assistant tailored for a specific task, a famous personality or a fictional character.
For detailed installation instructions, please visit our documentation:
To have a quick conversation without selecting a character card or to just test the LLM connection, simply type your prompt input into the input bar on the Welcome Screen after opening SillyTavern. This will create an empty "Assistant" character card that you can customize later.
To get a general idea on how to define character cards, see the default character (Seraphina) or download selected community-made cards from the "Download Extensions & Assets" menu.
## Key Features
* Advanced text generation settings with many community-made presets
* World Info support: create rich lore or save tokens on your character card
* Group chats: multi-bot rooms for characters to talk to you and/or each other
* Rich UI customization options: theme colors, background images, custom CSS, and more
* User personas: let the AI know a bit about you for greater immersion
* Built-in RAG support: add documents to your chats for the AI to reference
* Extensive chat commands subsystem and own [scripting engine](https://docs.sillytavern.app/usage/st-script/)
## Extensions
SillyTavern has extensibility support.
* Character emotional expressions (sprites)
* Auto-Summary of the chat history
* Automatic UI and chat translation
* Stable Diffusion/FLUX/DALL-E image generation
* Text-to-speech for AI response messages (via ElevenLabs, Silero, or the OS's System TTS)
* Web Search capabilities for adding additional real world context to your prompts
* Many more are available to download from the "Download Extensions & Assets" menu.
Tutorials on how to use them can be found in the [Docs](https://docs.sillytavern.app/).
## ⌛ Installation
### 🪟 Windows
> \[!WARNING]
>
> * DO NOT INSTALL INTO ANY WINDOWS CONTROLLED FOLDER (Program Files, System32, etc).
> * DO NOT RUN START.BAT WITH ADMIN PERMISSIONS
> * INSTALLATION ON WINDOWS 7 IS IMPOSSIBLE AS IT CAN NOT RUN NODEJS 18.16
#### Installing via Git (recommended)
1. Install [NodeJS](https://nodejs.org/en) (latest LTS version is recommended)
2. Install [Git for Windows](https://gitforwindows.org/)
3. Open Windows Explorer (`Win+E`)
4. Browse to or Create a folder that is not controlled or monitored by Windows. (ex: C:\MySpecialFolder\)
5. Open a Command Prompt inside that folder by clicking in the 'Address Bar' at the top, typing `cmd`, and pressing Enter.
6. Once the black box (Command Prompt) pops up, type ONE of the following into it and press Enter:
* for Release Branch: `git clone https://github.com/SillyTavern/SillyTavern -b release`
* for Staging Branch: `git clone https://github.com/SillyTavern/SillyTavern -b staging`
7. Once everything is cloned, double-click `Start.bat` to make NodeJS install its requirements.
8. The server will then start, and SillyTavern will pop up in your browser.
#### Installing via GitHub Desktop
(This allows git usage **only** in GitHub Desktop, if you want to use `git` on the command line too, you also need to install [Git for Windows](https://gitforwindows.org/))
1. Install [NodeJS](https://nodejs.org/en) (latest LTS version is recommended)
2. Install [GitHub Desktop](https://central.github.com/deployments/desktop/desktop/latest/win32)
3. After installing GitHub Desktop, click on `Clone a repository from the internet....` (Note: You **do NOT need** to create a GitHub account for this step)
4. On the menu, click the URL tab, enter this URL `https://github.com/SillyTavern/SillyTavern`, and click Clone. You can change the Local path to change where SillyTavern is going to be downloaded.
6. To open SillyTavern, use Windows Explorer to browse into the folder where you cloned the repository. By default, the repository will be cloned here: `C:\Users\[Your Windows Username]\Documents\GitHub\SillyTavern`
7. Double-click on the `start.bat` file. (Note: the `.bat` part of the file name might be hidden by your OS, in that case, it will look like a file called "`Start`". This is what you double-click to run SillyTavern)
8. After double-clicking, a large black command console window should open and SillyTavern will begin to install what it needs to operate.
9. After the installation process, if everything is working, the command console window should look like this and a SillyTavern tab should be open in your browser:
10. Connect to any of the [supported APIs](https://docs.sillytavern.app/usage/api-connections/) and start chatting!
### 🐧 Linux & 🍎 MacOS
For MacOS / Linux all of these will be done in a Terminal.
1. Install git and nodeJS (the method for doing this will vary depending on your OS)
2. Clone the repo
* for Release Branch: `git clone https://github.com/SillyTavern/SillyTavern -b release`
* for Staging Branch: `git clone https://github.com/SillyTavern/SillyTavern -b staging`
3. `cd SillyTavern` to navigate into the install folder.
4. Run the `start.sh` script with one of these commands:
* `./start.sh`
* `bash start.sh`
## 🐋 Installing via Docker
These instructions assume you have installed Docker, are able to access your command line for the installation of containers, and familiar with their general operation.
### Using the GitHub Container Registry
#### Docker Compose (easiest)
Grab the `docker-compose.yml` file from the [GitHub Repository](https://github.com/SillyTavern/SillyTavern/blob/release/docker/docker-compose.yml) and run the following command in the directory where the file is located. This will pull the latest release image from the GitHub Container Registry and start the container, automatically creating the necessary volumes.
```shell
docker-compose up
```
Customize the `docker-compose.yml` file to your needs. The default port is 8000. If you want to adjust the server configuration using environment variables, read the documentation [here](https://docs.sillytavern.app/administration/config-yaml/#environment-variables).
#### Docker CLI (advanced)
You will need two mandatory directory mappings and a port mapping to allow SillyTavern to function. In the command, replace your selections in the following places:
#### Container Variables
##### Volume Mappings
* `CONFIG_PATH` - The directory where SillyTavern configuration files will be stored on your host machine
* `DATA_PATH` - The directory where SillyTavern user data (including characters) will be stored on your host machine
* `PLUGINS_PATH` - (optional) The directory where SillyTavern server plugins will be stored on your host machine
* `EXTENSIONS_PATH` - (optional) The directory where global UI extensions will be stored on your host machine
##### Port Mappings
* `PUBLIC_PORT` - The port to expose the traffic on. This is mandatory, as you will be accessing the instance from outside of its virtual machine container. DO NOT expose this to the internet without implementing a separate service for security.
##### Additional Settings
* `SILLYTAVERN_VERSION` - On the right-hand side of this GitHub page, you'll see "Packages". Select the "sillytavern" package and you'll see the image versions. The image tag "latest" will keep you up-to-date with the current release. You can also utilize "staging" that points to the nightly image of the respective branch.
#### Running the container
1. Open your Command Line
2. Run the following command in a folder where you want to store the configuration and data files:
```bash
SILLYTAVERN_VERSION="latest"
PUBLIC_PORT="8000"
CONFIG_PATH="./config"
DATA_PATH="./data"
PLUGINS_PATH="./plugins"
EXTENSIONS_PATH="./extensions"
docker run \
--name="sillytavern" \
-p "$PUBLIC_PORT:8000/tcp" \
-v "$CONFIG_PATH:/home/node/app/config:rw" \
-v "$DATA_PATH:/home/node/app/data:rw" \
-v "$EXTENSIONS_PATH:/home/node/app/public/scripts/extensions/third-party:rw" \
-v "$PLUGINS_PATH:/home/node/app/plugins:rw" \
ghcr.io/sillytavern/sillytavern:"$SILLYTAVERN_VERSION"
```
> By default the container will run in the foreground. If you want to run it in the background, add the `-d` flag to the `docker run` command.
### Building the image yourself
We have a comprehensive guide on using SillyTavern in Docker [here](http://docs.sillytavern.app/installation/docker/) which covers installations on Windows, macOS and Linux! Give it a read if you wish to build the image yourself.
## ⚡ Installing via SillyTavern Launcher
SillyTavern Launcher is an installation wizard that will help you get setup with many options, including installing a backend for local inference.
### For Windows users
1. On your keyboard: press **`WINDOWS + R`** to open Run dialog box. Then, run the following command to install git:
```shell
cmd /c winget install -e --id Git.Git
```
2. On your keyboard: press **`WINDOWS + E`** to open File Explorer, then navigate to the folder where you want to install the launcher. Once in the desired folder, type `cmd` into the address bar and press enter. Then, run the following command:
```shell
git clone https://github.com/SillyTavern/SillyTavern-Launcher.git && cd SillyTavern-Launcher && start installer.bat
```
### For Linux users
1. Open your favorite terminal and install git
2. Git clone the Sillytavern-Launcher with:
```shell
git clone https://github.com/SillyTavern/SillyTavern-Launcher.git && cd SillyTavern-Launcher
```
3. Start the installer.sh with:
```shell
chmod +x install.sh && ./install.sh
```
4. After installation start the launcher.sh with:
```shell
chmod +x launcher.sh && ./launcher.sh
```
### For Mac users
1. Open a terminal and install brew with:
```shell
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
```
2. Install git with:
```shell
brew install git
```
3. Git clone the Sillytavern-Launcher with:
```shell
git clone https://github.com/SillyTavern/SillyTavern-Launcher.git && cd SillyTavern-Launcher
```
4. Start the installer.sh with:
```shell
chmod +x install.sh && ./install.sh
```
5. After installation start the launcher.sh with:
```shell
chmod +x launcher.sh && ./launcher.sh
```
## 📱 Installing via Termux on Android OS
> \[!NOTE]
> **SillyTavern can be run natively on Android devices using Termux, but we do not provide official support for this use case.**
>
> **Please refer to this guide by ArroganceComplex#2659:**
>
> * <https://rentry.org/STAI-Termux>
**Unsupported platform: android arm LEtime-web.** 32-bit Android requires an external dependency that can't be installed with npm. Use the following command to install it: `pkg install esbuild`. Then run the usual installation steps.
## Command-line arguments
You can pass command-line arguments to SillyTavern server startup to override some settings in `config.yaml`.
### Examples
```shell
node server.js --port 8000 --listen false
# or
npm run start -- --port 8000 --listen false
# or (Windows only)
Start.bat --port 8000 --listen false
```
### Supported arguments
> \[!TIP]
> None of the arguments are required. If you don't provide them, SillyTavern will use the settings in `config.yaml`.
| Option | Description | Type |
|-------------------------|----------------------------------------------------------------------|----------|
| `--version` | Show version number | boolean |
| `--configPath` | Override the path to the config.yaml file | string |
| `--dataRoot` | Root directory for data storage | string |
| `--port` | Sets the port under which SillyTavern will run | number |
| `--listen` | SillyTavern will listen on all network interfaces | boolean |
| `--whitelist` | Enables whitelist mode | boolean |
| `--basicAuthMode` | Enables basic authentication | boolean |
| `--enableIPv4` | Enables IPv4 protocol | boolean |
| `--enableIPv6` | Enables IPv6 protocol | boolean |
| `--listenAddressIPv4` | Specific IPv4 address to listen to | string |
| `--listenAddressIPv6` | Specific IPv6 address to listen to | string |
| `--dnsPreferIPv6` | Prefers IPv6 for DNS | boolean |
| `--ssl` | Enables SSL | boolean |
| `--certPath` | Path to your certificate file | string |
| `--keyPath` | Path to your private key file | string |
| `--autorun` | Automatically launch SillyTavern in the browser | boolean |
| `--autorunHostname` | Autorun hostname | string |
| `--autorunPortOverride` | Overrides the port for autorun | string |
| `--avoidLocalhost` | Avoids using 'localhost' for autorun in auto mode | boolean |
| `--corsProxy` | Enables CORS proxy | boolean |
| `--requestProxyEnabled` | Enables a use of proxy for outgoing requests | boolean |
| `--requestProxyUrl` | Request proxy URL (HTTP or SOCKS protocols) | string |
| `--requestProxyBypass` | Request proxy bypass list (space separated list of hosts) | array |
| `--disableCsrf` | Disables CSRF protection (NOT RECOMMENDED) | boolean |
## Remote connections
Most often this is for people who want to use SillyTavern on their mobile phones while their PC runs the ST server on the same Wi-Fi network. However, it can be used to allow remote connections from anywhere as well.
Read the detailed guide on how to set up remote connections in the [Docs](https://docs.sillytavern.app/usage/remoteconnections/).
You may also want to configure SillyTavern user profiles with (optional) password protection: [Users](https://docs.sillytavern.app/administration/multi-user/).
* **[Windows Installation Guide](https://docs.sillytavern.app/installation/windows/)**
* **[MacOS/Linux Installation Guide](https://docs.sillytavern.app/installation/linuxmacos/)**
* **[Android (Termux) Installation Guide](https://docs.sillytavern.app/installation/android-(termux)/)**
* **[Docker Installation Guide](https://docs.sillytavern.app/installation/docker/)**
## License and credits
+1
View File
@@ -13,3 +13,4 @@ access.log
.git
/public/scripts/extensions/third-party
/colab
.gemini
+3 -3
View File
@@ -1,4 +1,4 @@
FROM node:lts-alpine3.19
FROM node:lts-alpine3.21
# Arguments
ARG APP_HOME=/home/node/app
@@ -19,7 +19,7 @@ RUN \
echo "*** Install npm packages ***" && \
npm i --no-audit --no-fund --loglevel=error --no-progress --omit=dev && npm cache clean --force
# Copy default chats, characters and user avatars to <folder>.default folder
# Create config directory and link config.yaml
RUN \
rm -f "config.yaml" || true && \
ln -s "./config/config.yaml" "config.yaml" || true && \
@@ -30,7 +30,7 @@ RUN \
echo "*** Run Webpack ***" && \
node "./docker/build-lib.js"
# Cleanup unnecessary files
# Set the entrypoint script
RUN \
echo "*** Cleanup ***" && \
mv "./docker/docker-entrypoint.sh" "./" && \
+32 -17
View File
@@ -16,16 +16,28 @@ protocol:
ipv6: false
# Prefers IPv6 for DNS. Enable this on ISPs that don't have issues with IPv6
dnsPreferIPv6: false
# The hostname that autorun opens.
# - Use "auto" to let the server decide
# - Use options like 'localhost', 'st.example.com'
autorunHostname: "auto"
# -- BROWSER LAUNCH CONFIGURATION --
browserLaunch:
# Open the browser automatically on server startup.
enabled: true
# Browser to use for opening the URL.
# NOT SUPPORTED ON ANDROID DEVICES.
# - Use "default" to use the system default browser
# - Use "firefox", "chrome", "edge"
browser: 'default'
# Overrides the hostname that opens in the browser.
# - Use "auto" to let the server decide
# - Use options like 'localhost', 'st.example.com'
hostname: 'auto'
# Overrides the port for run in the browser.
# - Use -1 to use the server port.
# - Specify a port to override the default.
port: -1
# Avoids using 'localhost' as the hostname in auto mode.
# Use if you don't have 'localhost' in your hosts file
avoidLocalhost: false
# Server port
port: 8000
# Overrides the port for autorun in browser.
# - Use -1 to use the server port.
# - Specify a port to override the default.
autorunPortOverride: -1
# -- SSL options --
ssl:
enabled: false
@@ -70,7 +82,7 @@ enableDiscreetLogin: false
# https://www.authelia.com/
# This will use auto login to an account with the same username
# as that used for authlia. (Ensure the username in authlia
# is an exact match with that in sillytavern)
# is an exact match in lowercase with that in sillytavern)
autheliaAuth: false
# If `basicAuthMode` and this are enabled then
# the username and passwords for basic auth are the same as those
@@ -88,7 +100,7 @@ disableCsrfProtection: false
securityOverride: false
# -- LOGGING CONFIGURATION --
logging:
# Enable access logging to access.log file
# Enable access logging to access.log file and console output
# Records new connections with timestamp, IP address and user agent
enableAccessLog: true
# Minimum log level to display in the terminal (DEBUG = 0, INFO = 1, WARN = 2, ERROR = 3)
@@ -98,12 +110,6 @@ rateLimiting:
# Use X-Real-IP header instead of socket IP for rate limiting
# Only enable this if you are using a properly configured reverse proxy (like Nginx/traefik/Caddy)
preferRealIpHeader: false
# -- ADVANCED CONFIGURATION --
# Open the browser automatically
autorun: true
# Avoids using 'localhost' for autorun in auto mode.
# use if you don't have 'localhost' in your hosts file
avoidLocalhost: false
## BACKUP CONFIGURATION
backups:
@@ -133,7 +139,7 @@ thumbnails:
# JPG thumbnail quality (0-100)
quality: 95
# Maximum thumbnail dimensions per type [width, height]
dimensions: { 'bg': [160, 90], 'avatar': [96, 144] }
dimensions: { 'bg': [160, 90], 'avatar': [96, 144], 'persona': [96, 144] }
# PERFORMANCE-RELATED CONFIGURATION
performance:
@@ -145,6 +151,15 @@ performance:
# Enables disk caching for character cards. Improves performances with large card libraries.
useDiskCache: true
# CACHE BUSTER CONFIGURATION
# IMPORTANT: Requires localhost or a domain with HTTPS, otherwise will not work!
cacheBuster:
# Clear browser cache on first load or after uploading image files
enabled: false
# Only clear cache for the specified user agent regex pattern
# Example: 'firefox|safari' (case-insensitive)
userAgentPattern: ''
# Allow secret keys exposure via API
allowKeysExposure: false
# Skip new default content checks
+28
View File
@@ -687,6 +687,10 @@
"filename": "presets/instruct/ChatML-Names.json",
"type": "instruct"
},
{
"filename": "presets/instruct/KoboldAI.json",
"type": "instruct"
},
{
"filename": "presets/context/Llama-3-Instruct-Names.json",
"type": "context"
@@ -810,5 +814,29 @@
{
"filename": "presets/reasoning/Blank.json",
"type": "reasoning"
},
{
"filename": "presets/instruct/Dots1.json",
"type": "instruct"
},
{
"filename": "presets/context/Dots1.json",
"type": "context"
},
{
"filename": "presets/context/Mistral V7-Tekken.json",
"type": "context"
},
{
"filename": "presets/instruct/Mistral V7-Tekken.json",
"type": "instruct"
},
{
"filename": "presets/instruct/Moonshot AI.json",
"type": "instruct"
},
{
"filename": "presets/context/Moonshot AI.json",
"type": "context"
}
]
@@ -0,0 +1,11 @@
{
"story_string": "<|system|>\n{{#if system}}{{system}}\n{{/if}}{{#if wiBefore}}{{wiBefore}}\n{{/if}}{{#if description}}{{description}}\n{{/if}}{{#if personality}}{{char}}'s personality: {{personality}}\n{{/if}}{{#if scenario}}Scenario: {{scenario}}\n{{/if}}{{#if wiAfter}}{{wiAfter}}\n{{/if}}{{#if persona}}{{persona}}\n{{/if}}{{trim}}<|endofsystem|>",
"example_separator": "",
"chat_start": "",
"use_stop_strings": false,
"names_as_stop_strings": true,
"always_force_name2": true,
"trim_sentences": false,
"single_line": false,
"name": "Dots1"
}
@@ -0,0 +1,10 @@
{
"story_string": "[SYSTEM_PROMPT]{{#if system}}{{system}}\n{{/if}}{{#if wiBefore}}{{wiBefore}}\n{{/if}}{{#if description}}{{description}}\n{{/if}}{{#if personality}}{{personality}}\n{{/if}}{{#if scenario}}{{scenario}}\n{{/if}}{{#if wiAfter}}{{wiAfter}}\n{{/if}}{{#if persona}}{{persona}}\n{{/if}}{{trim}}[/SYSTEM_PROMPT]",
"example_separator": "",
"chat_start": "",
"use_stop_strings": false,
"always_force_name2": true,
"trim_sentences": false,
"single_line": false,
"name": "Mistral V7-Tekken"
}
@@ -0,0 +1,11 @@
{
"story_string": "<|im_system|>system<|im_middle|>{{#if system}}{{system}}\n{{/if}}{{#if wiBefore}}{{wiBefore}}\n{{/if}}{{#if description}}{{description}}\n{{/if}}{{#if personality}}{{char}}'s personality: {{personality}}\n{{/if}}{{#if scenario}}Scenario: {{scenario}}\n{{/if}}{{#if wiAfter}}{{wiAfter}}\n{{/if}}{{#if persona}}{{persona}}\n{{/if}}{{trim}}<|im_end|>",
"example_separator": "",
"chat_start": "",
"use_stop_strings": false,
"names_as_stop_strings": true,
"always_force_name2": true,
"trim_sentences": false,
"single_line": false,
"name": "Moonshot AI"
}
@@ -0,0 +1,24 @@
{
"input_sequence": "<|userprompt|>",
"output_sequence": "<|response|>",
"last_output_sequence": "",
"system_sequence": "<|system|>",
"stop_sequence": "<|endofresponse|>",
"wrap": true,
"macro": true,
"names_behavior": "force",
"activation_regex": "",
"system_sequence_prefix": "",
"system_sequence_suffix": "",
"first_output_sequence": "",
"skip_examples": false,
"output_suffix": "<|endofresponse|>\n",
"input_suffix": "<|endofuserprompt|>\n",
"system_suffix": "<|endofsystem|>\n",
"user_alignment_message": "",
"system_same_as_user": false,
"last_system_sequence": "",
"first_input_sequence": "",
"last_input_sequence": "",
"name": "Dots1"
}
@@ -0,0 +1,22 @@
{
"input_sequence": "{{[INPUT]}}",
"output_sequence": "{{[OUPUT]}}",
"last_output_sequence": "",
"system_sequence": "{{[SYSTEM]}}",
"stop_sequence": "",
"wrap": true,
"macro": true,
"names_behavior": "force",
"activation_regex": "",
"system_sequence_prefix": "",
"system_sequence_suffix": "",
"first_output_sequence": "",
"skip_examples": false,
"output_suffix": "{{[OUTPUT_END]}}",
"input_suffix": "{{[INPUT_END]}}",
"system_suffix": "{{[SYSTEM_END]}}",
"user_alignment_message": "",
"system_same_as_user": false,
"last_system_sequence": "",
"name": "KoboldAI"
}
@@ -0,0 +1,22 @@
{
"input_sequence": "[INST]",
"output_sequence": " ",
"last_output_sequence": "",
"system_sequence": "[SYSTEM_PROMPT]",
"stop_sequence": "</s>",
"wrap": false,
"macro": true,
"names_behavior": "force",
"activation_regex": "",
"system_sequence_prefix": "",
"system_sequence_suffix": "",
"first_output_sequence": "",
"skip_examples": false,
"output_suffix": "</s>",
"input_suffix": "[/INST]",
"system_suffix": "[/SYSTEM_PROMPT]",
"user_alignment_message": "",
"system_same_as_user": false,
"last_system_sequence": "",
"name": "Mistral V7-Tekken"
}
@@ -0,0 +1,24 @@
{
"input_sequence": "<|im_user|>user<|im_middle|>",
"output_sequence": "<|im_assistant|>assistant<|im_middle|>",
"last_output_sequence": "",
"system_sequence": "<|im_system|>system<|im_middle|>",
"stop_sequence": "<|im_end|>",
"wrap": false,
"macro": true,
"activation_regex": "",
"system_sequence_prefix": "",
"system_sequence_suffix": "",
"first_output_sequence": "",
"skip_examples": false,
"output_suffix": "<|im_end|>",
"input_suffix": "<|im_end|>",
"system_suffix": "<|im_end|>",
"user_alignment_message": "",
"system_same_as_user": false,
"last_system_sequence": "",
"first_input_sequence": "",
"last_input_sequence": "",
"names_behavior": "force",
"name": "Moonshot AI"
}
+1 -4
View File
@@ -2,12 +2,11 @@
"chat_completion_source": "openai",
"openai_model": "gpt-4-turbo",
"claude_model": "claude-3-5-sonnet-20240620",
"windowai_model": "",
"openrouter_model": "OR_Website",
"openrouter_use_fallback": false,
"openrouter_group_models": false,
"openrouter_sort_models": "alphabetically",
"ai21_model": "jamba-1.5-large",
"ai21_model": "jamba-large",
"mistralai_model": "mistral-large-latest",
"custom_model": "",
"custom_url": "",
@@ -226,12 +225,10 @@
]
}
],
"api_url_scale": "",
"show_external_models": false,
"assistant_prefill": "",
"assistant_impersonation": "",
"claude_use_sysprompt": false,
"use_alt_scale": false,
"squash_system_messages": false,
"image_inlining": false,
"bypass_status_check": false,
+1 -2
View File
@@ -623,8 +623,7 @@
"wi_format": "{0}",
"openai_model": "gpt-4-turbo",
"claude_model": "claude-3-5-sonnet-20240620",
"ai21_model": "jamba-1.5-large",
"windowai_model": "",
"ai21_model": "jamba-large",
"openrouter_model": "OR_Website",
"reverse_proxy": "",
"chat_completion_source": "openai",
Vendored
+5
View File
@@ -66,4 +66,9 @@ declare global {
* Parsed command line arguments.
*/
var COMMAND_LINE_ARGS: CommandLineArguments;
/**
* Forces a global mode if set to `true` before parsing the CLI arguments.
*/
var FORCE_GLOBAL_MODE: boolean;
}
+404 -239
View File
File diff suppressed because it is too large Load Diff
+33 -31
View File
@@ -1,6 +1,6 @@
{
"dependencies": {
"@adobe/css-tools": "^4.4.2",
"@adobe/css-tools": "^4.4.3",
"@agnai/sentencepiece-js": "^1.1.1",
"@agnai/web-tokenizers": "^0.1.3",
"@iconfu/svg-inject": "^1.2.3",
@@ -30,30 +30,31 @@
"@popperjs/core": "^2.11.8",
"@zeldafan0225/ai_horde": "^5.2.0",
"archiver": "^7.0.1",
"bing-translate-api": "^4.0.2",
"bing-translate-api": "^4.1.0",
"body-parser": "^1.20.2",
"bowser": "^2.11.0",
"bytes": "^3.1.2",
"chalk": "^5.4.1",
"command-exists": "^1.2.9",
"compression": "^1.8.0",
"compression": "^1.8.1",
"cookie-parser": "^1.4.6",
"cookie-session": "^2.1.0",
"cookie-session": "^2.1.1",
"cors": "^2.8.5",
"crc": "^4.3.2",
"csrf-sync": "^4.0.3",
"csrf-sync": "^4.2.1",
"diff-match-patch": "^1.0.5",
"dompurify": "^3.2.4",
"dompurify": "^3.2.6",
"droll": "^0.2.1",
"env-paths": "^3.0.0",
"express": "^4.21.0",
"form-data": "^4.0.2",
"form-data": "^4.0.4",
"fuse.js": "^7.1.0",
"google-translate-api-browser": "^3.0.1",
"google-translate-api-x": "^10.7.2",
"handlebars": "^4.7.8",
"helmet": "^7.2.0",
"helmet": "^8.1.0",
"highlight.js": "^11.11.1",
"html-entities": "^2.5.2",
"html-entities": "^2.6.0",
"iconv-lite": "^0.6.3",
"ip-matching": "^2.1.2",
"ip-regex": "^5.0.0",
@@ -61,34 +62,34 @@
"is-docker": "^3.0.0",
"localforage": "^1.10.0",
"lodash": "^4.17.21",
"mime-types": "^2.1.35",
"mime-types": "^3.0.1",
"moment": "^2.30.1",
"morphdom": "^2.7.4",
"multer": "^2.0.0",
"morphdom": "^2.7.5",
"multer": "^2.0.2",
"node-fetch": "^3.3.2",
"node-persist": "^4.0.4",
"open": "^8.4.2",
"open": "^10.2.0",
"png-chunk-text": "^1.0.0",
"png-chunks-extract": "^1.0.0",
"proxy-agent": "^6.5.0",
"rate-limiter-flexible": "^5.0.5",
"response-time": "^2.3.3",
"response-time": "^2.3.4",
"sanitize-filename": "^1.6.3",
"seedrandom": "^3.0.5",
"showdown": "^2.1.0",
"sillytavern-transformers": "2.14.6",
"simple-git": "^3.27.0",
"simple-git": "^3.28.0",
"slidetoggle": "^4.0.0",
"tiktoken": "^1.0.20",
"tiktoken": "^1.0.21",
"url-join": "^5.0.0",
"vectra": "^0.2.2",
"wavefile": "^11.0.0",
"webpack": "^5.98.0",
"write-file-atomic": "^5.0.1",
"ws": "^8.18.1",
"yaml": "^2.7.0",
"ws": "^8.18.3",
"yaml": "^2.8.0",
"yargs": "^17.7.1",
"yauzl": "^2.10.0"
"yauzl": "^3.2.0"
},
"engines": {
"node": ">= 18"
@@ -111,10 +112,11 @@
"type": "git",
"url": "https://github.com/SillyTavern/SillyTavern.git"
},
"version": "1.13.0",
"version": "1.13.2",
"scripts": {
"start": "node server.js",
"debug": "node --inspect server.js",
"start:global": "node server.js --global",
"start:electron": "cd ./src/electron && npm run start",
"start:deno": "deno run --allow-run --allow-net --allow-read --allow-write --allow-sys --allow-env server.js",
"start:bun": "bun server.js",
@@ -126,7 +128,7 @@
"plugins:install": "node plugins install"
},
"bin": {
"sillytavern": "./server.js"
"sillytavern": "./src/server-global.js"
},
"rules": {
"no-path-concat": "off",
@@ -137,24 +139,24 @@
"@types/archiver": "^6.0.3",
"@types/bytes": "^3.1.5",
"@types/command-exists": "^1.2.3",
"@types/compression": "^1.7.5",
"@types/cookie-parser": "^1.4.8",
"@types/compression": "^1.8.1",
"@types/cookie-parser": "^1.4.9",
"@types/cookie-session": "^2.0.49",
"@types/cors": "^2.8.17",
"@types/deno": "^2.2.0",
"@types/express": "^4.17.21",
"@types/cors": "^2.8.19",
"@types/deno": "^2.3.0",
"@types/express": "^4.17.23",
"@types/jquery": "^3.5.32",
"@types/jquery-cropper": "^1.0.4",
"@types/jquery.transit": "^0.9.33",
"@types/jqueryui": "^1.12.24",
"@types/lodash": "^4.17.16",
"@types/mime-types": "^2.1.4",
"@types/multer": "^1.4.12",
"@types/node": "^18.19.80",
"@types/lodash": "^4.17.20",
"@types/mime-types": "^3.0.1",
"@types/multer": "^2.0.0",
"@types/node": "^18.19.84",
"@types/node-persist": "^3.1.8",
"@types/png-chunk-text": "^1.0.3",
"@types/png-chunks-extract": "^1.0.2",
"@types/response-time": "^2.3.8",
"@types/response-time": "^2.3.9",
"@types/select2": "^4.0.63",
"@types/toastr": "^2.1.43",
"@types/write-file-atomic": "^4.0.3",
+10
View File
@@ -55,6 +55,7 @@
/* Flashing for highlighting animation */
@keyframes flash {
0%,
50%,
100% {
@@ -122,3 +123,12 @@
border-top-color: var(--progFlashColor);
}
}
/* Scroll delay animations */
@keyframes hide-scroll {
from,
to {
overflow-y: hidden;
}
}
+1 -1
View File
@@ -1,5 +1,5 @@
#rm_print_characters_block.group_overlay_mode_select .character_select {
transition: background-color 0.4s ease;
transition: background-color var(--animation-duration-3x) ease;
background-color: rgba(170, 170, 170, 0.15);
}
+149
View File
@@ -0,0 +1,149 @@
.dataMaidDialogContainer {
height: 100%;
overflow: hidden;
}
.dataMaidDialog {
display: flex;
flex-direction: column;
gap: 5px;
height: 100%;
overflow: hidden;
}
.dataMaidDialogHeader {
display: flex;
gap: 10px;
align-items: center;
text-align: left;
}
.dataMaidHeaderInfo {
flex: 1;
margin: 0;
padding: 5px 10px;
}
.dataMaidTextView {
width: 100%;
height: 100%;
font-family: var(--monoFontFamily);
resize: none;
font-size: 0.95em;
}
.dataMaidImageView {
width: 100%;
height: 100%;
object-fit: contain;
}
.dataMaidSpinner {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
.dataMaidPlaceholder {
display: flex;
justify-content: center;
align-items: center;
font-size: 1.05em;
}
.dataMaidResultsList:empty {
display: none;
}
.dataMaidResultsList {
text-align: left;
display: flex;
flex-direction: column;
gap: 2px;
overflow-y: auto;
height: 100%;
flex-grow: 1;
}
.dataMaidCategory {
border: 1px solid var(--SmartThemeBorderColor);
border-radius: 10px;
padding: 0 10px;
}
.dataMaidCategoryHeader {
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
margin-right: 5px;
padding: 0 5px;
}
.dataMaidCategoryDetails {
display: flex;
flex-direction: column;
gap: 1px;
}
.dataMaidCategoryName {
flex: 3;
font-weight: bold;
font-size: 1.1em;
}
.dataMaidCategoryInfo {
flex: 1;
display: flex;
align-items: baseline;
gap: 5px;
}
.dataMaidCategoryContent {
border: 1px solid var(--SmartThemeBorderColor);
padding: 5px;
border-radius: 10px;
background-color: var(--black30a);
margin: 10px 0;
}
.dataMaidCategoryContent>.info-block {
white-space: pre-wrap;
}
.dataMaidItem {
display: flex;
flex-direction: column;
padding: 5px;
width: 100%;
border-bottom: 1px solid var(--SmartThemeBorderColor);
}
.dataMaidItem:last-child {
border-bottom: none;
}
.dataMaidItemHeader {
display: flex;
align-items: center;
gap: 5px;
}
.dataMaidItemName {
display: flex;
flex: 1;
align-items: baseline;
gap: 2px;
word-break: break-all;
}
.dataMaidItemActions {
display: flex;
align-items: center;
gap: 5px;
}
.dataMaidItemActions>button {
font-size: 0.9em;
}
+1 -1
View File
@@ -18,7 +18,7 @@
#load-spinner {
--spinner-size: 2em;
transition: all 300ms ease-out;
transition: all var(--animation-duration-2x) ease-out;
opacity: 1;
top: calc(50% - var(--spinner-size) / 2);
left: calc(50% - var(--spinner-size) / 2);
+1 -1
View File
@@ -23,7 +23,7 @@ body.login .userSelect {
width: 30%;
cursor: pointer;
margin: 5px 0;
transition: background-color 0.15s ease-in-out;
transition: background-color var(--animation-duration) ease-in-out;
display: flex;
align-items: center;
justify-content: center;
+1 -1
View File
@@ -43,7 +43,7 @@
height: 25px;
margin-left: 5px;
opacity: 0.5;
transition: all 250ms;
transition: all var(--animation-duration-2x);
position: unset !important;
}
+9 -4
View File
@@ -25,10 +25,6 @@
font-size: 15px;
}
.mes_text img {
width: 100%;
}
#extensions_settings,
#extensions_settings2 {
width: 100% !important;
@@ -241,6 +237,15 @@
top: var(--topBarBlockSize) !important;
left: 0 !important;
backdrop-filter: blur(calc(var(--SmartThemeBlurStrength) * 2));
@starting-style {
height: 0;
}
}
#left-nav-panel:not(.openDrawer),
#right-nav-panel:not(.openDrawer) {
height: 0;
}
/*
+6 -2
View File
@@ -79,7 +79,7 @@
justify-content: center;
margin-left: 0.25em;
cursor: pointer;
transition: 0.3s ease-in-out;
transition: var(--animation-duration-2x) ease-in-out;
height: 20px;
width: 20px;
filter: drop-shadow(0px 0px 2px black);
@@ -112,6 +112,10 @@
flex-direction: column;
}
.completion_prompt_manager_popup_entry_form .select2-container {
margin: 5px 0;
}
#completion_prompt_manager_popup .completion_prompt_manager_popup_entry_form_control:has(#completion_prompt_manager_popup_entry_form_prompt) {
flex: 1;
display: flex;
@@ -239,7 +243,7 @@
flex-direction: column;
justify-content: center;
margin-left: 0.25em;
transition: 0.3s ease-in-out;
transition: var(--animation-duration-2x) ease-in-out;
filter: drop-shadow(0px 0px 2px black);
}
+1 -1
View File
@@ -172,7 +172,7 @@
#rm_group_members .group_member:not(.disabled) .right_menu_button[data-action="disable"] {
opacity: 0.4;
filter: brightness(0.5);
transition: all 0.2s ease-in-out;
transition: all var(--animation-duration-2x) ease-in-out;
}
/* #rm_group_members .right_menu_button[data-action="speak"]:hover, */
+102
View File
@@ -0,0 +1,102 @@
.secretKeyManager {
display: flex;
flex-direction: column;
gap: 5px;
height: 100%;
}
.secretKeyManagerHeader {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 5px;
}
.secretKeyManagerSubtitle {
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
width: 100%;
}
.secretKeyManagerInfo {
display: flex;
flex-direction: column;
align-items: baseline;
flex: 1;
font-size: 0.95em;
}
.secretKeyManagerList {
display: flex;
flex-direction: column;
text-align: left;
gap: 5px;
flex: 1;
overflow-y: auto;
height: 100%;
}
.secretKeyManagerItem {
border: 1px solid var(--SmartThemeBorderColor);
padding: 5px 10px;
border-radius: 10px;
background-color: var(--black30a);
display: flex;
flex-direction: row;
align-items: center;
}
.secretKeyManagerItem.active {
background-color: var(--cobalt30a);
}
.secretKeyManagerItemInfo {
display: flex;
flex-direction: column;
flex: 1;
gap: 5px;
}
.secretKeyManagerItemSubtitle,
.secretKeyManagerItemHeader {
word-break: break-all;
}
.secretKeyManagerItemId {
text-decoration: underline;
text-decoration-style: dotted;
cursor: pointer;
}
.secretKeyManagerItemActions {
display: flex;
flex-direction: column;
gap: 5px;
}
.secretKeyManagerItemActionsRow {
display: flex;
flex-direction: row;
gap: 5px;
}
.secretKeyManagerItemActionsRow>button {
margin: 0;
}
.secretKeyManagerList:empty {
display: none;
}
.secretKeyManagerListEmpty {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
opacity: 0.8;
font-weight: bold;
font-size: 1.05em;
}
+15 -62
View File
@@ -19,14 +19,15 @@
.select2-container .select2-selection .select2-selection__clear {
color: var(--SmartThemeBodyColor);
font-size: 20px;
padding: 0;
position: absolute;
right: 5px;
top: 0;
margin-top: 0; /* compensate for the increased font size */
margin-right: 0;
}
.select2-container .select2-search__field {
.select2-container .select2-search--inline textarea.select2-search__field {
opacity: 0.8;
margin-top: 7px; /* get placeholder text to the center */
}
.select2-selection--single .select2-selection__placeholder {
@@ -39,8 +40,8 @@
.select2-container .select2-selection--single .select2-selection__rendered {
color: var(--SmartThemeBodyColor);
line-height: revert;
padding-left: unset;
line-height: unset;
padding: 3px 5px;
}
.select2-container .select2-results>.select2-results__options {
@@ -63,9 +64,10 @@
background-color: var(--black30a);
color: var(--SmartThemeBodyColor);
border: 1px solid var(--SmartThemeBorderColor);
border-radius: 7px;
font-family: var(--mainFontFamily);
padding: 3px 5px;
display: unset; /* override the ST textarea display style */
border-radius: 0; /* border radius was interfering with cursor */
}
/* Customize the selected option */
@@ -93,7 +95,10 @@
border: 1px solid var(--SmartThemeBorderColor);
border-radius: 7px;
font-family: var(--mainFontFamily);
padding: 3px 5px;
}
.select2-container .select2-selection--multiple.select2-selection--clearable {
padding-right: 20px;
}
.select2-container.select2-container--focus .select2-selection--multiple,
@@ -125,7 +130,7 @@
background-color: unset;
color: var(--SmartThemeBodyColor);
opacity: 0.5;
transition: opacity 200ms ease-in-out;
transition: opacity var(--animation-duration-2x) ease-in-out;
position: relative;
}
@@ -203,7 +208,7 @@
/* Styling for choice remove icon */
span.select2.select2-container .select2-selection__choice__remove {
cursor: pointer;
transition: background-color 0.3s;
transition: background-color var(--animation-duration-2x);
color: var(--SmartThemeBodyColor);
background-color: var(--black50a);
}
@@ -220,7 +225,7 @@ span.select2.select2-container .select2-selection__choice__remove:hover {
.select2_choice_clickable_buttonstyle+span.select2-container .select2-selection__choice__display {
cursor: pointer;
transition: background-color 0.3s;
transition: background-color var(--animation-duration-2x);
color: var(--SmartThemeBodyColor);
background-color: var(--black50a);
white-space: break-spaces;
@@ -230,55 +235,3 @@ span.select2.select2-container .select2-selection__choice__remove:hover {
.select2_choice_clickable_buttonstyle+span.select2-container .select2-selection__choice__display:hover {
background-color: var(--white30a);
}
/* Custom class to support same line multi inputs of select2 controls */
.select2_multi_sameline+span.select2-container .select2-selection--multiple {
display: flex;
flex-wrap: wrap;
}
.select2_multi_sameline+span.select2-container .select2-selection--multiple .select2-search--inline {
/* Allow search placeholder to take up all space if needed */
flex-grow: 1;
}
.select2_multi_sameline+span.select2-container .select2-selection--multiple .select2-selection__rendered {
/* Fix weird styling choice or huge margin around selected options */
margin-block-start: 2px;
margin-block-end: 2px;
display: flex;
align-items: center;
flex-wrap: wrap;
row-gap: 5px;
}
.select2_multi_sameline+span.select2-container .select2-selection--multiple .select2-selection__choice {
margin-top: 0px;
}
.select2_multi_sameline+span.select2-container .select2-selection--multiple .select2-search__field {
/* Min height to reserve spacing */
min-height: calc(var(--mainFontSize) + 13px);
/* Min width to be clickable */
min-width: 4em;
align-content: center;
/* Fix search textarea alignment issue with UL elements */
margin-top: 0px;
height: unset;
/* Prevent height from jumping around when input is focused */
line-height: 1;
}
.select2_multi_sameline+span.select2-container .select2-selection--multiple .select2-selection__rendered {
/* Min height to reserve spacing */
min-height: calc(var(--mainFontSize) + 13px);
}
/* Make search bar invisible unless the select2 is active, to save space */
.select2_multi_sameline+span.select2-container .select2-selection--multiple .select2-search--inline {
height: 1px;
}
.select2_multi_sameline+span.select2-container.select2-container--focus .select2-selection--multiple .select2-search--inline {
height: unset;
}
+9 -9
View File
@@ -332,6 +332,10 @@
overflow: hidden;
}
.overflowYScroll {
overflow-y: scroll;
}
.padding0 {
padding: 0;
}
@@ -466,21 +470,13 @@
margin-left: 20px;
}
/*used to fix smallness of certain FontAwesome glyph which break button squareness*/
/*currently used on: CharList Import*/
.faSmallFontSquareFix {
font-size: calc(var(--mainFontSize) *1.25);
width: calc(var(--mainFontSize) *1.95);
}
.textarea_compact {
font-size: calc(var(--mainFontSize) * 0.95);
line-height: 1.2;
}
.hoverglow {
transition: opacity 200ms;
transition: opacity var(--animation-duration-2x);
}
.hoverglow:hover {
@@ -556,6 +552,10 @@ textarea:disabled {
min-width: fit-content;
}
.flexGap2 {
gap: 2px;
}
.flexGap5 {
gap: 5px;
}
+4 -2
View File
@@ -157,7 +157,9 @@
flex-direction: row;
flex-wrap: wrap;
align-items: flex-start;
margin: 5px;
margin-top: 5px;
max-height: 40dvh;
overflow-y: auto;
}
.rm_tag_filter .tag {
@@ -167,7 +169,7 @@
}
.rm_tag_filter .tag.actionable {
transition: opacity 200ms;
transition: opacity var(--animation-duration-2x);
}
.rm_tag_filter .tag:hover {
+9 -1
View File
@@ -19,6 +19,7 @@ body:not(.tts) #ttsExtensionNarrateAll {
}
body.no-hotswap .hotswap,
body.no-hotswap .hotswap~hr,
body.no-timer .mes_timer,
body.no-timestamps .timestamp,
body.no-tokenCount .tokenCounterDisplay,
@@ -28,6 +29,12 @@ body.hideChatAvatars .mesAvatarWrapper .avatar {
display: none !important;
}
body.no-hotswap #CharListButtonAndHotSwaps .flex-container {
flex-wrap: nowrap;
align-items: flex-end;
flex-flow: row;
}
body.hideChatAvatars .last_mes:not(.smallSysMes) {
padding-bottom: 20px !important;
}
@@ -86,7 +93,8 @@ body.charListGrid #rm_print_characters_block .group_select .ch_name,
body.charListGrid #rm_print_characters_block .group_select .group_select_counter,
#user_avatar_block.gridView .avatar-container .ch_name,
#user_avatar_block.gridView .avatar-container .bogus_folder_counter,
#user_avatar_block.gridView .avatar-container .group_select_counter {
#user_avatar_block.gridView .avatar-container .group_select_counter,
#user_avatar_block.gridView .avatar-container .ch_additional_info {
width: 100%;
max-width: 100px;
text-align: center;
+16
View File
@@ -142,12 +142,28 @@ body.hideChatAvatars .welcomePanel .recentChatList .recentChat .avatar {
justify-content: space-between;
align-items: baseline;
font-size: calc(var(--mainFontSize) * 1);
gap: 5px;
}
.welcomeRecent .recentChatList .recentChat .chatNameContainer .chatName {
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
flex: 1;
}
.welcomeRecent .recentChatList .recentChat .chatActions {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
gap: 5px;
}
.welcomeRecent .recentChatList .recentChat .chatActions button {
margin: 0;
font-size: 0.8em;
cursor: pointer;
}
.welcomeRecent .recentChatList .recentChat .chatMessageContainer {
+20 -3
View File
@@ -107,7 +107,6 @@
height: auto;
margin-top: 0;
margin-bottom: 0;
min-height: calc(var(--mainFontSize) + 14px);
}
.delete_entry_button {
@@ -198,7 +197,11 @@
}
.world_entry {
transition: opacity 500ms;
transition: opacity var(--animation-duration-3x);
}
.world_entry_edit {
display: contents;
}
.disabledWIEntry {
@@ -267,7 +270,7 @@ select.keyselect+span.select2-container .select2-selection--multiple {
opacity: 0.5;
color: var(--SmartThemeBodyColor);
transition: opacity 0.3s;
transition: opacity var(--animation-duration-2x);
}
.switch_input_type_icon:hover {
@@ -282,3 +285,17 @@ select.keyselect+span.select2-container .select2-selection--multiple {
.world_entry:has(input[name="delay_until_recursion"]:not(:checked)) .world_entry_form_control:has(input[name="delayUntilRecursionLevel"]) {
display: none;
}
.world_entry label[for="__invisible"] {
visibility: hidden;
pointer-events: none;
opacity: 0;
width: 0;
overflow: hidden;
}
#WIMultiSelector .select2-container .select2-selection--multiple {
max-height: 25vh;
overflow-y: auto;
overflow-x: hidden;
}
+13
View File
@@ -1,6 +1,7 @@
import libs from './lib';
import getContext from './scripts/st-context';
import { power_user } from './scripts/power-user';
import { QuickReplyApi } from './scripts/extensions/quick-reply/api/QuickReplyApi';
declare global {
// Custom types
@@ -13,6 +14,7 @@ declare global {
declare var pdfjsLib;
declare var ePub;
declare var quickReplyApi: QuickReplyApi;
declare var SillyTavern: {
getContext(): typeof getContext;
@@ -30,6 +32,11 @@ declare global {
izoomify(options?: any): JQuery;
}
// NPM package doesn't have the 'queue' property in the type definition
interface JQueryTransitOptions {
queue?: boolean;
}
namespace Select2 {
interface Options<Result = DataFormat | GroupedDataFormat, RemoteResult = any> {
/**
@@ -66,4 +73,10 @@ declare global {
* @param args - The arguments for the conversion function.
*/
function convertVideoToAnimatedWebp(args: ConvertVideoArgs): Promise<Uint8Array>;
interface ColorPickerEvent extends JQuery.ChangeEvent<HTMLElement> {
detail: {
rgba: string;
};
}
}
+4
View File
@@ -0,0 +1,4 @@
<svg width="24" height="21" viewBox="0 0 24 21" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M22.8059 9.20726C23.2424 9.96331 23.2424 10.8948 22.8059 11.6508L18.2791 19.4915C17.8426 20.2475 17.0359 20.7133 16.1629 20.7133H7.10934C6.23633 20.7133 5.42964 20.2475 4.99313 19.4915L0.466342 11.6508C0.0298381 10.8948 0.02984 9.96331 0.466344 9.20726L4.99313 1.36663C5.42964 0.61058 6.23633 0.144836 7.10934 0.144836H16.1629C17.0359 0.144836 17.8426 0.610581 18.2791 1.36663L22.8059 9.20726Z" />
<path fill-rule="evenodd" clip-rule="evenodd" d="M6.66791 13.8818C6.49765 13.8818 6.32633 13.8275 6.18162 13.7168C5.83259 13.4476 5.76662 12.9464 6.03583 12.5974L9.22068 8.45807C9.3505 8.28888 9.5431 8.17928 9.75379 8.15268C9.96874 8.12501 10.1794 8.1846 10.3465 8.31761L13.3472 10.6746L15.9724 7.28756C16.2427 6.93748 16.7428 6.87257 17.0918 7.14498C17.4408 7.41526 17.5047 7.91645 17.2344 8.26441L14.1166 12.2867C13.9868 12.4548 13.7952 12.5644 13.5845 12.59C13.3717 12.6187 13.161 12.557 12.9929 12.4261L9.99428 10.0702L7.30105 13.57C7.14356 13.7743 6.90733 13.8818 6.66791 13.8818Z" fill="black"/>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

+1 -43
View File
@@ -1,43 +1 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="190.91216mm"
height="201.47243mm"
viewBox="0 0 190.91216 201.47243"
version="1.1"
id="svg1"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs1" />
<g
id="layer1"
transform="translate(-2.2086436)">
<g
id="g8"
transform="matrix(0.99583856,0,0,1.0472862,2.2086437,-7.9847956)">
<path
style="font-weight:bold;font-size:89.3125px;font-family:'Courier New';-inkscape-font-specification:'Courier New Bold';letter-spacing:-8.37308px;stroke-width:1.73283"
d="m 161.17775,117.85719 v 23.36554 q 0,20.76935 -10.30578,39.77331 -10.21695,19.00395 -29.31819,19.00395 -11.01653,0 -18.65701,-5.60771 -7.551611,-5.71157 -14.392485,-20.8732 -6.752041,-15.26549 -6.752041,-32.29635 v -23.36554 q 0,-20.665499 10.216893,-39.669461 10.216893,-19.107806 29.318113,-19.107806 10.92769,0 18.47935,5.607725 7.64049,5.607727 14.48139,20.873203 6.92976,15.161629 6.92976,32.296339 z m -18.30165,0 q 0,-17.3424 -8.26241,-30.32325 -4.70867,-7.165428 -13.2376,-7.165428 -8.26239,0 -13.50413,7.892355 -7.906998,11.942383 -7.906998,29.596323 v 23.36554 q 0,17.44626 8.351218,30.32326 4.61983,7.16543 13.2376,7.16543 8.17356,0 13.4153,-7.89237 7.90702,-11.94237 7.90702,-29.59632 z"
id="path8" />
<path
style="font-weight:bold;font-size:89.3125px;font-family:'Courier New';-inkscape-font-specification:'Courier New Bold';letter-spacing:-8.37308px;stroke-width:1.67461"
d="M 54.800839,58.349248 V 166.67311 H 73.27526 q 6.604382,0 9.371083,2.79982 2.855949,2.70327 2.855949,7.14436 0,4.34453 -2.855949,7.14435 -2.766701,2.70327 -9.371083,2.70327 H 18.030494 q -6.604382,0 -9.4603308,-2.70327 -2.7667007,-2.79982 -2.7667007,-7.2409 0,-4.34454 2.7667007,-7.04781 2.8559488,-2.79982 9.4603308,-2.79982 H 36.504915 V 84.126852 l -16.332459,4.634176 q -3.926929,1.158544 -5.890395,1.158544 -3.480687,0 -6.0688915,-2.992905 -2.4989554,-2.992906 -2.4989554,-7.337446 0,-3.958358 1.8742165,-6.178902 1.8742167,-2.317087 7.8538604,-4.054903 z"
transform="matrix(0.99545738,0,0,1.0756271,-5.6882567,-3.6821097)"
id="path7" />
</g>
<g
id="g1"
transform="matrix(0.84984007,0,0,0.87855774,28.999003,5.2337341e-7)">
<path
style="font-weight:bold;font-size:89.3125px;font-family:'Courier New';-inkscape-font-specification:'Courier New Bold';letter-spacing:-8.37308px;stroke-width:1.73283"
d="m 184.13459,37.01017 q -3.34269,3.095908 -6.12102,4.409323 -2.77834,1.266508 -5.86056,1.266508 -7.1629,0 -12.54593,-6.191815 -5.33961,-6.191816 -5.33961,-15.385722 0,-7.176877 3.68997,-13.0403372 Q 162.99318,4.3096483e-6 172.15301,4.3096483e-6 q 6.55514,0 11.46064,4.2685995903517 4.90551,4.2216915 7.20632,12.2429061 2.30081,7.974308 2.30081,16.65223 0,14.729014 -10.549,23.641474 -8.16137,6.848524 -17.88555,6.848524 -5.38303,0 -8.33501,-2.345385 -1.99693,-1.547954 -1.99693,-4.080969 0,-2.063938 1.25893,-3.424261 1.30235,-1.407231 3.16905,-1.407231 1.04187,0 2.34422,0.703615 1.69304,0.938154 3.55974,0.938154 6.72879,0 12.4157,-4.925307 5.68691,-4.972215 7.03266,-12.102184 z m -1.25893,-15.151183 q -1.43258,-6.660892 -4.25433,-9.428446 -2.77834,-2.814461 -6.38149,-2.814461 -3.77681,0 -6.42491,3.142816 -2.6481,3.095907 -2.6481,8.255753 0,5.394384 2.6481,8.72483 2.69151,3.330446 6.12102,3.330446 6.03421,0 10.93971,-11.210938 z"
id="path6" />
<path
style="font-weight:bold;font-size:89.3125px;font-family:'Courier New';-inkscape-font-specification:'Courier New Bold';letter-spacing:-8.37308px;stroke-width:1.51638"
d="m 142.10195,39.730816 h -22.30654 q -3.49058,0 -4.15545,-0.234538 -0.99731,-0.375262 -1.69543,-1.641769 -0.69812,-1.313415 -0.69812,-2.955185 0,-1.594861 0.69812,-2.908276 0.69812,-1.313416 1.72867,-1.641769 0.66488,-0.234539 4.12221,-0.234539 h 22.30654 q 3.49059,0 4.15545,0.234539 0.99732,0.375261 1.69543,1.688676 0.69812,1.266508 0.69812,2.861369 0,1.64177 -0.69812,2.955185 -0.69811,1.266507 -1.72867,1.641769 -0.66487,0.234538 -4.12221,0.234538 z"
id="text2" />
</g>
</g>
</svg>
<svg xmlns="http://www.w3.org/2000/svg" width="734.222" height="756.943" viewBox="0 0 734.222 756.943"><path d="M357.038 52.288l-73.383 52.313-55.764 142.923-54.617 143.196c1.171.279 425.288-132.081 426.226-133.018C600.225 256.976 432.641.031 431.422 0c-.55-.014-34.023 23.515-74.384 52.288m181.711 32.471l-10.329 8.35c-.665.67 99.325 156.949 102.358 159.98 1.875 1.874 79.763 35.16 81.138 34.675 1.14-.403-160.629-210.253-162.275-210.505-.67-.103-5.572 3.272-10.892 7.5M57.422 239.973L.14 314.826c-1.188 1.714 3.842 4.638 68.856 40.032l71.106 37.861c1.12-.373 72.985-183.777 72.538-185.118-.294-.884-96.296-40.583-98.218-40.615-.55-.01-26.2 32.835-57 72.987m568.524 51.223l-91.43 199.175-88.086 193.416c.271.271.657.305.859.076s65.024-80.248 144.049-177.819l142.882-178.1c-.886-.775-103.789-42.998-104.792-42.998-.347 0-1.914 2.813-3.482 6.25m-243.024 63.521l-211.816 65.765c-.466.388 206.21 336.458 206.917 336.461.728.004 217.289-466.962 216.767-467.41-.202-.174-95.543 29.159-211.868 65.184m-343 16.73c0 .732 221.624 257.149 222.982 257.988.56.346 1.018.38 1.018.076 0-.611-122.164-199.524-125.049-203.612-1.152-1.632-18.448-11.562-48.125-27.63l-50.826-26.822"/></svg>

Before

Width:  |  Height:  |  Size: 4.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

+26
View File
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg version="1.1" viewBox="0 0 21.773 24.84" xmlns="http://www.w3.org/2000/svg">
<path d="m21.576 14.91a1 1 0 0 0-1.4-0.22l-9.29 6.86v0.29a1 1 0 1 1 0 1.91v0.05a1 1 0 0 0 0.6-0.19l9.88-7.3a1 1 0 0 0 0.21-1.4z"/>
<path d="m10.886 23.75a1 1 0 1 1 0-1.91v-0.29l-9.29-6.86a1 1 0 0 0-1.4 0.22 1 1 0 0 0 0.21 1.4l9.89 7.3a1 1 0 0 0 0.59 0.19z"/>
<path d="m10.886 20.84a2 2 0 1 0 2 2 2 2 0 0 0-2-2zm0 2.91a1 1 0 1 1 1-0.95 1 1 0 0 1-1 0.95z"/>
<path d="m2.8864 4.52a1 1 0 0 1-1-1v-2.51a1 1 0 1 1 2 0v2.51a1 1 0 0 1-1 1z"/>
<circle cx="2.8564" cy="12.38" r="1.01"/>
<circle cx="2.8564" cy="9.43" r="1.01"/>
<circle cx="2.8564" cy="6.47" r="1.01"/>
<path d="m18.886 7.45a1 1 0 0 1-1-1v-2.52a1 1 0 0 1 2 0v2.52a1 1 0 0 1-1 1z"/>
<circle cx="18.916" cy="12.39" r="1.01"/>
<circle cx="18.916" cy="9.4" r="1.01"/>
<circle cx="18.916" cy="1.01" r="1.01"/>
<path d="m10.886 16.38a1 1 0 0 1-1-1v-2.54a1 1 0 0 1 2 0v2.54a1 1 0 0 1-1 1z"/>
<circle cx="10.886" cy="18.31" r="1.01"/>
<circle cx="10.886" cy="9.89" r="1.01"/>
<circle cx="10.886" cy="6.94" r="1.01"/>
<path d="m14.886 10.43a1 1 0 0 1-1-1v-2.51a1 1 0 1 1 2 0v2.51a1 1 0 0 1-1 1z"/>
<circle cx="14.906" cy="3.96" r="1.01"/>
<circle cx="14.906" cy="15.3" r="1.01"/>
<circle cx="14.906" cy="12.35" r="1.01"/>
<circle cx="6.8664" cy="15.3" r="1.01"/>
<circle cx="6.8664" cy="6.94" r="1.01"/>
<circle cx="6.8664" cy="3.96" r="1.01"/>
<path d="m6.8864 13.38a1 1 0 0 1-1-1v-2.54a1 1 0 0 1 2 0v2.54a1 1 0 0 1-1 1z"/>
</svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

+1051 -860
View File
File diff suppressed because it is too large Load Diff
+3
View File
@@ -21,6 +21,7 @@ import droll from 'droll';
import morphdom from 'morphdom';
import { toggle as slideToggle } from 'slidetoggle';
import chalk from 'chalk';
import yaml from 'yaml';
/**
* Expose the libraries to the 'window' object.
@@ -98,6 +99,7 @@ export default {
morphdom,
slideToggle,
chalk,
yaml,
};
export {
@@ -121,4 +123,5 @@ export {
morphdom,
slideToggle,
chalk,
yaml,
};
+2 -3
View File
@@ -375,9 +375,6 @@
"Group by vendors Description": "ضع نماذج OpenAI في مجموعة واحدة، والنماذج الإنسانية في مجموعة أخرى، وما إلى ذلك. ويمكن دمجها مع الفرز.",
"Allow fallback routes": "السماح بمسارات الاحتياط",
"Allow fallback routes Description": "يختار النموذج البديل تلقائيًا إذا كان النموذج المحدد غير قادر على تلبية طلبك.",
"Scale API Key": "مفتاح API لـ Scale",
"Clear your cookie": "امسح ملف تعريف الارتباط الخاص بك",
"Alt Method": "طريقة بديلة",
"AI21 API Key": "مفتاح API لـ AI21",
"AI21 Model": "نموذج AI21",
"Google AI Studio API Key": "مفتاح واجهة برمجة تطبيقات Google AI Studio",
@@ -1379,6 +1376,8 @@
"char_import_6": "رابط PNG المباشر (راجع",
"char_import_7": "للمضيفين المسموح بهم)",
"char_import_8": "شخصية RisuRealm (رابط مباشر)",
"char_import_9": "شخصية Soulkyn (رابط مباشر)",
"char_import_10": "شخصية Perchance (رابط مباشر أو UUID + .gz)",
"Supports importing multiple characters.": "يدعم استيراد أحرف متعددة.",
"Write each URL or ID into a new line.": "اكتب كل عنوان URL أو معرف في سطر جديد.",
"Export for character": "تصدير للشخصية",
+2 -3
View File
@@ -375,9 +375,6 @@
"Group by vendors Description": "Platzieren Sie OpenAI-Modelle in einer Gruppe, anthropogene Modelle in einer anderen Gruppe usw. Kann mit Sortierung kombiniert werden.",
"Allow fallback routes": "Fallback-Routen zulassen",
"Allow fallback routes Description": "Das alternative Modell wird automatisch ausgewählt, wenn das ausgewählte Modell Ihre Anfrage nicht erfüllen kann.",
"Scale API Key": "Scale API-Schlüssel",
"Clear your cookie": "Löschen Sie Ihre Cookies",
"Alt Method": "Alternative Methode",
"AI21 API Key": "AI21 API-Schlüssel",
"AI21 Model": "AI21-Modell",
"Google AI Studio API Key": "Google AI Studio API-Schlüssel",
@@ -1379,6 +1376,8 @@
"char_import_6": "Direkter PNG-Link (siehe",
"char_import_7": "für erlaubte Hosts)",
"char_import_8": "RisuRealm-Charakter (Direktlink)",
"char_import_9": "Soulkyn-Charakter (Direktlink)",
"char_import_10": "Perchance-Charakter (Direktlink oder UUID + .gz)",
"Supports importing multiple characters.": "Unterstützt den Import mehrerer Zeichen.",
"Write each URL or ID into a new line.": "Schreiben Sie jede URL oder ID in eine neue Zeile.",
"Export for character": "Export für Zeichen",
+2 -3
View File
@@ -375,9 +375,6 @@
"Group by vendors Description": "Coloque los modelos OpenAI en un grupo, los modelos antrópicos en otro grupo, etc. Se puede combinar con la clasificación.",
"Allow fallback routes": "Permitir rutas de respaldo",
"Allow fallback routes Description": "El modelo alternativo se elige automáticamente si el modelo seleccionado no puede cumplir con tu solicitud.",
"Scale API Key": "Clave API de Scale",
"Clear your cookie": "Limpia tu cookie",
"Alt Method": "Método alternativo",
"AI21 API Key": "Clave API de AI21",
"AI21 Model": "Modelo de AI21",
"Google AI Studio API Key": "Clave API de Google AI Studio",
@@ -1379,6 +1376,8 @@
"char_import_6": "Enlace PNG directo (consulte",
"char_import_7": "para hosts permitidos)",
"char_import_8": "Personaje RisuRealm (Enlace directo)",
"char_import_9": "Personaje Soulkyn (Enlace directo)",
"char_import_10": "Personaje Perchance (enlace directo o UUID + .gz)",
"Supports importing multiple characters.": "Admite la importación de múltiples caracteres.",
"Write each URL or ID into a new line.": "Escriba cada URL o ID en una nueva línea.",
"Export for character": "Exportar para personaje",
+2 -3
View File
@@ -355,9 +355,6 @@
"Group by vendors": "Regrouper par fournisseurs",
"Group by vendors Description": "Placez les modèles OpenAI dans un groupe, les modèles Anthropic dans un autre groupe, etc. Peut être combiné avec le tri.",
"Allow fallback routes Description": "Le modèle alternatif est automatiquement sélectionné si le modèle choisi ne peut pas répondre à votre demande.",
"Scale API Key": "Clé API Scale",
"Clear your cookie": "Effacer vos cookies",
"Alt Method": "Méthode alternative",
"AI21 API Key": "Clé API AI21",
"AI21 Model": "Modèle AI21",
"Google AI Studio API Key": "Clé API Google AI Studio",
@@ -1301,6 +1298,8 @@
"char_import_6": "Lien PNG direct (voir",
"char_import_7": "pour les hôtes autorisés)",
"char_import_8": "Personnage de RisuRealm (lien direct)",
"char_import_9": "Personnage de Soulkyn (lien direct)",
"char_import_10": "Personnage de Perchance (lien direct ou UUID + .gz)",
"Supports importing multiple characters.": "Prend en charge l'importation de plusieurs caractères.",
"Write each URL or ID into a new line.": "Écrivez chaque URL ou identifiant dans une nouvelle ligne.",
"Export for character": "Exportation pour le personnage",
+2 -3
View File
@@ -375,9 +375,6 @@
"Group by vendors Description": "Setjið OpenAI módel í einn hóp, Anthropic módel í annan hóp osfrv. Hægt að sameina við flokkun.",
"Allow fallback routes": "Leyfa bakfallssvæði",
"Allow fallback routes Description": "Veldur hlutleysa vélbúnaðarinn við val þinn ef valið módel getur ekki uppfyllt beiðni þína.",
"Scale API Key": "Lykill API fyrir Scale",
"Clear your cookie": "Hreinsaðu kökuna þína",
"Alt Method": "Aðferð Bakmenn",
"AI21 API Key": "Lykill API fyrir AI21",
"AI21 Model": "AI21 Módel",
"Google AI Studio API Key": "Google AI Studio API lykill",
@@ -1379,6 +1376,8 @@
"char_import_6": "Beinn PNG hlekkur (sjá",
"char_import_7": "fyrir leyfilega gestgjafa)",
"char_import_8": "RisuRealm karakter (beinn hlekkur)",
"char_import_9": "Soulkyn karakter (beinn hlekkur)",
"char_import_10": "Perchance karakter (beinn hlekkur eða UUID + .gz)",
"Supports importing multiple characters.": "Styður innflutning á mörgum stöfum.",
"Write each URL or ID into a new line.": "Skrifaðu hverja vefslóð eða auðkenni í nýja línu.",
"Export for character": "Flytja út fyrir persónu",
+2 -3
View File
@@ -375,9 +375,6 @@
"Group by vendors Description": "Metti i modelli OpenAI in un gruppo, i modelli antropici in un altro gruppo, ecc. Può essere combinato con l'ordinamento.",
"Allow fallback routes": "Consenti percorsi alternativi",
"Allow fallback routes Description": "Il modello alternativo viene automaticamente scelto se il modello selezionato non può soddisfare la tua richiesta.",
"Scale API Key": "Chiave API di Scale",
"Clear your cookie": "Cancella il tuo cookie",
"Alt Method": "Metodo alternativo",
"AI21 API Key": "Chiave API di AI21",
"AI21 Model": "Modello AI21",
"Google AI Studio API Key": "Chiave API Google AI Studio",
@@ -1379,6 +1376,8 @@
"char_import_6": "Collegamento PNG diretto (fare riferimento a",
"char_import_7": "per gli host consentiti)",
"char_import_8": "Personaggio RisuRealm (collegamento diretto)",
"char_import_9": "Personaggio Soulkyn (collegamento diretto)",
"char_import_10": "Perchance Personaggio (collegamento diretto o UUID + .gz)",
"Supports importing multiple characters.": "Supporta l'importazione di più caratteri.",
"Write each URL or ID into a new line.": "Scrivi ogni URL o ID in una nuova riga.",
"Export for character": "Esporta per carattere",
+2 -3
View File
@@ -375,9 +375,6 @@
"Group by vendors Description": "OpenAI モデルを 1 つのグループに、Anthropic モデルを別のグループに配置するなどします。ソートと組み合わせることができます。",
"Allow fallback routes": "フォールバックルートを許可",
"Allow fallback routes Description": "選択したモデルが要求を満たせない場合、代替モデルが自動的に選択されます。",
"Scale API Key": "ScaleのAPIキー",
"Clear your cookie": "クッキーを消去する",
"Alt Method": "代替手法",
"AI21 API Key": "AI21のAPIキー",
"AI21 Model": "AI21モデル",
"Google AI Studio API Key": "Google AI Studio APIキー",
@@ -1381,6 +1378,8 @@
"char_import_6": "直接PNGリンク(参照",
"char_import_7": "許可されたホストの場合)",
"char_import_8": "RisuRealm キャラクター (直接リンク)",
"char_import_9": "Soulkyn キャラクター (直接リンク)",
"char_import_10": "Perchance キャラクター (直接リンクまたは UUID + .gz)",
"Supports importing multiple characters.": "複数のキャラクターのインポートをサポートします。",
"Write each URL or ID into a new line.": "各 URL または ID を新しい行に入力します。",
"Export for character": "キャラクターのエクスポート",
+2 -3
View File
@@ -384,9 +384,6 @@
"LEGACY": "유산",
"Force Instruct Mode formatting": "강제 지시 모드 형식",
"Force_Instruct_Mode_formatting_Description": "Instruct Mode와 이 모드가 모두 활성화된 경우 프롬프트는 SillyTavern에 의해 현재 형식을 사용하여 형식화됩니다.\n 고급 형식 설정(시스템 프롬프트 지시 제외) 비활성화된 경우 프롬프트는 OpenRouter에 의해 형식화됩니다.",
"Scale API Key": "Scale API 키",
"Clear your cookie": "쿠키 지우기",
"Alt Method": "대체 방법",
"AI21 API Key": "AI21 API 키",
"AI21 Model": "AI21 모델",
"Google AI Studio API Key": "Google AI Studio API 키",
@@ -1398,6 +1395,8 @@
"char_import_6": "직접 PNG 링크(참조",
"char_import_7": "허용된 호스트의 경우)",
"char_import_8": "RisuRealm 캐릭터 (직접링크)",
"char_import_9": "Soulkyn 캐릭터 (직접링크)",
"char_import_10": "Perchance 캐릭터 (직접 링크 또는 UUID + .gz)",
"Supports importing multiple characters.": "여러 문자 가져오기를 지원합니다.",
"Write each URL or ID into a new line.": "각 URL 또는 ID를 새 줄에 작성합니다.",
"Export for character": "캐릭터 내보내기",
+2 -3
View File
@@ -375,9 +375,6 @@
"Group by vendors Description": "Plaats OpenAI-modellen in één groep, antropische modellen in een andere groep, enz. Kan worden gecombineerd met sorteren.",
"Allow fallback routes": "Fallback-routes toestaan",
"Allow fallback routes Description": "Het alternatieve model wordt automatisch gekozen als het geselecteerde model niet aan uw verzoek kan voldoen.",
"Scale API Key": "Scale API-sleutel",
"Clear your cookie": "Wis uw cookie",
"Alt Method": "Alternatieve methode",
"AI21 API Key": "AI21 API-sleutel",
"AI21 Model": "AI21-model",
"MakerSuite API Key": "MakerSuite API-sleutel",
@@ -1379,6 +1376,8 @@
"char_import_6": "Directe PNG-link (zie",
"char_import_7": "voor toegestane hosts)",
"char_import_8": "RisuRealm-personage (directe link)",
"char_import_9": "Soulkyn-personage (directe link)",
"char_import_10": "Perchance-personage (directe link of UUID + .gz)",
"Supports importing multiple characters.": "Ondersteunt het importeren van meerdere tekens.",
"Write each URL or ID into a new line.": "Schrijf elke URL of ID op een nieuwe regel.",
"Export for character": "Exporteren voor karakter",
+2 -3
View File
@@ -375,9 +375,6 @@
"Group by vendors Description": "Coloque os modelos OpenAI em um grupo, os modelos antrópicos em outro grupo, etc.",
"Allow fallback routes": "Permitir rotas de fallback",
"Allow fallback routes Description": "O modelo alternativo será escolhido automaticamente se o modelo selecionado não puder atender à sua solicitação.",
"Scale API Key": "Chave da API Scale",
"Clear your cookie": "Limpe seu cookie",
"Alt Method": "Método Alternativo",
"AI21 API Key": "Chave da API AI21",
"AI21 Model": "Modelo AI21",
"Google AI Studio API Key": "Chave API Google AI Studio",
@@ -1379,6 +1376,8 @@
"char_import_6": "Link PNG direto (consulte",
"char_import_7": "para hosts permitidos)",
"char_import_8": "Personagem RisuRealm (link direto)",
"char_import_9": "Personagem Soulkyn (link direto)",
"char_import_10": "Personagem Perchance (Link Direto ou UUID + .gz)",
"Supports importing multiple characters.": "Suporta importação de vários caracteres.",
"Write each URL or ID into a new line.": "Escreva cada URL ou ID em uma nova linha.",
"Export for character": "Exportar para personagem",
+145 -9
View File
@@ -105,7 +105,7 @@
"Adjust context size to worker capabilities": "Подстраивать размер контекста под возможности рабочих машин",
"Adjust response length to worker capabilities": "Подстраивать длину ответа под возможности рабочих машин",
"API key": "API-ключ",
"Tabby API key": "Tabby API-ключ",
"Tabby API key": "Ключ от Tabby API",
"Get it here:": "Получите здесь:",
"Register": "Зарегистрироваться",
"TogetherAI Model": "Модель TogetherAI",
@@ -142,8 +142,6 @@
"Get your key from": "Получите ключ в",
"Anthropic's developer console": "консоли разработчика Anthropic",
"Claude Model": "Модель Claude",
"Scale API Key": "Ключ от Scale API",
"Alt Method": "Альтернативный метод",
"AI21 API Key": "Ключ от API AI21",
"AI21 Model": "Модель AI21",
"View API Usage Metrics": "Посмотреть статистику использования API",
@@ -275,7 +273,7 @@
"Chat History": "История чатов",
"Content": "Содержание",
"Selective": "Выборочно",
"Disable": "Отключено",
"Disable": "Откл.",
"Back to parent chat": "Вернуться в основной чат",
"Convert to group": "Сделать групповым",
"Start new chat": "Начать новый чат",
@@ -509,7 +507,7 @@
"Restore default prompt": "Восстановить станндартный промпт",
"New preset": "Новый пресет",
"Delete preset": "Удалить пресет",
"API Connections": "Соединения с API",
"API Connections": "Соединение с API",
"Can help with bad responses by queueing only the approved workers. May slowdown the response time.": "Может помочь при плохих ответах, делая запросы только к доверенным рабочим машинам. Может замедлить время ответа.",
"Clear your API key": "Стереть ключ от API",
"Refresh models": "Обновить модели",
@@ -965,6 +963,8 @@
"char_import_5": "Персонаж с AICharacterCards.com (прямая ссылка или ID)",
"char_import_6": "Прямая ссылка на PNG-файл (список разрешённых хостов находится в",
"char_import_7": ")",
"char_import_9": "Персонаж с Soulkyn (прямая ссылка)",
"char_import_10": "Персонаж с Perchance (прямая ссылка или UUID + .gz)",
"Grammar String": "Грамматика",
"GBNF or EBNF, depends on the backend in use. If you're using this you should know which.": "GBNF или EBNF, зависит от бэкенда. Если вы это используете, то, скорее всего, сами знаете, какой именно.",
"Account": "Аккаунт",
@@ -1253,7 +1253,6 @@
"vLLM Model": "Модель vLLM",
"Aphrodite Model": "Модель Aphrodite",
"Peek a password": "Посмотреть пароль",
"Clear your cookie": "Clear your cookie",
"Add Chat Start and Example Separator to a list of stopping strings.": "Использовать Начало чата и Разделитель примеров сообщений в качестве стоп-строк.",
"Context Order": "Context Order",
"Summary": "Summary",
@@ -1747,8 +1746,6 @@
"dot quota_error": "имеется достаточно кредитов.",
"If you have sufficient credits, please try again later.": "Если кредитов достаточно, то повторите попытку позднее.",
"Proxy preset '${0}' not found": "Пресет '${0}' не найден",
"Window.ai returned an error": "Window.ai ответил ошибкой",
"Extension is not installed": "Расширение не установлено",
"Update or remove your reverse proxy settings.": "Измените или удалите ваши настройки прокси.",
"An error occurred while importing prompts. More info available in console.": "В процессе импорта произошла ошибка. Подробную информацию см. в консоли.",
"Could not import prompts. Export failed validation.": "Не удалось импортировать промпты. Не пройдена валидация при экспорте.",
@@ -2418,5 +2415,144 @@
"Update enabled": "Обновить включенные",
"Could not connect to API": "Не удалось подключиться к API",
"Connected to API": "Соединение с API установлено",
"Go back": "Назад"
"Go back": "Назад",
"Recent Chats": "Недавние чаты",
"Docs": "Документация",
"Temporary Chat": "Временный чат",
"Load": "Загрузить",
"Import from JSONL": "Импорт из формата JSONL",
"**Hint:** Set any character as your welcome page assistant from their \"More...\" menu.": "**Подсказка**: задайте персонажа, который будет встречать вас на главной странице. Для этого зайдите в меню \"Ещё...\" в интерфейсе карточки.",
"[The chat is empty]": "[Чат пуст]",
"Show more recent chats": "Больше недавних чатов",
"Show less recent chats": "Меньше недавних чатов",
"Rename chat": "Переименовать чат",
"Delete chat": "Удалить чат",
"Hide recent chats": "Скрыть недавние чаты",
"Show recent chats": "Показать недавние чаты",
"Set / Unset as Welcome Page Assistant": "Установить / снять с роли помощника на экране приветствия",
"${0} is a system assistant. Choose another character.": "Персонаж ${0} выбран в качестве системного помощника. Выберите другого.",
"Set ${0} as your assistant.": "Персонаж ${0} установлен в качестве помощника.",
"${0} is no longer your assistant.": "Персонаж ${0} снят с роли помощника.",
"Manage API keys": "Управление ключами",
"Key:": "Ключ:",
"No secrets saved.": "Ключей нет.",
"Add Secret": "Добавить ключ",
"Enter the secret value:": "Ключ:",
"Enter a label for the secret (optional):": "Название ключа (необязательно):",
"Copy ID": "Копировать ID",
"Rename Secret": "Переименовать ключ",
"Enter new label for the secret:": "Новое название ключа:",
"Delete Secret: ${0}": "Удалить ключ ${0}",
"Are you sure you want to delete this secret? This action cannot be undone.": "Вы точно хотите удалить этот ключ? Отменить будет невозможно.",
"Secret ID copied to clipboard.": "ID ключа скопирован в буфер обмена.",
"The key exposure might be disabled by the server config.": "Вероятно, в настройках сервера отключена возможность раскрытия ключей.",
"Failed to copy secret value": "Не удалось скопировать значение",
"Select": "Выделить",
"Allow compressing requests by removing messages from the middle of the prompt.": "Включает возможность сжатия запроса путём удаления сообщений из середины промпта.",
"Allow": "Разрешить",
"Forbid": "Запретить",
"Auto": "Авто",
"Max prompt cost:": "Макс. стоимость промпта:",
"Unknown": "Неизвестно",
"enable_functions_desc_4": "Не работает, если выбрана постобработка промпта с отключенными функциями!",
"This setting affects visibility only.": "Влияет только на видимость.",
"openrouter_web_search_fee": "Платная опция! Добавляет $0,02 к стоимости каждого промпта.",
"prompt_post_processing_semi_tools": "Semi-strict (чередовать роли, функции включены)",
"prompt_post_processing_strict_tools": "Strict (чередовать роли, сначала пользователь; функции включены)",
"prompt_post_processing_single": "Только одно сообщение пользователя (функции отключены)",
"prompt_post_processing_merge_tools": "Объединять идущие подряд сообщение с одной ролью (функции включены)",
"completions note prefix": "Постфикс ",
"suffix will be added automatically.": "будет добавлен автоматически.",
"Tabby Model": "Модель Tabby",
"Experimental feature. Use at your own risk.": "Экспериментальная возможность. Используйте на собственный риск.",
"Tabby model hint prefix": "Чтобы иметь возможность менять модели на лету, укажите параметр ",
"must be set in Tabby's config.yml to switch models.": " в файле config.yml на сервере Tabby.",
"Use an admin API key.": "Используйте admin-ключ.",
"Use OpenRouter website setting": "Использовать указанную на сайте OpenRouter",
"Allocates a portion of the response length for thinking (min: 1024 tokens, low: 10%, medium: 25%, high: 50%, max: 95%), but minimum 1024 tokens. Auto does not request thinking.": "Отводит часть ответа под рассуждения (Минимальные: 10%, Обычные: 25%, Подробные: 50%, Максимальные: 95%), но минимум 1024 токена. При выборе значение Авто рассуждения не запрашиваются.",
"Use system prompt": "Включить системный промпт",
"Send inline videos": "Отправлять inline-видео",
"video_inlining_hint_1": "Отправляет модели видео, если она поддерживает такую возможность. Чтобы прикрепить видео к чату, используйте на любом сообщении кнопку",
"video_inlining_hint_2": "либо меню",
"video_inlining_hint_3": ".",
"video_inlining_hint_4": "Видео должно весить не более 20 Мб и длиться не дольше 1 минуты.",
"Allocates a portion of the response length for thinking (Flash 2.5/Pro 2.5) (min: 0/128 tokens, low: 10%, medium: 25%, high: 50%, max: 24576/32768 tokens). Auto lets the model decide.": "Отводит часть ответа под рассуждения (Flash 2.5/Pro 2.5) (Минимальные: 0/128 токенов, Поверхностные: 10%, Обычные: 25%, Подробные: 50%, Максимальные: 24576/32768 токенов). При выборе значения Авто модель определяет объём самостоятельно.",
"Google Vertex AI Configuration": "Настройки Google Vertex AI",
"Authentication Mode": "Режим аутентификации:",
"Express Mode (API Key)": "Express Mode (ключ от API)",
"Full Version (Service Account)": "Полновесный (аккаунт на сервисе)",
"Google Vertex AI API Key": "Ключ от Google Vertex AI",
"Service Account Configuration": "Настройки аккаунта",
"Region": "Регион",
"Service Account JSON Content": "Данные аккаунта в формате JSON",
"Validate JSON": "Провалидировать JSON",
"View available regions and models": "Посмотреть список доступных регионов и моделей",
"Click to Edit": "Редактирование по клику",
"Click the message text in the chat log to edit it.": "Нажмите на текст сообщения в чате, чтобы приступить к редактированию.",
"Rounded": "Закруглённые",
"Notifications:": "Уведомления:",
"Top Left": "Слева сверху",
"Top Center": "Сверху по центру",
"Top Right": "Справа сверху",
"Bottom Left": "Снизу слева",
"Bottom Center": "Снизу по центру",
"Bottom Right": "Снизу справа",
"Additional Matching Sources": "Доп. места для поиска",
"Character Personality": "Резюме по личности персонажа",
"Cap the number of entry activation recursions": "Макс. глубина рекурсии при активации записи другой записью",
"Animated background thumbnails": "Статичное превью анимированных фонов",
"Make animated backgrounds static in the selection menu. This will reduce UI and network lag if you have a large amount. This is only a change for the selection menu.": "Отключить анимацию фонов при их предпросмотре в меню выбора. Может помочь снизить объём лагов интерфейса и/или интернет-соединения. Затрагивает только меню выбора.",
"Clean-Up": "Уборка",
"Find and delete backups, unused chats, files, images, etc.": "Найти и удалить бэкапы, неиспользуемые чаты, файлы, картинки и т.д.",
"Once deleted, the files will be gone forever!": "Восстановить удалённые файлы будет невозможно!",
"Make sure to back up your data in advance.": "Перед удалением не забывайте делать копии.",
"No results yet. Tap 'Scan' to start scanning.": "Пока ничего не найдено. Нажмите \"Начать сканирование\", чтобы запустить процесс поиска.",
"Scan": "Начать сканирование",
"Chats": "Чаты",
"Chat files associated with deleted characters.": "Чаты с удалёнными персонажами.",
"Group Chats": "Групповые чаты",
"Chat files associated with deleted groups.": "Чаты с удалёнными группами.",
"Chat Backups": "Копии чатов",
"Automatically generated chat backups.": "Автоматически создаваемые бэкапы чатов.",
"Settings Backups": "Копии настроек",
"Automatically generated settings backups.": "Автоматически создаваемые бэкапы настроек.",
"Delete all items in this category": "Удалить всё в этой категории",
"View item content": "Посмотреть содержимое",
"Download item": "Скачать содержимое",
"Delete this item": "Удалить содержимое",
"This will permanently delete the file. THIS CANNOT BE UNDONE!": "Файл будет удалён навсегда. ОТМЕНИТЬ БУДЕТ НЕВОЗМОЖНО!",
"This will permanently delete all files in this category. THIS CANNOT BE UNDONE!": "Все файлы в этой категории будут удалены. ОТМЕНИТЬ БУДЕТ НЕВОЗМОЖНО!",
"Close popup": "Закрыть окно",
"Branch or tag name (optional)": "Ветка или тэг (необязательно)",
"ext_regex_bulk_edit": "Массовое редактирование",
"Enable": "Вкл.",
"Provided free of charge by Pollinations.AI": "Предоставляется бесплатно сервисом Pollinations.AI",
"Avoid sending sensitive information. Provider's outputs may include ads.": "Не отправляйте чувствительную информацию. Тексты от провайдера могут содержать рекламу.",
"Pollinations Model": "Модель Pollinations",
"Character details are hidden.": "Информация о персонаже скрыта.",
"Allow / Forbid the use of global styles for this character.": "Разрешить/запретить использование персонажем глобальных стилей.",
"Choose how to apply CSS style tags if they are defined in Creator's Notes of this character:": "Выберите, к чему применять CSS-теги, объявленные в Заметках создателя у этого персонажа:",
"CAUTION: Malformed styles may cause issues.": "ОСТОРОЖНО: некорректно размеченные стили могут приводить к неожиданному поведению.",
"Just to Creator's Notes": "Только к Заметкам создателя",
"Apply to the entire app": "Ко всему приложению",
"Pin greeting message styles": "CSS из первого сообщения активен всегда",
"Always render style tags from greetings, even if the message is unloaded due to lazy loading.": "Всегда учитывать CSS-стили из первого сообщения, даже если оно на данный момент скрыто механизмом ленивой загрузки.",
"Secret": "Ключ",
"Save and connect": "Сохранить и подключиться",
"No scripts found": "Скриптов нет",
"Are you sure you want to delete this regex script?": "Вы точно хотите удалить этот скрипт?",
"Are you sure you want to move this regex script to scoped?": "Вы точно хотите сделать этот скрипт локальным?",
"Cannot edit scoped scripts in group chats.": "Локальные скрипты невозможно редактировать в групповом чате.",
"No character selected.": "Не выбран персонаж.",
"Are you sure you want to move this regex script to global?": "Вы точно хотите сделать этот скрипт глобальным?",
"Could not save regex script: The script name was undefined or empty!": "Не удалось сохранить regex-скрипт: Не указано либо не определено название скрипта!",
"This regex script will not work, but was saved anyway: A find regex isn't present.": "Этот regex не будет работать, но всё равно сохранён: Не указано рег. выражение для поиска",
"Ephemerality": "Иллюзорность",
"This regex script will not work, but was saved anyway: One \"Affects\" checkbox must be selected!": "Этот regex не будет работать, но всё равно сохранён: Должна быть отмечена хотя бы одна галочка в блоке \"Затрагивает\"!",
"This character has embedded regex script(s).": "У этого персонажа имеются встроенные regex скрипты.",
"Would you like to allow using them?": "Должны ли они продолжать работу?",
"If you want to do it later, select 'Regex' from the extensions menu.": "Если захотите включить их позже, выберите в меню расширений пункт \"Regex\".",
"Are you sure you want to delete the selected regex scripts?": "Вы точно хотите удалить выбранные скрипты?",
"Regex script \"${0}\" imported.": "Успешно импортирован скрипт ${0}",
"Invalid regex object.": "Некорректный объект рег. выражения."
}
+2 -3
View File
@@ -375,9 +375,6 @@
"Group by vendors Description": "Помістіть моделі OpenAI в одну групу, моделі Anthropic в іншу групу тощо. Можна поєднати з сортуванням.",
"Allow fallback routes": "Дозволити резервні маршрути",
"Allow fallback routes Description": "Автоматично вибирає альтернативну модель, якщо вибрана модель не може задовольнити ваш запит.",
"Scale API Key": "Ключ API для Scale",
"Clear your cookie": "Очистіть файл cookie",
"Alt Method": "Альтернативний метод",
"AI21 API Key": "Ключ API для AI21",
"AI21 Model": "Модель AI21",
"Google AI Studio API Key": "Ключ API Google AI Studio",
@@ -1379,6 +1376,8 @@
"char_import_6": "Пряме посилання на PNG (див",
"char_import_7": "для дозволених хостів)",
"char_import_8": "Персонаж RisuRealm (пряме посилання)",
"char_import_9": "Персонаж Soulkyn (пряме посилання)",
"char_import_10": "Персонаж Perchance (пряме посилання або UUID + .gz)",
"Supports importing multiple characters.": "Підтримується імпорт кількох символів.",
"Write each URL or ID into a new line.": "Напишіть кожну URL-адресу або ідентифікатор у новому рядку.",
"Export for character": "Експорт для персонажа",
+2 -3
View File
@@ -375,9 +375,6 @@
"Group by vendors Description": "Xếp các mô hình OpenAI vào một nhóm, các mô hình Anthropic vào một nhóm khác, v.v. Có thể kết hợp với việc sắp xếp.",
"Allow fallback routes": "Cho phép các tuyến đường phụ",
"Allow fallback routes Description": "Bot thay thế tự động nếu mô hình được chọn không thể đáp ứng yêu cầu của bạn.",
"Scale API Key": "Scale API Key",
"Clear your cookie": "Xóa cookie",
"Alt Method": "Phương pháp thay thế",
"AI21 API Key": "AI21 API Key",
"AI21 Model": "Model của AI21",
"Google AI Studio API Key": "Google AI Studio API Key",
@@ -1379,6 +1376,8 @@
"char_import_6": "Nhập PNG trực tiếp (tham khảo",
"char_import_7": "đối với các máy chủ được phép)",
"char_import_8": "RisuRealm (URL trực tiếp)",
"char_import_9": "Soulkyn (URL trực tiếp)",
"char_import_10": "Perchance (Nhập URL trực tiếp hoặc UUID + .gz)",
"Supports importing multiple characters.": "Hỗ trợ nhập nhiều ký tự.",
"Write each URL or ID into a new line.": "Viết mỗi URL hoặc ID vào một dòng mới.",
"Export for character": "Xuất cho nhân vật",
+3 -4
View File
@@ -429,9 +429,6 @@
"Group by vendors": "按厂商分组",
"Group by vendors Description": "将 OpenAI 模型放在一组,将 Anthropic 模型放在另一组,等等。可以与排序结合。",
"To use instruct formatting, switch to OpenRouter under Text Completion API.": "To use instruct formatting, switch to OpenRouter under Text Completion API.",
"Scale API Key": "Scale API密钥",
"Clear your cookie": "清除你的 Cookie",
"Alt Method": "备用方法",
"AI21 API Key": "AI21 API 密钥",
"AI21 Model": "AI21 模型",
"Google AI Studio API Key": "Google AI Studio API 密钥",
@@ -670,7 +667,7 @@
"Square": "正方形",
"Rectangle": "矩形",
"Chat Style:": "聊天风格:",
"Flat": "扁平\n气泡\n文档",
"Flat": "扁平",
"Bubbles": "气泡",
"Document": "文档",
"Specify colors for your theme.": "指定您的主题的颜色。",
@@ -1893,6 +1890,8 @@
"char_import_6": "被允许的PNG直链(请参阅",
"char_import_7": ")",
"char_import_8": "RisuRealm 角色(直链)",
"char_import_9": "Soulkyn 角色(直链)",
"char_import_10": "Perchance 角色(直链或UUID + .gz)",
"Supports importing multiple characters.": "支持导入多个角色。",
"Write each URL or ID into a new line.": "将每个 URL 或 ID 写入新行。",
"Enter the Git URL of the extension to install": "输入扩展程序的 Git URL 以安装",
+150 -130
View File
@@ -19,7 +19,7 @@
"Delete the preset": "刪除預設設定檔",
"novelaipresets": "NovelAI 預設設定檔",
"Default": "預設",
"openaipresets": "OpenAI 預設設定檔",
"openaipresets": "聊天補全預設設定檔",
"Text Completion presets": "文字補全預設設定檔",
"AI Module": "AI 模組",
"Changes the style of the generated text.": "變更生成文字的樣式。",
@@ -376,9 +376,6 @@
"Group by vendors Description": "將 OpenAI、Anthropic 等模型放各自供應商的群組中。可以與排序功能結合使用。",
"Allow fallback routes": "允許備援路徑",
"Allow fallback routes Description": "如果選擇的模型無法滿足要求,會自動選擇替代模型。",
"Scale API Key": "Scale API 金鑰",
"Clear your cookie": "清除您的 Cookie",
"Alt Method": "替代方法",
"AI21 API Key": "AI21 API 金鑰",
"AI21 Model": "AI21 模型",
"Google AI Studio API Key": "Google AI Studio API 金鑰",
@@ -506,9 +503,9 @@
"Global Lore First": "全域知識書優先",
"Entries can activate other entries by mentioning their keywords": "條目可以透過提及其關鍵字來啟用其他條目",
"Recursive Scan": "遞迴掃描",
"Lookup for the entry keys in the context will respect the case": "在上下文中查詢條目鍵將區分大小寫",
"Lookup for the entry keys in the context will respect the case": "在上下文中查詢條目關鍵字將區分大小寫",
"Case Sensitive": "區分大小寫",
"If the entry key consists of only one word, it would not be matched as part of other words": "如果條目鍵僅包含一個詞,則不會作為其他詞的一部分進行配對",
"If the entry key consists of only one word, it would not be matched as part of other words": "如果條目關鍵字僅包含一個詞,則不會作為其他詞的一部分進行配對",
"Match Whole Words": "完全配對",
"Only the entries with the most number of key matches will be selected for Inclusion Group filtering": "只有符合最多鍵值數量的條目將被選中進行包含群組過濾",
"Use Group Scoring": "使用群組評分",
@@ -615,9 +612,9 @@
"Compact Input Area (Mobile)": "緊湊的聊天訊息輸入欄(行動版)",
"In the Character Management panel, show quick selection buttons for favorited characters": "在角色管理面板中,顯示加入到最愛角色的快速選擇按鈕。",
"Characters Hotswap": "角色卡快捷選單",
"Enable magnification for zoomed avatar display.": "啟用放大顯示頭像",
"Enable magnification for zoomed avatar display.": "啟用放大功能檢視頭像。",
"Avatar Hover Magnification": "頭像懸停時的放大倍數",
"Enables a magnification effect on hover when you display the zoomed avatar after clicking an avatar's image in chat.": "當你在聊天中點選頭像的圖片後,這會啟用滑鼠懸停時的放大效果。",
"Enables a magnification effect on hover when you display the zoomed avatar after clicking an avatar's image in chat.": "當您點選訊息中的角色頭像後,將啟用滑鼠懸停時的放大效果。",
"Show tagged character folders in the character list": "在角色列表中顯示標籤角色資料夾。",
"Tags as Folders": "標籤作為資料夾",
"Tags_as_Folders_desc": "標籤必須在「標籤管理」選單中標記為資料夾才可適用。點選這裡開啟。",
@@ -769,7 +766,7 @@
"Name": "名稱",
"Enter your name": "輸入您的名字",
"Click to set a new User Name": "設定新的使用者名稱",
"Click to lock your selected persona to the current chat. Click again to remove the lock.": "鎖定目前所選的使用者角色至本次聊天。再次點選將移除鎖定。",
"Click to lock your selected persona to the current chat. Click again to remove the lock.": "綁定目前所選的使用者角色至本次聊天。再次點選將移除綁定。",
"Click to set user name for all messages": "設定所有訊息的使用者名稱",
"Persona Description": "使用者角色描述",
"Example: [{{user}} is a 28-year-old Romanian cat girl.]": "範例:[{{user}} 是一個 28 歲的羅馬尼亞貓娘。]",
@@ -903,8 +900,8 @@
"@ Depth": "@ 深度",
"Role": "角色",
"Talkativeness": "健談度",
"How often the character speaks in group chats!": "角色在群組聊天中說話的頻率!",
"How often the character speaks in": "角色說話的頻率",
"How often the character speaks in group chats!": "角色在群組聊天中的發言頻率!",
"How often the character speaks in": "角色發言頻率",
"group chats!": "群組聊天!",
"Shy": "寡言",
"Normal": "正常",
@@ -970,10 +967,10 @@
"Comma separated list": "逗號分隔列表",
"Switch to plaintext mode": "切換到純文字模式",
"Logic": "邏輯",
"AND ANY": "AND 任何",
"AND ALL": "AND 所有",
"NOT ALL": "NOT 所有",
"NOT ANY": "NOT 任何",
"AND ANY": "且「包含任一」",
"AND ALL": "且「包含全部」",
"NOT ALL": "且「未完全包含」",
"NOT ANY": "且「完全不含」",
"(ignored if empty)": "(如果為空則忽略)",
"Optional Filter": "選填過濾器",
"Keywords or Regexes (ignored if empty)": "關鍵字或正規表示式(如果為空則忽略)",
@@ -993,11 +990,11 @@
"Filter to Character(s)": "角色篩選",
"Character Exclusion": "角色排除",
"-- Characters not found --": "-- 未找到角色 --",
"Inclusion Group": "包含的群組",
"Inclusion Groups ensure only one entry from a group is activated at a time, if multiple are triggered.Documentation: World Info - Inclusion Group": "如果觸發多個條目,包含群組可確保一次僅啟動一組中的一個條目。\r支援多個以逗號分隔的群組。\r\r文件:世界資訊——包容性集團",
"Prioritize this entry: When checked, this entry is prioritized out of all selections.If multiple are prioritized, the one with the highest 'Order' is chosen.": "優先考慮此條目:選取後,此條目將在所有選擇中優先。\r如果有多個優先順序,則選擇「順序」最高的一個。",
"Only one entry with the same label will be activated": "僅會啟用具有相同標籤的一個條目",
"A relative likelihood of entry activation within the group": "群組內條目啟用的相對可能性",
"Inclusion Group": "納入群組",
"Inclusion Groups ensure only one entry from a group is activated at a time, if multiple are triggered.Documentation: World Info - Inclusion Group": "納入群組可確保在同一群組中,同時被觸發的多個條目僅有一個會被啟用。\r支援多個以逗號分隔的群組。\r詳見 SillyTavern 官方文件:World Info - Inclusion Group",
"Prioritize this entry: When checked, this entry is prioritized out of all selections.If multiple are prioritized, the one with the highest 'Order' is chosen.": "優先此條目:勾選後,此條目將在所有可選條目中被優先考慮。\r若有多個條目同時設為優先,將選擇「順序(Order)」數值最高的條目。",
"Only one entry with the same label will be activated": "僅啟用一個具有相同標籤的條目",
"A relative likelihood of entry activation within the group": "此條目在群組中被選中的相對可能性",
"Group Weight": "群組權重",
"Selective": "選擇性",
"Use Probability": "使用機率",
@@ -1134,7 +1131,7 @@
"Manage chat files": "管理聊天檔案",
"Delete messages": "刪除訊息",
"Regenerate": "重新生成",
"Ask AI to write your message for you": "請 AI 為您撰寫訊息",
"Ask AI to write your message for you": "由 AI 扮演您的角色撰寫訊息",
"Impersonate": "AI 扮演使用者",
"Continue": "繼續",
"Bind user name to that avatar": "將使用者名稱附加到該頭像",
@@ -1384,6 +1381,8 @@
"char_import_6": "直接 PNG 連結(請參閱",
"char_import_7": "對於允許的主機)",
"char_import_8": "RisuRealm 角色(直接連結)",
"char_import_9": "Soulkyn 角色(直接連結)",
"char_import_10": "Perchance 角色(直接連結或 ID + .gz)",
"Supports importing multiple characters.": "支援匯入多個字元。",
"Write each URL or ID into a new line.": "將每個 URL 或 ID 寫入新行。",
"Export for character": "匯出字元",
@@ -2382,7 +2381,7 @@
"Do you want to remove these fields before exporting?": "是否要在匯出前移除這些欄位?",
"Delete the preset? This action is irreversible and your current settings will be overwritten.": "確定刪除此預設設定檔?刪除後無法復原,且此設定將被覆蓋。",
"Update all": "全部更新",
"Automatically chooses an alternative provider if chosen providers can't serve your request.": "當所選提供者無法滿足您的請求時,自動選擇替代提供者。",
"Automatically chooses an alternative provider if chosen providers can't serve your request.": "當所選供應商無法滿足您的請求時,自動選擇替代供應商。",
"Use extension settings": "使用擴充功能設定",
"To use instruct formatting, switch to OpenRouter under Text Completion API.": "若要使用指令格式,請在文字補全 API 下切換至 OpenRouter。",
"Automatically 'continue' a response if the model stopped before reaching a certain amount of tokens.": "如果模型在達到一定數量的符元前停止,則自動繼續生成回應。",
@@ -2456,7 +2455,7 @@
"openai_reasoning_effort_low": "低",
"openai_reasoning_effort_medium": "中",
"openai_reasoning_effort_high": "高",
"Reasoning": "推理 Reasoning",
"Reasoning": "推理",
"reasoning_auto_parse": "自動解析主要內容中推理區塊,需定義且不為空的前綴與後綴欄位。",
"Auto-Parse": "自動解析",
"reasoning_auto_expand": "自動展開推理區塊。",
@@ -2514,106 +2513,6 @@
"Note: Themes can be made/applied by going to the ": "注意:主題可通過前往以下位置進行創建/應用",
"Theme Name": "主題名稱",
"An unknown error occurred while counting tokens. Further information may be available in console.": "計算符元時發生未知錯誤。更多資訊可能可在主控台(console)中查看。",
"Qvink Memory": "Qvink Memory(進階聊天記憶)",
"Toggle whether memory is enabled for this chat specifically (overrides all settings).": "切換是否為此聊天啟用記憶功能(將覆蓋所有設定)。",
"Toggle Chat Memory": "切換聊天記憶",
"Preview current memory state (the exact text that will be injected into your context).": "預覽目前記憶狀態(包含將嵌入上下文的具體內容)。",
"Copy ALL memories to clipboard (all memories in the entire chat, not just those injected).": "將所有記憶複製到剪貼簿(包含整個聊天的所有記憶,而非僅限於注入的部分)。",
"Just refreshes which memories are included and re-renders the memories under each message, doesn't change summaries. This is done automatically all the time, the button is here just in case.": "不影響摘要,僅更新已包含的聊天記憶,並重新顯示在每則訊息下方。此過程通常會自動執行,按鈕只是備用選項。",
"Active Settings Profile ": "目前設定檔",
"Create, edit, and save configuration profiles for this extension.": "建立、編輯及儲存此擴充功能的設定檔。",
"The currently selected profile": "目前選取的設定檔",
"Save current profile": "儲存此設定檔",
"Rename current profile": "重新命名此設定檔",
"Create new profile": "建立新設定檔",
"Restore current profile": "還原此設定檔",
"Delete current profile": "刪除此設定檔",
"Set as default profile for current character": "設為目前角色的預設設定檔",
"Summarization": "摘要",
"Customize the prompt used to summarize a given message": "自訂用於摘要指定訊息的提示詞",
"Edit the summary prompt": "編輯摘要提示",
"Preview the filled-in summary prompt, using the last message as an example.": "以最後一則訊息為例,預覽填充完成的摘要提示",
"Mass re-summarization. Brings up dialog to choose subsets of messages to summarize or re-summarize.": "批量重新摘要:開啟對話框以選擇訊息子集進行摘要或重新摘要。",
"Stop all summarization immediately.": "立即停止所有摘要。",
"New messages will be automatically summarized if they will be included in short-term memory.": "如果新訊息將被納入短期記憶,將自動進行摘要。",
"Auto Summarize": "自動摘要",
"Auto-summarization will be triggered before a new message is sent instead of after.": "自動摘要將在發送新訊息之前觸發。",
"Auto Summarize Before Generation": "在生成內容前自動摘要",
"Show the progress bar when auto-summarizing more than 1 message.": "在自動摘要多於 1 則訊息時顯示進度條。",
"Auto Summarize Progress Bar": "自動摘要進度條",
"Number of messages to delay summarization (0 = summarize up to the most recent message, 1 = lag behind by one message, etc.)": "延遲摘要的訊息數量(0 = 摘要至最新訊息,1 = 延遲摘要 1 則訊息,以此類推)。",
"Auto Summarize Message Lag": "自動摘要訊息延遲",
"Wait until this many messages before auto-summarizing them all in sequence (1 = summarize every message immediately, 2 = summarize when you have two ready, etc). Still summarizes one at a time.": "在訊息數量達到此設定值後,依序自動摘要(1 = 即時摘要每則訊息,2 = 等待 2 則訊息後再摘要,以此類推)。摘要將逐條執行。",
"Auto Summarize Batch Size": "自動摘要批次大小",
"The maximum number of messages back that auto-summarization will apply (-1 to disable).": "自動摘要可回溯的訊息最大數量(-1 表示禁用此功能)。",
"Auto Summarize Message Limit": "自動摘要訊息上限",
"Time in seconds to wait between summarizations. May be needed if you are using a external API with a rate limit.": "每次摘要的間隔時間(秒)。此設定適用於使用具有請求速率限制的外部 API。",
"Summarization Time Delay": "摘要時間延遲",
"The maximum token length a summary is allowed to be before cutting it off. Use the {{words}} macro in the summarization prompt to get this value.": "摘要在被截斷前允許的最大符元(token)長度。可在摘要提示中使用 {{words}} 巨集以取得此數值。",
"Summary Max Token Length": "摘要允許的最大符元長度",
"Editing a message will automatically trigger a re-summarization if it has already been summarized.": "編輯訊息時,若該訊息已被摘要,將自動觸發重新摘要。",
"Re-summarize on Edit": "編輯後重新摘要",
"Swiping a message will automatically trigger a re-summarization if it has already been summarized.": "滑動訊息後若已進行摘要,將自動觸發重新摘要。",
"Re-summarize on Swipe": "滑動後重新摘要",
"Block chat input while summarizing.": "在摘要進行時暫時禁用聊天訊息輸入。",
"Block Chat": "訊息輸入鎖定",
"Whether to use messages and/or summaries as context for summarization. You must use {{history}} in the summary prompt.": "決定是否在摘要中使用訊息及/或過往摘要作為背景資訊。需於摘要提示詞中,使用 {{history}}。",
"Message History": "訊息歷史",
"Messages": "僅訊息",
"Summaries": "僅摘要",
"Both": "訊息與摘要",
"Preview what the message history will look like": "預覽訊息歷史的顯示效果",
"How many previous messages to include in the summarization prompt as context.": "摘要提示中要包含多少先前訊息作為上下文。",
"Number of Previous Messages": "先前訊息數量",
"When including previous messages, also include user messages.": "包含先前訊息時,也包含使用者訊息。",
"Include Previous User Messages": "包含先前使用者訊息",
"The message to summarize will be inside the system instruct template itself. In unchecked (default), the message will instead be added separately after the prompt. Some models benefit from this, but it is not recommended.": "系統指令模板內將直接包含需要摘要的訊息。若未啟用此選項(預設設定),訊息會在提示後分開添加。儘管某些模型可能更適合此設定,但一般不建議使用。",
"Nest Message in Summary Prompt": "在摘要提示中內嵌訊息",
"WARNING: doesn't work great. Attempts to preserve context-shifting by including all the content that is sent in regular prompts (world info, description, personas, example messages, message history, etc). If your regular prompts are static, this can allow Context Shifting to work between summarizations, but it decreases the accuracy of summarization due to all the extra stuff in the prompt. It also can't be previewed as this injection is handled by ST, not the extension.": "警告:效果不佳。此功能嘗試透過在摘要時包含所有常規提示內容(如世界資訊、描述、角色設定、示範訊息、聊天歷史等)來保留上下文轉換。若您的常規提示為靜態內容,則可在摘要之間維持上下文轉換,但由於提示中包含大量額外資訊,將降低摘要的準確性。此外,此內容注入由 ST 處理,而非此擴充功能,因此無法進行預覽。",
"Include All Context Content": "包含所有上下文內容",
"Short-term Memory Injection": "短期記憶注入",
"Determines which messages are included in the short-term memory injection and where. If you change this and include messages that weren't summarized previously, you can either manually trigger a re-summarization or just wait until automatic summarization triggers.": "設定短期記憶注入中所包含的訊息及其插入位置。若更改此設定並包含先前未摘要的訊息,您可手動觸發重新摘要,或等待自動摘要啟動。",
"Edit the short-term memory prompt": "編輯短期記憶提示",
"Include User Messages": "包含使用者訊息",
"Include System Messages": "包含系統訊息",
"Include Thought Message": "包含思考訊息",
"Message Length Threshold": "訊息長度閾值",
"The minimum token length a message has to be in order to get summarized.": "可被摘要的訊息最小符元長度。",
"The max percent of the context that short-term memory can take up.": "短期記憶可佔用上下文的最大百分比。",
"Short-Term Context %": "短期記憶上下文%",
"Include short-term memory in the World Info Scan": "在世界資訊掃描中包含短期記憶",
"Do not inject": "不注入",
"Before main prompt": "主提示之前",
"After main prompt": "主提示之後",
"In chat at depth": "在對話中位於深度",
"Long-Term Memory Injection": "長期記憶注入",
"Determines where long-term messages are injected.": "決定長期訊息注入的位置。",
"Edit the long-term memory prompt": "編輯長期記憶提示",
"The max percent of the context that long-term memory can take up.": "長期記憶可佔用上下文的最大百分比。",
"Long-Term Context %": "長期記憶上下文%",
"Include long-term memory in the World Info Scan": "在世界資訊掃描中包含長期記憶",
"Misc.": "其他",
"Fill your console with debug messages": "將偵錯訊息填入主控台",
"Debug Mode": "偵錯模式",
"Display summarizations below each message": "在每則訊息下顯示摘要",
"Display Memories": "顯示記憶",
"Enable Memory in New Chats": "在新對話中啟用記憶",
"Limit Message History": "限制訊息歷史",
"Revert Settings": "還原設定",
"Auto-summarize user messages and include summaries in memory.": "自動摘要使用者訊息,並將該摘要納入記憶。",
"Auto-summarize system messages and include summaries in memory.": "自動摘要系統訊息,並將該摘要納入記憶。",
"Auto-summarize thought messages and include summaries in memory (from the Stepped Thinking extension).": "自動摘要思考訊息並將摘要納入記憶(來自 Stepped Thinking 擴充功能)。",
"Revert all settings to default (not the default profile, just the default that comes with the extension). Your other profiles won't be affected.": "將所有設定恢復為預設值(並非恢復至「預設設定檔」,而是擴充功能隨附的原始預設值)。其他設定檔將不受影響。",
"Limit the number of messages to send in regular prompts to this number (-1 for no limit). Message memories will still be sent.": "限制常規提示中傳送的訊息數量至此數值(-1 表示無限制)。訊息記憶仍將一併傳送。",
"Whether memory is enabled by default for new chats.": "是否在新對話中預設啟用記憶。",
"Summarize Chat": "聊天摘要",
"Choose settings for the chat summarization. All message inclusion/exclusion settings from the main config profile are used, in addition to the following options.": "選擇聊天摘要的設定。摘要時將使用主要設定檔中的所有訊息包含/排除規則,並可額外設定以下選項。",
"Currently preparing to summarize:": "目前正在準備摘要:",
"Summarize messages with no existing summary": "摘要尚無摘要的訊息",
"Re-summarize messages with existing short-term memories": "重新摘要具有現有短期記憶的訊息",
"Re-summarize messages with existing long-term memories": "重新摘要具有現有長期記憶的訊息",
"Re-summarize messages with existing memories, but which are currently excluded from short-term and long-term memory": "重新摘要具有現有記憶,但目前被排除在短期和長期記憶之外的訊息",
"Re-summarize messages with existing memories that have been manually edited.": "重新摘要已手動編輯的訊息記憶",
"Type the folder name of the theme you want to apply.": "輸入您想套用的主題資料夾名稱。",
"Place your theme data in a folder.": "請將主題資料存於該資料夾內。",
"Unsure where to start? Type ": "不確定如何開始?輸入:",
@@ -2630,7 +2529,7 @@
"Allocates a portion of the response length for thinking (low: 10%, medium: 25%, high: 50%). Other options are model-dependent.": "分配部分回應長度用於推理功能(低:10%、中:25%、高:50%)。其他選項依模型而異。",
"Attach a file or image to a current chat.": "附加檔案或圖片至目前的聊天。",
"Change Persona Image": "變更使用者角色頭像",
"Click to lock your selected persona to the current character. Click again to remove the lock.": "點選以將所選使用者角色鎖定目前聊天的角色。再次點選以解除鎖定。",
"Click to lock your selected persona to the current character. Click again to remove the lock.": "點選以將所選使用者角色與目前聊天的角色綁定。再次點選可解除綁定。",
"Click to select this as default persona for the new chats. Click again to remove it.": "點選以將此設為新聊天的預設使用者角色,再次點選可取消設定。",
"Connected Personas": "已連結的使用者角色",
"Create a new prompt": "新增新提示詞",
@@ -2639,21 +2538,21 @@
"Duplicate Persona": "複製使用者角色",
"Expand and zoom": "展開並縮放",
"Move Entry to Another Lorebook": "將條目移動到其他知識書",
"Persona is locked to the current character": "使用者角色已鎖定至目前角色",
"Persona is locked to the current chat": "使用者角色已鎖定至目前聊天",
"Persona is locked to the current character": "使用者角色已綁定至目前角色",
"Persona is locked to the current chat": "使用者角色已綁定至目前聊天",
"Rename a prompt": "重新命名提示詞",
"Rename Persona": "重新命名使用者角色",
"Select your current Reasoning Template": "選擇你目前使用的推理範本",
"Toggles sprite scaling for character sprites.": "切換角色立繪的縮放比例",
"When multiple personas are connected to a character, a popup will appear to select which one to use.": "當多個使用者角色連接至一個角色時,將顯示選擇彈窗。",
"When using LLM or WebLLM classifier, only show and use expressions that have sprites assigned to them.": "使用 LLM 或 WebLLM 分類器時,僅顯示並使用已指派的表情立繪。",
"Whenever a persona is selected, it will be locked and automatically selected when the chat is opened.": "若已選擇使用者角色,將在開啟聊天時自動進行鎖定。",
"Whenever a persona is selected, it will be locked and automatically selected when the chat is opened.": "若已選擇使用者角色,將在開啟聊天時自動進行綁定。",
"Additional Matching Sources": "額外匹配來源",
"All Classes": "所有類別",
"Allow multiple persona connections per character": "允許每個角色連接多個使用者角色",
"Allows the model to return image attachments.": "允許模型返回圖片附件。",
"Auto-Hide Sprite Settings": "自動隱藏立繪設定",
"Auto-lock a chosen persona to the chat": "自動鎖定使用者角色至聊天中",
"Auto-lock a chosen persona to the chat": "自動綁定使用者角色至聊天中",
"Character": "角色",
"Character Personality": "角色個性",
"Character Tint/Share World Tint With Characters requires Prome to be enabled.": "角色著色/與角色共享世界著色功能需啟用 Prome。",
@@ -2703,7 +2602,7 @@
"Scan depth cannot be negative": "掃描深度不能為負值",
"Scan depth cannot exceed ${0}": "掃描深度不能超過 ${0}",
"Reasoning Template": "推理範本",
"OpenAI-style options: low, medium, high. Minimum and maximum are aliased to low and high. Auto does not send an effort level.": "OpenAI 支援程度:低、中、高。Minimum 與 Maximum 分別等同於低與高。選擇 Auto(自動)不會傳送努力等級。",
"OpenAI-style options: low, medium, high. Minimum and maximum are aliased to low and high. Auto does not send an effort level.": "OpenAI 支援程度:低、中、高。Minimum 與 Maximum 分別等同於低與高。選擇 Auto(自動)不會傳送推理耗費等級。",
"Branch or tag name (optional)": "分支/標籤名稱(可留空)",
"Update enabled": "僅更新啟用項目",
"Sort: Loading Order": "排序:載入順序",
@@ -2742,5 +2641,126 @@
"You deleted a character/chat and arrived back here for safety reasons! Pick another character!": "角色或對話已被刪除。系統為安全考量導回此頁,請重新選擇角色。",
"Could not connect to API": "無法連線至 API",
"Connected to API": "已成功連線至 API",
"help_macros_charDepthPrompt": "角色的 @ 深度註記"
"help_macros_charDepthPrompt": "角色的 @ 深度註記",
"Bind presets to API connections": "將預設綁定至 API 連線",
"Allow compressing requests by removing messages from the middle of the prompt.": "允許透過移除提示中間的訊息來壓縮請求。",
"Unknown": "未知",
"Min Keep": "最小保留",
"enable_functions_desc_4": "當使用「無工具」提示後處理時不支援!",
"Send inline videos": "傳送內嵌影片",
"video_inlining_hint_1": "若模型支援,則在提示中傳送影片。使用",
"video_inlining_hint_2": "操作於任何訊息或使用",
"video_inlining_hint_3": "選單以上傳影片檔案到聊天中。",
"video_inlining_hint_4": "影片大小必須小於 20 MB 且長度低於 1 分鐘",
"This setting affects visibility only.": "此設定僅影響可見性。",
"Allocates a portion of the response length for thinking (min: 1024 tokens, low: 10%, medium: 25%, high: 50%, max: 95%), but minimum 1024 tokens. Auto does not request thinking.": "為推理部分分配回應長度(最大回應長度至少需 1024 符元,低:10%、中:25%、高:50%、最高:95%)。選擇「自動」將不請求推理。",
"Allocates a portion of the response length for thinking (Flash 2.5/Pro 2.5) (min: 0/128 tokens, low: 10%, medium: 25%, high: 50%, max: 24576/32768 tokens). Auto lets the model decide.": "為推理部分分配回應長度(Flash 2.5/Pro 2.5)(最少:0/128 符元,低:10%、中:25%、高:50%、最高:24576/32768 符元)。選擇「自動」將由模型決定。",
"Save and connect": "儲存並連線",
"Manage API keys": "管理 API 金鑰",
"For privacy reasons, your API key will be hidden after you click 'Connect'.": "出於隱私考量,點選「連線」後,將隱藏您的 API 金鑰。",
"Experimental feature. Use at your own risk.": "實驗性功能。請自行斟酌使用風險。",
"suffix will be added automatically.": "後綴將自動新增。",
"Google Vertex AI Configuration": "Google Vertex AI 設定",
"Authentication Mode": "驗證模式:",
"Express Mode (API Key)": "快速模式(API 金鑰)",
"Full Version (Service Account)": "完整版(服務帳號)",
"Google Vertex AI API Key": "Google Vertex AI API 金鑰",
"(Express mode)": "(快速模式)",
"Service Account Configuration": "服務帳號設定",
"Region": "區域:",
"View available regions and models": "檢視可用區域和模型",
"Service Account JSON Content": "服務帳號 JSON 內容:",
"For privacy reasons, your Service Account JSON content will be hidden after you click 'Validate JSON'.": "出於隱私考量,點選「驗證 JSON」將隱藏您的服務帳號 JSON 內容。",
"Validate JSON": "驗證 JSON",
"Pollinations Model": "Pollinations 模型",
"Provided free of charge by Pollinations.AI": "由 Pollinations.AI 免費提供",
"Avoid sending sensitive information. Provider's outputs may include ads.": "請避免傳送敏感資訊。供應商的輸出可能包含廣告。",
"prompt_post_processing_merge_tools": "合併連續角色(含工具)",
"prompt_post_processing_semi_tools": "半嚴格(角色交替;含工具)",
"prompt_post_processing_strict_tools": "嚴格(使用者優先,角色交替;含工具)",
"prompt_post_processing_single": "單一使用者訊息(無工具)",
"Rounded": "圓角",
"Notifications:": "系統通知:",
"Top Left": "左上",
"Top Center": "上方置中",
"Top Right": "右上",
"Bottom Left": "左下",
"Bottom Center": "下方置中",
"Bottom Right": "右下",
"Click the message text in the chat log to edit it.": "點選對話訊息文字後即可編輯內容。",
"Click to Edit": "點選以編輯聊天訊息",
"Make animated backgrounds static in the selection menu. This will reduce UI and network lag if you have a large amount. This is only a change for the selection menu.": "將選單中的動畫背景靜態化,以減少背景過多所造成的介面與網路延遲。此設定僅影響選單。",
"Animated background thumbnails": "動畫背景縮圖",
"Find and delete backups, unused chats, files, images, etc.": "搜尋並刪除備份、未使用的聊天、檔案、圖片等。",
"Clean-Up": "清理",
"Always render style tags from greetings, even if the message is unloaded due to lazy loading.": "始終渲染問候訊息中的樣式標籤,即使該訊息因延遲載入而未顯示。",
"Pin greeting message styles": "固定問候訊息樣式",
"Visibility": "可見性",
"Don't show": "不顯示",
"Input length > 1": "輸入長度 > 1",
"Always show": "始終顯示",
"(DEPRECATED)": "(已淘汰)",
"When multiple personas are connected to a character, a popup will appear to select which one to use": "當多個使用者角色綁定至同一角色時,將顯示選單以擇一。",
"Whenever a persona is selected, it will be locked to the current chat and automatically selected when the chat is opened.": "您所選的使用者角色將綁定至目前聊天,並於開啟此聊天檔案時自動套用。",
"Set / Unset as Welcome Page Assistant": "設定/取消為歡迎頁面助理",
"Allow / Forbid the use of global styles for this character.": "允許/禁止此角色使用全域樣式。",
"This character will be used as a welcome page assistant.": "此角色將用作歡迎頁面助理。",
"prompt_manager_order": "順序",
"prompt_manager_order_note": "來自其他來源(世界資訊、作者備註等)的提示注入預設順序為 100。",
"Ordered from low/top to high/bottom, and at same order: Assistant, User, System.": "順序從低(上)至高(下);同順序時,排列為助理 > 使用者 > 系統。",
"Source:": "來源:",
"Secondary captioning endpoint URL": "次要說明文字端點 URL",
"ext_regex_bulk_edit": "批次編輯",
"Export": "匯出",
"No scripts found": "未找到腳本",
"ext_regex_flags_help": "點選此處了解更多關於正規表達式(regex)標誌的資訊。",
"ext_regex_other_options_desc": "預設情況下,正規表達式腳本會直接且不可逆地變更聊天檔案。\r\n啟用以下任一(或兩者)選項將防止更改聊天檔案,同時仍會變更指定項目。",
"This character has embedded regex script(s).": "此角色包含嵌入式正規表達式腳本。",
"Would you like to allow using them?": "您想允許使用它們嗎?",
"If you want to do it later, select \"Regex\" from the extensions menu.": "您可稍後從擴充功能選單中啟用 「正規表達式(Regex)」。",
"SillyTavern Settings": "SillyTavern 設定",
"Documentation": "文件",
"Import from JSONL": "從 JSONL 匯入",
"Load": "載入",
"Export as JSONL": "匯出為 JSONL",
"Delete all items in this category": "刪除此分類中的所有項目",
"View item content": "檢視項目內容",
"Download item": "下載項目",
"Delete this item": "刪除此項目",
"Once deleted, the files will be gone forever!": "一旦刪除,檔案將永久消失!",
"Make sure to back up your data in advance.": "請先備份您的資料。",
"Scan": "掃描",
"No results yet. Tap 'Scan' to start scanning.": "尚無結果。點選「掃描」以開始掃描。",
"Do you want to export connection data with the preset?": "您想將連線資料與預設一起匯出嗎?",
"This includes the selected source, models, and other preferences set in the API Connections panel.": "這包括在 API 連線面板中設定的來源、模型及其他偏好設定。",
"Your stored API keys are never exported.": "您的 API 金鑰將不會被匯出。",
"Export connection data": "匯出連線資料",
"Do not export connection data": "不匯出連線資料",
"Creator's Notes contain CSS style tags. Do you want to apply them just to Creator's Notes or to the entire application?": "此創作者備註內含 CSS 樣式。請選擇是否僅套用於備註區域,或應用至整體介面。",
"CAUTION: Malformed styles may cause issues.": "注意:樣式錯誤可能導致問題。",
"To change the preference later, use the": "若想稍後更改偏好設定,請使用",
"button in the Creator's Notes block.": "創作者備註區塊中的按鈕。",
"Class names will be automatically prefixed with 'custom-'.": "CSS 類別名稱將自動套用「custom-」前綴。",
"Choose how to apply CSS style tags if they are defined in Creator's Notes of this character:": "請選擇如何套用此角色創作者備註中的 CSS 樣式:",
"Just to Creator's Notes": "僅限創作者備註",
"Apply to the entire app": "應用於整個應用程式",
"API:": "API:",
"Key:": "金鑰:",
"Add Secret": "新增密鑰",
"No secrets saved.": "尚未儲存任何密鑰。",
"Copy ID": "複製 ID",
"Select": "選擇",
"Show recent chats": "顯示最近的聊天",
"Hide recent chats": "隱藏最近的聊天",
"Recent Chats": "最近的聊天",
"Docs": "文件",
"GitHub": "GitHub",
"Discord": "Discord",
"Temporary Chat": "臨時聊天",
"No recent chats": "沒有最近的聊天",
"(Message Box)": "(訊息框)",
"[title]Create a new": "新增",
"[title]Delete a ": "刪除 ",
"[title]Rename a ": "重新命名 ",
"completions note prefix": "完成提示前綴"
}
+887 -2194
View File
File diff suppressed because it is too large Load Diff
+6 -5
View File
@@ -2,7 +2,6 @@
import {
characterGroupOverlay,
callPopup,
characters,
event_types,
eventSource,
@@ -17,6 +16,7 @@ import {
import { favsToHotswap } from './RossAscends-mods.js';
import { hideLoader, showLoader } from './loader.js';
import { convertCharacterToPersona } from './personas.js';
import { callGenericPopup, POPUP_TYPE } from './popup.js';
import { createTagInput, getTagKeyForEntity, getTagsList, printTagList, tag_map, compareTagsForSort, removeTagFromMap, importTags, tag_import_setting } from './tags.js';
/**
@@ -835,12 +835,13 @@ class BulkEditOverlay {
*/
handleContextMenuDelete = () => {
const characterIds = this.selectedCharacters;
const popupContent = BulkEditOverlay.#getDeletePopupContentHtml(characterIds);
const promise = callPopup(popupContent, null)
const popupContent = $(BulkEditOverlay.#getDeletePopupContentHtml(characterIds));
const checkbox = popupContent.find('#del_char_checkbox');
const promise = callGenericPopup(popupContent, POPUP_TYPE.CONFIRM)
.then((accept) => {
if (true !== accept) return;
if (!accept) return;
const deleteChats = document.getElementById('del_char_checkbox').checked ?? false;
const deleteChats = checkbox.prop('checked') ?? false;
showLoader();
const toast = toastr.info('We\'re deleting your characters, please wait...', 'Working on it');
+259 -96
View File
@@ -6,7 +6,7 @@ import { event_types, eventSource, is_send_press, main_api, substituteParams } f
import { is_group_generating } from './group-chats.js';
import { Message, MessageCollection, TokenHandler } from './openai.js';
import { power_user } from './power-user.js';
import { debounce, waitUntilCondition, escapeHtml } from './utils.js';
import { debounce, waitUntilCondition, escapeHtml, uuidv4 } from './utils.js';
import { debounce_timeout } from './constants.js';
import { renderTemplateAsync } from './templates.js';
import { Popup } from './popup.js';
@@ -29,6 +29,7 @@ function debouncePromise(func, delay) {
}
const DEFAULT_DEPTH = 4;
const DEFAULT_ORDER = 100;
/**
* @enum {number}
@@ -77,25 +78,108 @@ const registerPromptManagerMigration = () => {
* Represents a prompt.
*/
class Prompt {
identifier; role; content; name; system_prompt; position; injection_position; injection_depth; injection_order; forbid_overrides; extension;
/**
* Indicates if the prompt is enabled.
* @type {boolean}
*/
enabled;
/**
* Unique identifier for the prompt.
* @type {string}
*/
identifier;
/**
* Role of the prompt, e.g., 'system', 'user', etc.
* @type {string}
*/
role;
/**
* Content of the prompt.
* @type {string}
*/
content;
/**
* Display name of the prompt.
* @type {string}
*/
name;
/**
* Indicates if the prompt is a system prompt.
* @type {boolean}
*/
system_prompt;
/**
* Position of the prompt in the prompt list.
* @type {string|number}
*/
position;
/**
* Inject position of the prompt (relative = 0 or in-chat = 1)
* @type {number}
*/
injection_position;
/**
* Depth of the prompt in the chat.
* @type {number}
*/
injection_depth;
/**
* Order of the prompt in the chat.
* @type {number}
*/
injection_order;
/**
* Indicates if the prompt should not be overridden.
* @type {boolean}
*/
forbid_overrides;
/**
* Prompt is added by an extension.
* @type {boolean}
*/
extension;
/**
* A list of generation type triggers for the prompt injection.
* @type {string[]}
*/
injection_trigger;
/**
* Indicates if the prompt is a marker prompt.
* @type {boolean}
*/
marker;
/**
* Create a new Prompt instance.
*
* @param {Object} param0 - Object containing the properties of the prompt.
* @param {string} param0.identifier - The unique identifier of the prompt.
* @param {string} param0.role - The role associated with the prompt.
* @param {string} param0.content - The content of the prompt.
* @param {Object} [param0] - Object containing the properties of the prompt.
* @param {string} [param0.identifier] - The unique identifier of the prompt.
* @param {string} [param0.role] - The role associated with the prompt.
* @param {string} [param0.content] - The content of the prompt.
* @param {string} [param0.name] - The name of the prompt.
* @param {boolean} [param0.system_prompt] - Indicates if the prompt is a system prompt.
* @param {string} [param0.position] - The position of the prompt in the prompt list.
* @param {string|number} [param0.position] - The position of the prompt in the prompt list.
* @param {number} [param0.injection_position] - The insert position of the prompt.
* @param {number} [param0.injection_depth] - The depth of the prompt in the chat.
* @param {number} [param0.injection_order] - The order of the prompt in the chat.
* @param {string[]} [param0.injection_trigger] - The generation type trigger for the prompt injection.
* @param {boolean} [param0.forbid_overrides] - Indicates if the prompt should not be overridden.
* @param {boolean} [param0.extension] - Prompt is added by an extension.
*/
constructor({ identifier, role, content, name, system_prompt, position, injection_depth, injection_position, forbid_overrides, extension, injection_order } = {}) {
constructor({ identifier, role, content, name, system_prompt, position, injection_depth, injection_position, forbid_overrides, extension, injection_order, injection_trigger } = {}) {
this.identifier = identifier;
this.role = role;
this.content = content;
@@ -106,7 +190,8 @@ class Prompt {
this.injection_position = injection_position;
this.forbid_overrides = forbid_overrides;
this.extension = extension ?? false;
this.injection_order = injection_order ?? 100;
this.injection_order = injection_order ?? DEFAULT_ORDER;
this.injection_trigger = injection_trigger ?? [];
}
}
@@ -114,7 +199,16 @@ class Prompt {
* Representing a collection of prompts.
*/
export class PromptCollection {
/**
* List of Prompts in the collection.
* @type {Prompt[]}
*/
collection = [];
/**
* List of identifiers of prompts that have been overridden.
* @type {string[]}
*/
overriddenPrompts = [];
/**
@@ -129,7 +223,7 @@ export class PromptCollection {
/**
* Checks if the provided instances are of the Prompt class.
*
* @param {...any} prompts - Instances to check.
* @param {...Prompt} prompts - Instances to check.
* @throws Will throw an error if one or more instances are not of the Prompt class.
*/
checkPromptInstance(...prompts) {
@@ -191,6 +285,12 @@ export class PromptCollection {
return this.index(identifier) !== -1;
}
/**
* Overrides a prompt at a specific position in the collection.
*
* @param {Prompt} prompt - The Prompt instance to override.
* @param {number} position - The position in the collection to override the Prompt instance.
*/
override(prompt, position) {
this.set(prompt, position);
this.overriddenPrompts.push(prompt.identifier);
@@ -274,7 +374,7 @@ class PromptManager {
this.tryGenerate = async () => { };
/** Called to persist the configuration, must return a promise */
this.saveServiceSettings = () => { };
this.saveServiceSettings = () => { return Promise.resolve(); };
/** Toggle prompt button click */
this.handleToggle = () => { };
@@ -444,32 +544,51 @@ class PromptManager {
break;
}
document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_name').value = prompt.name;
document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_role').value = 'system';
document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_prompt').value = prompt.content ?? '';
document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_injection_position').value = prompt.injection_position ?? 0;
document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_injection_depth').value = prompt.injection_depth ?? DEFAULT_DEPTH;
document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_injection_order').value = prompt.injection_order ?? 100;
document.getElementById(this.configuration.prefix + 'prompt_manager_depth_block').style.visibility = prompt.injection_position === INJECTION_POSITION.ABSOLUTE ? 'visible' : 'hidden';
document.getElementById(this.configuration.prefix + 'prompt_manager_order_block').style.visibility = prompt.injection_position === INJECTION_POSITION.ABSOLUTE ? 'visible' : 'hidden';
document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_forbid_overrides').checked = prompt.forbid_overrides ?? false;
document.getElementById(this.configuration.prefix + 'prompt_manager_forbid_overrides_block').style.visibility = this.overridablePrompts.includes(prompt.identifier) ? 'visible' : 'hidden';
document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_prompt').disabled = prompt.marker ?? false;
document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_source_block').style.display = isPulledPrompt ? '' : 'none';
const nameField = /** @type {HTMLInputElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_name'));
const roleField = /** @type {HTMLSelectElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_role'));
const promptField = /** @type {HTMLTextAreaElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_prompt'));
const injectionPositionField = /** @type {HTMLSelectElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_injection_position'));
const injectionDepthField = /** @type {HTMLInputElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_injection_depth'));
const injectionOrderField = /** @type {HTMLInputElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_injection_order'));
const injectionTriggerField = /** @type {HTMLSelectElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_injection_trigger'));
const depthBlock = /** @type {HTMLDivElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_depth_block'));
const orderBlock = /** @type {HTMLDivElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_order_block'));
const forbidOverridesField = /** @type {HTMLInputElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_forbid_overrides'));
const forbidOverridesBlock = /** @type {HTMLDivElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_forbid_overrides_block'));
const entrySourceBlock = /** @type {HTMLDivElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_source_block'));
const entrySource = /** @type {HTMLSpanElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_source'));
nameField.value = prompt.name;
roleField.value = 'system';
promptField.value = prompt.content ?? '';
injectionPositionField.value = (prompt.injection_position ?? 0).toString();
injectionDepthField.value = (prompt.injection_depth ?? DEFAULT_DEPTH).toString();
injectionOrderField.value = (prompt.injection_order ?? DEFAULT_ORDER).toString();
Array.from(injectionTriggerField.options).forEach(option => {
option.selected = false;
});
injectionTriggerField.dispatchEvent(new Event('change', { bubbles: true }));
depthBlock.style.visibility = prompt.injection_position === INJECTION_POSITION.ABSOLUTE ? 'visible' : 'hidden';
orderBlock.style.visibility = prompt.injection_position === INJECTION_POSITION.ABSOLUTE ? 'visible' : 'hidden';
forbidOverridesField.checked = prompt.forbid_overrides ?? false;
forbidOverridesBlock.style.visibility = this.overridablePrompts.includes(prompt.identifier) ? 'visible' : 'hidden';
promptField.disabled = prompt.marker ?? false;
entrySourceBlock.style.display = isPulledPrompt ? '' : 'none';
if (isPulledPrompt) {
const sourceName = this.promptSources[promptId];
document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_source').textContent = sourceName;
entrySource.textContent = sourceName;
}
if (!this.systemPrompts.includes(promptId)) {
document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_injection_position').removeAttribute('disabled');
injectionPositionField.removeAttribute('disabled');
}
};
// Append prompt to selected character
this.handleAppendPrompt = (event) => {
const promptID = document.getElementById(this.configuration.prefix + 'prompt_manager_footer_append_prompt').value;
const appendPromptFooter = /** @type {HTMLSelectElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_footer_append_prompt'));
const promptID = appendPromptFooter.value;
const prompt = this.getPromptById(promptID);
if (prompt) {
@@ -483,7 +602,8 @@ class PromptManager {
this.handleDeletePrompt = async (event) => {
Popup.show.confirm(t`Are you sure you want to delete this prompt?`, null).then((userChoice) => {
if (!userChoice) return;
const promptID = document.getElementById(this.configuration.prefix + 'prompt_manager_footer_append_prompt').value;
const appendPromptFooter = /** @type {HTMLSelectElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_footer_append_prompt'));
const promptID = appendPromptFooter.value;
const prompt = this.getPromptById(promptID);
if (prompt && true === this.isPromptDeletionAllowed(prompt)) {
@@ -566,6 +686,7 @@ class PromptManager {
fileOpener.accept = '.json';
fileOpener.addEventListener('change', (event) => {
if (!(event.target instanceof HTMLInputElement)) return;
const file = event.target.files[0];
if (!file) return;
@@ -575,7 +696,7 @@ class PromptManager {
const fileContent = event.target.result;
try {
const data = JSON.parse(fileContent);
const data = JSON.parse(fileContent.toString());
this.import(data);
} catch (err) {
toastr.error(t`An error occurred while importing prompts. More info available in console.`);
@@ -615,7 +736,7 @@ class PromptManager {
// Update edit form if present
// @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetParent
const popupEditFormPrompt = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_prompt');
const popupEditFormPrompt = /** @type {HTMLTextAreaElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_prompt'));
if (popupEditFormPrompt.offsetParent) {
popupEditFormPrompt.value = prompt.content;
}
@@ -673,6 +794,7 @@ class PromptManager {
// Trigger re-render when token settings are changed
document.getElementById('openai_max_context').addEventListener('change', (event) => {
if (!(event.target instanceof HTMLInputElement)) return;
this.serviceSettings.openai_max_context = event.target.value;
if (this.activeCharacter) this.renderDebounced();
});
@@ -778,23 +900,33 @@ class PromptManager {
/**
* Update a prompt with the values from the HTML form.
* @param {object} prompt - The prompt to be updated.
* @param {Partial<Prompt>} prompt - The prompt to be updated.
* @returns {void}
*/
updatePromptWithPromptEditForm(prompt) {
prompt.name = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_name').value;
prompt.role = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_role').value;
prompt.content = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_prompt').value;
prompt.injection_position = Number(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_injection_position').value);
prompt.injection_depth = Number(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_injection_depth').value);
prompt.injection_order = Number(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_injection_order').value);
prompt.forbid_overrides = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_forbid_overrides').checked;
const nameField = /** @type {HTMLInputElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_name'));
const roleField = /** @type {HTMLSelectElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_role'));
const promptField = /** @type {HTMLTextAreaElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_prompt'));
const injectionPositionField = /** @type {HTMLSelectElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_injection_position'));
const injectionDepthField = /** @type {HTMLInputElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_injection_depth'));
const injectionOrderField = /** @type {HTMLInputElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_injection_order'));
const injectionTriggerField = /** @type {HTMLSelectElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_injection_trigger'));
const forbidOverridesField = /** @type {HTMLInputElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_forbid_overrides'));
prompt.name = nameField.value;
prompt.role = roleField.value;
prompt.content = promptField.value;
prompt.injection_position = Number(injectionPositionField.value);
prompt.injection_depth = Number(injectionDepthField.value);
prompt.injection_order = Number(injectionOrderField.value);
prompt.injection_trigger = Array.from(injectionTriggerField.selectedOptions).map(option => option.value);
prompt.forbid_overrides = forbidOverridesField.checked;
}
/**
* Find a prompt by its identifier and update it with the provided object.
* @param {string} identifier - The identifier of the prompt.
* @param {object} updatePrompt - An object with properties to be updated in the prompt.
* @param {Prompt} updatePrompt - An object with properties to be updated in the prompt.
* @returns {void}
*/
updatePromptByIdentifier(identifier, updatePrompt) {
@@ -804,7 +936,7 @@ class PromptManager {
/**
* Iterate over an array of prompts, find each one by its identifier, and update them with the provided data.
* @param {object[]} prompts - An array of prompt updates.
* @param {Prompt[]} prompts - An array of prompt updates.
* @returns {void}
*/
updatePrompts(prompts) {
@@ -826,7 +958,7 @@ class PromptManager {
/**
* Add a prompt to the current character's prompt list.
* @param {object} prompt - The prompt to be added.
* @param {Prompt} prompt - The prompt to be added.
* @param {object} character - The character whose prompt list will be updated.
* @returns {void}
*/
@@ -839,7 +971,7 @@ class PromptManager {
/**
* Remove a prompt from the current character's prompt list.
* @param {object} prompt - The prompt to be removed.
* @param {Prompt} prompt - The prompt to be removed.
* @param {object} character - The character whose prompt list will be updated.
* @returns {void}
*/
@@ -853,7 +985,7 @@ class PromptManager {
/**
* Create a new prompt and add it to the list of prompts.
* @param {object} prompt - The prompt to be added.
* @param {Partial<Prompt>} prompt - The prompt to be added.
* @param {string} identifier - The identifier for the new prompt.
* @returns {void}
*/
@@ -931,7 +1063,7 @@ class PromptManager {
/**
* Check whether a prompt can be inspected.
* @param {object} prompt - The prompt to check.
* @param {Prompt} prompt - The prompt to check.
* @returns {boolean} True if the prompt is a marker, false otherwise.
*/
isPromptInspectionAllowed(prompt) {
@@ -940,7 +1072,7 @@ class PromptManager {
/**
* Check whether a prompt can be deleted. System prompts cannot be deleted.
* @param {object} prompt - The prompt to check.
* @param {Prompt} prompt - The prompt to check.
* @returns {boolean} True if the prompt can be deleted, false otherwise.
*/
isPromptDeletionAllowed(prompt) {
@@ -949,7 +1081,7 @@ class PromptManager {
/**
* Check whether a prompt can be edited.
* @param {object} prompt - The prompt to check.
* @param {Prompt} prompt - The prompt to check.
* @returns {boolean} True if the prompt can be edited, false otherwise.
*/
isPromptEditAllowed(prompt) {
@@ -966,7 +1098,7 @@ class PromptManager {
/**
* Check whether a prompt can be toggled on or off.
* @param {object} prompt - The prompt to check.
* @param {Prompt} prompt - The prompt to check.
* @returns {boolean} True if the prompt can be deleted, false otherwise.
*/
isPromptToggleAllowed(prompt) {
@@ -1062,7 +1194,7 @@ class PromptManager {
/**
* Get the prompts for a specific character. Can be filtered to only include enabled prompts.
* @returns {object[]} The prompts for the character.
* @returns {Prompt[]} The prompts for the character.
* @param character
* @param onlyEnabled
*/
@@ -1075,7 +1207,7 @@ class PromptManager {
/**
* Get the order of prompts for a specific character. If no character is specified or the character doesn't have a prompt list, an empty array is returned.
* @param {object|null} character - The character to get the prompt list for.
* @returns {object[]} The prompt list for the character, or an empty array.
* @returns {Partial<Prompt>[]} The prompt list for the character, or an empty array.
*/
getPromptOrderForCharacter(character) {
return !character ? [] : (this.serviceSettings.prompt_order.find(list => String(list.character_id) === String(character.id))?.order ?? []);
@@ -1083,7 +1215,7 @@ class PromptManager {
/**
* Set the prompts for the manager.
* @param {object[]} prompts - The prompts to be set.
* @param {Partial<Prompt>[]} prompts - The prompts to be set.
* @returns {void}
*/
setPrompts(prompts) {
@@ -1125,7 +1257,7 @@ class PromptManager {
/**
* Finds and returns a prompt by its identifier.
* @param {string} identifier - Identifier of the prompt
* @returns {Object|null} The prompt object, or null if not found
* @returns {Prompt|null} The prompt object, or null if not found
*/
getPromptById(identifier) {
return this.serviceSettings.prompts.find(item => item && item.identifier === identifier) ?? null;
@@ -1143,9 +1275,9 @@ class PromptManager {
/**
* Enriches a generic object, creating a new prompt object in the process
*
* @param {Object} prompt - Prompt object
* @param {Partial<Prompt>} prompt - Prompt object
* @param original
* @returns {Object} An object with "role" and "content" properties
* @returns {Prompt} An object with "role" and "content" properties
*/
preparePrompt(prompt, original = null) {
const groupMembers = this.getActiveGroupCharacters();
@@ -1184,7 +1316,7 @@ class PromptManager {
const debouncedSaveServiceSettings = debouncePromise(() => this.saveServiceSettings(), 300);
const textarea = document.getElementById(textareaIdentifier);
const textarea = /** @type {HTMLTextAreaElement} */(document.getElementById(textareaIdentifier));
textarea.addEventListener('blur', () => {
prompt.content = textarea.value;
this.updatePromptByIdentifier(identifier, prompt);
@@ -1193,9 +1325,15 @@ class PromptManager {
}
/**
* Updates the quick edit textarea for a specific prompt.
* @param {string} identifier - The identifier of the prompt.
* @param {Prompt} prompt - The updated prompt object.
* @returns {string} The ID of the updated textarea element.
*/
updateQuickEdit(identifier, prompt) {
const elementId = `${identifier}_prompt_quick_edit_textarea`;
const textarea = document.getElementById(elementId);
const textarea = /** @type {HTMLTextAreaElement} */(document.getElementById(elementId));
textarea.value = prompt.content;
return elementId;
@@ -1220,30 +1358,35 @@ class PromptManager {
/**
* Loads a given prompt into the edit form fields.
* @param {Object} prompt - Prompt object with properties 'name', 'role', 'content', and 'system_prompt'
* @param {Partial<Prompt>} prompt - Prompt object with properties 'name', 'role', 'content', and 'system_prompt'
*/
loadPromptIntoEditForm(prompt) {
const nameField = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_name');
const roleField = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_role');
const promptField = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_prompt');
const injectionPositionField = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_injection_position');
const injectionDepthField = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_injection_depth');
const injectionOrderField = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_injection_order');
const injectionDepthBlock = document.getElementById(this.configuration.prefix + 'prompt_manager_depth_block');
const injectionOrderBlock = document.getElementById(this.configuration.prefix + 'prompt_manager_order_block');
const forbidOverridesField = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_forbid_overrides');
const forbidOverridesBlock = document.getElementById(this.configuration.prefix + 'prompt_manager_forbid_overrides_block');
const entrySourceBlock = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_source_block');
const entrySource = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_source');
const nameField = /** @type {HTMLInputElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_name'));
const roleField = /** @type {HTMLSelectElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_role'));
const promptField = /** @type {HTMLTextAreaElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_prompt'));
const injectionPositionField = /** @type {HTMLSelectElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_injection_position'));
const injectionDepthField = /** @type {HTMLInputElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_injection_depth'));
const injectionOrderField = /** @type {HTMLInputElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_injection_order'));
const injectionTriggerField = /** @type {HTMLSelectElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_injection_trigger'));
const injectionDepthBlock = /** @type {HTMLDivElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_depth_block'));
const injectionOrderBlock = /** @type {HTMLDivElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_order_block'));
const forbidOverridesField = /** @type {HTMLInputElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_forbid_overrides'));
const forbidOverridesBlock = /** @type {HTMLDivElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_forbid_overrides_block'));
const entrySourceBlock = /** @type {HTMLDivElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_source_block'));
const entrySource = /** @type {HTMLSpanElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_source'));
const isPulledPrompt = Object.keys(this.promptSources).includes(prompt.identifier);
nameField.value = prompt.name ?? '';
roleField.value = prompt.role || 'system';
promptField.value = prompt.content ?? '';
promptField.disabled = prompt.marker ?? false;
injectionPositionField.value = prompt.injection_position ?? INJECTION_POSITION.RELATIVE;
injectionDepthField.value = prompt.injection_depth ?? DEFAULT_DEPTH;
injectionOrderField.value = prompt.injection_order ?? 100;
injectionPositionField.value = (prompt.injection_position ?? INJECTION_POSITION.RELATIVE).toString();
injectionDepthField.value = (prompt.injection_depth ?? DEFAULT_DEPTH).toString();
injectionOrderField.value = (prompt.injection_order ?? DEFAULT_ORDER).toString();
Array.from(injectionTriggerField.options).forEach(option => {
option.selected = Array.isArray(prompt.injection_trigger) && prompt.injection_trigger.includes(option.value);
});
injectionTriggerField.dispatchEvent(new Event('change', { bubbles: true }));
injectionDepthBlock.style.visibility = prompt.injection_position === INJECTION_POSITION.ABSOLUTE ? 'visible' : 'hidden';
injectionOrderBlock.style.visibility = prompt.injection_position === INJECTION_POSITION.ABSOLUTE ? 'visible' : 'hidden';
injectionPositionField.removeAttribute('disabled');
@@ -1335,17 +1478,19 @@ class PromptManager {
const editArea = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_edit');
editArea.style.display = 'none';
const nameField = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_name');
const roleField = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_role');
const promptField = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_prompt');
const injectionPositionField = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_injection_position');
const injectionDepthField = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_injection_depth');
const injectionDepthBlock = document.getElementById(this.configuration.prefix + 'prompt_manager_depth_block');
const injectionOrderBlock = document.getElementById(this.configuration.prefix + 'prompt_manager_order_block');
const forbidOverridesField = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_forbid_overrides');
const forbidOverridesBlock = document.getElementById(this.configuration.prefix + 'prompt_manager_forbid_overrides_block');
const entrySourceBlock = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_source_block');
const entrySource = document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_source');
const nameField = /** @type {HTMLInputElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_name'));
const roleField = /** @type {HTMLSelectElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_role'));
const promptField = /** @type {HTMLTextAreaElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_prompt'));
const injectionPositionField = /** @type {HTMLSelectElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_injection_position'));
const injectionDepthField = /** @type {HTMLInputElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_injection_depth'));
const injectionDepthBlock = /** @type {HTMLDivElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_depth_block'));
const injectionOrderBlock = /** @type {HTMLDivElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_order_block'));
const injectionOrderField = /** @type {HTMLInputElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_injection_order'));
const injectionTriggerField = /** @type {HTMLSelectElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_injection_trigger'));
const forbidOverridesField = /** @type {HTMLInputElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_form_forbid_overrides'));
const forbidOverridesBlock = /** @type {HTMLDivElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_forbid_overrides_block'));
const entrySourceBlock = /** @type {HTMLDivElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_source_block'));
const entrySource = /** @type {HTMLSpanElement} */(document.getElementById(this.configuration.prefix + 'prompt_manager_popup_entry_source'));
nameField.value = '';
roleField.selectedIndex = 0;
@@ -1353,7 +1498,9 @@ class PromptManager {
promptField.disabled = false;
injectionPositionField.selectedIndex = 0;
injectionPositionField.removeAttribute('disabled');
injectionDepthField.value = DEFAULT_DEPTH;
injectionDepthField.value = DEFAULT_DEPTH.toString();
injectionOrderField.value = DEFAULT_ORDER.toString();
injectionTriggerField.value = '';
injectionDepthBlock.style.visibility = 'unset';
injectionOrderBlock.style.visibility = 'unset';
forbidOverridesBlock.style.visibility = 'unset';
@@ -1373,28 +1520,48 @@ class PromptManager {
/**
* Returns a full list of prompts whose content markers have been substituted.
* @param {string} generationType - The type of generation, e.g., 'continue' or 'quiet'.
* @returns {PromptCollection} A PromptCollection object
*/
getPromptCollection() {
getPromptCollection(generationType) {
generationType = String(generationType || 'normal').toLowerCase().trim();
const promptCollection = new PromptCollection();
const promptOrder = this.getPromptOrderForCharacter(this.activeCharacter);
const promptCollection = new PromptCollection();
promptOrder.forEach(entry => {
if (true === entry.enabled) {
const prompt = this.getPromptById(entry.identifier);
if (prompt) promptCollection.add(this.preparePrompt(prompt));
} else if (!entry.enabled && entry.identifier === 'main') {
const prompt = this.getPromptById(entry.identifier);
const allowedTrigger = entry.enabled && this.shouldTrigger(prompt, generationType);
if (!prompt) {
return;
}
if (allowedTrigger) {
promptCollection.add(this.preparePrompt(prompt));
} else if (entry.identifier === 'main') {
// Some extensions require main prompt to be present for relative inserts.
// So we make a GMO-free vegan replacement.
const prompt = structuredClone(this.getPromptById(entry.identifier));
prompt.content = '';
if (prompt) promptCollection.add(this.preparePrompt(prompt));
const replacementPrompt = structuredClone(prompt);
replacementPrompt.content = '';
promptCollection.add(this.preparePrompt(replacementPrompt));
}
});
return promptCollection;
}
/**
* Checks if a prompt should be triggered based on its injection triggers.
* @param {Prompt} prompt - The prompt to check.
* @param {string} generationType - The type of generation to check against.
* @returns {boolean} True if the prompt should be triggered, false otherwise.
*/
shouldTrigger(prompt, generationType) {
if (!Array.isArray(prompt?.injection_trigger)) return true;
if (!prompt.injection_trigger.length) return true;
return prompt.injection_trigger.includes(generationType);
}
/**
* Setter for messages property
*
@@ -1807,11 +1974,7 @@ class PromptManager {
* @returns {string} A string representation of an uuid4
*/
getUuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
let r = Math.random() * 16 | 0,
v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
return uuidv4();
}
/**
+153 -201
View File
@@ -1,10 +1,9 @@
import { DOMPurify, Bowser, slideToggle } from '../lib.js';
import { DOMPurify, Bowser } from '../lib.js';
import {
characters,
online_status,
main_api,
api_server,
is_send_press,
max_context,
saveSettingsDebounced,
@@ -19,7 +18,7 @@ import {
menu_type,
substituteParams,
sendTextareaMessage,
getSlideToggleOptions,
doNavbarIconClick,
} from '../script.js';
import {
@@ -42,6 +41,7 @@ import { debounce_timeout } from './constants.js';
import { Popup } from './popup.js';
import { accountStorage } from './util/AccountStorage.js';
import { getCurrentUserHandle } from './user.js';
import { kai_settings } from './kai-settings.js';
var RPanelPin = document.getElementById('rm_button_panel_pin');
var LPanelPin = document.getElementById('lm_button_panel_pin');
@@ -371,7 +371,7 @@ function RA_autoconnect(PrevApi) {
if (online_status === 'no_connection' && power_user.auto_connect) {
switch (main_api) {
case 'kobold':
if (api_server && isValidUrl(api_server)) {
if (kai_settings.api_server && isValidUrl(kai_settings.api_server)) {
$('#api_button').trigger('click');
}
break;
@@ -397,12 +397,11 @@ function RA_autoconnect(PrevApi) {
case 'openai':
if (((secret_state[SECRET_KEYS.OPENAI] || oai_settings.reverse_proxy) && oai_settings.chat_completion_source == chat_completion_sources.OPENAI)
|| ((secret_state[SECRET_KEYS.CLAUDE] || oai_settings.reverse_proxy) && oai_settings.chat_completion_source == chat_completion_sources.CLAUDE)
|| ((secret_state[SECRET_KEYS.SCALE] || secret_state[SECRET_KEYS.SCALE_COOKIE]) && oai_settings.chat_completion_source == chat_completion_sources.SCALE)
|| (oai_settings.chat_completion_source == chat_completion_sources.WINDOWAI)
|| (secret_state[SECRET_KEYS.OPENROUTER] && oai_settings.chat_completion_source == chat_completion_sources.OPENROUTER)
|| (secret_state[SECRET_KEYS.AI21] && oai_settings.chat_completion_source == chat_completion_sources.AI21)
|| (secret_state[SECRET_KEYS.MAKERSUITE] && oai_settings.chat_completion_source == chat_completion_sources.MAKERSUITE)
|| (secret_state[SECRET_KEYS.VERTEXAI] && oai_settings.chat_completion_source == chat_completion_sources.VERTEXAI)
|| (secret_state[SECRET_KEYS.VERTEXAI] && oai_settings.chat_completion_source == chat_completion_sources.VERTEXAI && oai_settings.vertexai_auth_mode === 'express')
|| (secret_state[SECRET_KEYS.VERTEXAI_SERVICE_ACCOUNT] && oai_settings.chat_completion_source == chat_completion_sources.VERTEXAI && oai_settings.vertexai_auth_mode === 'full')
|| (secret_state[SECRET_KEYS.MISTRALAI] && oai_settings.chat_completion_source == chat_completion_sources.MISTRALAI)
|| (secret_state[SECRET_KEYS.COHERE] && oai_settings.chat_completion_source == chat_completion_sources.COHERE)
|| (secret_state[SECRET_KEYS.PERPLEXITY] && oai_settings.chat_completion_source == chat_completion_sources.PERPLEXITY)
@@ -411,6 +410,7 @@ function RA_autoconnect(PrevApi) {
|| (secret_state[SECRET_KEYS.NANOGPT] && oai_settings.chat_completion_source == chat_completion_sources.NANOGPT)
|| (secret_state[SECRET_KEYS.DEEPSEEK] && oai_settings.chat_completion_source == chat_completion_sources.DEEPSEEK)
|| (secret_state[SECRET_KEYS.XAI] && oai_settings.chat_completion_source == chat_completion_sources.XAI)
|| (secret_state[SECRET_KEYS.AIMLAPI] && oai_settings.chat_completion_source == chat_completion_sources.AIMLAPI)
|| (oai_settings.chat_completion_source === chat_completion_sources.POLLINATIONS)
|| (isValidUrl(oai_settings.custom_url) && oai_settings.chat_completion_source == chat_completion_sources.CUSTOM)
) {
@@ -432,19 +432,19 @@ function OpenNavPanels() {
//auto-open R nav if locked and previously open
if (accountStorage.getItem('NavLockOn') == 'true' && accountStorage.getItem('NavOpened') == 'true') {
//console.log("RA -- clicking right nav to open");
$('#rightNavDrawerIcon').click();
$('#rightNavDrawerIcon').trigger('click');
}
//auto-open L nav if locked and previously open
if (accountStorage.getItem('LNavLockOn') == 'true' && accountStorage.getItem('LNavOpened') == 'true') {
console.debug('RA -- clicking left nav to open');
$('#leftNavDrawerIcon').click();
$('#leftNavDrawerIcon').trigger('click');
}
//auto-open WI if locked and previously open
if (accountStorage.getItem('WINavLockOn') == 'true' && accountStorage.getItem('WINavOpened') == 'true') {
console.debug('RA -- clicking WI to open');
$('#WIDrawerIcon').click();
$('#WIDrawerIcon').trigger('click');
}
}
}
@@ -472,54 +472,72 @@ const saveUserInputDebounced = debounce(saveUserInput);
// Make the DIV element draggable:
export function dragElement(elmnt) {
var isHeaderBeingDragged = false;
var isMouseDown = false;
/**
* Make the given element draggable. This is used for Moving UI.
* @param {JQuery} $elmnt - The element to make draggable.
*/
export function dragElement($elmnt) {
let actionType = null; // "drag" or "resize"
let isMouseDown = false;
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
var height, width, top, left, right, bottom,
let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
let height, width, top, left, right, bottom,
maxX, maxY, winHeight, winWidth,
topbar, topBarFirstX, topBarLastY;
var elmntName = elmnt.attr('id');
console.debug(`dragElement called for ${elmntName}`);
const elmntName = $elmnt.attr('id');
const elmntNameEscaped = $.escapeSelector(elmntName);
const elmntHeader = $(`#${elmntNameEscaped}header`);
const $elmntHeader = $(`#${elmntNameEscaped}header`);
if (elmntHeader.length) {
elmntHeader.off('mousedown').on('mousedown', (e) => { //listener for drag handle repositioning
isHeaderBeingDragged = true;
isMouseDown = true;
observer.observe(elmnt.get(0), { attributes: true, attributeFilter: ['style'] });
dragMouseDown(e);
});
$(elmnt).off('mousedown').on('mousedown', () => { //listener for resize
isMouseDown = true;
observer.observe(elmnt.get(0), { attributes: true, attributeFilter: ['style'] });
});
// Helper: Save position/size to state and emit events
function savePositionAndSize() {
if (!power_user.movingUIState[elmntName]) power_user.movingUIState[elmntName] = {};
power_user.movingUIState[elmntName].top = top;
power_user.movingUIState[elmntName].left = left;
power_user.movingUIState[elmntName].right = right;
power_user.movingUIState[elmntName].bottom = bottom;
power_user.movingUIState[elmntName].margin = 'unset';
if (actionType === 'resize') {
power_user.movingUIState[elmntName].width = width;
power_user.movingUIState[elmntName].height = height;
eventSource.emit('resizeUI', elmntName);
}
saveSettingsDebounced();
}
// Helper: Clamp element within viewport
function clampToViewport() {
if (top <= 0) $elmnt.css('top', '0px');
else if (maxY >= winHeight) $elmnt.css('top', winHeight - maxY + top - 1 + 'px');
if (left <= 0) $elmnt.css('left', '0px');
else if (maxX >= winWidth) $elmnt.css('left', winWidth - maxX + left - 1 + 'px');
}
// Observer for style changes (position/size)
const observer = new MutationObserver((mutations) => {
const target = mutations[0].target;
if (!$(target).is(':visible') //abort if element is invisible
|| $(target).hasClass('resizing') //being auto-resized by other JS code
|| Number((String(target.height).replace('px', ''))) < 50 //too short
|| Number((String(target.width).replace('px', ''))) < 50 //too narrow
|| power_user.movingUI === false // if MUI is not turned on
|| isMobile() // if it's a mobile screen
const $target = $(mutations[0].target);
if (
!$target.is(':visible') ||
$target.hasClass('resizing') ||
$target.height() < 50 ||
$target.width() < 50 ||
power_user.movingUI === false ||
isMobile() ||
!isMouseDown
) {
observer.disconnect();
return;
}
const style = getComputedStyle(target);
const style = getComputedStyle($target[0]);
height = parseInt(style.height);
width = parseInt(style.width);
top = parseInt(style.top);
left = parseInt(style.left);
right = parseInt(style.right);
bottom = parseInt(style.bottom);
maxX = parseInt(width + left);
maxY = parseInt(height + top);
maxX = width + left;
maxY = height + top;
winWidth = window.innerWidth;
winHeight = window.innerHeight;
@@ -528,182 +546,119 @@ export function dragElement(elmnt) {
topBarFirstX = parseInt(topbarstyle.marginInline);
topBarLastY = parseInt(topbarstyle.height);
//prepare an empty poweruser object for the item being altered if we don't have one already
if (!power_user.movingUIState[elmntName]) {
console.debug(`adding config property for ${elmntName}`);
power_user.movingUIState[elmntName] = {};
}
// Prepare state object if missing
if (!power_user.movingUIState[elmntName]) power_user.movingUIState[elmntName] = {};
//handle resizing
if (!isHeaderBeingDragged && isMouseDown) { //if user is dragging the resize handle (not in header)
let imgHeight, imgWidth, imageAspectRatio;
if (actionType === 'resize') {
let containerAspectRatio = height / width;
//force aspect ratio for zoomed avatars
if ($(elmnt).attr('id').startsWith('zoomFor_')) {
let zoomedAvatarImage = $(elmnt).find('.zoomed_avatar_img');
imgHeight = zoomedAvatarImage.height();
imgWidth = zoomedAvatarImage.width();
imageAspectRatio = imgHeight / imgWidth;
// Maintain aspect ratio
if ($elmnt.attr('id').startsWith('zoomFor_')) {
const zoomedAvatarImage = $elmnt.find('.zoomed_avatar_img');
const imgHeight = zoomedAvatarImage.height();
const imgWidth = zoomedAvatarImage.width();
const imageAspectRatio = imgHeight / imgWidth;
if (containerAspectRatio !== imageAspectRatio) {
elmnt.css('width', elmnt.width());
elmnt.css('height', elmnt.width() * imageAspectRatio);
$elmnt.css('width', $elmnt.width());
$elmnt.css('height', $elmnt.width() * imageAspectRatio);
}
// Prevent resizing offscreen
if (top + elmnt.height() >= winHeight) {
elmnt.css('height', winHeight - top - 1 + 'px');
elmnt.css('width', (winHeight - top - 1) / imageAspectRatio + 'px');
if (top + $elmnt.height() >= winHeight) {
$elmnt.css('height', winHeight - top - 1 + 'px');
$elmnt.css('width', (winHeight - top - 1) / imageAspectRatio + 'px');
}
if (left + elmnt.width() >= winWidth) {
elmnt.css('width', winWidth - left - 1 + 'px');
elmnt.css('height', (winWidth - left - 1) * imageAspectRatio + 'px');
}
} else { //prevent divs that are not zoomedAvatars from resizing offscreen
if (top + elmnt.height() >= winHeight) {
elmnt.css('height', winHeight - top - 1 + 'px');
}
if (left + elmnt.width() >= winWidth) {
elmnt.css('width', winWidth - left - 1 + 'px');
if (left + $elmnt.width() >= winWidth) {
$elmnt.css('width', winWidth - left - 1 + 'px');
$elmnt.css('height', (winWidth - left - 1) * imageAspectRatio + 'px');
}
} else {
if (top + $elmnt.height() >= winHeight) $elmnt.css('height', winHeight - top - 1 + 'px');
if (left + $elmnt.width() >= winWidth) $elmnt.css('width', winWidth - left - 1 + 'px');
}
//prevent resizing from top left into the top bar
if (top < topBarLastY && maxX >= topBarFirstX && left <= topBarFirstX) {
elmnt.css('width', width - 1 + 'px');
$elmnt.css('width', width - 1 + 'px');
}
//set css to prevent weird resize behavior (does not save)
elmnt.css('left', left);
elmnt.css('top', top);
//set a listener for mouseup to save new width/height
$(window).off('mouseup').on('mouseup', () => {
console.log(`Saving ${elmntName} Height/Width`);
// check if the height or width actually changed
if (power_user.movingUIState[elmntName].width === elmnt.width() && power_user.movingUIState[elmntName].height === elmnt.height()) {
console.log('no change detected, aborting save');
return;
}
power_user.movingUIState[elmntName].width = width;
power_user.movingUIState[elmntName].height = height;
eventSource.emit('resizeUI', elmntName);
saveSettingsDebounced();
imgHeight = null;
imgWidth = null;
height = null;
width = null;
containerAspectRatio = null;
imageAspectRatio = null;
$(window).off('mouseup');
$elmnt.css({ left, top });
$elmnt.off('mouseup').on('mouseup', () => {
if (
power_user.movingUIState[elmntName].width === $elmnt.width() &&
power_user.movingUIState[elmntName].height === $elmnt.height()
) return;
savePositionAndSize();
observer.disconnect();
});
} else if (actionType === 'drag') {
clampToViewport();
}
//only record position changes if header is being dragged
power_user.movingUIState[elmntName].top = top;
power_user.movingUIState[elmntName].left = left;
power_user.movingUIState[elmntName].right = right;
power_user.movingUIState[elmntName].bottom = bottom;
power_user.movingUIState[elmntName].margin = 'unset';
//handle dragging hit detection to prevent dragging offscreen
if (isHeaderBeingDragged && isMouseDown) {
if (top <= 0) {
elmnt.css('top', '0px');
} else if (maxY >= winHeight) {
elmnt.css('top', winHeight - maxY + top - 1 + 'px');
}
if (left <= 0) {
elmnt.css('left', '0px');
} else if (maxX >= winWidth) {
elmnt.css('left', winWidth - maxX + left - 1 + 'px');
}
}
// Check if the element header exists and set the reposition listener on the grabber in the header
if (elmntHeader.length) {
elmntHeader.off('mousedown').on('mousedown', (e) => {
dragMouseDown(e);
});
} else { //if no header, put the listener on the elmnt itself.
elmnt.off('mousedown').on('mousedown', dragMouseDown);
}
// Always update position in state
savePositionAndSize();
});
// Mouse event handlers
function dragMouseDown(e) {
if (e) {
isHeaderBeingDragged = true;
actionType = 'drag';
isMouseDown = true;
e.preventDefault();
pos3 = e.clientX; //mouse X at click
pos4 = e.clientY; //mouse Y at click
pos3 = e.clientX;
pos4 = e.clientY;
}
$(document).on('mouseup', closeDragElement);
$(document).on('mousemove', elementDrag);
}
function elementDrag(e) {
if (!power_user.movingUIState[elmntName]) {
power_user.movingUIState[elmntName] = {};
}
e = e || window.event;
if (!power_user.movingUIState[elmntName]) power_user.movingUIState[elmntName] = {};
e.preventDefault();
pos1 = pos3 - e.clientX; //X change amt (-1 or 1)
pos2 = pos4 - e.clientY; //Y change amt (-1 or 1)
pos3 = e.clientX; //new mouse X
pos4 = e.clientY; //new mouse Y
elmnt.attr('data-dragged', 'true');
//first set css to computed values to avoid CSS NaN results from 'auto', etc
elmnt.css('left', (elmnt.offset().left) + 'px');
elmnt.css('top', (elmnt.offset().top) + 'px');
//then update element position styles to account for drag changes
elmnt.css('margin', 'unset');
elmnt.css('left', (elmnt.offset().left - pos1) + 'px');
elmnt.css('top', (elmnt.offset().top - pos2) + 'px');
/* elmnt.css('right', ((winWidth - maxX) + 'px'));
elmnt.css('bottom', ((winHeight - maxY) + 'px')); */
// Height/Width here are for visuals only, and are not saved to settings.
// This is required because some divs do hot have a set width/height
// and will default to shrink to min value of 100px set in CSS file
elmnt.css('height', height);
elmnt.css('width', width);
return;
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
$elmnt.attr('data-dragged', 'true');
$elmnt.css('left', ($elmnt.offset().left - pos1) + 'px');
$elmnt.css('top', ($elmnt.offset().top - pos2) + 'px');
$elmnt.css('margin', 'unset');
$elmnt.css('height', height);
$elmnt.css('width', width);
}
function closeDragElement() {
console.debug('drag finished');
isHeaderBeingDragged = false;
isMouseDown = false;
actionType = null;
$(document).off('mouseup', closeDragElement);
$(document).off('mousemove', elementDrag);
$('body').css('overflow', '');
// Clear the "data-dragged" attribute
elmnt.attr('data-dragged', 'false');
$elmnt.attr('data-dragged', 'false');
observer.disconnect();
console.debug(`Saving ${elmntName} UI position`);
saveSettingsDebounced();
top = null;
left = null;
right = null;
bottom = null;
maxX = null;
maxY = null;
savePositionAndSize();
}
// Setup event listeners
if ($elmntHeader.length) {
$elmntHeader.off('mousedown').on('mousedown', (e) => {
if ($(e.target).hasClass('drag-grabber')) {
actionType = 'drag';
isMouseDown = true;
observer.observe($elmnt[0], { attributes: true, attributeFilter: ['style'] });
dragMouseDown(e);
}
});
}
$elmnt.off('mousedown').on('mousedown', (e) => {
const rect = $elmnt[0].getBoundingClientRect();
const resizeMargin = 16;
const isNearRight = e.clientX > rect.right - resizeMargin;
const isNearBottom = e.clientY > rect.bottom - resizeMargin;
if (isNearRight && isNearBottom) {
actionType = 'resize';
isMouseDown = true;
observer.observe($elmnt[0], { attributes: true, attributeFilter: ['style'] });
}
});
$elmnt.off('mouseup').on('mouseup', () => {
isMouseDown = false;
actionType = null;
observer.disconnect();
});
}
export async function initMovingUI() {
@@ -754,7 +709,7 @@ export function initRossMods() {
RA_autoconnect();
}
$('#main_api').change(function () {
$('#main_api').on('change', function () {
var PrevAPI = main_api;
setTimeout(() => RA_autoconnect(PrevAPI), 100);
});
@@ -774,9 +729,8 @@ export function initRossMods() {
$(RightNavDrawerIcon).removeClass('drawerPinnedOpen');
if ($(RightNavPanel).hasClass('openDrawer') && $('.openDrawer').length > 1) {
slideToggle(RightNavPanel, getSlideToggleOptions());
$(RightNavDrawerIcon).toggleClass('closedIcon openIcon');
$(RightNavPanel).toggleClass('openDrawer closedDrawer');
const toggle = $('#unimportantYes');
doNavbarIconClick.call(toggle);
}
}
});
@@ -792,14 +746,13 @@ export function initRossMods() {
$(LeftNavDrawerIcon).removeClass('drawerPinnedOpen');
if ($(LeftNavPanel).hasClass('openDrawer') && $('.openDrawer').length > 1) {
slideToggle(LeftNavPanel, getSlideToggleOptions());
$(LeftNavDrawerIcon).toggleClass('closedIcon openIcon');
$(LeftNavPanel).toggleClass('openDrawer closedDrawer');
const toggle = $('#ai-config-button>.drawer-toggle');
doNavbarIconClick.call(toggle);
}
}
});
$(WIPanelPin).on('click', function () {
$(WIPanelPin).on('click', async function () {
accountStorage.setItem('WINavLockOn', $(WIPanelPin).prop('checked'));
if ($(WIPanelPin).prop('checked') == true) {
console.debug('adding pin class to WI');
@@ -812,9 +765,8 @@ export function initRossMods() {
if ($(WorldInfo).hasClass('openDrawer') && $('.openDrawer').length > 1) {
console.debug('closing WI after lock removal');
slideToggle(WorldInfo, getSlideToggleOptions());
$(WIDrawerIcon).toggleClass('closedIcon openIcon');
$(WorldInfo).toggleClass('openDrawer closedDrawer');
const toggle = $('#WI-SP-button>.drawer-toggle');
doNavbarIconClick.call(toggle);
}
}
});
@@ -880,11 +832,11 @@ export function initRossMods() {
});
var chatbarInFocus = false;
$('#send_textarea').focus(function () {
$('#send_textarea').on('focus', function () {
chatbarInFocus = true;
});
$('#send_textarea').blur(function () {
$('#send_textarea').on('blur', function () {
chatbarInFocus = false;
});
@@ -892,8 +844,8 @@ export function initRossMods() {
OpenNavPanels();
}, 300);
$(SelectedCharacterTab).click(function () { accountStorage.setItem('SelectedNavTab', 'rm_button_selected_ch'); });
$('#rm_button_characters').click(function () { accountStorage.setItem('SelectedNavTab', 'rm_button_characters'); });
$(SelectedCharacterTab).on('click', function () { accountStorage.setItem('SelectedNavTab', 'rm_button_selected_ch'); });
$('#rm_button_characters').on('click', function () { accountStorage.setItem('SelectedNavTab', 'rm_button_characters'); });
// when a char is selected from the list, save them as the auto-load character for next page load
@@ -978,7 +930,7 @@ export function initRossMods() {
var SwipeTargetMesClassParent = $(e.target).closest('.last_mes');
if (SwipeTargetMesClassParent !== null) {
if (SwipeButR.css('display') === 'flex') {
SwipeButR.click();
SwipeButR.trigger('click');
}
}
});
@@ -1002,7 +954,7 @@ export function initRossMods() {
var SwipeTargetMesClassParent = $(e.target).closest('.last_mes');
if (SwipeTargetMesClassParent !== null) {
if (SwipeButL.css('display') === 'flex') {
SwipeButL.click();
SwipeButL.trigger('click');
}
}
});
@@ -1205,7 +1157,7 @@ export function initRossMods() {
const lastMes = document.querySelector('.last_mes');
const editMes = lastMes.querySelector('.mes_block .mes_edit');
if (editMes !== null) {
$(editMes).click();
$(editMes).trigger('click');
return;
}
}
+17 -14
View File
@@ -1,9 +1,11 @@
import {
MAX_INJECTION_DEPTH,
animation_duration,
chat_metadata,
eventSource,
event_types,
extension_prompt_roles,
extension_prompt_types,
saveSettingsDebounced,
this_chid,
} from '../script.js';
@@ -347,7 +349,7 @@ export function setFloatingPrompt() {
}
if (lastMessageNumber <= 0 || chat_metadata[metadata_keys.interval] <= 0) {
context.setExtensionPrompt(MODULE_NAME, '');
context.setExtensionPrompt(MODULE_NAME, '', extension_prompt_types.NONE, MAX_INJECTION_DEPTH);
$('#extension_floating_counter').text('(disabled)');
shouldWIAddPrompt = false;
return;
@@ -380,7 +382,7 @@ export function setFloatingPrompt() {
}
context.setExtensionPrompt(
MODULE_NAME,
prompt,
String(prompt),
chat_metadata[metadata_keys.position],
chat_metadata[metadata_keys.depth],
extension_settings.note.allowWIScan,
@@ -396,37 +398,38 @@ function onANMenuItemClick() {
}
//show AN if it's hidden
if ($('#floatingPrompt').css('display') !== 'flex') {
$('#floatingPrompt').addClass('resizing');
$('#floatingPrompt').css('display', 'flex');
$('#floatingPrompt').css('opacity', 0.0);
$('#floatingPrompt').transition({
const $ANcontainer = $('#floatingPrompt');
if ($ANcontainer.css('display') !== 'flex') {
$ANcontainer.addClass('resizing');
$ANcontainer.css('display', 'flex');
$ANcontainer.css('opacity', 0.0);
$ANcontainer.transition({
opacity: 1.0,
duration: animation_duration,
}, async function () {
await delay(50);
$('#floatingPrompt').removeClass('resizing');
$ANcontainer.removeClass('resizing');
});
//auto-open the main AN inline drawer
if ($('#ANBlockToggle')
.siblings('.inline-drawer-content')
.css('display') !== 'block') {
$('#floatingPrompt').addClass('resizing');
$('#ANBlockToggle').click();
$ANcontainer.addClass('resizing');
$('#ANBlockToggle').trigger('click');
}
} else {
//hide AN if it's already displayed
$('#floatingPrompt').addClass('resizing');
$('#floatingPrompt').transition({
$ANcontainer.addClass('resizing');
$ANcontainer.transition({
opacity: 0.0,
duration: animation_duration,
}, async function () {
await delay(50);
$('#floatingPrompt').removeClass('resizing');
$ANcontainer.removeClass('resizing');
});
setTimeout(function () {
$('#floatingPrompt').hide();
$ANcontainer.hide();
}, animation_duration);
}
+36 -30
View File
@@ -21,6 +21,14 @@ export const AUTOCOMPLETE_SELECT_KEY = {
'ENTER': 2, // 2^1
};
/** @readonly */
/** @enum {Number} */
export const AUTOCOMPLETE_STATE = {
DISABLED: 0,
MIN_LENGTH: 1,
ALWAYS: 2,
};
export class AutoComplete {
/**@type {HTMLTextAreaElement|HTMLInputElement}*/ textarea;
/**@type {boolean}*/ isFloating = false;
@@ -109,20 +117,20 @@ export class AutoComplete {
this.updateDetailsPositionDebounced = debounce(this.updateDetailsPosition.bind(this), 10);
this.updateFloatingPositionDebounced = debounce(this.updateFloatingPosition.bind(this), 10);
textarea.addEventListener('input', ()=>{
textarea.addEventListener('input', () => {
this.selectionStart = this.textarea.selectionStart;
if (this.text != this.textarea.value) this.show(true, this.wasForced);
});
textarea.addEventListener('keydown', (evt)=>this.handleKeyDown(evt));
textarea.addEventListener('click', ()=>{
textarea.addEventListener('keydown', (evt) => this.handleKeyDown(evt));
textarea.addEventListener('click', () => {
this.selectionStart = this.textarea.selectionStart;
if (this.isActive) this.show();
});
textarea.addEventListener('blur', ()=>this.hide());
textarea.addEventListener('blur', () => this.hide());
if (isFloating) {
textarea.addEventListener('scroll', ()=>this.updateFloatingPositionDebounced());
textarea.addEventListener('scroll', () => this.updateFloatingPositionDebounced());
}
window.addEventListener('resize', ()=>this.updatePositionDebounced());
window.addEventListener('resize', () => this.updatePositionDebounced());
}
/**
@@ -132,9 +140,9 @@ export class AutoComplete {
makeItem(option) {
const li = option.renderItem();
// gotta listen to pointerdown (happens before textarea-blur)
li.addEventListener('pointerdown', (evt)=>{
li.addEventListener('pointerdown', (evt) => {
evt.preventDefault();
this.selectedItem = this.result.find(it=>it.name == li.getAttribute('data-name'));
this.selectedItem = this.result.find(it => it.name == li.getAttribute('data-name'));
this.select();
});
return li;
@@ -149,7 +157,7 @@ export class AutoComplete {
const chars = Array.from(item.dom.querySelector('.name').children);
switch (this.matchType) {
case 'strict': {
chars.forEach((it, idx)=>{
chars.forEach((it, idx) => {
if (idx + item.nameOffset < item.name.length) {
it.classList.add('matched');
} else {
@@ -160,7 +168,7 @@ export class AutoComplete {
}
case 'includes': {
const start = item.name.toLowerCase().search(this.name);
chars.forEach((it, idx)=>{
chars.forEach((it, idx) => {
if (idx + item.nameOffset < start) {
it.classList.remove('matched');
} else if (idx + item.nameOffset < start + item.name.length) {
@@ -172,18 +180,18 @@ export class AutoComplete {
break;
}
case 'fuzzy': {
item.name.replace(this.fuzzyRegex, (_, ...parts)=>{
item.name.replace(this.fuzzyRegex, (_, ...parts) => {
parts.splice(-2, 2);
if (parts.length == 2) {
chars.forEach(c=>c.classList.remove('matched'));
chars.forEach(c => c.classList.remove('matched'));
} else {
let cIdx = item.nameOffset;
parts.forEach((it, idx)=>{
parts.forEach((it, idx) => {
if (it === null || it.length == 0) return '';
if (idx % 2 == 1) {
chars.slice(cIdx, cIdx + it.length).forEach(c=>c.classList.add('matched'));
chars.slice(cIdx, cIdx + it.length).forEach(c => c.classList.add('matched'));
} else {
chars.slice(cIdx, cIdx + it.length).forEach(c=>c.classList.remove('matched'));
chars.slice(cIdx, cIdx + it.length).forEach(c => c.classList.remove('matched'));
}
cIdx += it.length;
});
@@ -230,7 +238,7 @@ export class AutoComplete {
if (current.length > 0) {
consecutive.push(current);
}
consecutive.sort((a,b)=>b.length - a.length);
consecutive.sort((a, b) => b.length - a.length);
option.score = new AutoCompleteFuzzyScore(start, consecutive[0]?.length ?? 0);
return option;
}
@@ -254,8 +262,7 @@ export class AutoComplete {
+ this.parserResult.name.length
+ (this.startQuote ? 1 : 0)
+ (this.endQuote ? 1 : 0)
+ 1
;
+ 1;
}
/**
@@ -344,7 +351,7 @@ export class AutoComplete {
if (this.matchType == 'fuzzy') {
// only build the fuzzy regex if match type is set to fuzzy
this.fuzzyRegex = new RegExp(`^(.*?)${this.name.split('').map(char=>`(${escapeRegex(char)})`).join('(.*?)')}(.*?)$`, 'i');
this.fuzzyRegex = new RegExp(`^(.*?)${this.name.split('').map(char => `(${escapeRegex(char)})`).join('(.*?)')}(.*?)$`, 'i');
}
//TODO maybe move the matchers somewhere else; a single match function? matchType is available as property
@@ -358,12 +365,12 @@ export class AutoComplete {
// filter the list of options by the partial name according to the matching type
.filter(it => this.isReplaceable || it.name == '' ? (it.matchProvider ? it.matchProvider(this.name) : matchers[this.matchType](it.name)) : it.name.toLowerCase() == this.name)
// remove aliases
.filter((it,idx,list) => list.findIndex(opt=>opt.value == it.value) == idx);
.filter((it, idx, list) => list.findIndex(opt => opt.value == it.value) == idx);
if (this.result.length == 0 && this.effectiveParserResult != this.parserResult && isForced) {
// no matching secondary results and forced trigger -> show current command details
this.secondaryParserResult = null;
this.result = [this.effectiveParserResult.optionList.find(it=>it.name == this.effectiveParserResult.name)];
this.result = [this.effectiveParserResult.optionList.find(it => it.name == this.effectiveParserResult.name)];
this.name = this.effectiveParserResult.name;
this.fuzzyRegex = /(.*)(.*)(.*)/;
}
@@ -387,8 +394,7 @@ export class AutoComplete {
return option;
})
// sort by fuzzy score or alphabetical
.toSorted(this.matchType == 'fuzzy' ? this.fuzzyScoreCompare : (a, b) => a.name.localeCompare(b.name))
;
.toSorted(this.matchType == 'fuzzy' ? this.fuzzyScoreCompare : (a, b) => a.name.localeCompare(b.name));
@@ -628,12 +634,12 @@ export class AutoComplete {
this.clone.style.position = 'fixed';
this.clone.style.visibility = 'hidden';
document.body.append(this.clone);
const mo = new MutationObserver(muts=>{
if (muts.find(it=>Array.from(it.removedNodes).includes(this.textarea))) {
const mo = new MutationObserver(muts => {
if (muts.find(it => Array.from(it.removedNodes).includes(this.textarea))) {
this.clone.remove();
}
});
mo.observe(this.textarea.parentElement, { childList:true });
mo.observe(this.textarea.parentElement, { childList: true });
}
this.clone.style.height = `${inputRect.height}px`;
this.clone.style.left = `${inputRect.left}px`;
@@ -685,7 +691,7 @@ export class AutoComplete {
this.textarea.selectionDirection = selectionEnd;
}
this.wasForced = false;
this.textarea.dispatchEvent(new Event('input', { bubbles:true }));
this.textarea.dispatchEvent(new Event('input', { bubbles: true }));
this.onSelect?.(this.selectedItem);
}
@@ -700,7 +706,7 @@ export class AutoComplete {
this.selectedItem.dom.classList.add('selected');
const rect = this.selectedItem.dom.children[0].getBoundingClientRect();
const rectParent = this.dom.getBoundingClientRect();
if (rect.top < rectParent.top || rect.bottom > rectParent.bottom ) {
if (rect.top < rectParent.top || rect.bottom > rectParent.bottom) {
this.dom.scrollTop += rect.top < rectParent.top ? rect.top - rectParent.top : rect.bottom - rectParent.bottom;
}
this.renderDetailsDebounced();
@@ -809,8 +815,8 @@ export class AutoComplete {
}
// await keyup to see if cursor position or text has changed
const oldText = this.textarea.value;
await new Promise(resolve=>{
window.addEventListener('keyup', resolve, { once:true });
await new Promise(resolve => {
window.addEventListener('keyup', resolve, { once: true });
});
if (this.selectionStart != this.textarea.selectionStart) {
this.selectionStart = this.textarea.selectionStart;
+174 -32
View File
@@ -1,20 +1,48 @@
import { Fuse } from '../lib.js';
import { callPopup, chat_metadata, eventSource, event_types, generateQuietPrompt, getCurrentChatId, getRequestHeaders, getThumbnailUrl, saveSettingsDebounced } from '../script.js';
import { Fuse, localforage } from '../lib.js';
import { chat_metadata, eventSource, event_types, generateQuietPrompt, getCurrentChatId, getRequestHeaders, getThumbnailUrl, saveSettingsDebounced } from '../script.js';
import { openThirdPartyExtensionMenu, saveMetadataDebounced } from './extensions.js';
import { SlashCommand } from './slash-commands/SlashCommand.js';
import { SlashCommandParser } from './slash-commands/SlashCommandParser.js';
import { flashHighlight, stringFormat } from './utils.js';
import { createThumbnail, flashHighlight, getBase64Async, stringFormat } from './utils.js';
import { t } from './i18n.js';
import { Popup } from './popup.js';
const BG_METADATA_KEY = 'custom_background';
const LIST_METADATA_KEY = 'chat_backgrounds';
// A single transparent PNG pixel used as a placeholder for errored backgrounds
const PNG_PIXEL = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=';
const PNG_PIXEL_BLOB = new Blob([Uint8Array.from(atob(PNG_PIXEL), c => c.charCodeAt(0))], { type: 'image/png' });
const PLACEHOLDER_IMAGE = `url('data:image/png;base64,${PNG_PIXEL}')`;
/**
* Storage for frontend-generated background thumbnails.
* This is used to store thumbnails for backgrounds that cannot be generated on the server.
*/
const THUMBNAIL_STORAGE = localforage.createInstance({ name: 'SillyTavern_Thumbnails' });
/**
* Cache for thumbnail blob URLs.
* @type {Map<string, string>}
*/
const THUMBNAIL_BLOBS = new Map();
const THUMBNAIL_CONFIG = {
width: 160,
height: 90,
};
/**
* Global IntersectionObserver instance for lazy loading backgrounds
* @type {IntersectionObserver|null}
*/
let lazyLoadObserver = null;
export let background_settings = {
name: '__transparent.png',
url: generateUrlParameter('__transparent.png', false),
fitting: 'classic',
animation: false,
};
export function loadBackgroundSettings(settings) {
@@ -25,16 +53,20 @@ export function loadBackgroundSettings(settings) {
if (!backgroundSettings.fitting) {
backgroundSettings.fitting = 'classic';
}
if (!Object.hasOwn(backgroundSettings, 'animation')) {
backgroundSettings.animation = false;
}
setBackground(backgroundSettings.name, backgroundSettings.url);
setFittingClass(backgroundSettings.fitting);
$('#background_fitting').val(backgroundSettings.fitting);
$('#background_thumbnails_animation').prop('checked', background_settings.animation);
}
/**
* Sets the background for the current chat and adds it to the list of custom backgrounds.
* @param {{url: string, path:string}} backgroundInfo
*/
function forceSetBackground(backgroundInfo) {
async function forceSetBackground(backgroundInfo) {
saveBackgroundMetadata(backgroundInfo.url);
setCustomBackground();
@@ -43,7 +75,7 @@ function forceSetBackground(backgroundInfo) {
list.push(bg);
chat_metadata[LIST_METADATA_KEY] = list;
saveMetadataDebounced();
getChatBackgroundsList();
await getChatBackgroundsList();
highlightNewBackground(bg);
highlightLockedBackground();
}
@@ -56,11 +88,11 @@ async function onChatChanged() {
unsetCustomBackground();
}
getChatBackgroundsList();
await getChatBackgroundsList();
highlightLockedBackground();
}
function getChatBackgroundsList() {
async function getChatBackgroundsList() {
const list = chat_metadata[LIST_METADATA_KEY];
const listEmpty = !Array.isArray(list) || list.length === 0;
@@ -72,9 +104,10 @@ function getChatBackgroundsList() {
}
for (const bg of list) {
const template = getBackgroundFromTemplate(bg, true);
const template = await getBackgroundFromTemplate(bg, true);
$('#bg_custom_content').append(template);
}
activateLazyLoader();
}
function getBackgroundPath(fileUrl) {
@@ -224,7 +257,49 @@ async function onCopyToSystemBackgroundClick(e) {
const index = list.indexOf(bgNames.oldBg);
list.splice(index, 1);
saveMetadataDebounced();
getChatBackgroundsList();
await getChatBackgroundsList();
}
/**
* Gets a thumbnail for the background from storage or fetches it if not available.
* It caches the thumbnail in local storage and returns a blob URL for the thumbnail.
* If the thumbnail cannot be fetched, it returns a transparent PNG pixel as a fallback.
* @param {string} bg Background URL
* @returns {Promise<string>} Blob URL of the thumbnail
*/
async function getThumbnailFromStorage(bg) {
const cachedBlobUrl = THUMBNAIL_BLOBS.get(bg);
if (cachedBlobUrl) {
return cachedBlobUrl;
}
const savedBlob = await THUMBNAIL_STORAGE.getItem(bg);
if (savedBlob) {
const savedBlobUrl = URL.createObjectURL(savedBlob);
THUMBNAIL_BLOBS.set(bg, savedBlobUrl);
return savedBlobUrl;
}
try {
const response = await fetch(getBackgroundPath(bg), { cache: 'force-cache' });
if (!response.ok) {
throw new Error('Fetch failed with status: ' + response.status);
}
const imageBlob = await response.blob();
const imageBase64 = await getBase64Async(imageBlob);
const thumbnailBase64 = await createThumbnail(imageBase64, THUMBNAIL_CONFIG.width, THUMBNAIL_CONFIG.height);
const thumbnailBlob = await fetch(thumbnailBase64).then(res => res.blob());
await THUMBNAIL_STORAGE.setItem(bg, thumbnailBlob);
const blobUrl = URL.createObjectURL(thumbnailBlob);
THUMBNAIL_BLOBS.set(bg, blobUrl);
return blobUrl;
} catch (error) {
console.error('Error fetching thumbnail, fallback image will be used:', error);
const fallbackBlob = PNG_PIXEL_BLOB;
const fallbackBlobUrl = URL.createObjectURL(fallbackBlob);
THUMBNAIL_BLOBS.set(bg, fallbackBlobUrl);
return fallbackBlobUrl;
}
}
/**
@@ -245,7 +320,7 @@ async function getNewBackgroundName(referenceElement) {
const fileExtension = oldBg.split('.').pop();
const fileNameBase = isCustom ? oldBg.split('/').pop() : oldBg;
const oldBgExtensionless = fileNameBase.replace(`.${fileExtension}`, '');
const newBgExtensionless = await callPopup('<h3>' + t`Enter new background name:` + '</h3>', 'input', oldBgExtensionless);
const newBgExtensionless = await Popup.show.input(t`Enter new background name:`, null, oldBgExtensionless);
if (!newBgExtensionless) {
console.debug('no new_bg_extensionless');
@@ -327,7 +402,7 @@ async function onDeleteBackgroundClick(e) {
}
if (isCustom) {
getChatBackgroundsList();
await getChatBackgroundsList();
saveMetadataDebounced();
}
}
@@ -346,7 +421,7 @@ async function autoBackgroundCommand() {
const list = options.map(option => `- ${option.text}`).join('\n');
const prompt = stringFormat(autoBgPrompt, list);
const reply = await generateQuietPrompt(prompt, false, false);
const reply = await generateQuietPrompt({ quietPrompt: prompt });
const fuse = new Fuse(options, { keys: ['text'] });
const bestMatch = fuse.search(reply, { limit: 1 });
@@ -372,22 +447,55 @@ export async function getBackgrounds() {
const response = await fetch('/api/backgrounds/all', {
method: 'POST',
headers: getRequestHeaders(),
body: JSON.stringify({
'': '',
}),
body: JSON.stringify({}),
});
if (response.ok) {
const getData = await response.json();
//background = getData;
//console.log(getData.length);
const { images, config } = await response.json();
Object.assign(THUMBNAIL_CONFIG, config);
$('#bg_menu_content').children('div').remove();
for (const bg of getData) {
const template = getBackgroundFromTemplate(bg, false);
for (const bg of images) {
const template = await getBackgroundFromTemplate(bg, false);
$('#bg_menu_content').append(template);
}
activateLazyLoader();
}
}
function activateLazyLoader() {
// Disconnect previous observer to prevent memory leaks
if (lazyLoadObserver) {
lazyLoadObserver.disconnect();
lazyLoadObserver = null;
}
const lazyLoadElements = document.querySelectorAll('.lazy-load-background');
const options = {
root: null,
rootMargin: '200px',
threshold: 0.01,
};
lazyLoadObserver = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.target instanceof HTMLElement && entry.isIntersecting) {
const target = entry.target;
const bg = target.getAttribute('bgfile');
const isCustom = target.getAttribute('custom') === 'true';
resolveImageUrl(bg, isCustom)
.then(url => { target.style.backgroundImage = url; })
.catch(() => { target.style.backgroundImage = PLACEHOLDER_IMAGE; });
target.classList.remove('lazy-load-background');
observer.unobserve(target);
}
});
}, options);
lazyLoadElements.forEach(element => {
lazyLoadObserver.observe(element);
});
}
/**
* Gets the CSS URL of the background
* @param {Element} block
@@ -401,23 +509,42 @@ function generateUrlParameter(bg, isCustom) {
return isCustom ? `url("${encodeURI(bg)}")` : `url("${getBackgroundPath(bg)}")`;
}
/**
* Resolves the image URL for the background.
* @param {string} bg Background file name
* @param {boolean} isCustom Is a custom background
* @returns {Promise<string>} CSS URL of the background
*/
async function resolveImageUrl(bg, isCustom) {
const fileExtension = bg.split('.').pop().toLowerCase();
const isAnimated = ['mp4', 'webp'].includes(fileExtension);
const thumbnailUrl = isAnimated && !background_settings.animation
? await getThumbnailFromStorage(bg)
: isCustom
? bg
: getThumbnailUrl('bg', bg);
return `url("${thumbnailUrl}")`;
}
/**
* Instantiates a background template
* @param {string} bg Path to background
* @param {boolean} isCustom Whether the background is custom
* @returns {JQuery<HTMLElement>} Background template
* @returns {Promise<JQuery<HTMLElement>>} Background template
*/
function getBackgroundFromTemplate(bg, isCustom) {
async function getBackgroundFromTemplate(bg, isCustom) {
const template = $('#background_template .bg_example').clone();
const thumbPath = isCustom ? bg : getThumbnailUrl('bg', bg);
const url = generateUrlParameter(bg, isCustom);
const title = isCustom ? bg.split('/').pop() : bg;
const friendlyTitle = title.slice(0, title.lastIndexOf('.'));
template.attr('title', title);
template.attr('bgfile', bg);
template.attr('custom', String(isCustom));
template.data('url', url);
template.css('background-image', `url('${thumbPath}')`);
template.addClass('lazy-load-background');
template.css('background-image', PLACEHOLDER_IMAGE);
template.find('.BGSampleTitle').text(friendlyTitle);
return template;
}
@@ -437,6 +564,12 @@ async function delBackground(bg) {
bg: bg,
}),
});
await THUMBNAIL_STORAGE.removeItem(bg);
if (THUMBNAIL_BLOBS.has(bg)) {
URL.revokeObjectURL(THUMBNAIL_BLOBS.get(bg));
THUMBNAIL_BLOBS.delete(bg);
}
}
async function onBackgroundUploadSelected() {
@@ -503,12 +636,9 @@ async function uploadBackground(formData) {
return;
}
const headers = getRequestHeaders();
delete headers['Content-Type'];
const response = await fetch('/api/backgrounds/upload', {
method: 'POST',
headers: headers,
headers: getRequestHeaders({ omitContentType: true }),
body: formData,
cache: 'no-cache',
});
@@ -572,17 +702,20 @@ export function initBackgrounds() {
$('#auto_background').on('click', autoBackgroundCommand);
$('#add_bg_button').on('change', onBackgroundUploadSelected);
$('#bg-filter').on('input', onBackgroundFilterInput);
SlashCommandParser.addCommandObject(SlashCommand.fromProps({ name: 'lockbg',
SlashCommandParser.addCommandObject(SlashCommand.fromProps({
name: 'lockbg',
callback: () => onLockBackgroundClick(new CustomEvent('click')),
aliases: ['bglock'],
helpString: 'Locks a background for the currently selected chat',
}));
SlashCommandParser.addCommandObject(SlashCommand.fromProps({ name: 'unlockbg',
SlashCommandParser.addCommandObject(SlashCommand.fromProps({
name: 'unlockbg',
callback: () => onUnlockBackgroundClick(new CustomEvent('click')),
aliases: ['bgunlock'],
helpString: 'Unlocks a background for the currently selected chat',
}));
SlashCommandParser.addCommandObject(SlashCommand.fromProps({ name: 'autobg',
SlashCommandParser.addCommandObject(SlashCommand.fromProps({
name: 'autobg',
callback: autoBackgroundCommand,
aliases: ['bgauto'],
helpString: 'Automatically changes the background based on the chat context using the AI request prompt',
@@ -593,4 +726,13 @@ export function initBackgrounds() {
setFittingClass(background_settings.fitting);
saveSettingsDebounced();
});
$('#background_thumbnails_animation').on('input', async function () {
background_settings.animation = !!$(this).prop('checked');
saveSettingsDebounced();
// Refresh background thumbnails
await getBackgrounds();
await onChatChanged();
});
}
+32 -13
View File
@@ -14,7 +14,6 @@ import {
} from '../script.js';
import { humanizedDateTime } from './RossAscends-mods.js';
import {
getGroupPastChats,
group_activation_strategy,
groups,
openGroupById,
@@ -40,22 +39,42 @@ import {
const bookmarkNameToken = 'Checkpoint #';
/**
* Gets the names of existing chats for the current character or group.
* @returns {Promise<string[]>} - Returns a promise that resolves to an array of existing chat names.
*/
async function getExistingChatNames() {
if (selected_group) {
const data = await getGroupPastChats(selected_group);
return data.map(x => x.file_name);
} else {
const response = await fetch('/api/characters/chats', {
method: 'POST',
headers: getRequestHeaders(),
body: JSON.stringify({ avatar_url: characters[this_chid].avatar }),
});
if (response.ok) {
const data = await response.json();
return Object.values(data).map(x => x.file_name.replace('.jsonl', ''));
const group = groups.find(x => x.id == selected_group);
if (group && Array.isArray(group.chats)) {
return [...group.chats];
}
return [];
}
if (this_chid === undefined) {
return [];
}
const character = characters[this_chid];
if (!character) {
return [];
}
const response = await fetch('/api/characters/chats', {
method: 'POST',
headers: getRequestHeaders(),
body: JSON.stringify({ avatar_url: character.avatar, simple: true }),
});
if (response.ok) {
const data = await response.json();
const chats = Object.values(data).map(x => x.file_name.replace('.jsonl', ''));
return [...chats];
}
return [];
}
async function getBookmarkName({ isReplace = false, forceName = null } = {}) {
+6 -2
View File
@@ -1,6 +1,6 @@
import { characterGroupOverlay } from '../script.js';
import { BulkEditOverlay, BulkEditOverlayState } from './BulkEditOverlay.js';
import { BulkEditOverlay, BulkEditOverlayState, CharacterContextMenu } from './BulkEditOverlay.js';
import { event_types, eventSource } from './events.js';
let is_bulk_edit = false;
@@ -121,4 +121,8 @@ export function initBulkEdit() {
$('#bulkEditButton').on('click', onEditButtonClick);
$('#bulkSelectAllButton').on('click', onSelectAllButtonClick);
$('#bulkDeleteButton').on('click', onDeleteButtonClick);
const characterContextMenu = new CharacterContextMenu(characterGroupOverlay);
eventSource.on(event_types.CHARACTER_PAGE_LOADED, characterGroupOverlay.onPageLoad);
console.debug('Character context menu initialized', characterContextMenu);
}
+1 -1
View File
@@ -135,7 +135,7 @@ function onCfgMenuItemClick() {
.siblings('.inline-drawer-content')
.css('display') !== 'block') {
$('#floatingPrompt').addClass('resizing');
$('#CFGBlockToggle').click();
$('#CFGBlockToggle').trigger('click');
}
} else {
//hide AN if it's already displayed
+78 -7
View File
@@ -1,3 +1,5 @@
import { t } from './i18n.js';
// the hash can be obtained from command line e.g. via: MODEL=path_to_model; python -c "import json, hashlib, sys; print(hashlib.sha256(json.load(open('"$MODEL"/tokenizer_config.json'))['chat_template'].encode()).hexdigest())"
// note that chat templates must be trimmed to match the llama.cpp metadata value
const hash_derivations = {
@@ -83,21 +85,31 @@ const hash_derivations = {
'854b703e44ca06bdb196cc471c728d15dbab61e744fe6cdce980086b61646ed1':
'GLM-4'
,
// Kimi K2, ...
'aab20feb9bc6881f941ea649356130ffbc4943b3c2577c0991e1fba90de5a0fc':
'Moonshot AI'
,
};
const substr_derivations = {
'<|im_start|>': 'ChatML', // qwen2.5, ...
};
const substr_derivations = [
['Moonshot AI', ['<|im_user|>user<|im_middle|>', '<|im_assistant|>assistant<|im_middle|>', '<|im_end|>']],
// Generic cases
['ChatML', ['<|im_start|>user', '<|im_start|>assistant', '<|im_end|>']],
];
const parse_derivation = derivation => (typeof derivation === 'string') ? {
'context': derivation,
'instruct': derivation,
} : derivation;
const not_found = { context: null, instruct: null };
export async function deriveTemplatesFromChatTemplate(chat_template, hash) {
if (chat_template.trim() === '') {
console.log('Missing chat template.');
return null;
return not_found;
}
if (hash in hash_derivations) {
@@ -105,12 +117,71 @@ export async function deriveTemplatesFromChatTemplate(chat_template, hash) {
}
// heuristics
for (const [substr, derivation] of Object.entries(substr_derivations) ) {
if (chat_template.includes(substr)) {
for (const [derivation, substr] of substr_derivations) {
if ([substr].flat().every(str => chat_template.includes(str))) {
return parse_derivation(derivation);
}
}
console.warn(`Unknown chat template hash: ${hash} for [${chat_template}]`);
return null;
return not_found;
}
export async function bindModelTemplates(power_user, online_status) {
if (online_status === 'no_connection') {
return false;
}
const chatTemplateHash = power_user.chat_template_hash;
const bindModelTemplates = power_user.model_templates_mappings[online_status]
?? power_user.model_templates_mappings[chatTemplateHash]
?? {};
const bindingsMatch = bindModelTemplates
&& power_user.context.preset == bindModelTemplates['context']
&& (!power_user.instruct.enabled || power_user.instruct.preset === bindModelTemplates['instruct']);
const bound = [];
if (bindingsMatch) {
// unmap current preset
delete power_user.model_templates_mappings[chatTemplateHash];
delete power_user.model_templates_mappings[online_status];
toastr.info(t`Context preset for ${online_status} will use defaults when loaded the next time.`);
} else {
if (power_user.context_derived) {
if (power_user.context.preset !== bindModelTemplates['context']) {
bound.push(`${power_user.context.preset} context preset`);
// toastr.info(`Bound ${power_user.context.preset} preset to currently loaded model and all models that share its chat template.`);
// map current preset to current chat template hash
bindModelTemplates['context'] = power_user.context.preset;
}
} else {
toastr.warning(t`Note: Context derivation is disabled. Not including context preset.`);
}
if (power_user.instruct.enabled) {
if (power_user.instruct_derived) {
if (power_user.instruct.preset !== bindModelTemplates['instruct']) {
bound.push(`${power_user.instruct.preset} instruct preset`);
bindModelTemplates['instruct'] = power_user.instruct.preset;
}
} else {
toastr.warning(t`Note: Instruct derivation is disabled. Not including instruct preset.`);
}
}
if (bound.length == 0) {
toastr.warning(t`No applicable presets available.`);
return false;
}
toastr.info(t`Bound ${online_status} to ${bound.join(', ')}.`);
if (!online_status.startsWith('koboldcpp/ggml-model-')) {
power_user.model_templates_mappings[online_status] = bindModelTemplates;
}
if (chatTemplateHash !== '') {
power_user.model_templates_mappings[chatTemplateHash] = bindModelTemplates;
}
}
return true;
}
+197 -17
View File
@@ -43,6 +43,8 @@ import {
extractTextFromOffice,
download,
getFileText,
getFileExtension,
convertTextToBase64,
} from './utils.js';
import { extension_settings, renderExtensionTemplateAsync, saveMetadataDebounced } from './extensions.js';
import { POPUP_RESULT, POPUP_TYPE, Popup, callGenericPopup } from './popup.js';
@@ -68,7 +70,7 @@ import { accountStorage } from './util/AccountStorage.js';
* @returns {Promise<string>} Converted file text
*/
const fileSizeLimit = 1024 * 1024 * 100; // 100 MB
const fileSizeLimit = 1024 * 1024 * 350; // 350 MB
const ATTACHMENT_SOURCE = {
GLOBAL: 'global',
CHARACTER: 'character',
@@ -204,13 +206,18 @@ export async function populateFileAttachment(message, inputId = 'file_form_input
const fileNamePrefix = `${Date.now()}_${slug}`;
const fileBase64 = await getBase64Async(file);
let base64Data = fileBase64.split(',')[1];
const extension = getFileExtension(file);
// If file is image
if (file.type.startsWith('image/')) {
const extension = file.type.split('/')[1];
const imageUrl = await saveBase64AsFile(base64Data, name2, fileNamePrefix, extension);
message.extra.image = imageUrl;
message.extra.inline_image = true;
}
// If file is video
else if (file.type.startsWith('video/')) {
const videoUrl = await saveBase64AsFile(base64Data, name2, fileNamePrefix, extension);
message.extra.video = videoUrl;
} else {
const uniqueFileName = `${fileNamePrefix}.txt`;
@@ -218,7 +225,7 @@ export async function populateFileAttachment(message, inputId = 'file_form_input
try {
const converter = getConverter(file.type);
const fileText = await converter(file);
base64Data = window.btoa(unescape(encodeURIComponent(fileText)));
base64Data = convertTextToBase64(fileText);
} catch (error) {
toastr.error(String(error), t`Could not convert file`);
console.error('Could not convert file', error);
@@ -241,6 +248,7 @@ export async function populateFileAttachment(message, inputId = 'file_form_input
} catch (error) {
console.error('Could not upload file', error);
toastr.error(t`Either the file is corrupted or its format is not supported.`, t`Could not upload the file`);
} finally {
$('#file_form').trigger('reset');
}
@@ -470,7 +478,7 @@ export async function appendFileContent(message, messageText) {
export function encodeStyleTags(text) {
const styleRegex = /<style>(.+?)<\/style>/gims;
return text.replaceAll(styleRegex, (_, match) => {
return `<custom-style>${escape(match)}</custom-style>`;
return `<custom-style>${encodeURIComponent(match)}</custom-style>`;
});
}
@@ -491,14 +499,7 @@ export function decodeStyleTags(text, { prefix } = { prefix: '.mes_text ' }) {
for (let i = 0; i < rule.selectors.length; i++) {
const selector = rule.selectors[i];
if (selector) {
const selectors = (selector.split(' ') ?? []).map((v) => {
if (v.startsWith('.')) {
return '.custom-' + v.substring(1);
}
return v;
}).join(' ');
rule.selectors[i] = prefix + selectors;
rule.selectors[i] = prefix + sanitizeSelector(selector);
}
}
}
@@ -507,6 +508,36 @@ export function decodeStyleTags(text, { prefix } = { prefix: '.mes_text ' }) {
}
}
function sanitizeSelector(selector) {
// Handle pseudo-classes that can contain nested selectors
const pseudoClasses = ['has', 'not', 'where', 'is', 'matches', 'any'];
const pseudoRegex = new RegExp(`:(${pseudoClasses.join('|')})\\(([^)]+)\\)`, 'g');
// First, sanitize any nested selectors within pseudo-classes
selector = selector.replace(pseudoRegex, (match, pseudoClass, content) => {
// Recursively sanitize the content within the pseudo-class
const sanitizedContent = sanitizeSimpleSelector(content);
return `:${pseudoClass}(${sanitizedContent})`;
});
// Then sanitize the main selector parts
return sanitizeSimpleSelector(selector);
}
function sanitizeSimpleSelector(selector) {
// Split by spaces but preserve complex selectors
return selector.split(/\s+/).map((part) => {
// Handle class selectors, but preserve pseudo-classes and other complex parts
return part.replace(/\.([\w-]+)/g, (match, className) => {
// Don't modify if it's already prefixed with 'custom-'
if (className.startsWith('custom-')) {
return match;
}
return `.custom-${className}`;
});
}).join(' ');
}
function sanitizeRuleSet(ruleSet) {
if (Array.isArray(ruleSet.selectors) || Array.isArray(ruleSet.declarations)) {
sanitizeRule(ruleSet);
@@ -523,7 +554,7 @@ export function decodeStyleTags(text, { prefix } = { prefix: '.mes_text ' }) {
return text.replaceAll(styleDecodeRegex, (_, style) => {
try {
let styleCleaned = unescape(style).replaceAll(/<br\/>/g, '');
let styleCleaned = decodeURIComponent(style).replaceAll(/<br\/>/g, '');
const ast = css.parse(styleCleaned);
const sheet = ast?.stylesheet;
if (sheet) {
@@ -887,6 +918,27 @@ async function deleteMessageImage() {
await saveChatConditional();
}
async function deleteMessageVideo() {
const confirm = await Popup.show.confirm(t`Delete video from message?`, t`This action can't be undone.`);
if (!confirm) {
return;
}
const mesBlock = $(this).closest('.mes');
const mesId = mesBlock.attr('mesid');
const message = chat[mesId];
if (!message?.extra?.video) {
console.warn('Message has no video or it is empty');
return;
}
delete message.extra.video;
mesBlock.find('.mes_video_container').remove();
await saveChatConditional();
}
/**
* Deletes file from the server.
* @param {string} url Path to the file on the server
@@ -1240,7 +1292,7 @@ async function openAttachmentManager() {
return () => {
modalButtonData.forEach(p => {
const { popper,bodyListener } = p;
const { popper, bodyListener } = p;
popper.destroy();
document.body.removeEventListener('click', bodyListener);
});
@@ -1469,14 +1521,14 @@ export async function uploadFileAttachmentToServer(file, target) {
try {
const converter = getConverter(file.type);
const fileText = await converter(file);
base64Data = window.btoa(unescape(encodeURIComponent(fileText)));
base64Data = convertTextToBase64(fileText);
} catch (error) {
toastr.error(String(error), t`Could not convert file`);
console.error('Could not convert file', error);
}
} else {
const fileText = await file.text();
base64Data = window.btoa(unescape(encodeURIComponent(fileText)));
base64Data = convertTextToBase64(fileText);
}
const fileUrl = await uploadFileAttachment(uniqueFileName, base64Data);
@@ -1664,6 +1716,132 @@ export function registerFileConverter(mimeType, converter) {
converters[mimeType] = converter;
}
export function addDOMPurifyHooks() {
// Allow target="_blank" in links
DOMPurify.addHook('afterSanitizeAttributes', function (node) {
if ('target' in node) {
node.setAttribute('target', '_blank');
node.setAttribute('rel', 'noopener');
}
});
DOMPurify.addHook('uponSanitizeAttribute', (node, data, config) => {
if (!config['MESSAGE_SANITIZE']) {
return;
}
/* Retain the classes on UI elements of messages that interact with the main UI */
const permittedNodeTypes = ['BUTTON', 'DIV'];
if (config['MESSAGE_ALLOW_SYSTEM_UI'] && node.classList.contains('menu_button') && permittedNodeTypes.includes(node.nodeName)) {
return;
}
switch (data.attrName) {
case 'class': {
if (data.attrValue) {
data.attrValue = data.attrValue.split(' ').map((v) => {
if (v.startsWith('fa-') || v.startsWith('note-') || v === 'monospace') {
return v;
}
return 'custom-' + v;
}).join(' ');
}
break;
}
}
});
DOMPurify.addHook('uponSanitizeElement', (node, _, config) => {
if (!config['MESSAGE_SANITIZE']) {
return;
}
// Replace line breaks with <br> in unknown elements
if (node instanceof HTMLUnknownElement) {
node.innerHTML = node.innerHTML.trim().replaceAll('\n', '<br>');
}
const isMediaAllowed = isExternalMediaAllowed();
if (isMediaAllowed) {
return;
}
if (!(node instanceof Element)) {
return;
}
let mediaBlocked = false;
switch (node.tagName) {
case 'AUDIO':
case 'VIDEO':
case 'SOURCE':
case 'TRACK':
case 'EMBED':
case 'OBJECT':
case 'IMG': {
const isExternalUrl = (url) => (url.indexOf('://') > 0 || url.indexOf('//') === 0) && !url.startsWith(window.location.origin);
const src = node.getAttribute('src');
const data = node.getAttribute('data');
const srcset = node.getAttribute('srcset');
if (srcset) {
const srcsetUrls = srcset.split(',');
for (const srcsetUrl of srcsetUrls) {
const [url] = srcsetUrl.trim().split(' ');
if (isExternalUrl(url)) {
console.warn('External media blocked', url);
node.remove();
mediaBlocked = true;
break;
}
}
}
if (src && isExternalUrl(src)) {
console.warn('External media blocked', src);
mediaBlocked = true;
node.remove();
}
if (data && isExternalUrl(data)) {
console.warn('External media blocked', data);
mediaBlocked = true;
node.remove();
}
if (mediaBlocked && (node instanceof HTMLMediaElement)) {
node.autoplay = false;
node.pause();
}
}
break;
}
if (mediaBlocked) {
const entityId = getCurrentEntityId();
const warningShownKey = `mediaWarningShown:${entityId}`;
if (accountStorage.getItem(warningShownKey) === null) {
const warningToast = toastr.warning(
t`Use the 'Ext. Media' button to allow it. Click on this message to dismiss.`,
t`External media has been blocked`,
{
timeOut: 0,
preventDuplicates: true,
onclick: () => toastr.clear(warningToast),
},
);
accountStorage.setItem(warningShownKey, 'true');
}
}
});
}
export function initChatUtilities() {
$(document).on('click', '.mes_hide', async function () {
const messageBlock = $(this).closest('.mes');
@@ -1843,13 +2021,15 @@ export function initChatUtilities() {
reloadCurrentChat();
});
$('#creators_note_styles_button').on('click', function () {
$('#creators_note_styles_button').on('click', function (e) {
e.stopPropagation();
openGlobalStylesPreferenceDialog();
});
$(document).on('click', '.mes_img', expandMessageImage);
$(document).on('click', '.mes_img_enlarge', expandAndZoomMessageImage);
$(document).on('click', '.mes_img_delete', deleteMessageImage);
$(document).on('click', '.mes_video_delete', deleteMessageVideo);
$('#file_form_input').on('change', async () => {
const fileInput = document.getElementById('file_form_input');
+18
View File
@@ -22,3 +22,21 @@ export const debounce_timeout = {
* which is needed to preserve world info timed effects.
*/
export const IGNORE_SYMBOL = Symbol.for('ignore');
/**
* Common video file extensions. Should be the same as supported by Gemini.
* https://ai.google.dev/gemini-api/docs/video-understanding#supported-formats
*/
export const VIDEO_EXTENSIONS = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm', '3gp', 'mkv', 'mpg'];
/**
* Known generation triggers that can be passed to Generate function.
*/
export const GENERATION_TYPE_TRIGGERS = [
'normal',
'continue',
'impersonate',
'swipe',
'regenerate',
'quiet',
];
+11 -6
View File
@@ -1,5 +1,5 @@
import { getPresetManager } from './preset-manager.js';
import { extractMessageFromData, getGenerateUrl, getRequestHeaders } from '../script.js';
import { extractJsonFromData, extractMessageFromData, getGenerateUrl, getRequestHeaders } from '../script.js';
import { getTextGenServer } from './textgen-settings.js';
import { extractReasoningFromData } from './reasoning.js';
import { formatInstructModeChat, formatInstructModePrompt, getInstructStoppingSequences, names_behavior_types } from './instruct-mode.js';
@@ -279,9 +279,9 @@ export class TextCompletionService {
instructPreset,
);
} else { // e.g. "<|im_start|>assistant: Hello, my name is"
const overridenInstructPreset = structuredClone(instructPreset);
overridenInstructPreset.output_suffix = '';
overridenInstructPreset.wrap = false;
const overriddenInstructPreset = structuredClone(instructPreset);
overriddenInstructPreset.output_suffix = '';
overriddenInstructPreset.wrap = false;
messageContent = formatInstructModeChat(
message.role,
message.content,
@@ -291,7 +291,7 @@ export class TextCompletionService {
undefined,
undefined,
undefined,
overridenInstructPreset,
overriddenInstructPreset,
);
}
}
@@ -467,7 +467,7 @@ export class ChatCompletionService {
return json;
}
return {
const result = {
content: extractMessageFromData(json, this.TYPE),
reasoning: extractReasoningFromData(json, {
mainApi: this.TYPE,
@@ -475,6 +475,11 @@ export class ChatCompletionService {
ignoreShowThoughts: true,
}),
};
// Try parse JSON
if (data.json_schema) {
result.content = JSON.parse(extractJsonFromData(json, { mainApi: this.TYPE, chatCompletionSource: data.chat_completion_source }));
}
return result;
}
if (!response.ok) {
+405
View File
@@ -0,0 +1,405 @@
import { getRequestHeaders } from '../script.js';
import { VIDEO_EXTENSIONS } from './constants.js';
import { t } from './i18n.js';
import { callGenericPopup, Popup, POPUP_TYPE } from './popup.js';
import { renderTemplateAsync } from './templates.js';
import { humanFileSize, timestampToMoment } from './utils.js';
/**
* @typedef {object} DataMaidReportResult
* @property {import('../../src/endpoints/data-maid.js').DataMaidSanitizedReport} report - The sanitized report of the Data Maid.
* @property {string} token - The token to use for the Data Maid report.
*/
/**
* Data Maid Dialog class for managing the cleanup dialog interface.
*/
class DataMaidDialog {
constructor() {
this.token = null;
this.container = null;
this.isScanning = false;
this.DATA_MAID_CATEGORIES = {
files: {
name: t`Files`,
description: t`Files that are not associated with chat messages or Data Bank. WILL DELETE MANUAL UPLOADS!`,
},
images: {
name: t`Images`,
description: t`Images that are not associated with chat messages. WILL DELETE MANUAL UPLOADS!`,
},
chats: {
name: t`Chats`,
description: t`Chat files associated with deleted characters.`,
},
groupChats: {
name: t`Group Chats`,
description: t`Chat files associated with deleted groups.`,
},
avatarThumbnails: {
name: t`Avatar Thumbnails`,
description: t`Thumbnails for avatars of missing or deleted characters.`,
},
backgroundThumbnails: {
name: t`Background Thumbnails`,
description: t`Thumbnails for missing or deleted backgrounds.`,
},
personaThumbnails: {
name: t`Persona Thumbnails`,
description: t`Thumbnails for missing or deleted personas.`,
},
chatBackups: {
name: t`Chat Backups`,
description: t`Automatically generated chat backups.`,
},
settingsBackups: {
name: t`Settings Backups`,
description: t`Automatically generated settings backups.`,
},
};
}
/**
* Returns a promise that resolves to the Data Maid report.
* @returns {Promise<DataMaidReportResult>}
* @private
*/
async getReport() {
const response = await fetch('/api/data-maid/report', {
method: 'POST',
headers: getRequestHeaders(),
});
if (!response.ok) {
throw new Error(`Error fetching Data Maid report: ${response.statusText}`);
}
return await response.json();
}
/**
* Finalizes the Data Maid process by sending a request to the server.
* @returns {Promise<void>}
* @private
*/
async finalize() {
const response = await fetch('/api/data-maid/finalize', {
method: 'POST',
headers: getRequestHeaders(),
body: JSON.stringify({ token: this.token }),
});
if (!response.ok) {
throw new Error(`Error finalizing Data Maid: ${response.statusText}`);
}
}
/**
* Sets up the dialog UI elements and event listeners.
* @private
*/
async setupDialogUI() {
const template = await renderTemplateAsync('dataMaidDialog');
this.container = document.createElement('div');
this.container.classList.add('dataMaidDialogContainer');
this.container.innerHTML = template;
const startButton = this.container.querySelector('.dataMaidStartButton');
startButton.addEventListener('click', () => this.handleScanClick());
}
/**
* Handles the scan button click event.
* @private
*/
async handleScanClick() {
if (this.isScanning) {
toastr.warning(t`The scan is already running. Please wait for it to finish.`);
return;
}
try {
const resultsList = this.container.querySelector('.dataMaidResultsList');
resultsList.innerHTML = '';
this.showSpinner();
this.isScanning = true;
const report = await this.getReport();
this.hideSpinner();
await this.renderReport(report, resultsList);
this.token = report.token;
} catch (error) {
this.hideSpinner();
toastr.error(t`An error has occurred. Check the console for details.`);
console.error('Error generating Data Maid report:', error);
} finally {
this.isScanning = false;
}
}
/**
* Shows the loading spinner and hides the placeholder.
* @private
*/
showSpinner() {
const spinner = this.container.querySelector('.dataMaidSpinner');
const placeholder = this.container.querySelector('.dataMaidPlaceholder');
placeholder.classList.add('displayNone');
spinner.classList.remove('displayNone');
}
/**
* Hides the loading spinner.
* @private
*/
hideSpinner() {
const spinner = this.container.querySelector('.dataMaidSpinner');
spinner.classList.add('displayNone');
}
/**
* Renders the Data Maid report into the results list.
* @param {DataMaidReportResult} report
* @param {Element} resultsList
* @private
*/
async renderReport(report, resultsList) {
for (const [prop, data] of Object.entries(this.DATA_MAID_CATEGORIES)) {
const category = await this.renderCategory(prop, data.name, data.description, report.report[prop]);
if (!category) {
continue;
}
resultsList.appendChild(category);
}
this.displayEmptyPlaceholder();
}
/**
* Displays a placeholder message if no items are found in the results list.
* @private
*/
displayEmptyPlaceholder() {
const resultsList = this.container.querySelector('.dataMaidResultsList');
if (resultsList.children.length === 0) {
const placeholder = this.container.querySelector('.dataMaidPlaceholder');
placeholder.classList.remove('displayNone');
placeholder.textContent = t`No items found to clean up. Come back later!`;
}
}
/**
* Renders a single Data Maid category into a DOM element.
* @param {string} prop Property name for the category
* @param {string} name Name of the category
* @param {string} description Description of the category
* @param {import('../../src/endpoints/data-maid.js').DataMaidSanitizedRecord[]} items List of items in the category
* @return {Promise<Element|null>} A promise that resolves to a DOM element containing the rendered category
* @private
*/
async renderCategory(prop, name, description, items) {
if (!Array.isArray(items) || items.length === 0) {
return null;
}
const viewModel = {
name: name,
description: description,
totalSize: humanFileSize(items.reduce((sum, item) => sum + item.size, 0)),
totalItems: items.length,
items: items.sort((a, b) => b.mtime - a.mtime).map(item => ({
...item,
size: humanFileSize(item.size),
date: timestampToMoment(item.mtime).format('L LT'),
})),
};
const template = await renderTemplateAsync('dataMaidCategory', viewModel);
const categoryElement = document.createElement('div');
categoryElement.innerHTML = template;
categoryElement.querySelectorAll('.dataMaidItemView').forEach(button => {
button.addEventListener('click', async () => {
const item = button.closest('.dataMaidItem');
const hash = item?.getAttribute('data-hash');
const itemName = items.find(i => i.hash === hash)?.name;
if (hash) {
await this.view(prop, hash, itemName);
}
});
});
categoryElement.querySelectorAll('.dataMaidItemDownload').forEach(button => {
button.addEventListener('click', async () => {
const item = button.closest('.dataMaidItem');
const hash = item?.getAttribute('data-hash');
if (hash) {
await this.download(items, hash);
}
});
});
categoryElement.querySelectorAll('.dataMaidDeleteAll').forEach(button => {
button.addEventListener('click', async (event) => {
event.stopPropagation();
const confirm = await Popup.show.confirm(t`Are you sure?`, t`This will permanently delete all files in this category. THIS CANNOT BE UNDONE!`);
if (!confirm) {
return;
}
const hashes = items.map(item => item.hash).filter(hash => hash);
await this.delete(hashes);
categoryElement.remove();
this.displayEmptyPlaceholder();
});
});
categoryElement.querySelectorAll('.dataMaidItemDelete').forEach(button => {
button.addEventListener('click', async () => {
const item = button.closest('.dataMaidItem');
const hash = item?.getAttribute('data-hash');
if (hash) {
const confirm = await Popup.show.confirm(t`Are you sure?`, t`This will permanently delete the file. THIS CANNOT BE UNDONE!`);
if (!confirm) {
return;
}
if (await this.delete([hash])) {
item.remove();
items.splice(items.findIndex(i => i.hash === hash), 1);
if (items.length === 0) {
categoryElement.remove();
this.displayEmptyPlaceholder();
}
}
}
});
});
return categoryElement;
}
/**
* Constructs the URL for viewing an item by its hash.
* @param {string} hash Hash of the item to view
* @returns {string} URL to view the item
* @private
*/
getViewUrl(hash) {
return `/api/data-maid/view?hash=${encodeURIComponent(hash)}&token=${encodeURIComponent(this.token)}`;
}
/**
* Downloads an item by its hash.
* @param {import('../../src/endpoints/data-maid.js').DataMaidSanitizedRecord[]} items List of items in the category
* @param {string} hash Hash of the item to download
* @private
*/
async download(items, hash) {
const item = items.find(i => i.hash === hash);
if (!item) {
return;
}
const url = this.getViewUrl(hash);
const a = document.createElement('a');
a.href = url;
a.download = item?.name || hash;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
/**
* Opens the item view for a specific hash.
* @param {string} prop Property name for the category
* @param {string} hash Item hash to view
* @param {string} name Name of the item to view
* @private
*/
async view(prop, hash, name) {
const url = this.getViewUrl(hash);
const isImage = ['images', 'avatarThumbnails', 'backgroundThumbnails'].includes(prop);
const element = isImage
? await this.getViewElement(url, name)
: await this.getTextViewElement(url);
await callGenericPopup(element, POPUP_TYPE.DISPLAY, '', { large: true, wide: true });
}
/**
* Deletes an item by its file path hash.
* @param {string[]} hashes Hashes of items to delete
* @return {Promise<boolean>} True if the deletion was successful, false otherwise
* @private
*/
async delete(hashes) {
try {
const response = await fetch('/api/data-maid/delete', {
method: 'POST',
headers: getRequestHeaders(),
body: JSON.stringify({ hashes: hashes, token: this.token }),
});
if (!response.ok) {
throw new Error(`Error deleting item: ${response.statusText}`);
}
return true;
} catch (error) {
console.error('Error deleting item:', error);
return false;
}
}
/**
* Gets a media element for viewing images or videos.
* @param {string} url View URL
* @param {string} name Name of the file
* @returns {Promise<HTMLElement>} Image element
* @private
*/
async getViewElement(url, name) {
const isVideo = VIDEO_EXTENSIONS.includes(name.split('.').pop());
const mediaElement = document.createElement(isVideo ? 'video' : 'img');
if (mediaElement instanceof HTMLVideoElement) {
mediaElement.controls = true;
}
mediaElement.src = url;
mediaElement.classList.add('dataMaidImageView');
return mediaElement;
}
/**
* Gets an iframe element for viewing text content.
* @param {string} url View URL
* @returns {Promise<HTMLTextAreaElement>} Frame element
* @private
*/
async getTextViewElement(url) {
const response = await fetch(url);
const text = await response.text();
const element = document.createElement('textarea');
element.classList.add('dataMaidTextView');
element.readOnly = true;
element.textContent = text;
return element;
}
/**
* Opens the Data Maid dialog and handles the interaction.
*/
async open() {
await this.setupDialogUI();
await callGenericPopup(this.container, POPUP_TYPE.TEXT, '', { wide: true, large: true });
if (this.token) {
await this.finalize();
}
}
}
export function initDataMaid() {
const dataMaidButton = document.getElementById('data_maid_button');
if (!dataMaidButton) {
console.warn('Data Maid button not found');
return;
}
dataMaidButton.addEventListener('click', () => new DataMaidDialog().open());
}
+92
View File
@@ -0,0 +1,92 @@
import { EventEmitter } from '../lib/eventemitter.js';
export const event_types = {
APP_READY: 'app_ready',
EXTRAS_CONNECTED: 'extras_connected',
MESSAGE_SWIPED: 'message_swiped',
MESSAGE_SENT: 'message_sent',
MESSAGE_RECEIVED: 'message_received',
MESSAGE_EDITED: 'message_edited',
MESSAGE_DELETED: 'message_deleted',
MESSAGE_UPDATED: 'message_updated',
MESSAGE_FILE_EMBEDDED: 'message_file_embedded',
MESSAGE_REASONING_EDITED: 'message_reasoning_edited',
MESSAGE_REASONING_DELETED: 'message_reasoning_deleted',
MORE_MESSAGES_LOADED: 'more_messages_loaded',
IMPERSONATE_READY: 'impersonate_ready',
CHAT_CHANGED: 'chat_id_changed',
GENERATION_AFTER_COMMANDS: 'GENERATION_AFTER_COMMANDS',
GENERATION_STARTED: 'generation_started',
GENERATION_STOPPED: 'generation_stopped',
GENERATION_ENDED: 'generation_ended',
SD_PROMPT_PROCESSING: 'sd_prompt_processing',
EXTENSIONS_FIRST_LOAD: 'extensions_first_load',
EXTENSION_SETTINGS_LOADED: 'extension_settings_loaded',
SETTINGS_LOADED: 'settings_loaded',
SETTINGS_UPDATED: 'settings_updated',
GROUP_UPDATED: 'group_updated',
MOVABLE_PANELS_RESET: 'movable_panels_reset',
SETTINGS_LOADED_BEFORE: 'settings_loaded_before',
SETTINGS_LOADED_AFTER: 'settings_loaded_after',
CHATCOMPLETION_SOURCE_CHANGED: 'chatcompletion_source_changed',
CHATCOMPLETION_MODEL_CHANGED: 'chatcompletion_model_changed',
OAI_PRESET_CHANGED_BEFORE: 'oai_preset_changed_before',
OAI_PRESET_CHANGED_AFTER: 'oai_preset_changed_after',
OAI_PRESET_EXPORT_READY: 'oai_preset_export_ready',
OAI_PRESET_IMPORT_READY: 'oai_preset_import_ready',
WORLDINFO_SETTINGS_UPDATED: 'worldinfo_settings_updated',
WORLDINFO_UPDATED: 'worldinfo_updated',
CHARACTER_EDITED: 'character_edited',
CHARACTER_PAGE_LOADED: 'character_page_loaded',
CHARACTER_GROUP_OVERLAY_STATE_CHANGE_BEFORE: 'character_group_overlay_state_change_before',
CHARACTER_GROUP_OVERLAY_STATE_CHANGE_AFTER: 'character_group_overlay_state_change_after',
USER_MESSAGE_RENDERED: 'user_message_rendered',
CHARACTER_MESSAGE_RENDERED: 'character_message_rendered',
FORCE_SET_BACKGROUND: 'force_set_background',
CHAT_DELETED: 'chat_deleted',
CHAT_CREATED: 'chat_created',
GROUP_CHAT_DELETED: 'group_chat_deleted',
GROUP_CHAT_CREATED: 'group_chat_created',
GENERATE_BEFORE_COMBINE_PROMPTS: 'generate_before_combine_prompts',
GENERATE_AFTER_COMBINE_PROMPTS: 'generate_after_combine_prompts',
GENERATE_AFTER_DATA: 'generate_after_data',
GROUP_MEMBER_DRAFTED: 'group_member_drafted',
GROUP_WRAPPER_STARTED: 'group_wrapper_started',
GROUP_WRAPPER_FINISHED: 'group_wrapper_finished',
WORLD_INFO_ACTIVATED: 'world_info_activated',
TEXT_COMPLETION_SETTINGS_READY: 'text_completion_settings_ready',
CHAT_COMPLETION_SETTINGS_READY: 'chat_completion_settings_ready',
CHAT_COMPLETION_PROMPT_READY: 'chat_completion_prompt_ready',
CHARACTER_FIRST_MESSAGE_SELECTED: 'character_first_message_selected',
// TODO: Naming convention is inconsistent with other events
CHARACTER_DELETED: 'characterDeleted',
CHARACTER_DUPLICATED: 'character_duplicated',
CHARACTER_RENAMED: 'character_renamed',
CHARACTER_RENAMED_IN_PAST_CHAT: 'character_renamed_in_past_chat',
/** @deprecated The event is aliased to STREAM_TOKEN_RECEIVED. */
SMOOTH_STREAM_TOKEN_RECEIVED: 'stream_token_received',
STREAM_TOKEN_RECEIVED: 'stream_token_received',
STREAM_REASONING_DONE: 'stream_reasoning_done',
FILE_ATTACHMENT_DELETED: 'file_attachment_deleted',
WORLDINFO_FORCE_ACTIVATE: 'worldinfo_force_activate',
OPEN_CHARACTER_LIBRARY: 'open_character_library',
ONLINE_STATUS_CHANGED: 'online_status_changed',
IMAGE_SWIPED: 'image_swiped',
CONNECTION_PROFILE_LOADED: 'connection_profile_loaded',
CONNECTION_PROFILE_CREATED: 'connection_profile_created',
CONNECTION_PROFILE_DELETED: 'connection_profile_deleted',
CONNECTION_PROFILE_UPDATED: 'connection_profile_updated',
TOOL_CALLS_PERFORMED: 'tool_calls_performed',
TOOL_CALLS_RENDERED: 'tool_calls_rendered',
CHARACTER_MANAGEMENT_DROPDOWN: 'charManagementDropdown',
SECRET_WRITTEN: 'secret_written',
SECRET_DELETED: 'secret_deleted',
SECRET_ROTATED: 'secret_rotated',
SECRET_EDITED: 'secret_edited',
PRESET_CHANGED: 'preset_changed',
PRESET_DELETED: 'preset_deleted',
MAIN_API_CHANGED: 'main_api_changed',
WORLDINFO_ENTRIES_LOADED: 'worldinfo_entries_loaded',
};
export const eventSource = new EventEmitter([event_types.APP_READY]);
+99 -12
View File
@@ -36,7 +36,13 @@ export let modules = [];
* A set of active extensions.
* @type {Set<string>}
*/
let activeExtensions = new Set();
const activeExtensions = new Set();
/**
* Errors that occurred while loading extensions.
* @type {Set<string>}
*/
const extensionLoadErrors = new Set();
const getApiUrl = () => extension_settings.apiUrl;
const sortManifestsByOrder = (a, b) => parseInt(a.loading_order) - parseInt(b.loading_order) || String(a.display_name).localeCompare(String(b.display_name));
@@ -172,6 +178,7 @@ export const extension_settings = {
llmPrompt: undefined,
allowMultiple: true,
rerollIfSame: false,
promptType: 'raw',
},
connectionManager: {
selectedProfile: '',
@@ -379,37 +386,90 @@ async function getManifests(names) {
* @returns {Promise<void>}
*/
async function activateExtensions() {
extensionLoadErrors.clear();
const extensions = Object.entries(manifests).sort((a, b) => sortManifestsByOrder(a[1], b[1]));
const extensionNames = extensions.map(x => x[0]);
const promises = [];
for (let entry of extensions) {
const name = entry[0];
const manifest = entry[1];
const extrasRequirements = manifest.requires;
const extensionDependencies = manifest.dependencies;
const displayName = manifest.display_name || name;
if (activeExtensions.has(name)) {
continue;
}
const meetsModuleRequirements = !Array.isArray(manifest.requires) || isSubsetOf(modules, manifest.requires);
// Module requirements: pass if 'requires' is undefined, null, or not an array; check subset if it's an array
let meetsModuleRequirements = true;
let missingModules = [];
if (extrasRequirements !== undefined) {
if (Array.isArray(extrasRequirements)) {
meetsModuleRequirements = isSubsetOf(modules, extrasRequirements);
missingModules = extrasRequirements.filter(req => !modules.includes(req));
} else {
console.warn(`Extension ${name}: manifest.json 'requires' field is not an array. Loading allowed, but any intended requirements were not verified to exist.`);
}
}
// Extension dependencies: pass if 'dependencies' is undefined or not an array; check subset and disabled status if it's an array
let meetsExtensionDeps = true;
let missingDependencies = [];
let disabledDependencies = [];
if (extensionDependencies !== undefined) {
if (Array.isArray(extensionDependencies)) {
// Check if all dependencies exist
meetsExtensionDeps = isSubsetOf(extensionNames, extensionDependencies);
missingDependencies = extensionDependencies.filter(dep => !extensionNames.includes(dep));
// Check for disabled dependencies
if (meetsExtensionDeps) {
disabledDependencies = extensionDependencies.filter(dep => extension_settings.disabledExtensions.includes(dep));
if (disabledDependencies.length > 0) {
// Fail if any dependencies are disabled
meetsExtensionDeps = false;
}
}
} else {
console.warn(`Extension ${name}: manifest.json 'dependencies' field is not an array. Loading allowed, but any intended requirements were not verified to exist.`);
}
}
const isDisabled = extension_settings.disabledExtensions.includes(name);
if (meetsModuleRequirements && !isDisabled) {
if (meetsModuleRequirements && meetsExtensionDeps && !isDisabled) {
try {
console.debug('Activating extension', name);
const promise = addExtensionLocale(name, manifest).finally(() => Promise.all([addExtensionScript(name, manifest), addExtensionStyle(name, manifest)]));
const promise = addExtensionLocale(name, manifest).finally(() =>
Promise.all([addExtensionScript(name, manifest), addExtensionStyle(name, manifest)]),
);
await promise
.then(() => activeExtensions.add(name))
.catch(err => console.log('Could not activate extension', name, err));
.catch(err => {
console.log('Could not activate extension', name, err);
extensionLoadErrors.add(t`Extension "${displayName}" failed to load: ${err}`);
});
promises.push(promise);
} catch (error) {
console.error('Could not activate extension', name, error);
}
catch (error) {
console.error('Could not activate extension', name);
console.error(error);
} else if (!meetsModuleRequirements && !isDisabled) {
console.warn(t`Extension "${name}" did not load. Missing required Extras module(s): "${missingModules.join(', ')}"`);
extensionLoadErrors.add(t`Extension "${displayName}" did not load. Missing required Extras module(s): "${missingModules.join(', ')}"`);
} else if (!meetsExtensionDeps && !isDisabled) {
if (disabledDependencies.length > 0) {
console.warn(t`Extension "${name}" did not load. Required extensions exist but are disabled: "${disabledDependencies.join(', ')}". Enable them first, then reload.`);
extensionLoadErrors.add(t`Extension "${displayName}" did not load. Required extensions exist but are disabled: "${disabledDependencies.join(', ')}". Enable them first, then reload.`);
} else {
console.warn(t`Extension "${name}" did not load. Missing required extensions: "${missingDependencies.join(', ')}"`);
extensionLoadErrors.add(t`Extension "${displayName}" did not load. Missing required extensions: "${missingDependencies.join(', ')}"`);
}
}
}
await Promise.allSettled(promises);
$('#extensions_details').toggleClass('warning', extensionLoadErrors.size > 0);
}
async function connectClickHandler() {
@@ -751,6 +811,27 @@ function getModuleInformation() {
`;
}
/**
* Generates HTML for the extension load errors.
* @returns {string} HTML string containing the errors that occurred while loading extensions.
*/
function getExtensionLoadErrorsHtml() {
if (extensionLoadErrors.size === 0) {
return '';
}
const container = document.createElement('div');
container.classList.add('info-block', 'error');
for (const error of extensionLoadErrors) {
const errorElement = document.createElement('div');
errorElement.textContent = error;
container.appendChild(errorElement);
}
return container.outerHTML;
}
/**
* Generates the HTML strings for all extensions and displays them in a popup.
*/
@@ -765,6 +846,7 @@ async function showExtensionsDetails() {
initialScrollTop = oldPopup.content.scrollTop;
await oldPopup.completeCancelled();
}
const htmlErrors = getExtensionLoadErrorsHtml();
const htmlDefault = $('<div class="marginBot10"><h3 class="textAlignCenter">' + t`Built-in Extensions:` + '</h3></div>');
const htmlExternal = $('<div class="marginBot10"><h3 class="textAlignCenter">' + t`Installed Extensions:` + '</h3></div>');
const htmlLoading = $(`<div class="flex-container alignItemsCenter justifyCenter marginTop10 marginBot5">
@@ -787,6 +869,7 @@ async function showExtensionsDetails() {
const html = $('<div></div>')
.addClass('extensions_info')
.append(htmlErrors)
.append(htmlDefault)
.append(htmlExternal)
.append(getModuleInformation());
@@ -893,11 +976,14 @@ async function onUpdateClick() {
* Updates a third-party extension via the API.
* @param {string} extensionName Extension folder name
* @param {boolean} quiet If true, don't show a success message
* @param {number?} timeout Timeout in milliseconds to wait for the update to complete. If null, no timeout is set.
*/
async function updateExtension(extensionName, quiet) {
async function updateExtension(extensionName, quiet, timeout = null) {
try {
const signal = timeout ? AbortSignal.timeout(timeout) : undefined;
const response = await fetch('/api/extensions/update', {
method: 'POST',
signal: signal,
headers: getRequestHeaders(),
body: JSON.stringify({
extensionName,
@@ -926,7 +1012,7 @@ async function updateExtension(extensionName, quiet) {
toastr.success(t`Extension ${extensionName} updated to ${data.shortCommitHash}`, t`Reload the page to apply updates`);
}
} catch (error) {
console.error('Error:', error);
console.error('Extension update error:', error);
}
}
@@ -1397,6 +1483,7 @@ async function autoUpdateExtensions(forceAll) {
const banner = toastr.info(t`Auto-updating extensions. This may take several minutes.`, t`Please wait...`, { timeOut: 10000, extendedTimeOut: 10000 });
const isCurrentUserAdmin = isAdmin();
const promises = [];
const autoUpdateTimeout = 60 * 1000;
for (const [id, manifest] of Object.entries(manifests)) {
const isDisabled = extension_settings.disabledExtensions.includes(id);
if (!forceAll && isDisabled) {
@@ -1410,7 +1497,7 @@ async function autoUpdateExtensions(forceAll) {
}
if ((forceAll || manifest.auto_update) && id.startsWith('third-party')) {
console.debug(`Auto-updating 3rd-party extension: ${manifest.display_name} (${id})`);
promises.push(updateExtension(id.replace('third-party', ''), true));
promises.push(updateExtension(id.replace('third-party', ''), true, autoUpdateTimeout));
}
}
await Promise.allSettled(promises);
@@ -1453,7 +1540,7 @@ export async function runGenerationInterceptors(chat, contextSize, type) {
/**
* Writes a field to the character's data extensions object.
* @param {number} characterId Index in the character array
* @param {number|string} characterId Index in the character array
* @param {string} key Field name
* @param {any} value Field value
* @returns {Promise<void>} When the field is written
+7 -7
View File
@@ -7,7 +7,7 @@ import { DOMPurify } from '../../../lib.js';
import { getRequestHeaders, processDroppedFiles, eventSource, event_types } from '../../../script.js';
import { deleteExtension, extensionNames, getContext, installExtension, renderExtensionTemplateAsync } from '../../extensions.js';
import { POPUP_TYPE, Popup, callGenericPopup } from '../../popup.js';
import { executeSlashCommands } from '../../slash-commands.js';
import { executeSlashCommandsWithOptions } from '../../slash-commands.js';
import { accountStorage } from '../../util/AccountStorage.js';
import { flashHighlight, getStringHash, isValidUrl } from '../../utils.js';
import { t } from '../../i18n.js';
@@ -53,11 +53,11 @@ function filterAssets() {
}
const KNOWN_TYPES = {
'extension': 'Extensions',
'character': 'Characters',
'ambient': 'Ambient sounds',
'bgm': 'Background music',
'blip': 'Blip sounds',
'extension': t`Extensions`,
'character': t`Characters`,
'ambient': t`Ambient sounds`,
'bgm': t`Background music`,
'blip': t`Blip sounds`,
};
async function downloadAssetsList(url) {
@@ -142,7 +142,7 @@ async function downloadAssetsList(url) {
const assetDelete = async function () {
if (assetType === 'character') {
toastr.error('Go to the characters menu to delete a character.', 'Character deletion not supported');
await executeSlashCommands(`/go ${asset['id']}`);
await executeSlashCommandsWithOptions(`/go ${asset['id']}`);
return;
}
element.off('click');
+1 -1
View File
@@ -65,7 +65,7 @@
.asset-download-button-text {
font: bold 20px "Quicksand", san-serif;
color: #ffffff;
transition: all 0.2s;
transition: all var(--animation-duration-2x);
}
.asset-download-button-loading .asset-download-button-text {
@@ -216,8 +216,37 @@ function cleanUpAttachments() {
}
}
/**
* Clean up character attachments when a character is deleted.
* @param {{character: import('../../char-data.js').v1CharData}} data Event data
*/
function cleanUpCharacterAttachments(data) {
const avatar = data?.character?.avatar;
if (!avatar) return;
if (Array.isArray(extension_settings?.character_attachments?.[avatar])) {
delete extension_settings.character_attachments[avatar];
saveSettingsDebounced();
}
}
/**
* Handle character rename event to update character attachments.
* @param {string} oldAvatar Old avatar name
* @param {string} newAvatar New avatar name
*/
function handleCharacterRename(oldAvatar, newAvatar) {
if (!oldAvatar || !newAvatar) return;
if (Array.isArray(extension_settings?.character_attachments?.[oldAvatar])) {
extension_settings.character_attachments[newAvatar] = extension_settings.character_attachments[oldAvatar];
delete extension_settings.character_attachments[oldAvatar];
saveSettingsDebounced();
}
}
jQuery(async () => {
eventSource.on(event_types.APP_READY, cleanUpAttachments);
eventSource.on(event_types.CHARACTER_DELETED, cleanUpCharacterAttachments);
eventSource.on(event_types.CHARACTER_RENAMED, handleCharacterRename);
const manageButton = await renderExtensionTemplateAsync('attachments', 'manage-button', {});
const attachButton = await renderExtensionTemplateAsync('attachments', 'attach-button', {});
$('#data_bank_wand_container').append(manageButton);
@@ -3,7 +3,7 @@
File Name
</label>
<input type="text" class="text_pole" id="notepadFileName" name="notepadFileName" value="" />
<labels>
<label>
File Content
</label>
<textarea id="notepadFileContent" name="notepadFileContent" class="text_pole textarea_compact monospace flex1" placeholder="Enter your notes here."></textarea>
+19 -8
View File
@@ -1,6 +1,6 @@
import { ensureImageFormatSupported, getBase64Async, isTrueBoolean, saveBase64AsFile } from '../../utils.js';
import { ensureImageFormatSupported, getBase64Async, getFileExtension, isTrueBoolean, saveBase64AsFile } from '../../utils.js';
import { getContext, getApiUrl, doExtrasFetch, extension_settings, modules, renderExtensionTemplateAsync } from '../../extensions.js';
import { appendMediaToMessage, callPopup, eventSource, event_types, getRequestHeaders, saveChatConditional, saveSettingsDebounced, substituteParamsExtended } from '../../../script.js';
import { appendMediaToMessage, eventSource, event_types, getRequestHeaders, saveChatConditional, saveSettingsDebounced, substituteParamsExtended } from '../../../script.js';
import { getMessageTimeStamp } from '../../RossAscends-mods.js';
import { SECRET_KEYS, secret_state } from '../../secrets.js';
import { getMultimodalCaption } from '../shared.js';
@@ -9,6 +9,7 @@ import { SlashCommandParser } from '../../slash-commands/SlashCommandParser.js';
import { SlashCommand } from '../../slash-commands/SlashCommand.js';
import { ARGUMENT_TYPE, SlashCommandArgument, SlashCommandNamedArgument } from '../../slash-commands/SlashCommandArgument.js';
import { commonEnumProviders } from '../../slash-commands/SlashCommandCommonEnumsProvider.js';
import { callGenericPopup, Popup, POPUP_TYPE } from '../../popup.js';
export { MODULE_NAME };
const MODULE_NAME = 'caption';
@@ -52,6 +53,10 @@ function migrateSettings() {
if (!extension_settings.caption.template) {
extension_settings.caption.template = TEMPLATE_DEFAULT;
}
if (!extension_settings.caption.show_in_chat) {
extension_settings.caption.show_in_chat = false;
}
}
/**
@@ -98,9 +103,9 @@ async function wrapCaptionTemplate(caption) {
let messageText = substituteParamsExtended(template, { caption: caption });
if (extension_settings.caption.refine_mode) {
messageText = await callPopup(
'<h3>Review and edit the generated caption:</h3>Press "Cancel" to abort the caption sending.',
'input',
messageText = await Popup.show.input(
'Review and edit the generated caption:',
'Press "Cancel" to abort the caption sending.',
messageText,
{ rows: 5, okButton: 'Send' });
@@ -166,6 +171,7 @@ async function sendCaptionedMessage(caption, image) {
extra: {
image: image,
title: messageText,
inline_image: !!extension_settings.caption.show_in_chat,
},
};
context.chat.push(message);
@@ -278,7 +284,7 @@ async function captionMultimodal(base64Img, externalPrompt) {
let prompt = externalPrompt || extension_settings.caption.prompt || PROMPT_DEFAULT;
if (!externalPrompt && extension_settings.caption.prompt_ask) {
const customPrompt = await callPopup('<h3>Enter a comment or question:</h3>', 'input', prompt, { rows: 2 });
const customPrompt = await callGenericPopup('Enter a comment or question:', POPUP_TYPE.INPUT, prompt, { rows: 2 });
if (!customPrompt) {
throw new Error('User aborted the caption sending.');
}
@@ -326,11 +332,11 @@ async function getCaptionForFile(file, prompt, quiet) {
setSpinnerIcon();
const context = getContext();
const fileData = await getBase64Async(await ensureImageFormatSupported(file));
const base64Format = fileData.split(',')[0].split(';')[0].split('/')[1];
const extension = getFileExtension(file);
const base64Data = fileData.split(',')[1];
const { caption } = await doCaptionRequest(base64Data, fileData, prompt);
if (!quiet) {
const imagePath = await saveBase64AsFile(base64Data, context.name2, '', base64Format);
const imagePath = await saveBase64AsFile(base64Data, context.name2, '', extension);
await sendCaptionedMessage(caption, imagePath);
}
return caption;
@@ -432,6 +438,7 @@ jQuery(async function () {
'zerooneai': SECRET_KEYS.ZEROONEAI,
'groq': SECRET_KEYS.GROQ,
'cohere': SECRET_KEYS.COHERE,
'aimlapi': SECRET_KEYS.AIMLAPI,
};
if (chatCompletionApis[api] && secret_state[chatCompletionApis[api]]) {
@@ -594,6 +601,10 @@ jQuery(async function () {
extension_settings.caption.alt_endpoint_enabled = !!$('#caption_altEndpoint_enabled').prop('checked');
saveSettingsDebounced();
});
$('#caption_show_in_chat').prop('checked', !!(extension_settings.caption.show_in_chat)).on('input', () => {
extension_settings.caption.show_in_chat = !!$('#caption_show_in_chat').prop('checked');
saveSettingsDebounced();
});
const onMessageEvent = async (index) => {
if (!extension_settings.caption.auto_mode) {
+47 -14
View File
@@ -18,6 +18,7 @@
<label for="caption_multimodal_api" data-i18n="API">API</label>
<select id="caption_multimodal_api" class="flex1 text_pole">
<option value="zerooneai">01.AI (Yi)</option>
<option value="aimlapi">AI/ML API</option>
<option value="anthropic">Anthropic</option>
<option value="cohere">Cohere</option>
<option value="custom" data-i18n="Custom (OpenAI-compatible)">Custom (OpenAI-compatible)</option>
@@ -47,6 +48,7 @@
<option data-type="mistral" value="pixtral-large-2411">pixtral-large-2411</option>
<option data-type="mistral" value="mistral-large-pixtral-2411">mistral-large-pixtral-2411</option>
<option data-type="mistral" value="mistral-small-2503">mistral-small-2503</option>
<option data-type="mistral" value="mistral-small-2506">mistral-small-2506</option>
<option data-type="mistral" value="mistral-small-latest">mistral-small-latest</option>
<option data-type="mistral" value="mistral-medium-latest">mistral-medium-latest</option>
<option data-type="mistral" value="mistral-medium-2505">mistral-medium-2505</option>
@@ -83,13 +85,16 @@
<option data-type="anthropic" value="claude-3-5-haiku-latest">claude-3-5-haiku-latest</option>
<option data-type="anthropic" value="claude-3-5-haiku-20241022">claude-3-5-haiku-20241022</option>
<option data-type="anthropic" value="claude-3-opus-20240229">claude-3-opus-20240229</option>
<option data-type="anthropic" value="claude-3-sonnet-20240229">claude-3-sonnet-20240229</option>
<option data-type="anthropic" value="claude-3-haiku-20240307">claude-3-haiku-20240307</option>
<option data-type="google" value="gemini-2.5-pro">gemini-2.5-pro</option>
<option data-type="google" value="gemini-2.5-pro-preview-06-05">gemini-2.5-pro-preview-06-05</option>
<option data-type="google" value="gemini-2.5-pro-preview-05-06">gemini-2.5-pro-preview-05-06</option>
<option data-type="google" value="gemini-2.5-pro-preview-03-25">gemini-2.5-pro-preview-03-25</option>
<option data-type="google" value="gemini-2.5-pro-exp-03-25">gemini-2.5-pro-exp-03-25</option>
<option data-type="google" value="gemini-2.5-flash">gemini-2.5-flash</option>
<option data-type="google" value="gemini-2.5-flash-preview-05-20">gemini-2.5-flash-preview-05-20</option>
<option data-type="google" value="gemini-2.5-flash-preview-04-17">gemini-2.5-flash-preview-04-17</option>
<option data-type="google" value="gemini-2.5-flash-lite-preview-06-17">gemini-2.5-flash-lite-preview-06-17</option>
<option data-type="google" value="gemini-2.0-pro-exp-02-05">gemini-2.0-pro-exp-02-05 → 2.5-pro-exp-03-25</option>
<option data-type="google" value="gemini-2.0-pro-exp">gemini-2.0-pro-exp → 2.5-pro-exp-03-25</option>
<option data-type="google" value="gemini-exp-1206">gemini-exp-1206 → 2.5-pro-exp-03-25</option>
@@ -116,15 +121,37 @@
<option data-type="google" value="gemini-1.5-flash-8b-exp-0827">gemini-1.5-flash-8b-exp-0827</option>
<option data-type="google" value="learnlm-2.0-flash-experimental">learnlm-2.0-flash-experimental</option>
<option data-type="google" value="learnlm-1.5-pro-experimental">learnlm-1.5-pro-experimental</option>
<option data-type="vertexai" value="gemini-2.5-pro">gemini-2.5-pro</option>
<option data-type="vertexai" value="gemini-2.5-pro-preview-06-05">gemini-2.5-pro-preview-06-05</option>
<option data-type="vertexai" value="gemini-2.5-pro-preview-05-06">gemini-2.5-pro-preview-05-06</option>
<option data-type="vertexai" value="gemini-2.5-pro-preview-03-25">gemini-2.5-pro-preview-03-25</option>
<option data-type="vertexai" value="gemini-2.5-flash">gemini-2.5-flash</option>
<option data-type="vertexai" value="gemini-2.5-flash-preview-05-20">gemini-2.5-flash-preview-05-20</option>
<option data-type="vertexai" value="gemini-2.5-flash-preview-04-17">gemini-2.5-flash-preview-04-17</option>
<option data-type="vertexai" value="gemini-2.5-flash-lite-preview-06-17">gemini-2.5-flash-lite-preview-06-17</option>
<option data-type="vertexai" value="gemini-2.0-flash-001">gemini-2.0-flash-001</option>
<option data-type="vertexai" value="gemini-2.0-flash-lite-001">gemini-2.0-flash-lite-001</option>
<option data-type="groq" value="llama-3.2-11b-vision-preview">llama-3.2-11b-vision-preview</option>
<option data-type="groq" value="llama-3.2-90b-vision-preview">llama-3.2-90b-vision-preview</option>
<option data-type="groq" value="llava-v1.5-7b-4096-preview">llava-v1.5-7b-4096-preview</option>
<option data-type="aimlapi" value="gpt-4o-2024-05-13">gpt-4o-2024-05-13</option>
<option data-type="aimlapi" value="gpt-4o-2024-08-06">gpt-4o-2024-08-06</option>
<option data-type="aimlapi" value="gpt-4o">gpt-4o</option>
<option data-type="aimlapi" value="gpt-4o-mini">gpt-4o-mini</option>
<option data-type="aimlapi" value="gpt-4o-mini-2024-07-18">gpt-4o-mini-2024-07-18</option>
<option data-type="aimlapi" value="chatgpt-4o-latest">chatgpt-4o-latest</option>
<option data-type="aimlapi" value="gpt-4-turbo">gpt-4-turbo</option>
<option data-type="aimlapi" value="claude-3-opus-20240229">claude-3-opus-20240229</option>
<option data-type="aimlapi" value="claude-3-sonnet-20240229">claude-3-sonnet-20240229</option>
<option data-type="aimlapi" value="claude-3-haiku-20240307">claude-3-haiku-20240307</option>
<option data-type="aimlapi" value="claude-3-5-sonnet-20240620">claude-3-5-sonnet-20240620</option>
<option data-type="aimlapi" value="google/gemini-1.5-flash">google/gemini-1.5-flash</option>
<option data-type="aimlapi" value="google/gemini-1.5-pro">google/gemini-1.5-pro</option>
<option data-type="aimlapi" value="google/gemini-2.0-flash">google/gemini-2.0-flash</option>
<option data-type="aimlapi" value="google/gemini-2.0-flash-exp">google/gemini-2.0-flash-exp</option>
<option data-type="aimlapi" value="google/gemini-2.5-flash-preview">google/gemini-2.5-flash-preview</option>
<option data-type="aimlapi" value="meta-llama/Llama-3.2-11B-Vision-Instruct-Turbo">meta-llama/Llama-3.2-11B-Vision-Instruct-Turbo</option>
<option data-type="aimlapi" value="meta-llama/Llama-3.2-90B-Vision-Instruct-Turbo">meta-llama/Llama-3.2-90B-Vision-Instruct-Turbo</option>
<option data-type="openrouter" value="openai/gpt-4-vision-preview">openai/gpt-4-vision-preview</option>
<option data-type="openrouter" value="openai/gpt-4o">openai/gpt-4o</option>
<option data-type="openrouter" value="openai/gpt-4o-2024-05-13">openai/gpt-4o-2024-05-13</option>
@@ -162,6 +189,7 @@
<option data-type="koboldcpp" value="koboldcpp_current" data-i18n="currently_loaded">[Currently loaded]</option>
<option data-type="vllm" value="vllm_current" data-i18n="currently_selected">[Currently selected]</option>
<option data-type="custom" value="custom_current" data-i18n="currently_selected">[Currently selected]</option>
<option data-type="xai" value="grok-4-0709">grok-4-0709</option>
<option data-type="xai" value="grok-2-vision-1212">grok-2-vision-1212</option>
<option data-type="xai" value="grok-vision-beta">grok-vision-beta</option>
<option data-type="pollinations" value="openai">openai</option>
@@ -188,36 +216,41 @@
<div class="flexBasis100p m-b-1">
<small><b data-i18n="Hint:">Hint:</b> <span data-i18n="Set your API keys and endpoints in the 'API Connections' tab first.">Set your API keys and endpoints in the 'API Connections' tab first.</span></small>
</div>
</div>
<div data-type="koboldcpp,ollama,vllm,llamacpp,ooba" class="flex-container flexFlowColumn">
<label for="caption_altEndpoint_enabled" class="checkbox_label">
<input id="caption_altEndpoint_enabled" type="checkbox">
<span data-i18n="Use secondary URL">Use secondary URL</span>
</label>
<label for="caption_altEndpoint_url" data-i18n="Secondary captioning endpoint URL">
Secondary captioning endpoint URL
</label>
<input id="caption_altEndpoint_url" class="text_pole" type="text" placeholder="e.g. http://localhost:5001" />
<div data-type="koboldcpp,ollama,vllm,llamacpp,ooba" class="flex-container flexFlowColumn">
<label for="caption_altEndpoint_enabled" class="checkbox_label">
<input id="caption_altEndpoint_enabled" type="checkbox">
<span data-i18n="Use secondary URL">Use secondary URL</span>
</label>
<label for="caption_altEndpoint_url" data-i18n="Secondary captioning endpoint URL">
Secondary captioning endpoint URL
</label>
<input id="caption_altEndpoint_url" class="text_pole" type="text" placeholder="e.g. http://localhost:5001" />
</div>
</div>
<div id="caption_prompt_block">
<label for="caption_prompt" data-i18n="Caption Prompt">Caption Prompt</label>
<textarea id="caption_prompt" class="text_pole" rows="1" placeholder="&lt; Use default &gt;">{{PROMPT_DEFAULT}}</textarea>
<textarea id="caption_prompt" class="text_pole textarea_compact autoSetHeight" rows="1" placeholder="&lt; Use default &gt;">{{PROMPT_DEFAULT}}</textarea>
<label class="checkbox_label margin-bot-10px" for="caption_prompt_ask" title="Ask for a custom prompt every time an image is captioned.">
<input id="caption_prompt_ask" type="checkbox" class="checkbox">
<span data-i18n="Ask every time">Ask every time</span>
</label>
</div>
<label for="caption_template"><span data-i18n="Message Template">Message Template</span> <small><span data-i18n="(use _space">(use </span> <code>&lcub;&lcub;caption&rcub;&rcub;</code> <span data-i18n="macro)">macro)</span></small></label>
<textarea id="caption_template" class="text_pole" rows="2" placeholder="&lt; Use default &gt;">{{TEMPLATE_DEFAULT}}</textarea>
<textarea id="caption_template" class="text_pole textarea_compact autoSetHeight" rows="2" placeholder="&lt; Use default &gt;">{{TEMPLATE_DEFAULT}}</textarea>
<label class="checkbox_label" for="caption_auto_mode">
<input id="caption_auto_mode" type="checkbox" class="checkbox">
<span data-i18n="Automatically caption images">Automatically caption images</span>
<i class="fa-solid fa-info-circle" title="Automatically caption images when they are pasted into the chat or attached to messages."></i>
</label>
<label class="checkbox_label margin-bot-10px" for="caption_refine_mode">
<label class="checkbox_label" for="caption_refine_mode">
<input id="caption_refine_mode" type="checkbox" class="checkbox">
<span data-i18n="Edit captions before saving">Edit captions before saving</span>
</label>
<label class="checkbox_label" for="caption_show_in_chat">
<input id="caption_show_in_chat" type="checkbox" class="checkbox">
<span data-i18n="Show captions in chat">Show captions in chat</span>
</label>
<div class="margin-bot-10px"></div>
</div>
</div>
</div>
@@ -13,6 +13,7 @@ import { SlashCommandParser } from '../../slash-commands/SlashCommandParser.js';
import { SlashCommandScope } from '../../slash-commands/SlashCommandScope.js';
import { collapseSpaces, getUniqueName, isFalseBoolean, uuidv4 } from '../../utils.js';
import { t } from '../../i18n.js';
import { getSecretLabelById } from '../../secrets.js';
const MODULE_NAME = 'connection-manager';
const NONE = '<None>';
@@ -40,6 +41,8 @@ const CC_COMMANDS = [
'stop-strings',
'start-reply-with',
'reasoning-template',
'prompt-post-processing',
'secret-id',
];
const TC_COMMANDS = [
@@ -56,6 +59,7 @@ const TC_COMMANDS = [
'stop-strings',
'start-reply-with',
'reasoning-template',
'secret-id',
];
const FANCY_NAMES = {
@@ -73,6 +77,8 @@ const FANCY_NAMES = {
'stop-strings': 'Custom Stopping Strings',
'start-reply-with': 'Start Reply With',
'reasoning-template': 'Reasoning Template',
'prompt-post-processing': 'Prompt Post-Processing',
'secret-id': 'Secret',
};
/**
@@ -342,6 +348,15 @@ function makeFancyProfile(profile) {
return acc;
}
// UUID is not very useful in the UI, so we replace it with a label (if available)
if (key === 'secret-id') {
const label = getSecretLabelById(profile[key]);
if (label) {
acc[value] = label;
return acc;
}
}
acc[value] = profile[key];
return acc;
}, {});
+67 -19
View File
@@ -1,6 +1,6 @@
import { Fuse } from '../../../lib.js';
import { characters, eventSource, event_types, generateRaw, getRequestHeaders, main_api, online_status, saveSettingsDebounced, substituteParams, substituteParamsExtended, system_message_types, this_chid } from '../../../script.js';
import { characters, eventSource, event_types, generateQuietPrompt, generateRaw, getRequestHeaders, online_status, saveSettingsDebounced, substituteParams, substituteParamsExtended, system_message_types, this_chid } from '../../../script.js';
import { dragElement, isMobile } from '../../RossAscends-mods.js';
import { getContext, getApiUrl, modules, extension_settings, ModuleWorkerWrapper, doExtrasFetch, renderExtensionTemplateAsync } from '../../extensions.js';
import { loadMovingUIState, performFuzzySearch, power_user } from '../../power-user.js';
@@ -86,6 +86,12 @@ const EXPRESSION_API = {
none: 99,
};
/** @enum {string} */
const PROMPT_TYPE = {
raw: 'raw',
full: 'full',
};
let expressionsList = null;
let lastCharacter = undefined;
let lastMessage = null;
@@ -909,10 +915,6 @@ function sampleClassifyText(text) {
* @returns {Promise<string>} Prompt for the LLM API.
*/
async function getLlmPrompt(labels) {
if (isJsonSchemaSupported()) {
return '';
}
const labelsString = labels.map(x => `"${x}"`).join(', ');
const prompt = substituteParamsExtended(String(extension_settings.expressions.llmPrompt), { labels: labelsString });
return prompt;
@@ -976,6 +978,7 @@ function getJsonSchema(emotions) {
required: [
'emotion',
],
additionalProperties: false,
};
}
@@ -1047,7 +1050,21 @@ export async function getExpressionLabel(text, expressionsApi = extension_settin
const expressionsList = await getExpressionsList({ filterAvailable: filterAvailable });
const prompt = substituteParamsExtended(customPrompt, { labels: expressionsList }) || await getLlmPrompt(expressionsList);
eventSource.once(event_types.TEXT_COMPLETION_SETTINGS_READY, onTextGenSettingsReady);
const emotionResponse = await generateRaw(text, main_api, false, false, prompt);
let emotionResponse;
try {
inApiCall = true;
switch (extension_settings.expressions.promptType) {
case PROMPT_TYPE.raw:
emotionResponse = await generateRaw({ prompt: text, systemPrompt: prompt });
break;
case PROMPT_TYPE.full:
emotionResponse = await generateQuietPrompt({ quietPrompt: prompt });
break;
}
} finally {
inApiCall = false;
}
return parseLlmResponse(emotionResponse, expressionsList);
}
// Using WebLLM
@@ -1314,7 +1331,7 @@ async function renderFallbackExpressionPicker() {
defaultPicker.empty();
addOption(OPTION_NO_FALLBACK, '[ No fallback ]', !extension_settings.expressions.fallback_expression);
addOption(OPTION_NO_FALLBACK, '[ No fallback ]', !extension_settings.expressions.fallback_expression && !extension_settings.expressions.showDefault);
addOption(OPTION_EMOJI_FALLBACK, '[ Default emojis ]', !!extension_settings.expressions.showDefault);
for (const expression of expressions) {
@@ -1702,6 +1719,7 @@ function onExpressionApiChanged() {
if (tempApi) {
extension_settings.expressions.api = Number(tempApi);
$('.expression_llm_prompt_block').toggle([EXPRESSION_API.llm, EXPRESSION_API.webllm].includes(extension_settings.expressions.api));
$('.expression_prompt_type_block').toggle(extension_settings.expressions.api === EXPRESSION_API.llm);
expressionsList = null;
spriteCache = {};
moduleWorker();
@@ -1740,27 +1758,38 @@ async function onExpressionFallbackChanged() {
saveSettingsDebounced();
}
/**
* Handles the file upload process for a sprite image.
* @param {string} url URL to upload the file to
* @param {FormData} formData FormData object containing the file and other data to upload
* @returns {Promise<any>} - The response data from the server
*/
async function handleFileUpload(url, formData) {
try {
const data = await jQuery.ajax({
type: 'POST',
url: url,
data: formData,
beforeSend: function () { },
cache: false,
contentType: false,
processData: false,
const result = await fetch(url, {
method: 'POST',
headers: getRequestHeaders({ omitContentType: true }),
body: formData,
cache: 'no-cache',
});
if (!result.ok) {
throw new Error(`Upload failed with status ${result.status}`);
}
const data = await result.json();
// Refresh sprites list
const name = formData.get('name');
const name = formData.get('name').toString();
delete spriteCache[name];
await fetchImagesNoCache();
await validateImages(name);
return data;
return data ?? {};
} catch (error) {
console.error('Error uploading image:', error);
toastr.error('Failed to upload image');
return {};
}
}
@@ -1978,7 +2007,11 @@ async function onClickExpressionUploadPackButton() {
const uploadToast = toastr.info('Please wait...', 'Upload is processing', { timeOut: 0, extendedTimeOut: 0 });
const { count } = await handleFileUpload('/api/sprites/upload-zip', formData);
toastr.clear(uploadToast);
toastr.success(`Uploaded ${count} image(s) for ${name}`);
// Only show success message if at least one image was uploaded
if (count) {
toastr.success(`Uploaded ${count} image(s) for ${name}`);
}
// Reset the input
e.target.form.reset();
@@ -2098,10 +2131,15 @@ function migrateSettings() {
saveSettingsDebounced();
}
if (extension_settings.expressions.showDefault && extension_settings.expressions.fallback_expression !== undefined) {
if (extension_settings.expressions.showDefault && extension_settings.expressions.fallback_expression) {
extension_settings.expressions.showDefault = false;
saveSettingsDebounced();
}
if (extension_settings.expressions.promptType === undefined) {
extension_settings.expressions.promptType = PROMPT_TYPE.raw;
saveSettingsDebounced();
}
}
(async function () {
@@ -2169,6 +2207,16 @@ function migrateSettings() {
extension_settings.expressions.llmPrompt = DEFAULT_LLM_PROMPT;
saveSettingsDebounced();
});
$('#expression_prompt_raw').on('input', function () {
extension_settings.expressions.promptType = PROMPT_TYPE.raw;
saveSettingsDebounced();
});
$('#expression_prompt_full').on('input', function () {
extension_settings.expressions.promptType = PROMPT_TYPE.full;
saveSettingsDebounced();
});
$(`input[name="expression_prompt_type"][value="${extension_settings.expressions.promptType}"]`).prop('checked', true);
$('.expression_prompt_type_block').toggle(extension_settings.expressions.api === EXPRESSION_API.llm);
$('#expression_custom_add').on('click', onClickExpressionAddCustom);
$('#expression_custom_remove').on('click', onClickExpressionRemoveCustom);
@@ -40,8 +40,21 @@
<i class="fa-solid fa-clock-rotate-left fa-sm"></i>
</div>
</label>
<small data-i18n="Will be used if the API doesn't support JSON schemas or function calling.">Will be used if the API doesn't support JSON schemas or function calling.</small>
<textarea id="expression_llm_prompt" type="text" class="text_pole textarea_compact" rows="2" placeholder="Use &lcub;&lcub;labels&rcub;&rcub; special macro."></textarea>
<small data-i18n="Used in addition to JSON schemas and function calling.">Used in addition to JSON schemas and function calling.</small>
<textarea id="expression_llm_prompt" type="text" class="text_pole textarea_compact autoSetHeight" rows="2" placeholder="Use &lcub;&lcub;labels&rcub;&rcub; special macro."></textarea>
</div>
<div class="expression_prompt_type_block flex-container flexFlowColumn">
<div data-i18n="LLM Prompt Strategy" class="title_restorable">
LLM Prompt Strategy
</div>
<label for="expression_prompt_raw" class="checkbox_label">
<input id="expression_prompt_raw" type="radio" name="expression_prompt_type" value="raw">
<span data-i18n="Limited Context">Limited Context</span>
</label>
<label for="expression_prompt_full" class="checkbox_label">
<input id="expression_prompt_full" type="radio" name="expression_prompt_type" value="full">
<span data-i18n="Full Context">Full Context</span>
</label>
</div>
<div class="expression_fallback_block m-b-1 m-t-1">
<label for="expression_fallback" data-i18n="Default / Fallback Expression">Default / Fallback Expression</label>
@@ -52,7 +65,7 @@
<label for="expression_custom" data-i18n="Custom Expressions">Custom Expressions</label>
<small><span data-i18n="Can be set manually or with an _space">Can be set manually or with an </span><tt>/emote</tt><span data-i18n="space_ slash command."> slash command.</span></small>
<div class="flex-container">
<select id="expression_custom" class="flex1 margin0"><select>
<select id="expression_custom" class="flex1 margin0"></select>
<i id="expression_custom_add" class="menu_button fa-solid fa-plus margin0" title="Add"></i>
<i id="expression_custom_remove" class="menu_button fa-solid fa-xmark margin0" title="Remove"></i>
</div>
+79 -29
View File
@@ -4,9 +4,11 @@ import {
characters,
getRequestHeaders,
event_types,
animation_duration,
animation_easing,
} from '../../../script.js';
import { groups, selected_group } from '../../group-chats.js';
import { loadFileToDocument, delay, getBase64Async, getSanitizedFilename } from '../../utils.js';
import { loadFileToDocument, delay, getBase64Async, getSanitizedFilename, saveBase64AsFile, getFileExtension } from '../../utils.js';
import { loadMovingUIState } from '../../power-user.js';
import { dragElement } from '../../RossAscends-mods.js';
import { SlashCommandParser } from '../../slash-commands/SlashCommandParser.js';
@@ -15,10 +17,12 @@ import { ARGUMENT_TYPE, SlashCommandNamedArgument } from '../../slash-commands/S
import { DragAndDropHandler } from '../../dragdrop.js';
import { commonEnumProviders } from '../../slash-commands/SlashCommandCommonEnumsProvider.js';
import { t, translate } from '../../i18n.js';
import { Popup } from '../../popup.js';
const extensionName = 'gallery';
const extensionFolderPath = `scripts/extensions/${extensionName}/`;
let firstTime = true;
let deleteModeActive = false;
// Exposed defaults for future tweaking
let thumbnailHeight = 150;
@@ -30,7 +34,15 @@ let galleryMaxRows = 3;
$('#movingDivs').on('click', '.dragClose', function () {
const relatedId = $(this).data('related-id');
if (!relatedId) return;
$(`#movingDivs > .draggable[id="${relatedId}"]`).remove();
const relatedElement = $(`#movingDivs > .draggable[id="${relatedId}"]`);
relatedElement.transition({
opacity: 0,
duration: animation_duration,
easing: animation_easing,
complete: () => {
relatedElement.remove();
},
});
});
const CUSTOM_GALLERY_REMOVED_EVENT = 'galleryRemoved';
@@ -146,6 +158,29 @@ async function getGalleryFolders() {
}
}
/**
* Deletes a gallery item based on the provided URL.
* @param {string} url - The URL of the image to be deleted.
*/
async function deleteGalleryItem(url) {
try {
const response = await fetch('/api/images/delete', {
method: 'POST',
headers: getRequestHeaders(),
body: JSON.stringify({ path: url }),
});
if (!response.ok) {
throw new Error(`HTTP error. Status: ${response.status}`);
}
toastr.success(t`Image deleted successfully.`);
} catch (error) {
console.error('Failed to delete the image:', error);
toastr.error(t`Failed to delete the image. Check the console for details.`);
}
}
/**
* Sets the sort order for the gallery.
* @param {string} order Sort order
@@ -260,7 +295,7 @@ async function initGallery(items, url) {
*
* @returns {Promise<void>} - Promise representing the completion of the gallery display process.
*/
async function showCharGallery() {
async function showCharGallery(deleteModeState = false) {
// Load necessary files if it's the first time calling the function
if (firstTime) {
await loadFileToDocument(
@@ -276,6 +311,7 @@ async function showCharGallery() {
}
try {
deleteModeActive = deleteModeState;
let url = selected_group || this_chid;
if (!selected_group && this_chid !== undefined) {
url = getGalleryFolder(characters[this_chid]);
@@ -288,7 +324,6 @@ async function showCharGallery() {
await delay(100);
await initGallery(items, url);
} catch (err) {
console.trace();
console.error(err);
}
}
@@ -305,27 +340,12 @@ async function showCharGallery() {
async function uploadFile(file, url) {
try {
// Convert the file to a base64 string
const base64Data = await getBase64Async(file);
const fileBase64 = await getBase64Async(file);
const base64Data = fileBase64.split(',')[1];
const extension = getFileExtension(file);
const path = await saveBase64AsFile(base64Data, url, '', extension);
// Create the payload
const payload = {
image: base64Data,
ch_name: url,
};
const response = await fetch('/api/images/upload', {
method: 'POST',
headers: getRequestHeaders(),
body: JSON.stringify(payload),
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const result = await response.json();
toastr.success(t`File uploaded successfully. Saved at: ${result.path}`);
toastr.success(t`File uploaded successfully. Saved at: ${path}`);
} catch (error) {
console.error('There was an issue uploading the file:', error);
@@ -347,7 +367,7 @@ async function makeMovable(url) {
const id = 'gallery';
const template = $('#generic_draggable_template').html();
const newElement = $(template);
newElement.css('background-color', 'var(--SmartThemeBlurTintColor)');
newElement.css({ 'background-color': 'var(--SmartThemeBlurTintColor)', 'opacity': 0 });
newElement.attr('forChar', id);
newElement.attr('id', id);
newElement.find('.drag-grabber').attr('id', `${id}header`);
@@ -429,6 +449,18 @@ async function makeMovable(url) {
galleryFolderAccept.title = t`Change gallery folder`;
galleryFolderAccept.addEventListener('click', onChangeFolder);
const galleryDeleteMode = document.createElement('div');
galleryDeleteMode.classList.add('right_menu_button', 'fa-solid', 'fa-trash', 'fa-fw');
galleryDeleteMode.classList.toggle('warning', deleteModeActive);
galleryDeleteMode.title = t`Delete mode`;
galleryDeleteMode.addEventListener('click', () => {
deleteModeActive = !deleteModeActive;
galleryDeleteMode.classList.toggle('warning', deleteModeActive);
if (deleteModeActive) {
toastr.info(t`Delete mode is ON. Click on images you want to delete.`);
}
});
const galleryFolderRestore = document.createElement('div');
galleryFolderRestore.classList.add('right_menu_button', 'fa-solid', 'fa-recycle', 'fa-fw');
galleryFolderRestore.title = t`Restore gallery folder`;
@@ -436,6 +468,7 @@ async function makeMovable(url) {
topBarElement.appendChild(galleryFolderInput);
topBarElement.appendChild(galleryFolderAccept);
topBarElement.appendChild(galleryDeleteMode);
topBarElement.appendChild(galleryFolderRestore);
newElement.append(topBarElement);
@@ -466,6 +499,11 @@ async function makeMovable(url) {
loadMovingUIState();
$(`.draggable[forChar="${id}"]`).css('display', 'block');
dragElement(newElement);
newElement.transition({
opacity: 1,
duration: animation_duration,
easing: animation_easing,
});
$(`.draggable[forChar="${id}"] img`).on('dragstart', (e) => {
console.log('saw drag on avatar!');
@@ -566,6 +604,9 @@ function makeDragImg(id, url) {
}
draggableElem.id = uniqueId;
// Add the galleryImageDraggable to have unique class
draggableElem.classList.add('galleryImageDraggable');
// Ensure that the newly added element is displayed as block
draggableElem.style.display = 'block';
//and has no padding unlike other non-zoomed-avatar draggables
@@ -635,9 +676,19 @@ function sanitizeHTMLId(id) {
function viewWithDragbox(items) {
if (items && items.length > 0) {
const url = items[0].responsiveURL(); // Get the URL of the clicked image/video
// ID should just be the last part of the URL, removing the extension
const id = sanitizeHTMLId(url.substring(url.lastIndexOf('/') + 1, url.lastIndexOf('.')));
makeDragImg(id, url);
if (deleteModeActive) {
Popup.show.confirm(t`Are you sure you want to delete this image?`, url)
.then(async (confirmed) => {
if (!confirmed) {
return;
}
deleteGalleryItem(url).then(() => showCharGallery(deleteModeActive));
});
} else {
// ID should just be the last part of the URL, removing the extension
const id = sanitizeHTMLId(url.substring(url.lastIndexOf('/') + 1, url.lastIndexOf('.')));
makeDragImg(id, url);
}
}
}
@@ -685,7 +736,6 @@ async function listGalleryCommand(args) {
return JSON.stringify(items.map(it => it.src));
} catch (err) {
console.trace();
console.error(err);
}
return JSON.stringify([]);
@@ -43,3 +43,8 @@
#dragGallery {
min-height: 25dvh;
}
#gallery .right_menu_button.warning {
opacity: 1;
filter: unset;
}
+18 -4
View File
@@ -16,6 +16,7 @@ import {
getMaxContextSize,
setExtensionPrompt,
streamingProcessor,
animation_easing,
} from '../../../script.js';
import { is_group_generating, selected_group } from '../../group-chats.js';
import { loadMovingUIState } from '../../power-user.js';
@@ -505,7 +506,7 @@ async function summarizeCallback(args, text) {
case summary_sources.extras:
return await callExtrasSummarizeAPI(text);
case summary_sources.main:
return removeReasoningFromString(await generateRaw(text, '', false, false, prompt, extension_settings.memory.overrideResponseLength));
return removeReasoningFromString(await generateRaw({ prompt: text, systemPrompt: prompt, responseLength: extension_settings.memory.overrideResponseLength }));
case summary_sources.webllm: {
const messages = [{ role: 'system', content: prompt }, { role: 'user', content: text }].filter(m => m.content);
const params = extension_settings.memory.overrideResponseLength > 0 ? { max_tokens: extension_settings.memory.overrideResponseLength } : {};
@@ -676,7 +677,13 @@ async function summarizeChatMain(context, force, skipWIAN) {
if (prompt_builders.DEFAULT === extension_settings.memory.prompt_builder) {
try {
inApiCall = true;
summary = await generateQuietPrompt(prompt, false, skipWIAN, '', '', extension_settings.memory.overrideResponseLength);
/** @type {import('../../../script.js').GenerateQuietPromptParams} */
const params = {
quietPrompt: prompt,
skipWIAN: skipWIAN,
responseLength: extension_settings.memory.overrideResponseLength,
};
summary = await generateQuietPrompt(params);
} finally {
inApiCall = false;
}
@@ -700,7 +707,13 @@ async function summarizeChatMain(context, force, skipWIAN) {
return null;
}
const rawSummary = await generateRaw(rawPrompt, '', false, false, prompt, extension_settings.memory.overrideResponseLength);
/** @type {import('../../../script.js').GenerateRawParams} */
const params = {
prompt: rawPrompt,
systemPrompt: prompt,
responseLength: extension_settings.memory.overrideResponseLength,
};
const rawSummary = await generateRaw(params);
summary = removeReasoningFromString(rawSummary);
index = lastUsedIndex;
} finally {
@@ -972,6 +985,7 @@ function doPopout(e) {
</div>`;
const newElement = $(template);
newElement.attr('id', 'summaryExtensionPopout')
.css('opacity', 0)
.removeClass('zoomed_avatar')
.addClass('draggable')
.empty();
@@ -980,13 +994,13 @@ function doPopout(e) {
originalElement.html('<div class="flex-container alignitemscenter justifyCenter wide100p"><small>Currently popped out</small></div>');
newElement.append(controlBarHtml).append(originalHTMLClone);
$('body').append(newElement);
newElement.transition({ opacity: 1, duration: animation_duration, easing: animation_easing });
$('#summaryExtensionDrawerContents').addClass('scrollableInnerFull');
setMemoryContext(prevSummaryBoxContents, false); //paste prev summary box contents into popout box
setupListeners();
loadSettings();
loadMovingUIState();
$('#summaryExtensionPopout').fadeIn(animation_duration);
dragElement(newElement);
//setup listener for close button to restore extensions menu
@@ -181,7 +181,7 @@ const init = async () => {
eventSource.on(event_types.APP_READY, async()=>await finalizeInit());
window['quickReplyApi'] = quickReplyApi;
globalThis.quickReplyApi = quickReplyApi;
};
const finalizeInit = async () => {
debug('executing startup');
@@ -1,5 +1,5 @@
import { chat_metadata, saveChatDebounced, saveSettingsDebounced } from '../../../../script.js';
import { extension_settings } from '../../../extensions.js';
import { chat_metadata, saveSettingsDebounced } from '../../../../script.js';
import { extension_settings, saveMetadataDebounced } from '../../../extensions.js';
import { QuickReplyConfig } from './QuickReplyConfig.js';
export class QuickReplySettings {
@@ -62,7 +62,7 @@ export class QuickReplySettings {
saveSettingsDebounced();
if (this.chatConfig) {
chat_metadata.quickReply = this.chatConfig.toJSON();
saveChatDebounced();
saveMetadataDebounced();
}
if (this.onSave) {
this.onSave();
+13 -16
View File
@@ -18,7 +18,7 @@
#qr--bar {
outline: none;
margin: 0;
transition: 0.3s;
transition: var(--animation-duration-2x);
opacity: 0.7;
display: flex;
align-items: center;
@@ -34,14 +34,12 @@
right: 0.25em;
top: 0;
}
/*hide QR popout for mobile*/
@media screen and (max-width: 1000px) {
#qr--bar > #qr--popoutTrigger {
display:none;
display: none;
}
}
#qr--bar.popoutVisible {
padding-right: 2.5em;
}
@@ -61,9 +59,8 @@
aspect-ratio: 1 / 1;
font-size: 20px;
opacity: 0.5;
transition: all 250ms;
transition: all var(--animation-duration-2x);
}
#qr--popout > .qr--body {
overflow-y: auto;
}
@@ -124,7 +121,7 @@
padding: 3px 5px;
margin: 3px 0;
cursor: pointer;
transition: 0.3s;
transition: var(--animation-duration-2x);
display: flex;
align-items: center;
justify-content: center;
@@ -175,7 +172,7 @@
overflow: visible;
}
.ctx-menu .ctx-item .qr--hidden {
display: none;
display: none;
}
.list-group .list-group-item.ctx-header {
font-weight: bold;
@@ -248,7 +245,7 @@
display: flex;
align-items: center;
opacity: 0;
transition: 100ms;
transition: var(--animation-duration);
margin: -2px 0 -11px 0;
position: relative;
}
@@ -461,7 +458,7 @@
cursor: not-allowed;
opacity: 0.5;
pointer-events: none;
transition: 200ms;
transition: var(--animation-duration-2x);
border-color: transparent;
}
.popup:has(#qr--modalEditor) .popup-content > #qr--modalEditor.qr--isExecuting.qr--isPaused #qr--modal-debugButtons .menu_button:not(#qr--modal-minimize, #qr--modal-maximize) {
@@ -492,7 +489,7 @@
width: 6px;
background-color: var(--SmartThemeBorderColor);
border: 2px solid var(--SmartThemeBlurTintColor);
transition: border-color 200ms, background-color 200ms;
transition: border-color var(--animation-duration-2x), background-color var(--animation-duration-2x);
cursor: w-resize;
}
.popup:has(#qr--modalEditor) .popup-content > #qr--modalEditor.qr--isExecuting #qr--resizeHandle:hover {
@@ -574,7 +571,7 @@
gap: 1em;
text-align: left;
opacity: 0.75;
transition: 200ms;
transition: var(--animation-duration-2x);
cursor: pointer;
}
.popup:has(#qr--modalEditor) .popup-content > #qr--modalEditor > #qr--main > .qr--labels > label .qr--modal-switcherList .qr--modal-switcherItem:hover,
@@ -736,7 +733,7 @@
display: flex;
}
.popup:has(#qr--modalEditor) .popup-content > #qr--modalEditor #qr--modal-executeButtons #qr--modal-execute {
transition: 200ms;
transition: var(--animation-duration-2x);
filter: grayscale(0);
}
.popup:has(#qr--modalEditor) .popup-content > #qr--modalEditor #qr--modal-executeButtons #qr--modal-execute.qr--busy {
@@ -825,7 +822,7 @@
position: absolute;
inset: 0;
right: calc(100% - var(--prog) * 1%);
transition: 200ms;
transition: var(--animation-duration-2x);
}
.popup:has(#qr--modalEditor) .popup-content > #qr--modalEditor #qr--modal-executeProgress.qr--paused:after {
animation-name: qr--progressPulse;
@@ -1053,7 +1050,7 @@
white-space: pre;
font-weight: normal;
box-shadow: 0 0 0;
transition: 200ms;
transition: var(--animation-duration-2x);
}
.popup:has(.qr--transferModal) .popup-button-ok:after {
content: 'Transfer';
@@ -1068,7 +1065,7 @@
white-space: pre;
font-weight: normal;
box-shadow: 0 0 0;
transition: 200ms;
transition: var(--animation-duration-2x);
}
.popup:has(.qr--transferModal) .qr--copy:after {
content: 'Copy';
File diff suppressed because it is too large Load Diff
+28 -2
View File
@@ -21,6 +21,32 @@
<small data-i18n="ext_regex_import_script">Import</small>
</div>
<input type="file" id="import_regex_file" hidden accept="*.json" multiple />
<label for="regex_bulk_edit" class="menu_button menu_button_icon">
<input id="regex_bulk_edit" type="checkbox" class="displayNone" />
<i class="fa-solid fa-edit"></i>
<small data-i18n="ext_regex_bulk_edit">Bulk Edit</small>
</label>
</div>
<div class="regex_bulk_operations flex-container justifyCenter">
<div id="bulk_select_all_toggle" class="menu_button menu_button_icon" title="Toggle Select All">
<i class="fa-solid fa-check-double"></i>
</div>
<div id="bulk_enable_regex" class="menu_button menu_button_icon">
<i class="fa-solid fa-toggle-on"></i>
<small data-i18n="Enable">Enable</small>
</div>
<div id="bulk_disable_regex" class="menu_button menu_button_icon">
<i class="fa-solid fa-toggle-off"></i>
<small data-i18n="Disable">Disable</small>
</div>
<div id="bulk_export_regex" class="menu_button menu_button_icon">
<i class="fa-solid fa-file-export"></i>
<small data-i18n="Export">Export</small>
</div>
<div id="bulk_delete_regex" class="menu_button menu_button_icon">
<i class="fa-solid fa-trash"></i>
<small data-i18n="Delete">Delete</small>
</div>
</div>
<hr />
<div id="global_scripts_block" class="padding5">
@@ -30,7 +56,7 @@
<small data-i18n="ext_regex_global_scripts_desc">
Available for all characters. Saved to local settings.
</small>
<div id="saved_regex_scripts" class="flex-container regex-script-container flexFlowColumn"></div>
<div id="saved_regex_scripts" no-scripts-text="No scripts found" data-i18n="[no-scripts-text]No scripts found" class="flex-container regex-script-container flexFlowColumn"></div>
</div>
<hr />
<div id="scoped_scripts_block" class="padding5">
@@ -45,7 +71,7 @@
<small data-i18n="ext_regex_scoped_scripts_desc">
Only available for this character. Saved to the card data.
</small>
<div id="saved_scoped_scripts" class="flex-container regex-script-container flexFlowColumn"></div>
<div id="saved_scoped_scripts" no-scripts-text="No scripts found" data-i18n="[no-scripts-text]No scripts found" class="flex-container regex-script-container flexFlowColumn"></div>
</div>
</div>
</div>
+1 -1
View File
@@ -146,7 +146,7 @@
</select>
</label>
<span>
<small data-i18n="ext_regex_other_options" data-i18n="Ephemerality">Ephemerality</small>
<small data-i18n="Ephemerality">Ephemerality</small>
<span class="fa-solid fa-circle-question note-link-span" data-i18n="[title]ext_regex_other_options_desc" title="By default, regex scripts alter the chat file directly and irreversibly.&#13;Enabling either (or both) of the options below will prevent chat file alteration, while still altering the specified item(s)."></span>
</span>
<label class="checkbox flex-container" data-i18n="[title]ext_regex_only_format_visual_desc" title="Chat history file contents won't change, but regex will be applied to the messages displayed in the Chat UI.">
@@ -1,5 +1,5 @@
<div>
<h3>This character has embedded regex script(s).</h3>
<h3>Would you like to allow using them?</h3>
<div class="m-b-1">If you want to do it later, select "Regex" from the extensions menu.</div>
<h3 data-i18n="This character has embedded regex script(s).">This character has embedded regex script(s).</h3>
<h3 data-i18n="Would you like to allow using them?">Would you like to allow using them?</h3>
<div class="m-b-1" data-i18n="If you want to do it later, select 'Regex' from the extensions menu.">If you want to do it later, select "Regex" from the extensions menu.</div>
</div>
+161 -33
View File
@@ -1,4 +1,4 @@
import { callPopup, characters, eventSource, event_types, getCurrentChatId, reloadCurrentChat, saveSettingsDebounced, this_chid } from '../../../script.js';
import { characters, eventSource, event_types, getCurrentChatId, reloadCurrentChat, saveSettingsDebounced, this_chid } from '../../../script.js';
import { extension_settings, renderExtensionTemplateAsync, writeExtensionField } from '../../extensions.js';
import { selected_group } from '../../group-chats.js';
import { callGenericPopup, POPUP_TYPE } from '../../popup.js';
@@ -12,6 +12,8 @@ import { regex_placement, runRegexScript, substitute_find_regex } from './engine
import { t } from '../../i18n.js';
import { accountStorage } from '../../util/AccountStorage.js';
const sanitizeFileName = name => name.replace(/[\s.<>:"/\\|?*\x00-\x1F\x7F]/g, '_').toLowerCase();
/**
* @typedef {import('../../char-data.js').RegexScriptData} RegexScript
*/
@@ -25,6 +27,18 @@ export function getRegexScripts() {
return [...(extension_settings.regex ?? []), ...(characters[this_chid]?.data?.extensions?.regex_scripts ?? [])];
}
/**
* Toggle the icon for the "select all" checkbox in the regex settings.
* - Use `fa-check-double` when the checkbox is unchecked (indicating all scripts are not selected).
* - Use `fa-minus` when the checkbox is checked (indicating all scripts are selected).
* @param {boolean} allAreChecked Should the "select all" icon be in the checked state?
*/
function setToggleAllIcon(allAreChecked) {
const selectAllIcon = $('#bulk_select_all_toggle').find('i');
selectAllIcon.toggleClass('fa-check-double', !allAreChecked);
selectAllIcon.toggleClass('fa-minus', allAreChecked);
}
/**
* Saves a regex script to the extension settings or character data.
* @param {import('../../char-data.js').RegexScriptData} regexScript
@@ -43,18 +57,18 @@ async function saveRegexScript(regexScript, existingScriptIndex, isScoped) {
// Is the script name undefined or empty?
if (!regexScript.scriptName) {
toastr.error('Could not save regex script: The script name was undefined or empty!');
toastr.error(t`Could not save regex script: The script name was undefined or empty!`);
return;
}
// Is a find regex present?
if (regexScript.findRegex.length === 0) {
toastr.warning('This regex script will not work, but was saved anyway: A find regex isn\'t present.');
toastr.warning(t`This regex script will not work, but was saved anyway: A find regex isn't present.`);
}
// Is there someplace to place results?
if (regexScript.placement.length === 0) {
toastr.warning('This regex script will not work, but was saved anyway: One "Affects" checkbox must be selected!');
toastr.warning(t`This regex script will not work, but was saved anyway: One "Affects" checkbox must be selected!`);
}
if (existingScriptIndex !== -1) {
@@ -101,6 +115,7 @@ async function deleteRegexScript({ id, isScoped }) {
async function loadRegexScripts() {
$('#saved_regex_scripts').empty();
$('#saved_scoped_scripts').empty();
setToggleAllIcon(false);
const scriptTemplate = $(await renderExtensionTemplateAsync('regex', 'scriptTemplate'));
@@ -137,7 +152,7 @@ async function loadRegexScripts() {
await onRegexEditorOpenClick(scriptHtml.attr('id'), isScoped);
});
scriptHtml.find('.move_to_global').on('click', async function () {
const confirm = await callGenericPopup('Are you sure you want to move this regex script to global?', POPUP_TYPE.CONFIRM);
const confirm = await callGenericPopup(t`Are you sure you want to move this regex script to global?`, POPUP_TYPE.CONFIRM);
if (!confirm) {
return;
@@ -148,16 +163,16 @@ async function loadRegexScripts() {
});
scriptHtml.find('.move_to_scoped').on('click', async function () {
if (this_chid === undefined) {
toastr.error('No character selected.');
toastr.error(t`No character selected.`);
return;
}
if (selected_group) {
toastr.error('Cannot edit scoped scripts in group chats.');
toastr.error(t`Cannot edit scoped scripts in group chats.`);
return;
}
const confirm = await callGenericPopup('Are you sure you want to move this regex script to scoped?', POPUP_TYPE.CONFIRM);
const confirm = await callGenericPopup(t`Are you sure you want to move this regex script to scoped?`, POPUP_TYPE.CONFIRM);
if (!confirm) {
return;
@@ -167,12 +182,12 @@ async function loadRegexScripts() {
await saveRegexScript(script, -1, true);
});
scriptHtml.find('.export_regex').on('click', async function () {
const fileName = `${script.scriptName.replace(/[\s.<>:"/\\|?*\x00-\x1F\x7F]/g, '_').toLowerCase()}.json`;
const fileName = `regex-${sanitizeFileName(script.scriptName)}.json`;
const fileData = JSON.stringify(script, null, 4);
download(fileData, fileName, 'application/json');
});
scriptHtml.find('.delete_regex').on('click', async function () {
const confirm = await callGenericPopup('Are you sure you want to delete this regex script?', POPUP_TYPE.CONFIRM);
const confirm = await callGenericPopup(t`Are you sure you want to delete this regex script?`, POPUP_TYPE.CONFIRM);
if (!confirm) {
return;
@@ -181,12 +196,17 @@ async function loadRegexScripts() {
await deleteRegexScript({ id: script.id, isScoped });
await reloadCurrentChat();
});
scriptHtml.find('.regex_bulk_checkbox').on('change', function () {
const checkboxes = $('#regex_container .regex_bulk_checkbox');
const allAreChecked = checkboxes.length === checkboxes.filter(':checked').length;
setToggleAllIcon(allAreChecked);
});
$(container).append(scriptHtml);
}
extension_settings?.regex?.forEach((script, index, array) => renderScript('#saved_regex_scripts', script, false, index, array));
characters[this_chid]?.data?.extensions?.regex_scripts?.forEach((script, index, array) => renderScript('#saved_scoped_scripts', script, true, index, array));
extension_settings?.regex?.forEach((script, index) => renderScript('#saved_regex_scripts', script, false, index));
characters[this_chid]?.data?.extensions?.regex_scripts?.forEach((script, index) => renderScript('#saved_scoped_scripts', script, true, index));
const isAllowed = extension_settings?.character_allowed_regex?.includes(characters?.[this_chid]?.avatar);
$('#regex_scoped_toggle').prop('checked', isAllowed);
@@ -260,11 +280,18 @@ async function onRegexEditorOpenClick(existingId, isScoped) {
const testScript = {
id: uuidv4(),
scriptName: editorHtml.find('.regex_script_name').val(),
findRegex: editorHtml.find('.find_regex').val(),
replaceString: editorHtml.find('.regex_replace_string').val(),
scriptName: editorHtml.find('.regex_script_name').val().toString(),
findRegex: editorHtml.find('.find_regex').val().toString(),
replaceString: editorHtml.find('.regex_replace_string').val().toString(),
trimStrings: String(editorHtml.find('.regex_trim_strings').val()).split('\n').filter((e) => e.length !== 0) || [],
substituteRegex: Number(editorHtml.find('select[name="substitute_regex"]').val()),
disabled: false,
promptOnly: false,
markdownOnly: false,
runOnEdit: false,
minDepth: null,
maxDepth: null,
placement: null,
};
const rawTestString = String(editorHtml.find('#regex_test_input').val());
const result = runRegexScript(testScript, rawTestString);
@@ -274,19 +301,19 @@ async function onRegexEditorOpenClick(existingId, isScoped) {
editorHtml.find('input, textarea, select').on('input', updateTestResult);
updateInfoBlock(editorHtml);
const popupResult = await callPopup(editorHtml, 'confirm', undefined, { okButton: t`Save` });
const popupResult = await callGenericPopup(editorHtml, POPUP_TYPE.CONFIRM, '', { okButton: t`Save`, cancelButton: t`Cancel`, allowVerticalScrolling: true });
if (popupResult) {
const newRegexScript = {
id: existingId ? String(existingId) : uuidv4(),
scriptName: String(editorHtml.find('.regex_script_name').val()),
findRegex: String(editorHtml.find('.find_regex').val()),
replaceString: String(editorHtml.find('.regex_replace_string').val()),
trimStrings: editorHtml.find('.regex_trim_strings').val().split('\n').filter((e) => e.length !== 0) || [],
trimStrings: String(editorHtml.find('.regex_trim_strings').val()).split('\n').filter((e) => e.length !== 0) || [],
placement:
editorHtml
.find('input[name="replace_position"]')
.filter(':checked')
.map(function () { return parseInt($(this).val()); })
.map(function () { return parseInt($(this).val().toString()); })
.get()
.filter((e) => !isNaN(e)) || [],
disabled: editorHtml.find('input[name="disabled"]').prop('checked'),
@@ -348,6 +375,11 @@ function migrateSettings() {
performSave = true;
}
if (!Array.isArray(script.placement)) {
script.placement = [];
performSave = true;
}
if (script.placement.includes(regex_placement.MD_DISPLAY)) {
script.placement = script.placement.length === 1 ?
Object.values(regex_placement).filter((e) => e !== regex_placement.MD_DISPLAY) :
@@ -459,19 +491,12 @@ async function toggleRegexCallback(args, scriptName) {
}
/**
* Performs the import of the regex file.
* @param {File} file Input file
* Performs the import of the regex object.
* @param {Object} regexScript Input object
* @param {boolean} isScoped Is the script scoped to a character?
*/
async function onRegexImportFileChange(file, isScoped) {
if (!file) {
toastr.error('No file provided.');
return;
}
async function onRegexImportObjectChange(regexScript, isScoped) {
try {
const fileText = await getFileText(file);
const regexScript = JSON.parse(fileText);
if (!regexScript.scriptName) {
throw new Error('No script name provided.');
}
@@ -488,7 +513,34 @@ async function onRegexImportFileChange(file, isScoped) {
saveSettingsDebounced();
await loadRegexScripts();
toastr.success(`Regex script "${regexScript.scriptName}" imported.`);
toastr.success(t`Regex script "${regexScript.scriptName}" imported.`);
} catch (error) {
console.log(error);
toastr.error(t`Invalid regex object.`);
return;
}
}
/**
* Performs the import of the regex file.
* @param {File} file Input file
* @param {boolean} isScoped Is the script scoped to a character?
*/
async function onRegexImportFileChange(file, isScoped) {
if (!file) {
toastr.error('No file provided.');
return;
}
try {
const regexScripts = JSON.parse(await getFileText(file));
if (Array.isArray(regexScripts)) {
for (const regexScript of regexScripts) {
await onRegexImportObjectChange(regexScript, isScoped);
}
} else {
await onRegexImportObjectChange(regexScripts, isScoped);
}
} catch (error) {
console.log(error);
toastr.error('Invalid JSON file.');
@@ -556,12 +608,12 @@ jQuery(async () => {
});
$('#open_scoped_editor').on('click', function () {
if (this_chid === undefined) {
toastr.error('No character selected.');
toastr.error(t`No character selected.`);
return;
}
if (selected_group) {
toastr.error('Cannot edit scoped scripts in group chats.');
toastr.error(t`Cannot edit scoped scripts in group chats.`);
return;
}
@@ -585,6 +637,82 @@ jQuery(async () => {
$('#import_regex_file').trigger('click');
});
function getSelectedScripts() {
const scripts = getRegexScripts();
const selector = '#regex_container .regex-script-label:has(.regex_bulk_checkbox:checked)';
const selectedIds = Array.from(document.querySelectorAll(selector)).map(e => e.getAttribute('id')).filter(id => id);
return scripts.filter(script => selectedIds.includes(script.id));
}
$('#bulk_select_all_toggle').on('click', async function () {
const checkboxes = $('#regex_container .regex_bulk_checkbox');
if (checkboxes.length === 0) {
return;
}
const allAreChecked = checkboxes.length === checkboxes.filter(':checked').length;
const newState = !allAreChecked; // true if we just checked all, false if we just unchecked all
checkboxes.prop('checked', newState);
setToggleAllIcon(newState);
});
$('#bulk_enable_regex').on('click', async function () {
const scripts = getSelectedScripts().filter(script => script.disabled);
if (scripts.length === 0) {
toastr.warning(t`No regex scripts selected for enabling.`);
return;
}
for (const script of scripts) {
script.disabled = false;
}
saveSettingsDebounced();
await loadRegexScripts();
});
$('#bulk_disable_regex').on('click', async function () {
const scripts = getSelectedScripts().filter(script => !script.disabled);
if (scripts.length === 0) {
toastr.warning(t`No regex scripts selected for disabling.`);
return;
}
for (const script of scripts) {
script.disabled = true;
}
saveSettingsDebounced();
await loadRegexScripts();
});
$('#bulk_delete_regex').on('click', async function () {
const scripts = getSelectedScripts();
if (scripts.length === 0) {
toastr.warning(t`No regex scripts selected for deletion.`);
return;
}
const confirm = await callGenericPopup('Are you sure you want to delete the selected regex scripts?', POPUP_TYPE.CONFIRM);
if (!confirm) {
return;
}
for (const script of scripts) {
const isScoped = characters[this_chid]?.data?.extensions?.regex_scripts?.some(s => s.id === script.id);
await deleteRegexScript({ id: script.id, isScoped: isScoped });
}
await reloadCurrentChat();
saveSettingsDebounced();
});
$('#bulk_export_regex').on('click', async function () {
const scripts = getSelectedScripts();
if (scripts.length === 0) {
toastr.warning(t`No regex scripts selected for export.`);
return;
}
const fileName = `regex-${new Date().toISOString()}.json`;
const fileData = JSON.stringify(scripts, null, 4);
download(fileData, fileName, 'application/json');
await loadRegexScripts();
});
let sortableDatas = [
{
selector: '#saved_regex_scripts',
@@ -622,12 +750,12 @@ jQuery(async () => {
$('#regex_scoped_toggle').on('input', function () {
if (this_chid === undefined) {
toastr.error('No character selected.');
toastr.error(t`No character selected.`);
return;
}
if (selected_group) {
toastr.error('Cannot edit scoped scripts in group chats.');
toastr.error(t`Cannot edit scoped scripts in group chats.`);
return;
}
@@ -1,4 +1,5 @@
<div class="regex-script-label flex-container flexnowrap">
<input type="checkbox" class="regex_bulk_checkbox" />
<span class="drag-handle menu-handle">&#9776;</span>
<div class="regex_script_name flexGrow overflow-hidden"></div>
<div class="flex-container flexnowrap">

Some files were not shown because too many files have changed in this diff Show More