stail00016 commited on
Commit
5c43797
·
verified ·
1 Parent(s): c49e17d

Upload 28 files

Browse files
Files changed (28) hide show
  1. .dockerignore +15 -0
  2. .editorconfig +14 -0
  3. .eslintrc.cjs +102 -0
  4. .gitignore +57 -0
  5. .nomedia +0 -0
  6. .npmignore +14 -0
  7. .replit +81 -0
  8. CONTRIBUTING.md +41 -0
  9. Dockerfile +51 -0
  10. LICENSE +661 -0
  11. Remote-Link.cmd +18 -0
  12. SECURITY.md +25 -0
  13. Start.bat +7 -0
  14. Update-Instructions.txt +75 -0
  15. UpdateAndStart.bat +27 -0
  16. UpdateForkAndStart.bat +110 -0
  17. config.yaml +235 -0
  18. index.d.ts +69 -0
  19. jsconfig.json +25 -0
  20. package-lock.json +0 -0
  21. package.json +145 -0
  22. plugins.js +96 -0
  23. post-install.js +343 -0
  24. recover.js +68 -0
  25. replit.nix +8 -0
  26. server.js +374 -0
  27. start.sh +32 -0
  28. webpack.config.js +72 -0
.dockerignore ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .git
2
+ .github
3
+ .vscode
4
+ node_modules
5
+ npm-debug.log
6
+ readme*
7
+ Start.bat
8
+ /dist
9
+ /backups
10
+ cloudflared.exe
11
+ access.log
12
+ /data
13
+ /cache
14
+ .DS_Store
15
+ /public/scripts/extensions/third-party
.editorconfig ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ root = true
2
+
3
+ [*]
4
+ end_of_line = lf
5
+ insert_final_newline = true
6
+ trim_trailing_whitespace = true
7
+
8
+ [*.{js,conf,json,css,less,html}]
9
+ charset = utf-8
10
+ indent_style = space
11
+ indent_size = 4
12
+
13
+ [*.md]
14
+ trim_trailing_whitespace = false
.eslintrc.cjs ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ module.exports = {
2
+ root: true,
3
+ extends: [
4
+ 'eslint:recommended',
5
+ ],
6
+ env: {
7
+ es6: true,
8
+ },
9
+ parserOptions: {
10
+ ecmaVersion: 'latest',
11
+ },
12
+ overrides: [
13
+ {
14
+ // Server-side files (plus this configuration file)
15
+ files: ['src/**/*.js', './*.js', 'plugins/**/*.js'],
16
+ env: {
17
+ node: true,
18
+ },
19
+ parserOptions: {
20
+ sourceType: 'module',
21
+ },
22
+ globals: {
23
+ globalThis: 'readonly',
24
+ Deno: 'readonly',
25
+ },
26
+ },
27
+ {
28
+ files: ['*.cjs'],
29
+ parserOptions: {
30
+ sourceType: 'commonjs',
31
+ },
32
+ env: {
33
+ node: true,
34
+ },
35
+ },
36
+ {
37
+ files: ['src/**/*.mjs'],
38
+ parserOptions: {
39
+ sourceType: 'module',
40
+ },
41
+ env: {
42
+ node: true,
43
+ },
44
+ },
45
+ {
46
+ // Browser-side files
47
+ files: ['public/**/*.js'],
48
+ env: {
49
+ browser: true,
50
+ jquery: true,
51
+ },
52
+ parserOptions: {
53
+ sourceType: 'module',
54
+ },
55
+ // These scripts are loaded in HTML; tell ESLint not to complain about them being undefined
56
+ globals: {
57
+ globalThis: 'readonly',
58
+ ePub: 'readonly',
59
+ pdfjsLib: 'readonly',
60
+ toastr: 'readonly',
61
+ SillyTavern: 'readonly',
62
+ },
63
+ },
64
+ ],
65
+ ignorePatterns: [
66
+ '**/node_modules/**',
67
+ '**/dist/**',
68
+ '**/.git/**',
69
+ 'public/lib/**',
70
+ 'backups/**',
71
+ 'data/**',
72
+ 'cache/**',
73
+ 'src/tokenizers/**',
74
+ 'docker/**',
75
+ 'plugins/**',
76
+ '**/*.min.js',
77
+ 'public/scripts/extensions/quick-reply/lib/**',
78
+ 'public/scripts/extensions/tts/lib/**',
79
+ ],
80
+ rules: {
81
+ 'no-unused-vars': ['error', { args: 'none' }],
82
+ 'no-control-regex': 'off',
83
+ 'no-constant-condition': ['error', { checkLoops: false }],
84
+ 'require-yield': 'off',
85
+ 'quotes': ['error', 'single'],
86
+ 'semi': ['error', 'always'],
87
+ 'indent': ['error', 4, { SwitchCase: 1, FunctionDeclaration: { parameters: 'first' } }],
88
+ 'comma-dangle': ['error', 'always-multiline'],
89
+ 'eol-last': ['error', 'always'],
90
+ 'no-trailing-spaces': 'error',
91
+ 'object-curly-spacing': ['error', 'always'],
92
+ 'space-infix-ops': 'error',
93
+ 'no-unused-expressions': ['error', { allowShortCircuit: true, allowTernary: true }],
94
+ 'no-cond-assign': 'error',
95
+ 'no-unneeded-ternary': 'error',
96
+ 'no-irregular-whitespace': ['error', { skipStrings: true, skipTemplates: true }],
97
+
98
+ // These rules should eventually be enabled.
99
+ 'no-async-promise-executor': 'off',
100
+ 'no-inner-declarations': 'off',
101
+ },
102
+ };
.gitignore ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ node_modules/
2
+ public/chats/
3
+ public/characters/
4
+ public/User Avatars/
5
+ public/backgrounds/
6
+ public/groups/
7
+ public/group chats/
8
+ public/worlds/
9
+ public/user/
10
+ public/css/bg_load.css
11
+ public/themes/
12
+ public/OpenAI Settings/
13
+ public/KoboldAI Settings/
14
+ public/NovelAI Settings/
15
+ public/TextGen Settings/
16
+ public/instruct/
17
+ public/context/
18
+ public/scripts/extensions/third-party/
19
+ public/stats.json
20
+ /uploads/
21
+ *.jsonl
22
+ /config.conf
23
+ /config.yaml
24
+ /config.conf.bak
25
+ /docker/config
26
+ /docker/user
27
+ /docker/extensions
28
+ /docker/data
29
+ .DS_Store
30
+ public/settings.json
31
+ /thumbnails
32
+ whitelist.txt
33
+ .vscode/**
34
+ !.vscode/extensions.json
35
+ .idea/
36
+ secrets.json
37
+ /dist
38
+ /backups/
39
+ public/movingUI/
40
+ public/QuickReplies/
41
+ content.log
42
+ cloudflared.exe
43
+ public/assets/
44
+ access.log
45
+ /vectors/
46
+ /cache/
47
+ public/css/user.css
48
+ public/error/
49
+ /plugins/
50
+ /data
51
+ /default/scaffold
52
+ public/scripts/extensions/third-party
53
+ /certs
54
+ .aider*
55
+ .env
56
+ /StartDev.bat
57
+
.nomedia ADDED
File without changes
.npmignore ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ node_modules/
2
+ /uploads/
3
+ .DS_Store
4
+ /thumbnails
5
+ secrets.json
6
+ /dist
7
+ /backups/
8
+ /data
9
+ /cache
10
+ access.log
11
+ .github
12
+ .vscode
13
+ .git
14
+ /public/scripts/extensions/third-party
.replit ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ hidden = [".config", "package-lock.json"]
3
+ run = "chmod 755 ./start.sh && ./start.sh"
4
+ entrypoint = "server.js"
5
+
6
+ [[hints]]
7
+ regex = "Error \\[ERR_REQUIRE_ESM\\]"
8
+ message = "We see that you are using require(...) inside your code. We currently do not support this syntax. Please use 'import' instead when using external modules. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)"
9
+
10
+ [nix]
11
+ channel = "stable-22_11"
12
+
13
+ [env]
14
+ XDG_CONFIG_HOME = "/home/runner/$REPL_SLUG/.config"
15
+ PATH = "/home/runner/$REPL_SLUG/.config/npm/node_global/bin:/home/runner/$REPL_SLUG/node_modules/.bin"
16
+ npm_config_prefix = "/home/runner/$REPL_SLUG/.config/npm/node_global"
17
+
18
+ [gitHubImport]
19
+ requiredFiles = [".replit", "replit.nix", ".config", "package.json", "package-lock.json"]
20
+
21
+ [packager]
22
+ language = "nodejs"
23
+
24
+ [packager.features]
25
+ packageSearch = true
26
+ guessImports = true
27
+ enabledForHosting = false
28
+
29
+ [unitTest]
30
+ language = "nodejs"
31
+
32
+ [debugger]
33
+ support = true
34
+
35
+ [debugger.interactive]
36
+ transport = "localhost:0"
37
+ startCommand = [ "dap-node" ]
38
+
39
+ [debugger.interactive.initializeMessage]
40
+ command = "initialize"
41
+ type = "request"
42
+
43
+ [debugger.interactive.initializeMessage.arguments]
44
+ clientID = "replit"
45
+ clientName = "replit.com"
46
+ columnsStartAt1 = true
47
+ linesStartAt1 = true
48
+ locale = "en-us"
49
+ pathFormat = "path"
50
+ supportsInvalidatedEvent = true
51
+ supportsProgressReporting = true
52
+ supportsRunInTerminalRequest = true
53
+ supportsVariablePaging = true
54
+ supportsVariableType = true
55
+
56
+ [debugger.interactive.launchMessage]
57
+ command = "launch"
58
+ type = "request"
59
+
60
+ [debugger.interactive.launchMessage.arguments]
61
+ args = []
62
+ console = "externalTerminal"
63
+ cwd = "."
64
+ environment = []
65
+ pauseForSourceMap = false
66
+ program = "./server.js"
67
+ request = "launch"
68
+ sourceMaps = true
69
+ stopOnEntry = false
70
+ type = "pwa-node"
71
+
72
+ [languages]
73
+
74
+ [languages.javascript]
75
+ pattern = "**/{*.js,*.jsx,*.ts,*.tsx,*.json}"
76
+
77
+ [languages.javascript.languageServer]
78
+ start = "typescript-language-server --stdio"
79
+
80
+ [deployment]
81
+ run = ["sh", "-c", "./start.sh"]
CONTRIBUTING.md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # How to contribute to SillyTavern
2
+
3
+ ## Setting up the dev environment
4
+
5
+ 1. Required software: git and node.
6
+ 2. Recommended editor: Visual Studio Code.
7
+ 3. You can also use GitHub Codespaces which sets up everything for you.
8
+
9
+ ## Getting the code ready
10
+
11
+ 1. Register a GitHub account.
12
+ 2. Fork this repository under your account.
13
+ 3. Clone the fork onto your machine.
14
+ 4. Open the cloned repository in the code editor.
15
+ 5. Create a git branch (recommended).
16
+ 6. Make your changes and test them locally.
17
+ 7. Commit the changes and push the branch to the remote repo.
18
+ 8. Go to GitHub, and open a pull request, targeting the upstream branch.
19
+
20
+ ## Contribution guidelines
21
+
22
+ 1. Our standards are pretty low, but make sure the code is not too ugly:
23
+ - Run VS Code's autoformat when you're done.
24
+ - Check with ESLint by running `npm run lint`, then fix the errors.
25
+ - Use common sense and follow existing naming conventions.
26
+ 2. Create pull requests for the staging branch, 99% of contributions should go there. That way people could test your code before the next stable release.
27
+ 3. You can still send a pull request for release in the following scenarios:
28
+ - Updating README.
29
+ - Updating GitHub Actions.
30
+ - Hotfixing a critical bug.
31
+ 4. Project maintainers will test and can change your code before merging.
32
+ 5. Write at least somewhat meaningful PR descriptions. There's no "right" way to do it, but the following may help with outlining a general structure:
33
+ - What is the reason for a change?
34
+ - What did you do to achieve this?
35
+ - How would a reviewer test the change?
36
+ 6. Mind the license. Your contributions will be licensed under the GNU Affero General Public License. If you don't know what that implies, consult your lawyer.
37
+
38
+ ## Further reading
39
+
40
+ 1. [How to write UI extensions](https://docs.sillytavern.app/for-contributors/writing-extensions/)
41
+ 2. [How to write server plugins](https://docs.sillytavern.app/for-contributors/server-plugins)
Dockerfile ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM node:lts-alpine3.19
2
+
3
+ # Arguments
4
+ ARG APP_HOME=/home/node/app
5
+
6
+ # Install system dependencies
7
+ RUN apk add --no-cache gcompat tini git
8
+
9
+ # Create app directory
10
+ WORKDIR ${APP_HOME}
11
+
12
+ # Set NODE_ENV to production
13
+ ENV NODE_ENV=production
14
+
15
+ # Install app dependencies
16
+ COPY package*.json post-install.js ./
17
+ RUN \
18
+ echo "*** Install npm packages ***" && \
19
+ npm i --no-audit --no-fund --loglevel=error --no-progress --omit=dev && npm cache clean --force
20
+
21
+ # Bundle app source
22
+ COPY . ./
23
+
24
+ # Copy default chats, characters and user avatars to <folder>.default folder
25
+ RUN \
26
+ rm -f "config.yaml" || true && \
27
+ ln -s "./config/config.yaml" "config.yaml" || true && \
28
+ mkdir "config" || true
29
+
30
+ # Pre-compile public libraries
31
+ RUN \
32
+ echo "*** Run Webpack ***" && \
33
+ node "./docker/build-lib.js"
34
+
35
+ # Cleanup unnecessary files
36
+ RUN \
37
+ echo "*** Cleanup ***" && \
38
+ mv "./docker/docker-entrypoint.sh" "./" && \
39
+ rm -rf "./docker" && \
40
+ echo "*** Make docker-entrypoint.sh executable ***" && \
41
+ chmod +x "./docker-entrypoint.sh" && \
42
+ echo "*** Convert line endings to Unix format ***" && \
43
+ dos2unix "./docker-entrypoint.sh"
44
+
45
+ # Fix extension repos permissions
46
+ RUN git config --global --add safe.directory "*"
47
+
48
+ EXPOSE 8000
49
+
50
+ # Ensure proper handling of kernel signals
51
+ ENTRYPOINT ["tini", "--", "./docker-entrypoint.sh"]
LICENSE ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU AFFERO GENERAL PUBLIC LICENSE
2
+ Version 3, 19 November 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU Affero General Public License is a free, copyleft license for
11
+ software and other kinds of works, specifically designed to ensure
12
+ cooperation with the community in the case of network server software.
13
+
14
+ The licenses for most software and other practical works are designed
15
+ to take away your freedom to share and change the works. By contrast,
16
+ our General Public Licenses are intended to guarantee your freedom to
17
+ share and change all versions of a program--to make sure it remains free
18
+ software for all its users.
19
+
20
+ When we speak of free software, we are referring to freedom, not
21
+ price. Our General Public Licenses are designed to make sure that you
22
+ have the freedom to distribute copies of free software (and charge for
23
+ them if you wish), that you receive source code or can get it if you
24
+ want it, that you can change the software or use pieces of it in new
25
+ free programs, and that you know you can do these things.
26
+
27
+ Developers that use our General Public Licenses protect your rights
28
+ with two steps: (1) assert copyright on the software, and (2) offer
29
+ you this License which gives you legal permission to copy, distribute
30
+ and/or modify the software.
31
+
32
+ A secondary benefit of defending all users' freedom is that
33
+ improvements made in alternate versions of the program, if they
34
+ receive widespread use, become available for other developers to
35
+ incorporate. Many developers of free software are heartened and
36
+ encouraged by the resulting cooperation. However, in the case of
37
+ software used on network servers, this result may fail to come about.
38
+ The GNU General Public License permits making a modified version and
39
+ letting the public access it on a server without ever releasing its
40
+ source code to the public.
41
+
42
+ The GNU Affero General Public License is designed specifically to
43
+ ensure that, in such cases, the modified source code becomes available
44
+ to the community. It requires the operator of a network server to
45
+ provide the source code of the modified version running there to the
46
+ users of that server. Therefore, public use of a modified version, on
47
+ a publicly accessible server, gives the public access to the source
48
+ code of the modified version.
49
+
50
+ An older license, called the Affero General Public License and
51
+ published by Affero, was designed to accomplish similar goals. This is
52
+ a different license, not a version of the Affero GPL, but Affero has
53
+ released a new version of the Affero GPL which permits relicensing under
54
+ this license.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ TERMS AND CONDITIONS
60
+
61
+ 0. Definitions.
62
+
63
+ "This License" refers to version 3 of the GNU Affero General Public License.
64
+
65
+ "Copyright" also means copyright-like laws that apply to other kinds of
66
+ works, such as semiconductor masks.
67
+
68
+ "The Program" refers to any copyrightable work licensed under this
69
+ License. Each licensee is addressed as "you". "Licensees" and
70
+ "recipients" may be individuals or organizations.
71
+
72
+ To "modify" a work means to copy from or adapt all or part of the work
73
+ in a fashion requiring copyright permission, other than the making of an
74
+ exact copy. The resulting work is called a "modified version" of the
75
+ earlier work or a work "based on" the earlier work.
76
+
77
+ A "covered work" means either the unmodified Program or a work based
78
+ on the Program.
79
+
80
+ To "propagate" a work means to do anything with it that, without
81
+ permission, would make you directly or secondarily liable for
82
+ infringement under applicable copyright law, except executing it on a
83
+ computer or modifying a private copy. Propagation includes copying,
84
+ distribution (with or without modification), making available to the
85
+ public, and in some countries other activities as well.
86
+
87
+ To "convey" a work means any kind of propagation that enables other
88
+ parties to make or receive copies. Mere interaction with a user through
89
+ a computer network, with no transfer of a copy, is not conveying.
90
+
91
+ An interactive user interface displays "Appropriate Legal Notices"
92
+ to the extent that it includes a convenient and prominently visible
93
+ feature that (1) displays an appropriate copyright notice, and (2)
94
+ tells the user that there is no warranty for the work (except to the
95
+ extent that warranties are provided), that licensees may convey the
96
+ work under this License, and how to view a copy of this License. If
97
+ the interface presents a list of user commands or options, such as a
98
+ menu, a prominent item in the list meets this criterion.
99
+
100
+ 1. Source Code.
101
+
102
+ The "source code" for a work means the preferred form of the work
103
+ for making modifications to it. "Object code" means any non-source
104
+ form of a work.
105
+
106
+ A "Standard Interface" means an interface that either is an official
107
+ standard defined by a recognized standards body, or, in the case of
108
+ interfaces specified for a particular programming language, one that
109
+ is widely used among developers working in that language.
110
+
111
+ The "System Libraries" of an executable work include anything, other
112
+ than the work as a whole, that (a) is included in the normal form of
113
+ packaging a Major Component, but which is not part of that Major
114
+ Component, and (b) serves only to enable use of the work with that
115
+ Major Component, or to implement a Standard Interface for which an
116
+ implementation is available to the public in source code form. A
117
+ "Major Component", in this context, means a major essential component
118
+ (kernel, window system, and so on) of the specific operating system
119
+ (if any) on which the executable work runs, or a compiler used to
120
+ produce the work, or an object code interpreter used to run it.
121
+
122
+ The "Corresponding Source" for a work in object code form means all
123
+ the source code needed to generate, install, and (for an executable
124
+ work) run the object code and to modify the work, including scripts to
125
+ control those activities. However, it does not include the work's
126
+ System Libraries, or general-purpose tools or generally available free
127
+ programs which are used unmodified in performing those activities but
128
+ which are not part of the work. For example, Corresponding Source
129
+ includes interface definition files associated with source files for
130
+ the work, and the source code for shared libraries and dynamically
131
+ linked subprograms that the work is specifically designed to require,
132
+ such as by intimate data communication or control flow between those
133
+ subprograms and other parts of the work.
134
+
135
+ The Corresponding Source need not include anything that users
136
+ can regenerate automatically from other parts of the Corresponding
137
+ Source.
138
+
139
+ The Corresponding Source for a work in source code form is that
140
+ same work.
141
+
142
+ 2. Basic Permissions.
143
+
144
+ All rights granted under this License are granted for the term of
145
+ copyright on the Program, and are irrevocable provided the stated
146
+ conditions are met. This License explicitly affirms your unlimited
147
+ permission to run the unmodified Program. The output from running a
148
+ covered work is covered by this License only if the output, given its
149
+ content, constitutes a covered work. This License acknowledges your
150
+ rights of fair use or other equivalent, as provided by copyright law.
151
+
152
+ You may make, run and propagate covered works that you do not
153
+ convey, without conditions so long as your license otherwise remains
154
+ in force. You may convey covered works to others for the sole purpose
155
+ of having them make modifications exclusively for you, or provide you
156
+ with facilities for running those works, provided that you comply with
157
+ the terms of this License in conveying all material for which you do
158
+ not control copyright. Those thus making or running the covered works
159
+ for you must do so exclusively on your behalf, under your direction
160
+ and control, on terms that prohibit them from making any copies of
161
+ your copyrighted material outside their relationship with you.
162
+
163
+ Conveying under any other circumstances is permitted solely under
164
+ the conditions stated below. Sublicensing is not allowed; section 10
165
+ makes it unnecessary.
166
+
167
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168
+
169
+ No covered work shall be deemed part of an effective technological
170
+ measure under any applicable law fulfilling obligations under article
171
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172
+ similar laws prohibiting or restricting circumvention of such
173
+ measures.
174
+
175
+ When you convey a covered work, you waive any legal power to forbid
176
+ circumvention of technological measures to the extent such circumvention
177
+ is effected by exercising rights under this License with respect to
178
+ the covered work, and you disclaim any intention to limit operation or
179
+ modification of the work as a means of enforcing, against the work's
180
+ users, your or third parties' legal rights to forbid circumvention of
181
+ technological measures.
182
+
183
+ 4. Conveying Verbatim Copies.
184
+
185
+ You may convey verbatim copies of the Program's source code as you
186
+ receive it, in any medium, provided that you conspicuously and
187
+ appropriately publish on each copy an appropriate copyright notice;
188
+ keep intact all notices stating that this License and any
189
+ non-permissive terms added in accord with section 7 apply to the code;
190
+ keep intact all notices of the absence of any warranty; and give all
191
+ recipients a copy of this License along with the Program.
192
+
193
+ You may charge any price or no price for each copy that you convey,
194
+ and you may offer support or warranty protection for a fee.
195
+
196
+ 5. Conveying Modified Source Versions.
197
+
198
+ You may convey a work based on the Program, or the modifications to
199
+ produce it from the Program, in the form of source code under the
200
+ terms of section 4, provided that you also meet all of these conditions:
201
+
202
+ a) The work must carry prominent notices stating that you modified
203
+ it, and giving a relevant date.
204
+
205
+ b) The work must carry prominent notices stating that it is
206
+ released under this License and any conditions added under section
207
+ 7. This requirement modifies the requirement in section 4 to
208
+ "keep intact all notices".
209
+
210
+ c) You must license the entire work, as a whole, under this
211
+ License to anyone who comes into possession of a copy. This
212
+ License will therefore apply, along with any applicable section 7
213
+ additional terms, to the whole of the work, and all its parts,
214
+ regardless of how they are packaged. This License gives no
215
+ permission to license the work in any other way, but it does not
216
+ invalidate such permission if you have separately received it.
217
+
218
+ d) If the work has interactive user interfaces, each must display
219
+ Appropriate Legal Notices; however, if the Program has interactive
220
+ interfaces that do not display Appropriate Legal Notices, your
221
+ work need not make them do so.
222
+
223
+ A compilation of a covered work with other separate and independent
224
+ works, which are not by their nature extensions of the covered work,
225
+ and which are not combined with it such as to form a larger program,
226
+ in or on a volume of a storage or distribution medium, is called an
227
+ "aggregate" if the compilation and its resulting copyright are not
228
+ used to limit the access or legal rights of the compilation's users
229
+ beyond what the individual works permit. Inclusion of a covered work
230
+ in an aggregate does not cause this License to apply to the other
231
+ parts of the aggregate.
232
+
233
+ 6. Conveying Non-Source Forms.
234
+
235
+ You may convey a covered work in object code form under the terms
236
+ of sections 4 and 5, provided that you also convey the
237
+ machine-readable Corresponding Source under the terms of this License,
238
+ in one of these ways:
239
+
240
+ a) Convey the object code in, or embodied in, a physical product
241
+ (including a physical distribution medium), accompanied by the
242
+ Corresponding Source fixed on a durable physical medium
243
+ customarily used for software interchange.
244
+
245
+ b) Convey the object code in, or embodied in, a physical product
246
+ (including a physical distribution medium), accompanied by a
247
+ written offer, valid for at least three years and valid for as
248
+ long as you offer spare parts or customer support for that product
249
+ model, to give anyone who possesses the object code either (1) a
250
+ copy of the Corresponding Source for all the software in the
251
+ product that is covered by this License, on a durable physical
252
+ medium customarily used for software interchange, for a price no
253
+ more than your reasonable cost of physically performing this
254
+ conveying of source, or (2) access to copy the
255
+ Corresponding Source from a network server at no charge.
256
+
257
+ c) Convey individual copies of the object code with a copy of the
258
+ written offer to provide the Corresponding Source. This
259
+ alternative is allowed only occasionally and noncommercially, and
260
+ only if you received the object code with such an offer, in accord
261
+ with subsection 6b.
262
+
263
+ d) Convey the object code by offering access from a designated
264
+ place (gratis or for a charge), and offer equivalent access to the
265
+ Corresponding Source in the same way through the same place at no
266
+ further charge. You need not require recipients to copy the
267
+ Corresponding Source along with the object code. If the place to
268
+ copy the object code is a network server, the Corresponding Source
269
+ may be on a different server (operated by you or a third party)
270
+ that supports equivalent copying facilities, provided you maintain
271
+ clear directions next to the object code saying where to find the
272
+ Corresponding Source. Regardless of what server hosts the
273
+ Corresponding Source, you remain obligated to ensure that it is
274
+ available for as long as needed to satisfy these requirements.
275
+
276
+ e) Convey the object code using peer-to-peer transmission, provided
277
+ you inform other peers where the object code and Corresponding
278
+ Source of the work are being offered to the general public at no
279
+ charge under subsection 6d.
280
+
281
+ A separable portion of the object code, whose source code is excluded
282
+ from the Corresponding Source as a System Library, need not be
283
+ included in conveying the object code work.
284
+
285
+ A "User Product" is either (1) a "consumer product", which means any
286
+ tangible personal property which is normally used for personal, family,
287
+ or household purposes, or (2) anything designed or sold for incorporation
288
+ into a dwelling. In determining whether a product is a consumer product,
289
+ doubtful cases shall be resolved in favor of coverage. For a particular
290
+ product received by a particular user, "normally used" refers to a
291
+ typical or common use of that class of product, regardless of the status
292
+ of the particular user or of the way in which the particular user
293
+ actually uses, or expects or is expected to use, the product. A product
294
+ is a consumer product regardless of whether the product has substantial
295
+ commercial, industrial or non-consumer uses, unless such uses represent
296
+ the only significant mode of use of the product.
297
+
298
+ "Installation Information" for a User Product means any methods,
299
+ procedures, authorization keys, or other information required to install
300
+ and execute modified versions of a covered work in that User Product from
301
+ a modified version of its Corresponding Source. The information must
302
+ suffice to ensure that the continued functioning of the modified object
303
+ code is in no case prevented or interfered with solely because
304
+ modification has been made.
305
+
306
+ If you convey an object code work under this section in, or with, or
307
+ specifically for use in, a User Product, and the conveying occurs as
308
+ part of a transaction in which the right of possession and use of the
309
+ User Product is transferred to the recipient in perpetuity or for a
310
+ fixed term (regardless of how the transaction is characterized), the
311
+ Corresponding Source conveyed under this section must be accompanied
312
+ by the Installation Information. But this requirement does not apply
313
+ if neither you nor any third party retains the ability to install
314
+ modified object code on the User Product (for example, the work has
315
+ been installed in ROM).
316
+
317
+ The requirement to provide Installation Information does not include a
318
+ requirement to continue to provide support service, warranty, or updates
319
+ for a work that has been modified or installed by the recipient, or for
320
+ the User Product in which it has been modified or installed. Access to a
321
+ network may be denied when the modification itself materially and
322
+ adversely affects the operation of the network or violates the rules and
323
+ protocols for communication across the network.
324
+
325
+ Corresponding Source conveyed, and Installation Information provided,
326
+ in accord with this section must be in a format that is publicly
327
+ documented (and with an implementation available to the public in
328
+ source code form), and must require no special password or key for
329
+ unpacking, reading or copying.
330
+
331
+ 7. Additional Terms.
332
+
333
+ "Additional permissions" are terms that supplement the terms of this
334
+ License by making exceptions from one or more of its conditions.
335
+ Additional permissions that are applicable to the entire Program shall
336
+ be treated as though they were included in this License, to the extent
337
+ that they are valid under applicable law. If additional permissions
338
+ apply only to part of the Program, that part may be used separately
339
+ under those permissions, but the entire Program remains governed by
340
+ this License without regard to the additional permissions.
341
+
342
+ When you convey a copy of a covered work, you may at your option
343
+ remove any additional permissions from that copy, or from any part of
344
+ it. (Additional permissions may be written to require their own
345
+ removal in certain cases when you modify the work.) You may place
346
+ additional permissions on material, added by you to a covered work,
347
+ for which you have or can give appropriate copyright permission.
348
+
349
+ Notwithstanding any other provision of this License, for material you
350
+ add to a covered work, you may (if authorized by the copyright holders of
351
+ that material) supplement the terms of this License with terms:
352
+
353
+ a) Disclaiming warranty or limiting liability differently from the
354
+ terms of sections 15 and 16 of this License; or
355
+
356
+ b) Requiring preservation of specified reasonable legal notices or
357
+ author attributions in that material or in the Appropriate Legal
358
+ Notices displayed by works containing it; or
359
+
360
+ c) Prohibiting misrepresentation of the origin of that material, or
361
+ requiring that modified versions of such material be marked in
362
+ reasonable ways as different from the original version; or
363
+
364
+ d) Limiting the use for publicity purposes of names of licensors or
365
+ authors of the material; or
366
+
367
+ e) Declining to grant rights under trademark law for use of some
368
+ trade names, trademarks, or service marks; or
369
+
370
+ f) Requiring indemnification of licensors and authors of that
371
+ material by anyone who conveys the material (or modified versions of
372
+ it) with contractual assumptions of liability to the recipient, for
373
+ any liability that these contractual assumptions directly impose on
374
+ those licensors and authors.
375
+
376
+ All other non-permissive additional terms are considered "further
377
+ restrictions" within the meaning of section 10. If the Program as you
378
+ received it, or any part of it, contains a notice stating that it is
379
+ governed by this License along with a term that is a further
380
+ restriction, you may remove that term. If a license document contains
381
+ a further restriction but permits relicensing or conveying under this
382
+ License, you may add to a covered work material governed by the terms
383
+ of that license document, provided that the further restriction does
384
+ not survive such relicensing or conveying.
385
+
386
+ If you add terms to a covered work in accord with this section, you
387
+ must place, in the relevant source files, a statement of the
388
+ additional terms that apply to those files, or a notice indicating
389
+ where to find the applicable terms.
390
+
391
+ Additional terms, permissive or non-permissive, may be stated in the
392
+ form of a separately written license, or stated as exceptions;
393
+ the above requirements apply either way.
394
+
395
+ 8. Termination.
396
+
397
+ You may not propagate or modify a covered work except as expressly
398
+ provided under this License. Any attempt otherwise to propagate or
399
+ modify it is void, and will automatically terminate your rights under
400
+ this License (including any patent licenses granted under the third
401
+ paragraph of section 11).
402
+
403
+ However, if you cease all violation of this License, then your
404
+ license from a particular copyright holder is reinstated (a)
405
+ provisionally, unless and until the copyright holder explicitly and
406
+ finally terminates your license, and (b) permanently, if the copyright
407
+ holder fails to notify you of the violation by some reasonable means
408
+ prior to 60 days after the cessation.
409
+
410
+ Moreover, your license from a particular copyright holder is
411
+ reinstated permanently if the copyright holder notifies you of the
412
+ violation by some reasonable means, this is the first time you have
413
+ received notice of violation of this License (for any work) from that
414
+ copyright holder, and you cure the violation prior to 30 days after
415
+ your receipt of the notice.
416
+
417
+ Termination of your rights under this section does not terminate the
418
+ licenses of parties who have received copies or rights from you under
419
+ this License. If your rights have been terminated and not permanently
420
+ reinstated, you do not qualify to receive new licenses for the same
421
+ material under section 10.
422
+
423
+ 9. Acceptance Not Required for Having Copies.
424
+
425
+ You are not required to accept this License in order to receive or
426
+ run a copy of the Program. Ancillary propagation of a covered work
427
+ occurring solely as a consequence of using peer-to-peer transmission
428
+ to receive a copy likewise does not require acceptance. However,
429
+ nothing other than this License grants you permission to propagate or
430
+ modify any covered work. These actions infringe copyright if you do
431
+ not accept this License. Therefore, by modifying or propagating a
432
+ covered work, you indicate your acceptance of this License to do so.
433
+
434
+ 10. Automatic Licensing of Downstream Recipients.
435
+
436
+ Each time you convey a covered work, the recipient automatically
437
+ receives a license from the original licensors, to run, modify and
438
+ propagate that work, subject to this License. You are not responsible
439
+ for enforcing compliance by third parties with this License.
440
+
441
+ An "entity transaction" is a transaction transferring control of an
442
+ organization, or substantially all assets of one, or subdividing an
443
+ organization, or merging organizations. If propagation of a covered
444
+ work results from an entity transaction, each party to that
445
+ transaction who receives a copy of the work also receives whatever
446
+ licenses to the work the party's predecessor in interest had or could
447
+ give under the previous paragraph, plus a right to possession of the
448
+ Corresponding Source of the work from the predecessor in interest, if
449
+ the predecessor has it or can get it with reasonable efforts.
450
+
451
+ You may not impose any further restrictions on the exercise of the
452
+ rights granted or affirmed under this License. For example, you may
453
+ not impose a license fee, royalty, or other charge for exercise of
454
+ rights granted under this License, and you may not initiate litigation
455
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
456
+ any patent claim is infringed by making, using, selling, offering for
457
+ sale, or importing the Program or any portion of it.
458
+
459
+ 11. Patents.
460
+
461
+ A "contributor" is a copyright holder who authorizes use under this
462
+ License of the Program or a work on which the Program is based. The
463
+ work thus licensed is called the contributor's "contributor version".
464
+
465
+ A contributor's "essential patent claims" are all patent claims
466
+ owned or controlled by the contributor, whether already acquired or
467
+ hereafter acquired, that would be infringed by some manner, permitted
468
+ by this License, of making, using, or selling its contributor version,
469
+ but do not include claims that would be infringed only as a
470
+ consequence of further modification of the contributor version. For
471
+ purposes of this definition, "control" includes the right to grant
472
+ patent sublicenses in a manner consistent with the requirements of
473
+ this License.
474
+
475
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
476
+ patent license under the contributor's essential patent claims, to
477
+ make, use, sell, offer for sale, import and otherwise run, modify and
478
+ propagate the contents of its contributor version.
479
+
480
+ In the following three paragraphs, a "patent license" is any express
481
+ agreement or commitment, however denominated, not to enforce a patent
482
+ (such as an express permission to practice a patent or covenant not to
483
+ sue for patent infringement). To "grant" such a patent license to a
484
+ party means to make such an agreement or commitment not to enforce a
485
+ patent against the party.
486
+
487
+ If you convey a covered work, knowingly relying on a patent license,
488
+ and the Corresponding Source of the work is not available for anyone
489
+ to copy, free of charge and under the terms of this License, through a
490
+ publicly available network server or other readily accessible means,
491
+ then you must either (1) cause the Corresponding Source to be so
492
+ available, or (2) arrange to deprive yourself of the benefit of the
493
+ patent license for this particular work, or (3) arrange, in a manner
494
+ consistent with the requirements of this License, to extend the patent
495
+ license to downstream recipients. "Knowingly relying" means you have
496
+ actual knowledge that, but for the patent license, your conveying the
497
+ covered work in a country, or your recipient's use of the covered work
498
+ in a country, would infringe one or more identifiable patents in that
499
+ country that you have reason to believe are valid.
500
+
501
+ If, pursuant to or in connection with a single transaction or
502
+ arrangement, you convey, or propagate by procuring conveyance of, a
503
+ covered work, and grant a patent license to some of the parties
504
+ receiving the covered work authorizing them to use, propagate, modify
505
+ or convey a specific copy of the covered work, then the patent license
506
+ you grant is automatically extended to all recipients of the covered
507
+ work and works based on it.
508
+
509
+ A patent license is "discriminatory" if it does not include within
510
+ the scope of its coverage, prohibits the exercise of, or is
511
+ conditioned on the non-exercise of one or more of the rights that are
512
+ specifically granted under this License. You may not convey a covered
513
+ work if you are a party to an arrangement with a third party that is
514
+ in the business of distributing software, under which you make payment
515
+ to the third party based on the extent of your activity of conveying
516
+ the work, and under which the third party grants, to any of the
517
+ parties who would receive the covered work from you, a discriminatory
518
+ patent license (a) in connection with copies of the covered work
519
+ conveyed by you (or copies made from those copies), or (b) primarily
520
+ for and in connection with specific products or compilations that
521
+ contain the covered work, unless you entered into that arrangement,
522
+ or that patent license was granted, prior to 28 March 2007.
523
+
524
+ Nothing in this License shall be construed as excluding or limiting
525
+ any implied license or other defenses to infringement that may
526
+ otherwise be available to you under applicable patent law.
527
+
528
+ 12. No Surrender of Others' Freedom.
529
+
530
+ If conditions are imposed on you (whether by court order, agreement or
531
+ otherwise) that contradict the conditions of this License, they do not
532
+ excuse you from the conditions of this License. If you cannot convey a
533
+ covered work so as to satisfy simultaneously your obligations under this
534
+ License and any other pertinent obligations, then as a consequence you may
535
+ not convey it at all. For example, if you agree to terms that obligate you
536
+ to collect a royalty for further conveying from those to whom you convey
537
+ the Program, the only way you could satisfy both those terms and this
538
+ License would be to refrain entirely from conveying the Program.
539
+
540
+ 13. Remote Network Interaction; Use with the GNU General Public License.
541
+
542
+ Notwithstanding any other provision of this License, if you modify the
543
+ Program, your modified version must prominently offer all users
544
+ interacting with it remotely through a computer network (if your version
545
+ supports such interaction) an opportunity to receive the Corresponding
546
+ Source of your version by providing access to the Corresponding Source
547
+ from a network server at no charge, through some standard or customary
548
+ means of facilitating copying of software. This Corresponding Source
549
+ shall include the Corresponding Source for any work covered by version 3
550
+ of the GNU General Public License that is incorporated pursuant to the
551
+ following paragraph.
552
+
553
+ Notwithstanding any other provision of this License, you have
554
+ permission to link or combine any covered work with a work licensed
555
+ under version 3 of the GNU General Public License into a single
556
+ combined work, and to convey the resulting work. The terms of this
557
+ License will continue to apply to the part which is the covered work,
558
+ but the work with which it is combined will remain governed by version
559
+ 3 of the GNU General Public License.
560
+
561
+ 14. Revised Versions of this License.
562
+
563
+ The Free Software Foundation may publish revised and/or new versions of
564
+ the GNU Affero General Public License from time to time. Such new versions
565
+ will be similar in spirit to the present version, but may differ in detail to
566
+ address new problems or concerns.
567
+
568
+ Each version is given a distinguishing version number. If the
569
+ Program specifies that a certain numbered version of the GNU Affero General
570
+ Public License "or any later version" applies to it, you have the
571
+ option of following the terms and conditions either of that numbered
572
+ version or of any later version published by the Free Software
573
+ Foundation. If the Program does not specify a version number of the
574
+ GNU Affero General Public License, you may choose any version ever published
575
+ by the Free Software Foundation.
576
+
577
+ If the Program specifies that a proxy can decide which future
578
+ versions of the GNU Affero General Public License can be used, that proxy's
579
+ public statement of acceptance of a version permanently authorizes you
580
+ to choose that version for the Program.
581
+
582
+ Later license versions may give you additional or different
583
+ permissions. However, no additional obligations are imposed on any
584
+ author or copyright holder as a result of your choosing to follow a
585
+ later version.
586
+
587
+ 15. Disclaimer of Warranty.
588
+
589
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597
+
598
+ 16. Limitation of Liability.
599
+
600
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608
+ SUCH DAMAGES.
609
+
610
+ 17. Interpretation of Sections 15 and 16.
611
+
612
+ If the disclaimer of warranty and limitation of liability provided
613
+ above cannot be given local legal effect according to their terms,
614
+ reviewing courts shall apply local law that most closely approximates
615
+ an absolute waiver of all civil liability in connection with the
616
+ Program, unless a warranty or assumption of liability accompanies a
617
+ copy of the Program in return for a fee.
618
+
619
+ END OF TERMS AND CONDITIONS
620
+
621
+ How to Apply These Terms to Your New Programs
622
+
623
+ If you develop a new program, and you want it to be of the greatest
624
+ possible use to the public, the best way to achieve this is to make it
625
+ free software which everyone can redistribute and change under these terms.
626
+
627
+ To do so, attach the following notices to the program. It is safest
628
+ to attach them to the start of each source file to most effectively
629
+ state the exclusion of warranty; and each file should have at least
630
+ the "copyright" line and a pointer to where the full notice is found.
631
+
632
+ <one line to give the program's name and a brief idea of what it does.>
633
+ Copyright (C) <year> <name of author>
634
+
635
+ This program is free software: you can redistribute it and/or modify
636
+ it under the terms of the GNU Affero General Public License as published
637
+ by the Free Software Foundation, either version 3 of the License, or
638
+ (at your option) any later version.
639
+
640
+ This program is distributed in the hope that it will be useful,
641
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
642
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643
+ GNU Affero General Public License for more details.
644
+
645
+ You should have received a copy of the GNU Affero General Public License
646
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
647
+
648
+ Also add information on how to contact you by electronic and paper mail.
649
+
650
+ If your software can interact with users remotely through a computer
651
+ network, you should also make sure that it provides a way for users to
652
+ get its source. For example, if your program is a web application, its
653
+ interface could display a "Source" link that leads users to an archive
654
+ of the code. There are many ways you could offer source, and different
655
+ solutions will be better for different programs; see section 13 for the
656
+ specific requirements.
657
+
658
+ You should also get your employer (if you work as a programmer) or school,
659
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
660
+ For more information on this, and how to apply and follow the GNU AGPL, see
661
+ <https://www.gnu.org/licenses/>.
Remote-Link.cmd ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ echo ========================================================================================================================
3
+ echo WARNING: Cloudflare Tunnel!
4
+ echo ========================================================================================================================
5
+ echo This script downloads and runs the latest cloudflared.exe from Cloudflare to set up an HTTPS tunnel to your SillyTavern!
6
+ echo Using the randomly generated temporary tunnel URL, anyone can access your SillyTavern over the Internet while the tunnel
7
+ echo is active. Keep the URL safe and secure your SillyTavern installation by setting a username and password in config.yaml!
8
+ echo.
9
+ echo See https://docs.sillytavern.app/usage/remoteconnections/ for more details about how to secure your SillyTavern install.
10
+ echo.
11
+ echo By continuing you confirm that you're aware of the potential dangers of having a tunnel open and take all responsibility
12
+ echo to properly use and secure it!
13
+ echo.
14
+ echo To abort, press Ctrl+C or close this window now!
15
+ echo.
16
+ pause
17
+ if not exist cloudflared.exe curl -Lo cloudflared.exe https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-windows-amd64.exe
18
+ cloudflared.exe tunnel --url localhost:8000
SECURITY.md ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Security Policy
2
+
3
+ We take the security of this project seriously. If you discover any security vulnerabilities or have concerns regarding the security of this repository, please reach out to us immediately. We appreciate your efforts in responsibly disclosing the issue and will make every effort to address it promptly.
4
+
5
+ ## Reporting a Vulnerability
6
+
7
+ To report a security vulnerability, please follow these steps:
8
+
9
+ 1. Go to the **Security** tab of this repository on GitHub.
10
+ 2. Click on **"Report a vulnerability"**.
11
+ 3. Provide a clear description of the vulnerability and its potential impact. Be as detailed as possible.
12
+ 4. If applicable, include steps or a PoC (Proof of Concept) to reproduce the vulnerability.
13
+ 5. Submit the report.
14
+
15
+ Once we receive the private report notification, we will promptly investigate and assess the reported vulnerability.
16
+
17
+ Please do not disclose any potential vulnerabilities in public repositories, issue trackers, or forums until we have had a chance to review and address the issue.
18
+
19
+ ## Scope
20
+
21
+ This security policy applies to all the code and files within this repository and its dependencies actively maintained by us. If you encounter a security issue in a dependency that is not directly maintained by us, please follow responsible disclosure practices and report it to the respective project.
22
+
23
+ While we strive to ensure the security of this project, please note that there may be limitations on resources, response times, and mitigations.
24
+
25
+ Thank you for your help in making this project more secure.
Start.bat ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ pushd %~dp0
3
+ set NODE_ENV=production
4
+ call npm install --no-audit --no-fund --loglevel=error --no-progress --omit=dev
5
+ node server.js %*
6
+ pause
7
+ popd
Update-Instructions.txt ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ How to Update SillyTavern
2
+
3
+ The most recent version can be found here: https://docs.sillytavern.app/usage/update/
4
+
5
+ This is not an installation guide. If you need installation instructions, look here:
6
+ https://docs.sillytavern.app/installation/windows/
7
+
8
+ This guide assumes you have already installed SillyTavern once, and know how to run it on your OS.
9
+
10
+ Linux/Termux:
11
+
12
+ You definitely installed via git, so just 'git pull' inside the SillyTavern directory.
13
+
14
+ Windows/MacOS:
15
+
16
+ Method 1 - GIT
17
+
18
+ We always recommend users install using 'git'. Here's why:
19
+
20
+ When you have installed via `git clone`, all you have to do to update is type `git pull` in a command line in the ST folder.
21
+ You can also try running the 'UpdateAndStart.bat' file, which will almost do the same thing. (Windows only)
22
+ Alternatively, if the command prompt gives you problems (and you have GitHub Desktop installed), you can use the 'Repository' menu and select 'Pull'.
23
+ The updates are applied automatically and safely.
24
+
25
+ If you are a developer and use a fork of ST or switch branches regularly, you can use the 'UpdateForkAndStart.bat', which works similarly to 'UpdateAndStart.bat',
26
+ but automatically pulls changes into your fork and handles switched branches gracefully by asking if you want to switch back.
27
+
28
+ Method 2 - ZIP
29
+
30
+ If you insist on installing via a zip, here is the tedious process for doing the update:
31
+
32
+ 1. Download the new release zip.
33
+ 2. Unzip it into a folder OUTSIDE of your current ST installation.
34
+ 3. Do the usual setup procedure for your OS to install the NodeJS requirements.
35
+
36
+ 4a. Updating 1.12.0 and above
37
+
38
+ Copy the user data directory from your data root into the data root of the new install.
39
+
40
+ By default: /data/default-user
41
+
42
+ 4a. Migrating from <1.12.0 to >=1.20.0
43
+ Copy the following files/folders as necessary(*) from your old ST installation:
44
+
45
+ - Assets
46
+ - Backgrounds
47
+ - Characters
48
+ - Chats
49
+ - Context
50
+ - Groups
51
+ - Group chats
52
+ - Instruct
53
+ - movingUI
54
+ - KoboldAI Settings
55
+ - NovelAI Settings
56
+ - OpenAI Settings (Chat Completion API)
57
+ - TextGen Settings (Text Completion API)
58
+ - QuickReplies
59
+ - Themes
60
+ - User Avatars
61
+ - Worlds
62
+ - User
63
+ - settings.json
64
+ - secrets.json <---- This one is in the base folder, not /public/
65
+
66
+ (*) 'As necessary' = "If you made any custom content related to those folders".
67
+ None of the folders are mandatory, so only copy what you need.
68
+
69
+ **NB: DO NOT COPY THE ENTIRE /PUBLIC/ FOLDER.**
70
+ Doing so could break the new install and prevent new features from being present.
71
+ Paste those items into the /data/default-user folder of the new install.
72
+
73
+ 5. Start SillyTavern once again with the method appropriate to your OS, and pray you got it right.
74
+
75
+ 6. If everything shows up, you can safely delete the old ST folder.
UpdateAndStart.bat ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ pushd %~dp0
3
+ git --version > nul 2>&1
4
+ if %errorlevel% neq 0 (
5
+ echo Git is not installed on this system.
6
+ echo Install it from https://git-scm.com/downloads
7
+ goto end
8
+ ) else (
9
+ if not exist .git (
10
+ echo Not running from a Git repository. Reinstall using an officially supported method to get updates.
11
+ echo See: https://docs.sillytavern.app/installation/windows/
12
+ goto end
13
+ )
14
+ call git pull --rebase --autostash
15
+ if %errorlevel% neq 0 (
16
+ REM incase there is still something wrong
17
+ echo There were errors while updating.
18
+ echo See the update FAQ at https://docs.sillytavern.app/usage/update/#common-update-problems
19
+ goto end
20
+ )
21
+ )
22
+ set NODE_ENV=production
23
+ call npm install --no-audit --no-fund --loglevel=error --no-progress --omit=dev
24
+ node server.js %*
25
+ :end
26
+ pause
27
+ popd
UpdateForkAndStart.bat ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ @setlocal enabledelayedexpansion
3
+ pushd %~dp0
4
+
5
+ echo Checking Git installation
6
+ git --version > nul 2>&1
7
+ if %errorlevel% neq 0 (
8
+ echo Git is not installed on this system.
9
+ echo Install it from https://git-scm.com/downloads
10
+ goto end
11
+ )
12
+
13
+ if not exist .git (
14
+ echo Not running from a Git repository. Reinstall using an officially supported method to get updates.
15
+ echo See: https://docs.sillytavern.app/installation/windows/
16
+ goto end
17
+ )
18
+
19
+ REM Checking current branch
20
+ FOR /F "tokens=*" %%i IN ('git rev-parse --abbrev-ref HEAD') DO SET CURRENT_BRANCH=%%i
21
+ echo Current branch: %CURRENT_BRANCH%
22
+
23
+ REM Checking for automatic branch switching configuration
24
+ set AUTO_SWITCH=
25
+ FOR /F "tokens=*" %%j IN ('git config --local script.autoSwitch') DO SET AUTO_SWITCH=%%j
26
+
27
+ SET TARGET_BRANCH=%CURRENT_BRANCH%
28
+
29
+ if NOT "!AUTO_SWITCH!"=="" (
30
+ if "!AUTO_SWITCH!"=="s" (
31
+ goto autoswitch-staging
32
+ )
33
+ if "!AUTO_SWITCH!"=="r" (
34
+ goto autoswitch-release
35
+ )
36
+
37
+ if "!AUTO_SWITCH!"=="staging" (
38
+ :autoswitch-staging
39
+ echo Auto-switching to staging branch
40
+ git checkout staging
41
+ SET TARGET_BRANCH=staging
42
+ goto update
43
+ )
44
+ if "!AUTO_SWITCH!"=="release" (
45
+ :autoswitch-release
46
+ echo Auto-switching to release branch
47
+ git checkout release
48
+ SET TARGET_BRANCH=release
49
+ goto update
50
+ )
51
+
52
+ echo Auto-switching defined to stay on current branch
53
+ goto update
54
+ )
55
+
56
+ if "!CURRENT_BRANCH!"=="staging" (
57
+ echo Staying on the current branch
58
+ goto update
59
+ )
60
+ if "!CURRENT_BRANCH!"=="release" (
61
+ echo Staying on the current branch
62
+ goto update
63
+ )
64
+
65
+ echo You are not on 'staging' or 'release'. You are on '!CURRENT_BRANCH!'.
66
+ set /p "CHOICE=Do you want to switch to 'staging' (s), 'release' (r), or stay (any other key)? "
67
+ if /i "!CHOICE!"=="s" (
68
+ echo Switching to staging branch
69
+ git checkout staging
70
+ SET TARGET_BRANCH=staging
71
+ goto update
72
+ )
73
+ if /i "!CHOICE!"=="r" (
74
+ echo Switching to release branch
75
+ git checkout release
76
+ SET TARGET_BRANCH=release
77
+ goto update
78
+ )
79
+
80
+ echo Staying on the current branch
81
+
82
+ :update
83
+ REM Checking for 'upstream' remote
84
+ git remote | findstr "upstream" > nul
85
+ if %errorlevel% equ 0 (
86
+ echo Updating and rebasing against 'upstream'
87
+ git fetch upstream
88
+ git rebase upstream/%TARGET_BRANCH% --autostash
89
+ goto install
90
+ )
91
+
92
+ echo Updating and rebasing against 'origin'
93
+ git pull --rebase --autostash origin %TARGET_BRANCH%
94
+
95
+
96
+ :install
97
+ if %errorlevel% neq 0 (
98
+ echo There were errors while updating.
99
+ echo See the update FAQ at https://docs.sillytavern.app/usage/update/#common-update-problems
100
+ goto end
101
+ )
102
+
103
+ echo Installing npm packages and starting server
104
+ set NODE_ENV=production
105
+ call npm install --no-audit --no-fund --loglevel=error --no-progress --omit=dev
106
+ node server.js %*
107
+
108
+ :end
109
+ pause
110
+ popd
config.yaml ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -- DATA CONFIGURATION --
2
+ # Root directory for user data storage
3
+ dataRoot: ./data
4
+ # -- SERVER CONFIGURATION --
5
+ # Listen for incoming connections
6
+ listen: false
7
+ # Listen on a specific address, supports IPv4 and IPv6
8
+ listenAddress:
9
+ ipv4: 0.0.0.0
10
+ ipv6: '[::]'
11
+ # Enables IPv6 and/or IPv4 protocols. Need to have at least one enabled!
12
+ # - Use option "auto" to automatically detect support
13
+ # - Use true or false (no qoutes) to enable or disable each protocol
14
+ protocol:
15
+ ipv4: true
16
+ ipv6: false
17
+ # Prefers IPv6 for DNS. Enable this on ISPs that don't have issues with IPv6
18
+ dnsPreferIPv6: false
19
+ # The hostname that autorun opens.
20
+ # - Use "auto" to let the server decide
21
+ # - Use options like 'localhost', 'st.example.com'
22
+ autorunHostname: "auto"
23
+ # Server port
24
+ port: 8000
25
+ # Overrides the port for autorun in browser.
26
+ # - Use -1 to use the server port.
27
+ # - Specify a port to override the default.
28
+ autorunPortOverride: -1
29
+ # -- SSL options --
30
+ ssl:
31
+ enabled: false
32
+ certPath: "./certs/cert.pem"
33
+ keyPath: "./certs/privkey.pem"
34
+ # -- SECURITY CONFIGURATION --
35
+ # Toggle whitelist mode
36
+ whitelistMode: true
37
+ # Whitelist will also verify IP in X-Forwarded-For / X-Real-IP headers
38
+ enableForwardedWhitelist: true
39
+ # Whitelist of allowed IP addresses
40
+ whitelist:
41
+ - ::1
42
+ - 127.0.0.1
43
+ # Automatically whitelist Docker host and gateway IPs
44
+ whitelistDockerHosts: true
45
+ # Toggle basic authentication for endpoints
46
+ basicAuthMode: false
47
+ # Basic authentication credentials
48
+ basicAuthUser:
49
+ username: "user"
50
+ password: "password"
51
+ # Enables CORS proxy middleware
52
+ enableCorsProxy: false
53
+ # -- REQUEST PROXY CONFIGURATION --
54
+ requestProxy:
55
+ # If a proxy is enabled, all outgoing HTTP/HTTPS requests will be routed through it.
56
+ enabled: false
57
+ # Proxy URL. Possible protocols: http, https, socks, socks5, socks4, pac
58
+ url: "socks5://username:[email protected]:1080"
59
+ # Proxy bypass list. Requests to these hosts won't be routed through the proxy.
60
+ bypass:
61
+ - localhost
62
+ - 127.0.0.1
63
+ # Enable multi-user mode
64
+ enableUserAccounts: false
65
+ # Enable discreet login mode: hides user list on the login screen
66
+ enableDiscreetLogin: false
67
+ # Enable's authlia based auto login. Only enable this if you
68
+ # have setup and installed Authelia as a middle-ware on your
69
+ # reverse proxy
70
+ # https://www.authelia.com/
71
+ # This will use auto login to an account with the same username
72
+ # as that used for authlia. (Ensure the username in authlia
73
+ # is an exact match with that in sillytavern)
74
+ autheliaAuth: false
75
+ # If `basicAuthMode` and this are enabled then
76
+ # the username and passwords for basic auth are the same as those
77
+ # for the individual accounts
78
+ perUserBasicAuth: false
79
+
80
+ # User session timeout *in seconds* (defaults to 24 hours).
81
+ ## Set to a positive number to expire session after a certain time of inactivity
82
+ ## Set to 0 to expire session when the browser is closed
83
+ ## Set to a negative number to disable session expiration
84
+ sessionTimeout: -1
85
+ # Disable CSRF protection - NOT RECOMMENDED
86
+ disableCsrfProtection: false
87
+ # Disable startup security checks - NOT RECOMMENDED
88
+ securityOverride: false
89
+ # -- LOGGING CONFIGURATION --
90
+ logging:
91
+ # Enable access logging to access.log file
92
+ # Records new connections with timestamp, IP address and user agent
93
+ enableAccessLog: true
94
+ # Minimum log level to display in the terminal (DEBUG = 0, INFO = 1, WARN = 2, ERROR = 3)
95
+ minLogLevel: 0
96
+ # -- RATE LIMITING CONFIGURATION --
97
+ rateLimiting:
98
+ # Use X-Real-IP header instead of socket IP for rate limiting
99
+ # Only enable this if you are using a properly configured reverse proxy (like Nginx/traefik/Caddy)
100
+ preferRealIpHeader: false
101
+ # -- ADVANCED CONFIGURATION --
102
+ # Open the browser automatically
103
+ autorun: true
104
+ # Avoids using 'localhost' for autorun in auto mode.
105
+ # use if you don't have 'localhost' in your hosts file
106
+ avoidLocalhost: false
107
+
108
+ ## BACKUP CONFIGURATION
109
+ backups:
110
+ # Common settings for all backup types
111
+ common:
112
+ # Number of backups to keep for each chat and settings file
113
+ numberOfBackups: 50
114
+ chat:
115
+ # Enable automatic chat backups
116
+ enabled: true
117
+ # Maximum number of chat backups to keep per user (starting from the most recent). Set to -1 to keep all backups.
118
+ maxTotalBackups: -1
119
+ # Interval in milliseconds to throttle chat backups per user
120
+ throttleInterval: 10000
121
+
122
+ # THUMBNAILING CONFIGURATION
123
+ thumbnails:
124
+ # Enable thumbnail generation
125
+ enabled: true
126
+ # Image format of avatar thumbnails:
127
+ # * "jpg": best compression with adjustable quality, no transparency
128
+ # * "png": preserves transparency but increases filesize by about 100%
129
+ # Changing this only affects new thumbnails. To recreate the old ones, clear out /thumbnails folder in your user data.
130
+ format: "jpg"
131
+ # JPG thumbnail quality (0-100)
132
+ quality: 95
133
+ # Maximum thumbnail dimensions per type [width, height]
134
+ dimensions: { 'bg': [160, 90], 'avatar': [96, 144] }
135
+
136
+ # PERFORMANCE-RELATED CONFIGURATION
137
+ performance:
138
+ # Enables lazy loading of character cards. Improves performances with large card libraries.
139
+ # May have compatibility issues with some extensions.
140
+ lazyLoadCharacters: false
141
+ # The maximum amount of memory that parsed character cards can use. Set to 0 to disable memory caching.
142
+ memoryCacheCapacity: '100mb'
143
+
144
+ # Allow secret keys exposure via API
145
+ allowKeysExposure: false
146
+ # Skip new default content checks
147
+ skipContentCheck: false
148
+ # Allowed hosts for card downloads
149
+ whitelistImportDomains:
150
+ - localhost
151
+ - cdn.discordapp.com
152
+ - files.catbox.moe
153
+ - raw.githubusercontent.com
154
+ # API request overrides (for KoboldAI and Text Completion APIs)
155
+ ## Note: host includes the port number if it's not the default (80 or 443)
156
+ ## Format is an array of objects:
157
+ ## - hosts:
158
+ ## - example.com
159
+ ## headers:
160
+ ## Content-Type: application/json
161
+ ## - 127.0.0.1:5001
162
+ ## headers:
163
+ ## User-Agent: "Googlebot/2.1 (+http://www.google.com/bot.html)"
164
+ requestOverrides: []
165
+
166
+ # EXTENSIONS CONFIGURATION
167
+ extensions:
168
+ # Enable UI extensions
169
+ enabled: true
170
+ # Automatically update extensions when a release version changes
171
+ autoUpdate: true
172
+ models:
173
+ # Enables automatic model download from HuggingFace
174
+ autoDownload: true
175
+ # Additional models for extensions. Expects model IDs from HuggingFace model hub in ONNX format
176
+ classification: Cohee/distilbert-base-uncased-go-emotions-onnx
177
+ captioning: Xenova/vit-gpt2-image-captioning
178
+ embedding: Cohee/jina-embeddings-v2-base-en
179
+ speechToText: Xenova/whisper-small
180
+ textToSpeech: Xenova/speecht5_tts
181
+
182
+ # Additional model tokenizers can be downloaded on demand.
183
+ # Disabling will fallback to another locally available tokenizer.
184
+ enableDownloadableTokenizers: true
185
+ # -- OPENAI CONFIGURATION --
186
+ # A placeholder message to use in strict prompt post-processing mode when the prompt doesn't start with a user message
187
+ promptPlaceholder: "[Start a new chat]"
188
+ openai:
189
+ # Will send a random user ID to OpenAI completion API
190
+ randomizeUserId: false
191
+ # If not empty, will add this as a system message to the start of every caption completion prompt
192
+ # Example: "Perform the instructions to the best of your ability.\n" (for LLaVA)
193
+ # Not used in image inlining mode
194
+ captionSystemPrompt: ""
195
+ # -- DEEPL TRANSLATION CONFIGURATION --
196
+ deepl:
197
+ # Available options: default, more, less, prefer_more, prefer_less
198
+ formality: default
199
+ # -- MISTRAL API CONFIGURATION --
200
+ mistral:
201
+ # Enables prefilling of the reply with the last assistant message in the prompt
202
+ # CAUTION: The prefix is echoed into the completion. You may want to use regex to trim it out.
203
+ enablePrefix: false
204
+ # -- OLLAMA API CONFIGURATION --
205
+ ollama:
206
+ # Controls how long the model will stay loaded into memory following the request
207
+ # * -1: Keep the model loaded indefinitely
208
+ # * 0: Unload the model immediately after the request
209
+ # * N (any positive number): Keep the model loaded for N seconds after the request.
210
+ keepAlive: -1
211
+ # Controls the "num_batch" (batch size) parameter of the generation request
212
+ # * -1: Use the default value of the model
213
+ # * N (positive number): Use the specified value. Must be a power of 2, e.g. 128, 256, 512, etc.
214
+ batchSize: -1
215
+ # -- ANTHROPIC CLAUDE API CONFIGURATION --
216
+ claude:
217
+ # Enables caching of the system prompt (if supported).
218
+ # https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
219
+ # -- IMPORTANT! --
220
+ # Use only when the prompt before the chat history is static and doesn't change between requests
221
+ # (e.g {{random}} macro or lorebooks not as in-chat injections).
222
+ # Otherwise, you'll just waste money on cache misses.
223
+ enableSystemPromptCache: false
224
+ # Enables caching of the message history at depth (if supported).
225
+ # https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
226
+ # -- IMPORTANT! --
227
+ # Use with caution. Behavior may be unpredictable and no guarantees can or will be made.
228
+ # Set to an integer to specify the desired depth. 0 (which does NOT include the prefill)
229
+ # should be ideal for most use cases.
230
+ # Any value other than a non-negative integer will be ignored and caching at depth will not be enabled.
231
+ cachingAtDepth: -1
232
+ # -- SERVER PLUGIN CONFIGURATION --
233
+ enableServerPlugins: false
234
+ # Attempt to automatically update server plugins on startup
235
+ enableServerPluginsAutoUpdate: true
index.d.ts ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { EventEmitter } from 'node:events';
2
+ import { CsrfSyncedToken } from 'csrf-sync';
3
+ import { UserDirectoryList, User } from './src/users.js';
4
+ import { CommandLineArguments } from './src/command-line.js';
5
+ import { EVENT_NAMES } from './src/server-events.js';
6
+
7
+ /**
8
+ * Event payload for SERVER_STARTED event.
9
+ */
10
+ export interface ServerStartedEvent {
11
+ /**
12
+ * The URL the server is listening on.
13
+ */
14
+ url: URL;
15
+ }
16
+
17
+ /**
18
+ * Map of all server events to their payload types.
19
+ */
20
+ export interface ServerEventMap {
21
+ [EVENT_NAMES.SERVER_STARTED]: [ServerStartedEvent];
22
+ }
23
+
24
+ declare global {
25
+ declare namespace NodeJS {
26
+ export interface Process {
27
+ /**
28
+ * A global instance of the server events emitter.
29
+ */
30
+ serverEvents: EventEmitter<ServerEventMap>;
31
+ }
32
+ }
33
+
34
+ declare namespace CookieSessionInterfaces {
35
+ export interface CookieSessionObject {
36
+ /**
37
+ * The CSRF token for the session.
38
+ */
39
+ csrfToken: CsrfSyncedToken;
40
+ /**
41
+ * Authenticated user handle.
42
+ */
43
+ handle: string;
44
+ /**
45
+ * Last time the session was extended.
46
+ */
47
+ touch: number;
48
+ }
49
+ }
50
+
51
+ namespace Express {
52
+ export interface Request {
53
+ user: {
54
+ profile: User;
55
+ directories: UserDirectoryList;
56
+ };
57
+ }
58
+ }
59
+
60
+ /**
61
+ * The root directory for user data.
62
+ */
63
+ var DATA_ROOT: string;
64
+
65
+ /**
66
+ * Parsed command line arguments.
67
+ */
68
+ var COMMAND_LINE_ARGS: CommandLineArguments;
69
+ }
jsconfig.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "compilerOptions": {
3
+ "module": "ESNext",
4
+ "target": "ES2023",
5
+ "moduleResolution": "Node",
6
+ "strictNullChecks": true,
7
+ "strictFunctionTypes": true,
8
+ "checkJs": true,
9
+ "allowUmdGlobalAccess": true,
10
+ "allowSyntheticDefaultImports": true,
11
+ "resolveJsonModule": true,
12
+ "strictBindCallApply": true
13
+ },
14
+ "exclude": [
15
+ "**/node_modules/**",
16
+ "**/dist/**",
17
+ "**/.git/**",
18
+ "public/**",
19
+ "backups/**",
20
+ "data/**",
21
+ "cache/**",
22
+ "src/tokenizers/**",
23
+ "docker/**"
24
+ ]
25
+ }
package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
package.json ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dependencies": {
3
+ "@adobe/css-tools": "^4.4.2",
4
+ "@agnai/sentencepiece-js": "^1.1.1",
5
+ "@agnai/web-tokenizers": "^0.1.3",
6
+ "@iconfu/svg-inject": "^1.2.3",
7
+ "@mozilla/readability": "^0.6.0",
8
+ "@popperjs/core": "^2.11.8",
9
+ "@zeldafan0225/ai_horde": "^5.2.0",
10
+ "archiver": "^7.0.1",
11
+ "bing-translate-api": "^4.0.2",
12
+ "body-parser": "^1.20.2",
13
+ "bowser": "^2.11.0",
14
+ "bytes": "^3.1.2",
15
+ "chalk": "^5.4.1",
16
+ "command-exists": "^1.2.9",
17
+ "compression": "^1.8.0",
18
+ "cookie-parser": "^1.4.6",
19
+ "cookie-session": "^2.1.0",
20
+ "cors": "^2.8.5",
21
+ "csrf-sync": "^4.0.3",
22
+ "diff-match-patch": "^1.0.5",
23
+ "dompurify": "^3.2.4",
24
+ "droll": "^0.2.1",
25
+ "express": "^4.21.0",
26
+ "form-data": "^4.0.2",
27
+ "fuse.js": "^7.1.0",
28
+ "google-translate-api-browser": "^3.0.1",
29
+ "google-translate-api-x": "^10.7.2",
30
+ "handlebars": "^4.7.8",
31
+ "helmet": "^7.2.0",
32
+ "highlight.js": "^11.11.1",
33
+ "html-entities": "^2.5.2",
34
+ "iconv-lite": "^0.6.3",
35
+ "ip-matching": "^2.1.2",
36
+ "ip-regex": "^5.0.0",
37
+ "ipaddr.js": "^2.2.0",
38
+ "is-docker": "^3.0.0",
39
+ "jimp": "^0.22.10",
40
+ "localforage": "^1.10.0",
41
+ "lodash": "^4.17.21",
42
+ "mime-types": "^2.1.35",
43
+ "moment": "^2.30.1",
44
+ "morphdom": "^2.7.4",
45
+ "multer": "^1.4.5-lts.1",
46
+ "node-fetch": "^3.3.2",
47
+ "node-persist": "^4.0.4",
48
+ "open": "^8.4.2",
49
+ "png-chunk-text": "^1.0.0",
50
+ "png-chunks-encode": "^1.0.0",
51
+ "png-chunks-extract": "^1.0.0",
52
+ "proxy-agent": "^6.5.0",
53
+ "rate-limiter-flexible": "^5.0.5",
54
+ "response-time": "^2.3.3",
55
+ "sanitize-filename": "^1.6.3",
56
+ "seedrandom": "^3.0.5",
57
+ "showdown": "^2.1.0",
58
+ "sillytavern-transformers": "2.14.6",
59
+ "simple-git": "^3.27.0",
60
+ "slidetoggle": "^4.0.0",
61
+ "tiktoken": "^1.0.20",
62
+ "url-join": "^5.0.0",
63
+ "vectra": "^0.2.2",
64
+ "wavefile": "^11.0.0",
65
+ "webpack": "^5.98.0",
66
+ "write-file-atomic": "^5.0.1",
67
+ "ws": "^8.18.1",
68
+ "yaml": "^2.7.0",
69
+ "yargs": "^17.7.1",
70
+ "yauzl": "^2.10.0"
71
+ },
72
+ "engines": {
73
+ "node": ">= 18"
74
+ },
75
+ "overrides": {
76
+ "vectra": {
77
+ "openai": "^4.17.0"
78
+ },
79
+ "axios": {
80
+ "follow-redirects": "^1.15.4"
81
+ },
82
+ "node-fetch": {
83
+ "whatwg-url": "^14.0.0"
84
+ }
85
+ },
86
+ "name": "sillytavern",
87
+ "type": "module",
88
+ "license": "AGPL-3.0",
89
+ "repository": {
90
+ "type": "git",
91
+ "url": "https://github.com/SillyTavern/SillyTavern.git"
92
+ },
93
+ "version": "1.12.13",
94
+ "scripts": {
95
+ "start": "node server.js",
96
+ "debug": "node --inspect server.js",
97
+ "start:electron": "cd ./src/electron && npm run start",
98
+ "start:deno": "deno run --allow-run --allow-net --allow-read --allow-write --allow-sys --allow-env server.js",
99
+ "start:bun": "bun server.js",
100
+ "start:no-csrf": "node server.js --disableCsrf",
101
+ "postinstall": "node post-install.js",
102
+ "lint": "eslint \"src/**/*.js\" \"public/**/*.js\" ./*.js",
103
+ "lint:fix": "eslint \"src/**/*.js\" \"public/**/*.js\" ./*.js --fix",
104
+ "plugins:update": "node plugins update",
105
+ "plugins:install": "node plugins install"
106
+ },
107
+ "bin": {
108
+ "sillytavern": "./server.js"
109
+ },
110
+ "rules": {
111
+ "no-path-concat": "off",
112
+ "no-var": "off"
113
+ },
114
+ "main": "server.js",
115
+ "devDependencies": {
116
+ "@types/archiver": "^6.0.3",
117
+ "@types/bytes": "^3.1.5",
118
+ "@types/command-exists": "^1.2.3",
119
+ "@types/compression": "^1.7.5",
120
+ "@types/cookie-parser": "^1.4.8",
121
+ "@types/cookie-session": "^2.0.49",
122
+ "@types/cors": "^2.8.17",
123
+ "@types/deno": "^2.2.0",
124
+ "@types/express": "^4.17.21",
125
+ "@types/jquery": "^3.5.32",
126
+ "@types/jquery-cropper": "^1.0.4",
127
+ "@types/jquery.transit": "^0.9.33",
128
+ "@types/jqueryui": "^1.12.24",
129
+ "@types/lodash": "^4.17.16",
130
+ "@types/mime-types": "^2.1.4",
131
+ "@types/multer": "^1.4.12",
132
+ "@types/node": "^18.19.80",
133
+ "@types/node-persist": "^3.1.8",
134
+ "@types/png-chunk-text": "^1.0.3",
135
+ "@types/png-chunks-encode": "^1.0.2",
136
+ "@types/png-chunks-extract": "^1.0.2",
137
+ "@types/response-time": "^2.3.8",
138
+ "@types/select2": "^4.0.63",
139
+ "@types/toastr": "^2.1.43",
140
+ "@types/write-file-atomic": "^4.0.3",
141
+ "@types/yargs": "^17.0.33",
142
+ "@types/yauzl": "^2.10.3",
143
+ "eslint": "^8.57.1"
144
+ }
145
+ }
plugins.js ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Plugin manager script.
2
+ // Usage:
3
+ // 1. node plugins.js update
4
+ // 2. node plugins.js install <plugin-git-url>
5
+ // More operations coming soon.
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import process from 'node:process';
9
+ import { fileURLToPath } from 'node:url';
10
+
11
+ import { default as git, CheckRepoActions } from 'simple-git';
12
+ import { color } from './src/util.js';
13
+
14
+ const __dirname = import.meta.dirname ?? path.dirname(fileURLToPath(import.meta.url));
15
+ process.chdir(__dirname);
16
+ const pluginsPath = './plugins';
17
+
18
+ const command = process.argv[2];
19
+
20
+ if (!command) {
21
+ console.log('Usage: node plugins.js <command>');
22
+ console.log('Commands:');
23
+ console.log(' update - Update all installed plugins');
24
+ console.log(' install <plugin-git-url> - Install plugin from a Git URL');
25
+ process.exit(1);
26
+ }
27
+
28
+ if (command === 'update') {
29
+ console.log(color.magenta('Updating all plugins'));
30
+ updatePlugins();
31
+ }
32
+
33
+ if (command === 'install') {
34
+ const pluginName = process.argv[3];
35
+ console.log('Installing a new plugin', color.green(pluginName));
36
+ installPlugin(pluginName);
37
+ }
38
+
39
+ async function updatePlugins() {
40
+ const directories = fs.readdirSync(pluginsPath)
41
+ .filter(file => !file.startsWith('.'))
42
+ .filter(file => fs.statSync(path.join(pluginsPath, file)).isDirectory());
43
+
44
+ console.log(`Found ${color.cyan(directories.length)} directories in ./plugins`);
45
+
46
+ for (const directory of directories) {
47
+ try {
48
+ console.log(`Updating plugin ${color.green(directory)}...`);
49
+ const pluginPath = path.join(pluginsPath, directory);
50
+ const pluginRepo = git(pluginPath);
51
+
52
+ const isRepo = await pluginRepo.checkIsRepo(CheckRepoActions.IS_REPO_ROOT);
53
+ if (!isRepo) {
54
+ console.log(`Directory ${color.yellow(directory)} is not a Git repository`);
55
+ continue;
56
+ }
57
+
58
+ await pluginRepo.fetch();
59
+ const commitHash = await pluginRepo.revparse(['HEAD']);
60
+ const trackingBranch = await pluginRepo.revparse(['--abbrev-ref', '@{u}']);
61
+ const log = await pluginRepo.log({
62
+ from: commitHash,
63
+ to: trackingBranch,
64
+ });
65
+
66
+ if (log.total === 0) {
67
+ console.log(`Plugin ${color.blue(directory)} is already up to date`);
68
+ continue;
69
+ }
70
+
71
+ await pluginRepo.pull();
72
+ const latestCommit = await pluginRepo.revparse(['HEAD']);
73
+ console.log(`Plugin ${color.green(directory)} updated to commit ${color.cyan(latestCommit)}`);
74
+ } catch (error) {
75
+ console.error(color.red(`Failed to update plugin ${directory}: ${error.message}`));
76
+ }
77
+ }
78
+
79
+ console.log(color.magenta('All plugins updated!'));
80
+ }
81
+
82
+ async function installPlugin(pluginName) {
83
+ try {
84
+ const pluginPath = path.join(pluginsPath, path.basename(pluginName, '.git'));
85
+
86
+ if (fs.existsSync(pluginPath)) {
87
+ return console.log(color.yellow(`Directory already exists at ${pluginPath}`));
88
+ }
89
+
90
+ await git().clone(pluginName, pluginPath, { '--depth': 1 });
91
+ console.log(`Plugin ${color.green(pluginName)} installed to ${color.cyan(pluginPath)}`);
92
+ }
93
+ catch (error) {
94
+ console.error(color.red(`Failed to install plugin ${pluginName}`), error);
95
+ }
96
+ }
post-install.js ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Scripts to be done before starting the server for the first time.
3
+ */
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import crypto from 'node:crypto';
7
+ import process from 'node:process';
8
+ import yaml from 'yaml';
9
+ import _ from 'lodash';
10
+ import chalk from 'chalk';
11
+ import { createRequire } from 'node:module';
12
+
13
+ /**
14
+ * Colorizes console output.
15
+ */
16
+ const color = chalk;
17
+
18
+ const keyMigrationMap = [
19
+ {
20
+ oldKey: 'disableThumbnails',
21
+ newKey: 'thumbnails.enabled',
22
+ migrate: (value) => !value,
23
+ },
24
+ {
25
+ oldKey: 'thumbnailsQuality',
26
+ newKey: 'thumbnails.quality',
27
+ migrate: (value) => value,
28
+ },
29
+ {
30
+ oldKey: 'avatarThumbnailsPng',
31
+ newKey: 'thumbnails.format',
32
+ migrate: (value) => (value ? 'png' : 'jpg'),
33
+ },
34
+ {
35
+ oldKey: 'disableChatBackup',
36
+ newKey: 'backups.chat.enabled',
37
+ migrate: (value) => !value,
38
+ },
39
+ {
40
+ oldKey: 'numberOfBackups',
41
+ newKey: 'backups.common.numberOfBackups',
42
+ migrate: (value) => value,
43
+ },
44
+ {
45
+ oldKey: 'maxTotalChatBackups',
46
+ newKey: 'backups.chat.maxTotalBackups',
47
+ migrate: (value) => value,
48
+ },
49
+ {
50
+ oldKey: 'chatBackupThrottleInterval',
51
+ newKey: 'backups.chat.throttleInterval',
52
+ migrate: (value) => value,
53
+ },
54
+ {
55
+ oldKey: 'enableExtensions',
56
+ newKey: 'extensions.enabled',
57
+ migrate: (value) => value,
58
+ },
59
+ {
60
+ oldKey: 'enableExtensionsAutoUpdate',
61
+ newKey: 'extensions.autoUpdate',
62
+ migrate: (value) => value,
63
+ },
64
+ {
65
+ oldKey: 'extras.disableAutoDownload',
66
+ newKey: 'extensions.models.autoDownload',
67
+ migrate: (value) => !value,
68
+ },
69
+ {
70
+ oldKey: 'extras.classificationModel',
71
+ newKey: 'extensions.models.classification',
72
+ migrate: (value) => value,
73
+ },
74
+ {
75
+ oldKey: 'extras.captioningModel',
76
+ newKey: 'extensions.models.captioning',
77
+ migrate: (value) => value,
78
+ },
79
+ {
80
+ oldKey: 'extras.embeddingModel',
81
+ newKey: 'extensions.models.embedding',
82
+ migrate: (value) => value,
83
+ },
84
+ {
85
+ oldKey: 'extras.speechToTextModel',
86
+ newKey: 'extensions.models.speechToText',
87
+ migrate: (value) => value,
88
+ },
89
+ {
90
+ oldKey: 'extras.textToSpeechModel',
91
+ newKey: 'extensions.models.textToSpeech',
92
+ migrate: (value) => value,
93
+ },
94
+ {
95
+ oldKey: 'minLogLevel',
96
+ newKey: 'logging.minLogLevel',
97
+ migrate: (value) => value,
98
+ },
99
+ {
100
+ oldKey: 'cardsCacheCapacity',
101
+ newKey: 'performance.memoryCacheCapacity',
102
+ migrate: (value) => `${value}mb`,
103
+ },
104
+ // uncomment one release after 1.12.13
105
+ /*
106
+ {
107
+ oldKey: 'cookieSecret',
108
+ newKey: 'cookieSecret',
109
+ migrate: () => void 0,
110
+ remove: true,
111
+ },
112
+ */
113
+ ];
114
+
115
+ /**
116
+ * Gets all keys from an object recursively.
117
+ * @param {object} obj Object to get all keys from
118
+ * @param {string} prefix Prefix to prepend to all keys
119
+ * @returns {string[]} Array of all keys in the object
120
+ */
121
+ function getAllKeys(obj, prefix = '') {
122
+ if (typeof obj !== 'object' || Array.isArray(obj) || obj === null) {
123
+ return [];
124
+ }
125
+
126
+ return _.flatMap(Object.keys(obj), key => {
127
+ const newPrefix = prefix ? `${prefix}.${key}` : key;
128
+ if (typeof obj[key] === 'object' && !Array.isArray(obj[key])) {
129
+ return getAllKeys(obj[key], newPrefix);
130
+ } else {
131
+ return [newPrefix];
132
+ }
133
+ });
134
+ }
135
+
136
+ /**
137
+ * Converts the old config.conf file to the new config.yaml format.
138
+ */
139
+ function convertConfig() {
140
+ if (fs.existsSync('./config.conf')) {
141
+ if (fs.existsSync('./config.yaml')) {
142
+ console.log(color.yellow('Both config.conf and config.yaml exist. Please delete config.conf manually.'));
143
+ return;
144
+ }
145
+
146
+ try {
147
+ console.log(color.blue('Converting config.conf to config.yaml. Your old config.conf will be renamed to config.conf.bak'));
148
+ fs.renameSync('./config.conf', './config.conf.cjs'); // Force loading as CommonJS
149
+ const require = createRequire(import.meta.url);
150
+ const config = require(path.join(process.cwd(), './config.conf.cjs'));
151
+ fs.copyFileSync('./config.conf.cjs', './config.conf.bak');
152
+ fs.rmSync('./config.conf.cjs');
153
+ fs.writeFileSync('./config.yaml', yaml.stringify(config));
154
+ console.log(color.green('Conversion successful. Please check your config.yaml and fix it if necessary.'));
155
+ } catch (error) {
156
+ console.error(color.red('FATAL: Config conversion failed. Please check your config.conf file and try again.'), error);
157
+ return;
158
+ }
159
+ }
160
+ }
161
+
162
+ /**
163
+ * Compares the current config.yaml with the default config.yaml and adds any missing values.
164
+ */
165
+ function addMissingConfigValues() {
166
+ try {
167
+ const defaultConfig = yaml.parse(fs.readFileSync(path.join(process.cwd(), './default/config.yaml'), 'utf8'));
168
+ let config = yaml.parse(fs.readFileSync(path.join(process.cwd(), './config.yaml'), 'utf8'));
169
+
170
+ // Migrate old keys to new keys
171
+ const migratedKeys = [];
172
+ for (const { oldKey, newKey, migrate, remove } of keyMigrationMap) {
173
+ if (_.has(config, oldKey)) {
174
+ if (remove) {
175
+ _.unset(config, oldKey);
176
+ migratedKeys.push({
177
+ oldKey,
178
+ newValue: void 0,
179
+ });
180
+ continue;
181
+ }
182
+
183
+ const oldValue = _.get(config, oldKey);
184
+ const newValue = migrate(oldValue);
185
+ _.set(config, newKey, newValue);
186
+ _.unset(config, oldKey);
187
+
188
+ migratedKeys.push({
189
+ oldKey,
190
+ newKey,
191
+ oldValue,
192
+ newValue,
193
+ });
194
+ }
195
+ }
196
+
197
+ // Get all keys from the original config
198
+ const originalKeys = getAllKeys(config);
199
+
200
+ // Use lodash's defaultsDeep function to recursively apply default properties
201
+ config = _.defaultsDeep(config, defaultConfig);
202
+
203
+ // Get all keys from the updated config
204
+ const updatedKeys = getAllKeys(config);
205
+
206
+ // Find the keys that were added
207
+ const addedKeys = _.difference(updatedKeys, originalKeys);
208
+
209
+ if (addedKeys.length === 0 && migratedKeys.length === 0) {
210
+ return;
211
+ }
212
+
213
+ if (addedKeys.length > 0) {
214
+ console.log('Adding missing config values to config.yaml:', addedKeys);
215
+ }
216
+
217
+ if (migratedKeys.length > 0) {
218
+ console.log('Migrating config values in config.yaml:', migratedKeys);
219
+ }
220
+
221
+ fs.writeFileSync('./config.yaml', yaml.stringify(config));
222
+ } catch (error) {
223
+ console.error(color.red('FATAL: Could not add missing config values to config.yaml'), error);
224
+ }
225
+ }
226
+
227
+ /**
228
+ * Creates the default config files if they don't exist yet.
229
+ */
230
+ function createDefaultFiles() {
231
+ /**
232
+ * @typedef DefaultItem
233
+ * @type {object}
234
+ * @property {'file' | 'directory'} type - Whether the item should be copied as a single file or merged into a directory structure.
235
+ * @property {string} defaultPath - The path to the default item (typically in `default/`).
236
+ * @property {string} productionPath - The path to the copied item for production use.
237
+ */
238
+
239
+ /** @type {DefaultItem[]} */
240
+ const defaultItems = [
241
+ {
242
+ type: 'file',
243
+ defaultPath: './default/config.yaml',
244
+ productionPath: './config.yaml',
245
+ },
246
+ {
247
+ type: 'directory',
248
+ defaultPath: './default/public/',
249
+ productionPath: './public/',
250
+ },
251
+ ];
252
+
253
+ for (const defaultItem of defaultItems) {
254
+ try {
255
+ if (defaultItem.type === 'file') {
256
+ if (!fs.existsSync(defaultItem.productionPath)) {
257
+ fs.copyFileSync(
258
+ defaultItem.defaultPath,
259
+ defaultItem.productionPath,
260
+ );
261
+ console.log(
262
+ color.green(`Created default file: ${defaultItem.productionPath}`),
263
+ );
264
+ }
265
+ } else if (defaultItem.type === 'directory') {
266
+ fs.cpSync(defaultItem.defaultPath, defaultItem.productionPath, {
267
+ force: false, // Don't overwrite existing files!
268
+ recursive: true,
269
+ });
270
+ console.log(
271
+ color.green(`Synchronized missing files: ${defaultItem.productionPath}`),
272
+ );
273
+ } else {
274
+ throw new Error(
275
+ 'FATAL: Unexpected default file format in `post-install.js#createDefaultFiles()`.',
276
+ );
277
+ }
278
+ } catch (error) {
279
+ console.error(
280
+ color.red(
281
+ `FATAL: Could not write default ${defaultItem.type}: ${defaultItem.productionPath}`,
282
+ ),
283
+ error,
284
+ );
285
+ }
286
+ }
287
+ }
288
+
289
+ /**
290
+ * Returns the MD5 hash of the given data.
291
+ * @param {Buffer} data Input data
292
+ * @returns {string} MD5 hash of the input data
293
+ */
294
+ function getMd5Hash(data) {
295
+ return crypto
296
+ .createHash('md5')
297
+ .update(new Uint8Array(data))
298
+ .digest('hex');
299
+ }
300
+
301
+ /**
302
+ * Copies the WASM binaries from the sillytavern-transformers package to the dist folder.
303
+ */
304
+ function copyWasmFiles() {
305
+ if (!fs.existsSync('./dist')) {
306
+ fs.mkdirSync('./dist');
307
+ }
308
+
309
+ const listDir = fs.readdirSync('./node_modules/sillytavern-transformers/dist');
310
+
311
+ for (const file of listDir) {
312
+ if (file.endsWith('.wasm')) {
313
+ const sourcePath = `./node_modules/sillytavern-transformers/dist/${file}`;
314
+ const targetPath = `./dist/${file}`;
315
+
316
+ // Don't copy if the file already exists and is the same checksum
317
+ if (fs.existsSync(targetPath)) {
318
+ const sourceChecksum = getMd5Hash(fs.readFileSync(sourcePath));
319
+ const targetChecksum = getMd5Hash(fs.readFileSync(targetPath));
320
+
321
+ if (sourceChecksum === targetChecksum) {
322
+ continue;
323
+ }
324
+ }
325
+
326
+ fs.copyFileSync(sourcePath, targetPath);
327
+ console.log(`${file} successfully copied to ./dist/${file}`);
328
+ }
329
+ }
330
+ }
331
+
332
+ try {
333
+ // 0. Convert config.conf to config.yaml
334
+ convertConfig();
335
+ // 1. Create default config files
336
+ createDefaultFiles();
337
+ // 2. Copy transformers WASM binaries from node_modules
338
+ copyWasmFiles();
339
+ // 3. Add missing config values
340
+ addMissingConfigValues();
341
+ } catch (error) {
342
+ console.error(error);
343
+ }
recover.js ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import fs from 'node:fs';
2
+ import process from 'node:process';
3
+ import yaml from 'yaml';
4
+ import storage from 'node-persist';
5
+ import {
6
+ initUserStorage,
7
+ getPasswordSalt,
8
+ getPasswordHash,
9
+ toKey,
10
+ } from './src/users.js';
11
+
12
+ const userAccount = process.argv[2];
13
+ const userPassword = process.argv[3];
14
+
15
+ if (!userAccount) {
16
+ console.error('A tool for recovering lost SillyTavern accounts. Uses a "dataRoot" setting from config.yaml file.');
17
+ console.error('Usage: node recover.js [account] (password)');
18
+ console.error('Example: node recover.js admin password');
19
+ process.exit(1);
20
+ }
21
+
22
+ async function initStorage() {
23
+ const config = yaml.parse(fs.readFileSync('config.yaml', 'utf8'));
24
+ const dataRoot = config.dataRoot;
25
+
26
+ if (!dataRoot) {
27
+ console.error('No "dataRoot" setting found in config.yaml file.');
28
+ process.exit(1);
29
+ }
30
+
31
+ await initUserStorage(dataRoot);
32
+ }
33
+
34
+ async function main() {
35
+ await initStorage();
36
+
37
+ /**
38
+ * @type {import('./src/users').User}
39
+ */
40
+ const user = await storage.get(toKey(userAccount));
41
+
42
+ if (!user) {
43
+ console.error(`User "${userAccount}" not found.`);
44
+ process.exit(1);
45
+ }
46
+
47
+ if (!user.enabled) {
48
+ console.log('User is disabled. Enabling...');
49
+ user.enabled = true;
50
+ }
51
+
52
+ if (userPassword) {
53
+ console.log('Setting new password...');
54
+ const salt = getPasswordSalt();
55
+ const passwordHash = getPasswordHash(userPassword, salt);
56
+ user.password = passwordHash;
57
+ user.salt = salt;
58
+ } else {
59
+ console.log('Setting an empty password...');
60
+ user.password = '';
61
+ user.salt = '';
62
+ }
63
+
64
+ await storage.setItem(toKey(userAccount), user);
65
+ console.log('User recovered. A program will exit now.');
66
+ }
67
+
68
+ main();
replit.nix ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ { pkgs }: {
2
+ deps = [
3
+ pkgs.nodejs-18_x
4
+ pkgs.nodePackages.typescript-language-server
5
+ pkgs.yarn
6
+ pkgs.replitPackages.jest
7
+ ];
8
+ }
server.js ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env node
2
+
3
+ // native node modules
4
+ import path from 'node:path';
5
+ import util from 'node:util';
6
+ import net from 'node:net';
7
+ import dns from 'node:dns';
8
+ import process from 'node:process';
9
+ import { fileURLToPath } from 'node:url';
10
+
11
+ import cors from 'cors';
12
+ import { csrfSync } from 'csrf-sync';
13
+ import express from 'express';
14
+ import compression from 'compression';
15
+ import cookieSession from 'cookie-session';
16
+ import multer from 'multer';
17
+ import responseTime from 'response-time';
18
+ import helmet from 'helmet';
19
+ import bodyParser from 'body-parser';
20
+ import open from 'open';
21
+
22
+ // local library imports
23
+ import { serverEvents, EVENT_NAMES } from './src/server-events.js';
24
+ import { CommandLineParser } from './src/command-line.js';
25
+ import { loadPlugins } from './src/plugin-loader.js';
26
+ import {
27
+ initUserStorage,
28
+ getCookieSecret,
29
+ getCookieSessionName,
30
+ ensurePublicDirectoriesExist,
31
+ getUserDirectoriesList,
32
+ migrateSystemPrompts,
33
+ migrateUserData,
34
+ requireLoginMiddleware,
35
+ setUserDataMiddleware,
36
+ shouldRedirectToLogin,
37
+ cleanUploads,
38
+ getSessionCookieAge,
39
+ verifySecuritySettings,
40
+ loginPageMiddleware,
41
+ } from './src/users.js';
42
+
43
+ import getWebpackServeMiddleware from './src/middleware/webpack-serve.js';
44
+ import basicAuthMiddleware from './src/middleware/basicAuth.js';
45
+ import getWhitelistMiddleware from './src/middleware/whitelist.js';
46
+ import accessLoggerMiddleware, { getAccessLogPath, migrateAccessLog } from './src/middleware/accessLogWriter.js';
47
+ import multerMonkeyPatch from './src/middleware/multerMonkeyPatch.js';
48
+ import initRequestProxy from './src/request-proxy.js';
49
+ import getCacheBusterMiddleware from './src/middleware/cacheBuster.js';
50
+ import corsProxyMiddleware from './src/middleware/corsProxy.js';
51
+ import {
52
+ getVersion,
53
+ color,
54
+ removeColorFormatting,
55
+ getSeparator,
56
+ safeReadFileSync,
57
+ setupLogLevel,
58
+ setWindowTitle,
59
+ } from './src/util.js';
60
+ import { UPLOADS_DIRECTORY } from './src/constants.js';
61
+ import { ensureThumbnailCache } from './src/endpoints/thumbnails.js';
62
+
63
+ // Routers
64
+ import { router as usersPublicRouter } from './src/endpoints/users-public.js';
65
+ import { init as statsInit, onExit as statsOnExit } from './src/endpoints/stats.js';
66
+ import { checkForNewContent } from './src/endpoints/content-manager.js';
67
+ import { init as settingsInit } from './src/endpoints/settings.js';
68
+ import { redirectDeprecatedEndpoints, ServerStartup, setupPrivateEndpoints } from './src/server-startup.js';
69
+
70
+ // Unrestrict console logs display limit
71
+ util.inspect.defaultOptions.maxArrayLength = null;
72
+ util.inspect.defaultOptions.maxStringLength = null;
73
+ util.inspect.defaultOptions.depth = 4;
74
+
75
+ // Set a working directory for the server
76
+ const serverDirectory = import.meta.dirname ?? path.dirname(fileURLToPath(import.meta.url));
77
+ console.log(`Node version: ${process.version}. Running in ${process.env.NODE_ENV} environment. Server directory: ${serverDirectory}`);
78
+ process.chdir(serverDirectory);
79
+
80
+ // Work around a node v20.0.0, v20.1.0, and v20.2.0 bug. The issue was fixed in v20.3.0.
81
+ // https://github.com/nodejs/node/issues/47822#issuecomment-1564708870
82
+ // Safe to remove once support for Node v20 is dropped.
83
+ if (process.versions && process.versions.node && process.versions.node.match(/20\.[0-2]\.0/)) {
84
+ // @ts-ignore
85
+ if (net.setDefaultAutoSelectFamily) net.setDefaultAutoSelectFamily(false);
86
+ }
87
+
88
+ const cliArgs = new CommandLineParser().parse(process.argv);
89
+ globalThis.DATA_ROOT = cliArgs.dataRoot;
90
+ globalThis.COMMAND_LINE_ARGS = cliArgs;
91
+
92
+ if (!cliArgs.enableIPv6 && !cliArgs.enableIPv4) {
93
+ console.error('error: You can\'t disable all internet protocols: at least IPv6 or IPv4 must be enabled.');
94
+ process.exit(1);
95
+ }
96
+
97
+ try {
98
+ if (cliArgs.dnsPreferIPv6) {
99
+ dns.setDefaultResultOrder('ipv6first');
100
+ console.log('Preferring IPv6 for DNS resolution');
101
+ } else {
102
+ dns.setDefaultResultOrder('ipv4first');
103
+ console.log('Preferring IPv4 for DNS resolution');
104
+ }
105
+ } catch (error) {
106
+ console.warn('Failed to set DNS resolution order. Possibly unsupported in this Node version.');
107
+ }
108
+
109
+ const app = express();
110
+ app.use(helmet({
111
+ contentSecurityPolicy: false,
112
+ }));
113
+ app.use(compression());
114
+ app.use(responseTime());
115
+
116
+ app.use(bodyParser.json({ limit: '200mb' }));
117
+ app.use(bodyParser.urlencoded({ extended: true, limit: '200mb' }));
118
+
119
+ // CORS Settings //
120
+ const CORS = cors({
121
+ origin: 'null',
122
+ methods: ['OPTIONS'],
123
+ });
124
+
125
+ app.use(CORS);
126
+
127
+ if (cliArgs.listen && cliArgs.basicAuthMode) {
128
+ app.use(basicAuthMiddleware);
129
+ }
130
+
131
+ if (cliArgs.whitelistMode) {
132
+ const whitelistMiddleware = await getWhitelistMiddleware();
133
+ app.use(whitelistMiddleware);
134
+ }
135
+
136
+ if (cliArgs.listen) {
137
+ app.use(accessLoggerMiddleware());
138
+ }
139
+
140
+ if (cliArgs.enableCorsProxy) {
141
+ app.use('/proxy/:url(*)', corsProxyMiddleware);
142
+ } else {
143
+ app.use('/proxy/:url(*)', async (_, res) => {
144
+ const message = 'CORS proxy is disabled. Enable it in config.yaml or use the --corsProxy flag.';
145
+ console.log(message);
146
+ res.status(404).send(message);
147
+ });
148
+ }
149
+
150
+ app.use(cookieSession({
151
+ name: getCookieSessionName(),
152
+ sameSite: 'strict',
153
+ httpOnly: true,
154
+ maxAge: getSessionCookieAge(),
155
+ secret: getCookieSecret(globalThis.DATA_ROOT),
156
+ }));
157
+
158
+ app.use(setUserDataMiddleware);
159
+
160
+ // CSRF Protection //
161
+ if (!cliArgs.disableCsrf) {
162
+ const csrfSyncProtection = csrfSync({
163
+ getTokenFromState: (req) => {
164
+ if (!req.session) {
165
+ console.error('(CSRF error) getTokenFromState: Session object not initialized');
166
+ return;
167
+ }
168
+ return req.session.csrfToken;
169
+ },
170
+ getTokenFromRequest: (req) => {
171
+ return req.headers['x-csrf-token']?.toString();
172
+ },
173
+ storeTokenInState: (req, token) => {
174
+ if (!req.session) {
175
+ console.error('(CSRF error) storeTokenInState: Session object not initialized');
176
+ return;
177
+ }
178
+ req.session.csrfToken = token;
179
+ },
180
+ size: 32,
181
+ });
182
+
183
+ app.get('/csrf-token', (req, res) => {
184
+ res.json({
185
+ 'token': csrfSyncProtection.generateToken(req),
186
+ });
187
+ });
188
+
189
+ // Customize the error message
190
+ csrfSyncProtection.invalidCsrfTokenError.message = color.red('Invalid CSRF token. Please refresh the page and try again.');
191
+ csrfSyncProtection.invalidCsrfTokenError.stack = undefined;
192
+
193
+ app.use(csrfSyncProtection.csrfSynchronisedProtection);
194
+ } else {
195
+ console.warn('\nCSRF protection is disabled. This will make your server vulnerable to CSRF attacks.\n');
196
+ app.get('/csrf-token', (req, res) => {
197
+ res.json({
198
+ 'token': 'disabled',
199
+ });
200
+ });
201
+ }
202
+
203
+ // Static files
204
+ // Host index page
205
+ app.get('/', getCacheBusterMiddleware(), (request, response) => {
206
+ if (shouldRedirectToLogin(request)) {
207
+ const query = request.url.split('?')[1];
208
+ const redirectUrl = query ? `/login?${query}` : '/login';
209
+ return response.redirect(redirectUrl);
210
+ }
211
+
212
+ return response.sendFile('index.html', { root: path.join(process.cwd(), 'public') });
213
+ });
214
+
215
+ // Host login page
216
+ app.get('/login', loginPageMiddleware);
217
+
218
+ // Host frontend assets
219
+ const webpackMiddleware = getWebpackServeMiddleware();
220
+ app.use(webpackMiddleware);
221
+ app.use(express.static(process.cwd() + '/public', {}));
222
+
223
+ // Public API
224
+ app.use('/api/users', usersPublicRouter);
225
+
226
+ // Everything below this line requires authentication
227
+ app.use(requireLoginMiddleware);
228
+ app.get('/api/ping', (request, response) => {
229
+ if (request.query.extend && request.session) {
230
+ request.session.touch = Date.now();
231
+ }
232
+
233
+ response.sendStatus(204);
234
+ });
235
+
236
+ // File uploads
237
+ const uploadsPath = path.join(cliArgs.dataRoot, UPLOADS_DIRECTORY);
238
+ app.use(multer({ dest: uploadsPath, limits: { fieldSize: 10 * 1024 * 1024 } }).single('avatar'));
239
+ app.use(multerMonkeyPatch);
240
+
241
+ app.get('/version', async function (_, response) {
242
+ const data = await getVersion();
243
+ response.send(data);
244
+ });
245
+
246
+ redirectDeprecatedEndpoints(app);
247
+ setupPrivateEndpoints(app);
248
+
249
+ /**
250
+ * Tasks that need to be run before the server starts listening.
251
+ * @returns {Promise<void>}
252
+ */
253
+ async function preSetupTasks() {
254
+ const version = await getVersion();
255
+
256
+ // Print formatted header
257
+ console.log();
258
+ console.log(`SillyTavern ${version.pkgVersion}`);
259
+ if (version.gitBranch) {
260
+ console.log(`Running '${version.gitBranch}' (${version.gitRevision}) - ${version.commitDate}`);
261
+ if (!version.isLatest && ['staging', 'release'].includes(version.gitBranch)) {
262
+ console.log('INFO: Currently not on the latest commit.');
263
+ console.log(' Run \'git pull\' to update. If you have any merge conflicts, run \'git reset --hard\' and \'git pull\' to reset your branch.');
264
+ }
265
+ }
266
+ console.log();
267
+
268
+ const directories = await getUserDirectoriesList();
269
+ await checkForNewContent(directories);
270
+ await ensureThumbnailCache();
271
+ cleanUploads();
272
+ migrateAccessLog();
273
+
274
+ await settingsInit();
275
+ await statsInit();
276
+
277
+ const pluginsDirectory = path.join(serverDirectory, 'plugins');
278
+ const cleanupPlugins = await loadPlugins(app, pluginsDirectory);
279
+ const consoleTitle = process.title;
280
+
281
+ let isExiting = false;
282
+ const exitProcess = async () => {
283
+ if (isExiting) return;
284
+ isExiting = true;
285
+ await statsOnExit();
286
+ if (typeof cleanupPlugins === 'function') {
287
+ await cleanupPlugins();
288
+ }
289
+ setWindowTitle(consoleTitle);
290
+ process.exit();
291
+ };
292
+
293
+ // Set up event listeners for a graceful shutdown
294
+ process.on('SIGINT', exitProcess);
295
+ process.on('SIGTERM', exitProcess);
296
+ process.on('uncaughtException', (err) => {
297
+ console.error('Uncaught exception:', err);
298
+ exitProcess();
299
+ });
300
+
301
+ // Add request proxy.
302
+ initRequestProxy({ enabled: cliArgs.requestProxyEnabled, url: cliArgs.requestProxyUrl, bypass: cliArgs.requestProxyBypass });
303
+
304
+ // Wait for frontend libs to compile
305
+ await webpackMiddleware.runWebpackCompiler();
306
+ }
307
+
308
+ /**
309
+ * Tasks that need to be run after the server starts listening.
310
+ * @param {import('./src/server-startup.js').ServerStartupResult} result The result of the server startup
311
+ * @returns {Promise<void>}
312
+ */
313
+ async function postSetupTasks(result) {
314
+ const autorunHostname = await cliArgs.getAutorunHostname(result);
315
+ const autorunUrl = cliArgs.getAutorunUrl(autorunHostname);
316
+
317
+ if (cliArgs.autorun) {
318
+ console.log('Launching in a browser...');
319
+ await open(autorunUrl.toString());
320
+ }
321
+
322
+ setWindowTitle('SillyTavern WebServer');
323
+
324
+ let logListen = 'SillyTavern is listening on';
325
+
326
+ if (result.useIPv6 && !result.v6Failed) {
327
+ logListen += color.green(
328
+ ' IPv6: ' + cliArgs.getIPv6ListenUrl().host,
329
+ );
330
+ }
331
+
332
+ if (result.useIPv4 && !result.v4Failed) {
333
+ logListen += color.green(
334
+ ' IPv4: ' + cliArgs.getIPv4ListenUrl().host,
335
+ );
336
+ }
337
+
338
+ const goToLog = 'Go to: ' + color.blue(autorunUrl) + ' to open SillyTavern';
339
+ const plainGoToLog = removeColorFormatting(goToLog);
340
+
341
+ console.log(logListen);
342
+ if (cliArgs.listen) {
343
+ console.log();
344
+ console.log('To limit connections to internal localhost only ([::1] or 127.0.0.1), change the setting in config.yaml to "listen: false".');
345
+ console.log('Check the "access.log" file in the data directory to inspect incoming connections:', color.green(getAccessLogPath()));
346
+ }
347
+ console.log('\n' + getSeparator(plainGoToLog.length) + '\n');
348
+ console.log(goToLog);
349
+ console.log('\n' + getSeparator(plainGoToLog.length) + '\n');
350
+
351
+ setupLogLevel();
352
+ serverEvents.emit(EVENT_NAMES.SERVER_STARTED, { url: autorunUrl });
353
+ }
354
+
355
+ /**
356
+ * Registers a not-found error response if a not-found error page exists. Should only be called after all other middlewares have been registered.
357
+ */
358
+ function apply404Middleware() {
359
+ const notFoundWebpage = safeReadFileSync('./public/error/url-not-found.html') ?? '';
360
+ app.use((req, res) => {
361
+ res.status(404).send(notFoundWebpage);
362
+ });
363
+ }
364
+
365
+ // User storage module needs to be initialized before starting the server
366
+ initUserStorage(globalThis.DATA_ROOT)
367
+ .then(ensurePublicDirectoriesExist)
368
+ .then(migrateUserData)
369
+ .then(migrateSystemPrompts)
370
+ .then(verifySecuritySettings)
371
+ .then(preSetupTasks)
372
+ .then(apply404Middleware)
373
+ .then(() => new ServerStartup(app, cliArgs).start())
374
+ .then(postSetupTasks);
start.sh ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+
3
+ # Make sure pwd is the directory of the script
4
+ cd "$(dirname "$0")"
5
+
6
+ if ! command -v npm &> /dev/null
7
+ then
8
+ read -p "npm is not installed. Do you want to install nodejs and npm? (y/n)" choice
9
+ case "$choice" in
10
+ y|Y )
11
+ echo "Installing nvm..."
12
+ export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
13
+ [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
14
+ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash
15
+ source ~/.bashrc
16
+ nvm install --lts
17
+ nvm use --lts;;
18
+ n|N )
19
+ echo "Nodejs and npm will not be installed."
20
+ exit;;
21
+ * )
22
+ echo "Invalid option. Nodejs and npm will not be installed."
23
+ exit;;
24
+ esac
25
+ fi
26
+
27
+ echo "Installing Node Modules..."
28
+ export NODE_ENV=production
29
+ npm i --no-audit --no-fund --loglevel=error --no-progress --omit=dev
30
+
31
+ echo "Entering SillyTavern..."
32
+ node "server.js" "$@"
webpack.config.js ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import process from 'node:process';
2
+ import path from 'node:path';
3
+ import isDocker from 'is-docker';
4
+
5
+ /**
6
+ * Get the Webpack configuration for the public/lib.js file.
7
+ * 1. Docker has got cache and the output file pre-baked.
8
+ * 2. Non-Docker environments use the global DATA_ROOT variable to determine the cache and output directories.
9
+ * @param {boolean} forceDist Whether to force the use the /dist folder.
10
+ * @returns {import('webpack').Configuration}
11
+ * @throws {Error} If the DATA_ROOT variable is not set.
12
+ * */
13
+ export default function getPublicLibConfig(forceDist = false) {
14
+ function getCacheDirectory() {
15
+ if (forceDist || isDocker()) {
16
+ return path.resolve(process.cwd(), 'dist/webpack');
17
+ }
18
+
19
+ if (typeof globalThis.DATA_ROOT === 'string') {
20
+ return path.resolve(globalThis.DATA_ROOT, '_webpack', 'cache');
21
+ }
22
+
23
+ throw new Error('DATA_ROOT variable is not set.');
24
+ }
25
+
26
+ function getOutputDirectory() {
27
+ if (forceDist || isDocker()) {
28
+ return path.resolve(process.cwd(), 'dist');
29
+ }
30
+
31
+ if (typeof globalThis.DATA_ROOT === 'string') {
32
+ return path.resolve(globalThis.DATA_ROOT, '_webpack', 'output');
33
+ }
34
+
35
+ throw new Error('DATA_ROOT variable is not set.');
36
+ }
37
+
38
+ const cacheDirectory = getCacheDirectory();
39
+ const outputDirectory = getOutputDirectory();
40
+
41
+ return {
42
+ mode: 'production',
43
+ entry: './public/lib.js',
44
+ cache: {
45
+ type: 'filesystem',
46
+ cacheDirectory: cacheDirectory,
47
+ store: 'pack',
48
+ compression: 'gzip',
49
+ },
50
+ devtool: false,
51
+ watch: false,
52
+ module: {},
53
+ stats: {
54
+ preset: 'minimal',
55
+ assets: false,
56
+ modules: false,
57
+ colors: true,
58
+ timings: true,
59
+ },
60
+ experiments: {
61
+ outputModule: true,
62
+ },
63
+ performance: {
64
+ hints: false,
65
+ },
66
+ output: {
67
+ path: outputDirectory,
68
+ filename: 'lib.js',
69
+ libraryTarget: 'module',
70
+ },
71
+ };
72
+ }