@dsh-agentic-roleplay/core 0.3.5 → 0.3.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/authoring.js +5 -5
- package/lib/client.js +1735 -459
- package/lib/client.js.map +1 -1
- package/lib/{deliver-Cl6bjp7g.js → deliver-BBgciEEK.js} +2 -2
- package/lib/doctor.js +3 -3
- package/lib/{hooks-DdO_tNhu.js → hooks-DkwFGtNH.js} +3 -3
- package/lib/index.js +394 -28
- package/lib/{load-Clkl0T7C.js → load-CVwJjIJ5.js} +7 -7
- package/lib/lorebook-author-tools-Bj31z1cu.js +619 -0
- package/lib/lorebook-authoring.js +67 -0
- package/lib/orchestration.js +6 -6
- package/lib/{pack-jail-ClMpVc__.js → pack-jail-2XztyYAX.js} +6 -5
- package/lib/{packs-BC2A3geF.js → packs-xHRCcGdb.js} +2 -2
- package/lib/preset-D0FMSeZ9.js +59 -0
- package/lib/{preset-author-tools-Dibp-LY9.js → preset-author-tools-BxycmoAr.js} +22 -16
- package/lib/preset-authoring.js +3 -3
- package/lib/{presets-DNjNxQL5.js → presets-gkBWAiVb.js} +44 -5
- package/lib/{reflection-Bju_LPFn.js → reflection-q0UpwXlx.js} +5 -5
- package/lib/{preset-ClQm7KPQ.js → tools-Dy1fgP6B.js} +424 -247
- package/package.json +3 -2
- package/prompts/en/import/lorebook.md +7 -0
- package/prompts/en/lorebook/persona.md +1 -0
- package/prompts/en/lorebook/procedure.md +1 -0
- package/prompts/en/lorebook/welcome.md +1 -0
- package/prompts/en/preset/persona.md +1 -1
- package/prompts/en/preset/procedure.md +1 -1
- package/prompts/zh/import/lorebook.md +7 -0
- package/prompts/zh/lorebook/persona.md +1 -0
- package/prompts/zh/lorebook/procedure.md +1 -0
- package/prompts/zh/lorebook/welcome.md +1 -0
- package/prompts/zh/preset/persona.md +1 -1
- package/prompts/zh/preset/procedure.md +1 -1
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as isPresetName, b as INTENT_STATUSES, m as PROSE_PROMPTS, x as INTENT_TYPES, y as INTENT_HORIZONS } from "./presets-gkBWAiVb.js";
|
|
2
2
|
import { c as VARIABLE_SUBJECTS, i as parseSwitchboard, l as VARIABLE_VISIBILITIES, s as VARIABLE_KINDS } from "./settings-CA6icLL_.js";
|
|
3
|
-
import { S as InvalidWorldError, _ as shippedLanguages, a as readDocument, c as
|
|
3
|
+
import { S as InvalidWorldError, _ as shippedLanguages, a as readDocument, c as errorMessage, g as promptProblem, i as plotReferenceProblems, n as loadPlots, o as Reader, s as formatIssue, u as PROMPTS_FOLDER } from "./load-CVwJjIJ5.js";
|
|
4
4
|
import { a as runChild } from "./child-CFjnaTZt.js";
|
|
5
5
|
import { b as slug, c as referenceImagePath, d as MEDIA_TYPES, h as writeImageFileMetadata, n as imageExtensionOf, t as addToLibrary, v as mapLimit, x as uniqueKey, y as norm } from "./library-9JB9zw5a.js";
|
|
6
6
|
import { dirname, join } from "node:path";
|
|
7
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
7
8
|
import { createHash, randomUUID } from "node:crypto";
|
|
8
9
|
import { createUserMessage } from "@deepseek-ai/dsh-llm";
|
|
9
10
|
import { inflateSync } from "node:zlib";
|
|
@@ -146,6 +147,8 @@ const LORE_KINDS = [
|
|
|
146
147
|
"legend",
|
|
147
148
|
"other"
|
|
148
149
|
];
|
|
150
|
+
/** Who knows an entry: `everyone` is common knowledge of the story's world, `listed` only the characters that have a knowledge edge to it (the game master always reads all of it). */
|
|
151
|
+
const LORE_SCOPES = ["everyone", "listed"];
|
|
149
152
|
const LORE_SUBJECT_KINDS = [
|
|
150
153
|
"character",
|
|
151
154
|
"faction",
|
|
@@ -257,7 +260,7 @@ function urlsOf(value) {
|
|
|
257
260
|
return [...found];
|
|
258
261
|
}
|
|
259
262
|
const object = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
260
|
-
const text$
|
|
263
|
+
const text$1 = (value) => typeof value === "string" ? value : typeof value === "number" ? String(value) : "";
|
|
261
264
|
const texts = (value) => Array.isArray(value) ? value.flatMap((entry) => typeof entry === "string" ? [entry] : typeof entry === "number" ? [String(entry)] : []) : [];
|
|
262
265
|
function entryOf(value, index) {
|
|
263
266
|
const entry = object(value);
|
|
@@ -265,10 +268,10 @@ function entryOf(value, index) {
|
|
|
265
268
|
const position = entry["position"];
|
|
266
269
|
return {
|
|
267
270
|
id: `entry:${index}`,
|
|
268
|
-
title: text$
|
|
271
|
+
title: text$1(entry["comment"]).trim() || text$1(entry["name"]).trim(),
|
|
269
272
|
keys: texts(entry["keys"]),
|
|
270
273
|
secondaryKeys: texts(entry["secondary_keys"]),
|
|
271
|
-
content: text$
|
|
274
|
+
content: text$1(entry["content"]),
|
|
272
275
|
enabled: entry["enabled"] !== false,
|
|
273
276
|
constant: entry["constant"] === true,
|
|
274
277
|
selective: entry["selective"] === true,
|
|
@@ -283,10 +286,10 @@ function entryOf(value, index) {
|
|
|
283
286
|
function readCard(file, name) {
|
|
284
287
|
const root = object(jsonOf(file, name));
|
|
285
288
|
const spec = root === void 0 ? void 0 : root["spec"];
|
|
286
|
-
if (spec !== "chara_card_v2" && spec !== "chara_card_v3") throw new ImportCardError(spec === void 0 ? `${name} is not a V2 or V3 character card (it has no "spec")` : `${name} is a "${text$
|
|
289
|
+
if (spec !== "chara_card_v2" && spec !== "chara_card_v3") throw new ImportCardError(spec === void 0 ? `${name} is not a V2 or V3 character card (it has no "spec")` : `${name} is a "${text$1(spec)}" card: only V2 and V3 cards are read`);
|
|
287
290
|
const data = object(root?.["data"]);
|
|
288
291
|
if (data === void 0) throw new ImportCardError(`${name} has no card data`);
|
|
289
|
-
const cardName = text$
|
|
292
|
+
const cardName = text$1(data["name"]).trim();
|
|
290
293
|
if (cardName === "") throw new ImportCardError(`${name} has a card with no name`);
|
|
291
294
|
const book = object(data["character_book"]);
|
|
292
295
|
const entries = Array.isArray(book?.["entries"]) ? book["entries"].flatMap((entry, index) => entryOf(entry, index) ?? []) : [];
|
|
@@ -295,21 +298,21 @@ function readCard(file, name) {
|
|
|
295
298
|
return {
|
|
296
299
|
sourceSpec: spec,
|
|
297
300
|
name: cardName,
|
|
298
|
-
description: text$
|
|
299
|
-
personality: text$
|
|
300
|
-
scenario: text$
|
|
301
|
-
firstMessage: text$
|
|
301
|
+
description: text$1(data["description"]),
|
|
302
|
+
personality: text$1(data["personality"]),
|
|
303
|
+
scenario: text$1(data["scenario"]),
|
|
304
|
+
firstMessage: text$1(data["first_mes"]),
|
|
302
305
|
alternateGreetings: texts(data["alternate_greetings"]),
|
|
303
|
-
messageExample: text$
|
|
304
|
-
creatorNotes: text$
|
|
305
|
-
systemPrompt: text$
|
|
306
|
-
postHistoryInstructions: text$
|
|
306
|
+
messageExample: text$1(data["mes_example"]),
|
|
307
|
+
creatorNotes: text$1(data["creator_notes"]),
|
|
308
|
+
systemPrompt: text$1(data["system_prompt"]),
|
|
309
|
+
postHistoryInstructions: text$1(data["post_history_instructions"]),
|
|
307
310
|
tags: texts(data["tags"]),
|
|
308
|
-
creator: text$
|
|
309
|
-
characterVersion: text$
|
|
311
|
+
creator: text$1(data["creator"]),
|
|
312
|
+
characterVersion: text$1(data["character_version"]),
|
|
310
313
|
...book === void 0 ? {} : { book: {
|
|
311
|
-
name: text$
|
|
312
|
-
description: text$
|
|
314
|
+
name: text$1(book["name"]),
|
|
315
|
+
description: text$1(book["description"]),
|
|
313
316
|
entries
|
|
314
317
|
} },
|
|
315
318
|
ignored: {
|
|
@@ -895,6 +898,326 @@ function readIdentifier(reader, fallback) {
|
|
|
895
898
|
if (id !== void 0 && id.length > 100) reader.fail("id", `must be at most 100 characters`);
|
|
896
899
|
return id;
|
|
897
900
|
}
|
|
901
|
+
//#endregion
|
|
902
|
+
//#region src/host/folders.ts
|
|
903
|
+
/**
|
|
904
|
+
* Names of the subfolders of `dir`, sorted. Symbolic links are not followed
|
|
905
|
+
* and a missing directory has none; any other failure is thrown.
|
|
906
|
+
*/
|
|
907
|
+
async function subfolders(dir) {
|
|
908
|
+
try {
|
|
909
|
+
return (await readdir(dir, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort((a, b) => a.localeCompare(b));
|
|
910
|
+
} catch (error) {
|
|
911
|
+
if (error.code === "ENOENT") return [];
|
|
912
|
+
throw error;
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
//#endregion
|
|
916
|
+
//#region src/host/lore/lore-file.ts
|
|
917
|
+
const LORE_FILE_NAME = "lore.json";
|
|
918
|
+
function instant(reader, key) {
|
|
919
|
+
const value = reader.string(key);
|
|
920
|
+
if (value === void 0) return void 0;
|
|
921
|
+
const parsed = Date.parse(value);
|
|
922
|
+
if (!Number.isFinite(parsed)) {
|
|
923
|
+
reader.fail(key, "must be an ISO date or date-time");
|
|
924
|
+
return;
|
|
925
|
+
}
|
|
926
|
+
return parsed;
|
|
927
|
+
}
|
|
928
|
+
function parseLoreFile(text, fallbackId) {
|
|
929
|
+
const issues = [];
|
|
930
|
+
const reader = Reader.fromJson(text, issues);
|
|
931
|
+
if (reader === void 0) return {
|
|
932
|
+
ok: false,
|
|
933
|
+
issues
|
|
934
|
+
};
|
|
935
|
+
const id = readIdentifier(reader, fallbackId) ?? fallbackId;
|
|
936
|
+
const title = reader.string("title", { required: true }) ?? "";
|
|
937
|
+
const subjects = reader.objects("subjects").flatMap((entry) => {
|
|
938
|
+
const kind = entry.oneOf("kind", LORE_SUBJECT_KINDS, "lore");
|
|
939
|
+
const subjectId = entry.string("id", { required: true });
|
|
940
|
+
return subjectId === void 0 ? [] : [{
|
|
941
|
+
kind,
|
|
942
|
+
id: subjectId
|
|
943
|
+
}];
|
|
944
|
+
});
|
|
945
|
+
const startsAt = instant(reader, "starts_at");
|
|
946
|
+
const endsAt = instant(reader, "ends_at");
|
|
947
|
+
if (startsAt !== void 0 && endsAt !== void 0 && endsAt < startsAt) reader.fail("ends_at", "must not be before starts_at");
|
|
948
|
+
const scope = reader.oneOf("scope", LORE_SCOPES, "listed");
|
|
949
|
+
const knownBy = reader.strings("known_by");
|
|
950
|
+
if (scope === "everyone" && knownBy.length > 0) reader.fail("known_by", "applies only to lore whose scope is \"listed\"");
|
|
951
|
+
const value = {
|
|
952
|
+
id,
|
|
953
|
+
title,
|
|
954
|
+
kind: reader.oneOf("kind", LORE_KINDS, "other"),
|
|
955
|
+
scope,
|
|
956
|
+
knownBy,
|
|
957
|
+
summary: reader.text("summary"),
|
|
958
|
+
body: reader.text("body"),
|
|
959
|
+
subjects,
|
|
960
|
+
related: reader.strings("related"),
|
|
961
|
+
sources: reader.strings("sources"),
|
|
962
|
+
...startsAt === void 0 ? {} : { startsAt },
|
|
963
|
+
...endsAt === void 0 ? {} : { endsAt }
|
|
964
|
+
};
|
|
965
|
+
return issues.length === 0 ? {
|
|
966
|
+
ok: true,
|
|
967
|
+
value
|
|
968
|
+
} : {
|
|
969
|
+
ok: false,
|
|
970
|
+
issues
|
|
971
|
+
};
|
|
972
|
+
}
|
|
973
|
+
//#endregion
|
|
974
|
+
//#region src/host/lore/load.ts
|
|
975
|
+
const LORE_DIR = "lore";
|
|
976
|
+
async function loadLore(worldDir) {
|
|
977
|
+
const dir = join(worldDir, LORE_DIR);
|
|
978
|
+
const result = {
|
|
979
|
+
lore: [],
|
|
980
|
+
problems: []
|
|
981
|
+
};
|
|
982
|
+
let folders;
|
|
983
|
+
try {
|
|
984
|
+
folders = await subfolders(dir);
|
|
985
|
+
} catch (error) {
|
|
986
|
+
if (error.code !== "ENOENT") result.problems.push({
|
|
987
|
+
path: dir,
|
|
988
|
+
message: errorMessage(error)
|
|
989
|
+
});
|
|
990
|
+
return result;
|
|
991
|
+
}
|
|
992
|
+
const owners = /* @__PURE__ */ new Map();
|
|
993
|
+
for (const folder of folders) {
|
|
994
|
+
const file = join(dir, folder, LORE_FILE_NAME);
|
|
995
|
+
try {
|
|
996
|
+
const entry = await readDocument(file, (text) => parseLoreFile(text, folder), result.problems);
|
|
997
|
+
if (entry === void 0) continue;
|
|
998
|
+
const owner = owners.get(entry.id);
|
|
999
|
+
if (owner !== void 0) {
|
|
1000
|
+
result.problems.push({
|
|
1001
|
+
path: file,
|
|
1002
|
+
message: `id "${entry.id}" is already used by ${owner}`
|
|
1003
|
+
});
|
|
1004
|
+
continue;
|
|
1005
|
+
}
|
|
1006
|
+
owners.set(entry.id, folder);
|
|
1007
|
+
result.lore.push(entry);
|
|
1008
|
+
} catch (error) {
|
|
1009
|
+
if (error.code !== "ENOENT") result.problems.push({
|
|
1010
|
+
path: file,
|
|
1011
|
+
message: errorMessage(error)
|
|
1012
|
+
});
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
if (result.lore.length > 500) result.problems.push({
|
|
1016
|
+
path: dir,
|
|
1017
|
+
message: `a world has at most 500 lore entries`
|
|
1018
|
+
});
|
|
1019
|
+
return result;
|
|
1020
|
+
}
|
|
1021
|
+
//#endregion
|
|
1022
|
+
//#region src/host/lorebooks/lorebooks.ts
|
|
1023
|
+
const LOREBOOKS_FOLDER = "lorebooks";
|
|
1024
|
+
const LOREBOOK_FILE = "lorebook.json";
|
|
1025
|
+
const NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
1026
|
+
const ENTRY_ID = /^[\p{L}\p{N}][\p{L}\p{N}_-]{0,79}$/u;
|
|
1027
|
+
const MAX_TEXT = 300;
|
|
1028
|
+
const isLorebookName = (name) => NAME.test(name);
|
|
1029
|
+
const isEntryId = (id) => ENTRY_ID.test(id);
|
|
1030
|
+
const lorebooksDirectory = (root) => join(root, LOREBOOKS_FOLDER);
|
|
1031
|
+
function lorebookDirectory(root, name) {
|
|
1032
|
+
if (!isLorebookName(name)) throw new Error(`"${name}" is not a usable lorebook name (letters, digits, "-" and "_", up to 64)`);
|
|
1033
|
+
return join(lorebooksDirectory(root), name);
|
|
1034
|
+
}
|
|
1035
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1036
|
+
function parseHeader(value, problems) {
|
|
1037
|
+
if (!isRecord(value)) {
|
|
1038
|
+
problems.push(`${LOREBOOK_FILE} must be an object`);
|
|
1039
|
+
return {};
|
|
1040
|
+
}
|
|
1041
|
+
const text = (key) => {
|
|
1042
|
+
const field = value[key];
|
|
1043
|
+
if (field === void 0 || field === null) return void 0;
|
|
1044
|
+
if (typeof field !== "string" || field.length > MAX_TEXT) {
|
|
1045
|
+
problems.push(`${LOREBOOK_FILE}: "${key}" must be text of at most ${MAX_TEXT} characters`);
|
|
1046
|
+
return;
|
|
1047
|
+
}
|
|
1048
|
+
return field.trim() || void 0;
|
|
1049
|
+
};
|
|
1050
|
+
const title = text("title");
|
|
1051
|
+
const description = text("description");
|
|
1052
|
+
return {
|
|
1053
|
+
...title === void 0 ? {} : { title },
|
|
1054
|
+
...description === void 0 ? {} : { description }
|
|
1055
|
+
};
|
|
1056
|
+
}
|
|
1057
|
+
function readHeader(directory, problems) {
|
|
1058
|
+
const file = join(directory, LOREBOOK_FILE);
|
|
1059
|
+
if (!existsSync(file)) return {};
|
|
1060
|
+
let value;
|
|
1061
|
+
try {
|
|
1062
|
+
value = JSON.parse(readFileSync(file, "utf8"));
|
|
1063
|
+
} catch {
|
|
1064
|
+
problems.push(`${LOREBOOK_FILE} is not valid JSON`);
|
|
1065
|
+
return {};
|
|
1066
|
+
}
|
|
1067
|
+
return parseHeader(value, problems);
|
|
1068
|
+
}
|
|
1069
|
+
/** What is wrong with the entries of a book as a whole: an entry about a character or place of some world, or relating to one that is not there. */
|
|
1070
|
+
function bookProblems(entries) {
|
|
1071
|
+
const ids = new Set(entries.map((entry) => entry.id));
|
|
1072
|
+
return entries.flatMap((entry) => [...entry.subjects.length > 0 ? [`${entry.id}: a lorebook does not belong to a world, so its entries have no subjects`] : [], ...entry.related.flatMap((other) => other === entry.id ? [`${entry.id}: related: an entry cannot relate to itself`] : ids.has(other) ? [] : [`${entry.id}: related: "${other}" is not an entry of this book`])]);
|
|
1073
|
+
}
|
|
1074
|
+
/** Reads one lorebook folder, collecting every problem instead of stopping at the first. @throws {Error} when the folder does not exist. */
|
|
1075
|
+
async function readLorebook(directory, name) {
|
|
1076
|
+
if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
|
|
1077
|
+
const problems = [];
|
|
1078
|
+
const header = readHeader(directory, problems);
|
|
1079
|
+
const { lore, problems: found } = await loadLore(directory);
|
|
1080
|
+
for (const problem of found) problems.push(`${problem.path.slice(directory.length + 1)}: ${problem.message}`);
|
|
1081
|
+
problems.push(...bookProblems(lore));
|
|
1082
|
+
if (lore.length === 0 && problems.length === 0) problems.push("the lorebook has no entries");
|
|
1083
|
+
return {
|
|
1084
|
+
summary: {
|
|
1085
|
+
name,
|
|
1086
|
+
title: header.title ?? name,
|
|
1087
|
+
description: header.description ?? "",
|
|
1088
|
+
entries: lore.length,
|
|
1089
|
+
common: lore.filter((entry) => entry.scope === "everyone").length,
|
|
1090
|
+
problems
|
|
1091
|
+
},
|
|
1092
|
+
entries: lore.sort((a, b) => a.title.localeCompare(b.title))
|
|
1093
|
+
};
|
|
1094
|
+
}
|
|
1095
|
+
async function listLorebooks(root) {
|
|
1096
|
+
const folder = lorebooksDirectory(root);
|
|
1097
|
+
if (!existsSync(folder)) return [];
|
|
1098
|
+
const found = (await readdir(folder, { withFileTypes: true })).filter((entry) => entry.isDirectory() && isLorebookName(entry.name));
|
|
1099
|
+
return (await Promise.all(found.map((entry) => readLorebook(join(folder, entry.name), entry.name)))).sort((a, b) => a.summary.name.localeCompare(b.summary.name));
|
|
1100
|
+
}
|
|
1101
|
+
async function loadLorebook(root, name) {
|
|
1102
|
+
return await readLorebook(lorebookDirectory(root, name), name);
|
|
1103
|
+
}
|
|
1104
|
+
const toEntry = (definition) => ({
|
|
1105
|
+
id: definition.id,
|
|
1106
|
+
title: definition.title,
|
|
1107
|
+
kind: definition.kind,
|
|
1108
|
+
scope: definition.scope,
|
|
1109
|
+
knownBy: definition.knownBy,
|
|
1110
|
+
summary: definition.summary,
|
|
1111
|
+
body: definition.body,
|
|
1112
|
+
related: definition.related
|
|
1113
|
+
});
|
|
1114
|
+
const entriesOf = (book) => book.entries.map(toEntry);
|
|
1115
|
+
function headerFile(header) {
|
|
1116
|
+
return `${JSON.stringify(header, null, 2)}\n`;
|
|
1117
|
+
}
|
|
1118
|
+
async function writeAtomic(file, text) {
|
|
1119
|
+
await mkdir(dirname(file), { recursive: true });
|
|
1120
|
+
await writeFile(`${file}.tmp`, text);
|
|
1121
|
+
await rename(`${file}.tmp`, file);
|
|
1122
|
+
}
|
|
1123
|
+
/** Makes an empty lorebook. @throws {Error} when the name is taken or the information is not acceptable. */
|
|
1124
|
+
async function createLorebook(root, request) {
|
|
1125
|
+
const target = lorebookDirectory(root, request.name);
|
|
1126
|
+
if (existsSync(target)) throw new Error(`there is already a lorebook "${request.name}"`);
|
|
1127
|
+
const problems = [];
|
|
1128
|
+
const header = parseHeader({
|
|
1129
|
+
title: request.title?.trim(),
|
|
1130
|
+
description: request.description?.trim()
|
|
1131
|
+
}, problems);
|
|
1132
|
+
if (problems.length > 0) throw new Error(problems.join("; "));
|
|
1133
|
+
await writeAtomic(join(target, LOREBOOK_FILE), headerFile(header));
|
|
1134
|
+
return await readLorebook(target, request.name);
|
|
1135
|
+
}
|
|
1136
|
+
/** Makes an empty folder that an import is about to fill; it has no entries yet, so it reads as having problems until it does. */
|
|
1137
|
+
async function reserveLorebook(root, name, title) {
|
|
1138
|
+
const target = lorebookDirectory(root, name);
|
|
1139
|
+
if (existsSync(target)) throw new Error(`there is already a lorebook "${name}"`);
|
|
1140
|
+
await writeAtomic(join(target, LOREBOOK_FILE), headerFile({ title: title.trim().slice(0, MAX_TEXT) || name }));
|
|
1141
|
+
return target;
|
|
1142
|
+
}
|
|
1143
|
+
/** Changes what a lorebook says about itself. @throws {Error} when the lorebook does not exist or the change is not acceptable; nothing is written then. */
|
|
1144
|
+
async function updateLorebookInfo(root, name, change) {
|
|
1145
|
+
const directory = lorebookDirectory(root, name);
|
|
1146
|
+
if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
|
|
1147
|
+
const current = readHeader(directory, []);
|
|
1148
|
+
const problems = [];
|
|
1149
|
+
const next = parseHeader({
|
|
1150
|
+
title: change.title ?? current.title,
|
|
1151
|
+
description: change.description ?? current.description
|
|
1152
|
+
}, problems);
|
|
1153
|
+
if (problems.length > 0) throw new Error(problems.join("; "));
|
|
1154
|
+
await writeAtomic(join(directory, LOREBOOK_FILE), headerFile(next));
|
|
1155
|
+
return await readLorebook(directory, name);
|
|
1156
|
+
}
|
|
1157
|
+
/** The file of an entry: written in the format of a world's own lore, with its scope always said. */
|
|
1158
|
+
function entryFile(entry) {
|
|
1159
|
+
return `${JSON.stringify({
|
|
1160
|
+
title: entry.title,
|
|
1161
|
+
kind: entry.kind,
|
|
1162
|
+
scope: entry.scope,
|
|
1163
|
+
...entry.scope === "listed" && entry.knownBy.length > 0 ? { known_by: entry.knownBy } : {},
|
|
1164
|
+
summary: entry.summary,
|
|
1165
|
+
body: entry.body,
|
|
1166
|
+
...entry.related.length > 0 ? { related: entry.related } : {}
|
|
1167
|
+
}, null, 2)}\n`;
|
|
1168
|
+
}
|
|
1169
|
+
/** Checks an entry the way a story start would, before anything is written. @returns why it cannot be used, or nothing. */
|
|
1170
|
+
function entryProblem(entry) {
|
|
1171
|
+
if (!isEntryId(entry.id)) return `"${entry.id}" is not a usable entry id (letters, digits, "-" and "_", up to 80)`;
|
|
1172
|
+
if (!LORE_KINDS.includes(entry.kind)) return `kind must be one of ${LORE_KINDS.join(", ")}`;
|
|
1173
|
+
if (!LORE_SCOPES.includes(entry.scope)) return `scope must be one of ${LORE_SCOPES.join(", ")}`;
|
|
1174
|
+
if (entry.title.trim() === "") return "the entry needs a title";
|
|
1175
|
+
if (entry.body.trim() === "" && entry.summary.trim() === "") return "the entry needs a summary or a body";
|
|
1176
|
+
const parsed = parseLoreFile(entryFile({
|
|
1177
|
+
...entry,
|
|
1178
|
+
title: entry.title.trim()
|
|
1179
|
+
}), entry.id);
|
|
1180
|
+
return parsed.ok ? void 0 : parsed.issues.map((issue) => `${issue.path}: ${issue.message}`).join("; ");
|
|
1181
|
+
}
|
|
1182
|
+
/** Creates or replaces one entry. @throws {Error} when the lorebook does not exist, the entry is not acceptable or the book would have more entries than a world may. */
|
|
1183
|
+
async function writeLorebookEntry(root, name, entry) {
|
|
1184
|
+
const directory = lorebookDirectory(root, name);
|
|
1185
|
+
if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
|
|
1186
|
+
const problem = entryProblem(entry);
|
|
1187
|
+
if (problem !== void 0) throw new Error(problem);
|
|
1188
|
+
const file = join(directory, LORE_DIR, entry.id, LORE_FILE_NAME);
|
|
1189
|
+
const book = await readLorebook(directory, name);
|
|
1190
|
+
if (!existsSync(file) && book.entries.length >= 500) throw new Error(`a lorebook has at most 500 entries`);
|
|
1191
|
+
const others = book.entries.filter((other) => other.id !== entry.id);
|
|
1192
|
+
const missing = entry.related.filter((id) => id === entry.id || !others.some((other) => other.id === id));
|
|
1193
|
+
if (missing.length > 0) throw new Error(`related: ${missing.map((id) => `"${id}"`).join(", ")} ${missing.length === 1 ? "is" : "are"} not (other) entries of this book`);
|
|
1194
|
+
await writeAtomic(file, entryFile({
|
|
1195
|
+
...entry,
|
|
1196
|
+
title: entry.title.trim()
|
|
1197
|
+
}));
|
|
1198
|
+
return await readLorebook(directory, name);
|
|
1199
|
+
}
|
|
1200
|
+
/** Moves an entry into the book's `.trash`. @throws {Error} when it does not exist or other entries relate to it. */
|
|
1201
|
+
async function deleteLorebookEntry(root, name, id, now = Date.now) {
|
|
1202
|
+
const directory = lorebookDirectory(root, name);
|
|
1203
|
+
const folder = join(directory, LORE_DIR, id);
|
|
1204
|
+
if (!isEntryId(id) || !existsSync(join(folder, "lore.json"))) throw new Error(`the lorebook "${name}" has no entry "${id}"`);
|
|
1205
|
+
const citing = (await readLorebook(directory, name)).entries.filter((entry) => entry.id !== id && entry.related.includes(id)).map((entry) => entry.id);
|
|
1206
|
+
if (citing.length > 0) throw new Error(`the entries ${citing.join(", ")} relate to "${id}"; change them first`);
|
|
1207
|
+
const aside = join(directory, ".trash", LORE_DIR, `${id}-${now()}`);
|
|
1208
|
+
await mkdir(dirname(aside), { recursive: true });
|
|
1209
|
+
await rename(folder, aside);
|
|
1210
|
+
return await readLorebook(directory, name);
|
|
1211
|
+
}
|
|
1212
|
+
/** Moves a lorebook out of the library into `<root>/.trash/lorebooks/`. @returns where it went. */
|
|
1213
|
+
async function deleteLorebook(root, name, now = Date.now) {
|
|
1214
|
+
const directory = lorebookDirectory(root, name);
|
|
1215
|
+
if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
|
|
1216
|
+
const aside = join(root, ".trash", LOREBOOKS_FOLDER, `${name}-${now()}`);
|
|
1217
|
+
await mkdir(dirname(aside), { recursive: true });
|
|
1218
|
+
await rename(directory, aside);
|
|
1219
|
+
return aside;
|
|
1220
|
+
}
|
|
898
1221
|
const MAX_OPENING_CHARS = 2e4;
|
|
899
1222
|
const TEXT_FIELDS = [
|
|
900
1223
|
"name",
|
|
@@ -907,7 +1230,11 @@ const TEXT_FIELDS = [
|
|
|
907
1230
|
"version",
|
|
908
1231
|
"preset"
|
|
909
1232
|
];
|
|
910
|
-
const LIST_FIELDS = [
|
|
1233
|
+
const LIST_FIELDS = [
|
|
1234
|
+
"tags",
|
|
1235
|
+
"rules",
|
|
1236
|
+
"lorebooks"
|
|
1237
|
+
];
|
|
911
1238
|
/** Reads a body that came from the browser; every field is checked and each problem is reported. */
|
|
912
1239
|
function parseWorldInfoEdit(value) {
|
|
913
1240
|
const problems = [];
|
|
@@ -1086,6 +1413,8 @@ function parseWorldFile(text) {
|
|
|
1086
1413
|
const narrationVoice = reader.string("narration_voice")?.trim() || void 0;
|
|
1087
1414
|
const preset = reader.string("preset")?.trim() || void 0;
|
|
1088
1415
|
if (preset !== void 0 && !isPresetName(preset)) reader.fail("preset", "must be the name of a preset: letters, digits, \"-\" and \"_\"");
|
|
1416
|
+
const lorebooks = reader.strings("lorebooks").map((entry) => entry.trim()).filter((entry) => entry !== "");
|
|
1417
|
+
for (const [index, entry] of lorebooks.entries()) if (!isLorebookName(entry)) reader.fail(`lorebooks[${index}]`, "must be the name of a lorebook: letters, digits, \"-\" and \"_\"");
|
|
1089
1418
|
if (name === void 0 || issues.length > 0) return {
|
|
1090
1419
|
ok: false,
|
|
1091
1420
|
issues
|
|
@@ -1107,7 +1436,8 @@ function parseWorldFile(text) {
|
|
|
1107
1436
|
...tools === void 0 ? {} : { tools },
|
|
1108
1437
|
...alternateOpenings === void 0 ? {} : { alternateOpenings },
|
|
1109
1438
|
...narrationVoice === void 0 ? {} : { narrationVoice },
|
|
1110
|
-
...preset === void 0 ? {} : { preset }
|
|
1439
|
+
...preset === void 0 ? {} : { preset },
|
|
1440
|
+
...lorebooks.length === 0 ? {} : { lorebooks: [...new Set(lorebooks)] }
|
|
1111
1441
|
}
|
|
1112
1442
|
};
|
|
1113
1443
|
}
|
|
@@ -1879,59 +2209,6 @@ function parseLocationFile(text, fallbackId) {
|
|
|
1879
2209
|
};
|
|
1880
2210
|
}
|
|
1881
2211
|
//#endregion
|
|
1882
|
-
//#region src/host/lore/lore-file.ts
|
|
1883
|
-
const LORE_FILE_NAME = "lore.json";
|
|
1884
|
-
function instant(reader, key) {
|
|
1885
|
-
const value = reader.string(key);
|
|
1886
|
-
if (value === void 0) return void 0;
|
|
1887
|
-
const parsed = Date.parse(value);
|
|
1888
|
-
if (!Number.isFinite(parsed)) {
|
|
1889
|
-
reader.fail(key, "must be an ISO date or date-time");
|
|
1890
|
-
return;
|
|
1891
|
-
}
|
|
1892
|
-
return parsed;
|
|
1893
|
-
}
|
|
1894
|
-
function parseLoreFile(text, fallbackId) {
|
|
1895
|
-
const issues = [];
|
|
1896
|
-
const reader = Reader.fromJson(text, issues);
|
|
1897
|
-
if (reader === void 0) return {
|
|
1898
|
-
ok: false,
|
|
1899
|
-
issues
|
|
1900
|
-
};
|
|
1901
|
-
const id = readIdentifier(reader, fallbackId) ?? fallbackId;
|
|
1902
|
-
const title = reader.string("title", { required: true }) ?? "";
|
|
1903
|
-
const subjects = reader.objects("subjects").flatMap((entry) => {
|
|
1904
|
-
const kind = entry.oneOf("kind", LORE_SUBJECT_KINDS, "lore");
|
|
1905
|
-
const subjectId = entry.string("id", { required: true });
|
|
1906
|
-
return subjectId === void 0 ? [] : [{
|
|
1907
|
-
kind,
|
|
1908
|
-
id: subjectId
|
|
1909
|
-
}];
|
|
1910
|
-
});
|
|
1911
|
-
const startsAt = instant(reader, "starts_at");
|
|
1912
|
-
const endsAt = instant(reader, "ends_at");
|
|
1913
|
-
if (startsAt !== void 0 && endsAt !== void 0 && endsAt < startsAt) reader.fail("ends_at", "must not be before starts_at");
|
|
1914
|
-
const value = {
|
|
1915
|
-
id,
|
|
1916
|
-
title,
|
|
1917
|
-
kind: reader.oneOf("kind", LORE_KINDS, "other"),
|
|
1918
|
-
summary: reader.text("summary"),
|
|
1919
|
-
body: reader.text("body"),
|
|
1920
|
-
subjects,
|
|
1921
|
-
related: reader.strings("related"),
|
|
1922
|
-
sources: reader.strings("sources"),
|
|
1923
|
-
...startsAt === void 0 ? {} : { startsAt },
|
|
1924
|
-
...endsAt === void 0 ? {} : { endsAt }
|
|
1925
|
-
};
|
|
1926
|
-
return issues.length === 0 ? {
|
|
1927
|
-
ok: true,
|
|
1928
|
-
value
|
|
1929
|
-
} : {
|
|
1930
|
-
ok: false,
|
|
1931
|
-
issues
|
|
1932
|
-
};
|
|
1933
|
-
}
|
|
1934
|
-
//#endregion
|
|
1935
2212
|
//#region src/host/variables/load.ts
|
|
1936
2213
|
const VARIABLES_FILE_NAME = "variables.json";
|
|
1937
2214
|
function readDefinition(reader) {
|
|
@@ -2516,7 +2793,7 @@ const SOURCE_BUDGET_CHARS = 14e3;
|
|
|
2516
2793
|
const MAX_TAGGED = 8;
|
|
2517
2794
|
const MAX_MENTIONS = 6;
|
|
2518
2795
|
const MIN_MENTION_CHARS = 2;
|
|
2519
|
-
const text
|
|
2796
|
+
const text = (value) => typeof value === "string" ? value.trim() : "";
|
|
2520
2797
|
const list = (value) => Array.isArray(value) ? value.flatMap((entry) => typeof entry === "string" && entry.trim() !== "" ? [entry.trim()] : []) : [];
|
|
2521
2798
|
const objects = (value) => Array.isArray(value) ? value.filter((entry) => typeof entry === "object" && entry !== null && !Array.isArray(entry)) : [];
|
|
2522
2799
|
const put = (document, key, value) => {
|
|
@@ -2677,7 +2954,7 @@ function characterDocument(entity, answer, roster) {
|
|
|
2677
2954
|
"age",
|
|
2678
2955
|
"gender",
|
|
2679
2956
|
"pronouns"
|
|
2680
|
-
]) put(document, field, text
|
|
2957
|
+
]) put(document, field, text(answer[field]));
|
|
2681
2958
|
const playable = entity.player;
|
|
2682
2959
|
const group = answer["kind"] === "group" && !playable;
|
|
2683
2960
|
document["role"] = playable ? "playable" : "npc";
|
|
@@ -2688,10 +2965,10 @@ function characterDocument(entity, answer, roster) {
|
|
|
2688
2965
|
"personality",
|
|
2689
2966
|
"background",
|
|
2690
2967
|
"appearance"
|
|
2691
|
-
]) document[field] = text
|
|
2968
|
+
]) document[field] = text(answer[field]);
|
|
2692
2969
|
const speech = typeof answer["speech"] === "object" && answer["speech"] !== null ? answer["speech"] : {};
|
|
2693
2970
|
document["speech"] = {
|
|
2694
|
-
style: text
|
|
2971
|
+
style: text(speech["style"]),
|
|
2695
2972
|
examples: list(speech["examples"]).slice(0, 8)
|
|
2696
2973
|
};
|
|
2697
2974
|
const start = {};
|
|
@@ -2700,17 +2977,17 @@ function characterDocument(entity, answer, roster) {
|
|
|
2700
2977
|
["public_state", "public_state"],
|
|
2701
2978
|
["inner_state", "inner_state"],
|
|
2702
2979
|
["activity", "activity"]
|
|
2703
|
-
]) put(start, to, text
|
|
2704
|
-
const place = text
|
|
2705
|
-
if (text
|
|
2980
|
+
]) put(start, to, text(given[from]));
|
|
2981
|
+
const place = text(given["location"]) === "" ? void 0 : findEntity(roster, text(given["location"]), "place");
|
|
2982
|
+
if (text(given["location"]) !== "" && place === void 0) notes.push(`${entity.name}: the place "${text(given["location"])}" is not one of the world's places, so the character starts nowhere`);
|
|
2706
2983
|
if (place !== void 0) {
|
|
2707
2984
|
start["location"] = place.key;
|
|
2708
|
-
put(start, "position", text
|
|
2985
|
+
put(start, "position", text(given["position"]));
|
|
2709
2986
|
}
|
|
2710
|
-
const goals = objects(answer["goals"]).filter((goal) => text
|
|
2987
|
+
const goals = objects(answer["goals"]).filter((goal) => text(goal["name"]) !== "").map((goal) => ({
|
|
2711
2988
|
type: "agenda",
|
|
2712
|
-
name: text
|
|
2713
|
-
...text
|
|
2989
|
+
name: text(goal["name"]),
|
|
2990
|
+
...text(goal["description"]) === "" ? {} : { description: text(goal["description"]) },
|
|
2714
2991
|
status: "active"
|
|
2715
2992
|
}));
|
|
2716
2993
|
put(start, "intents", goals);
|
|
@@ -2718,17 +2995,17 @@ function characterDocument(entity, answer, roster) {
|
|
|
2718
2995
|
const seen = /* @__PURE__ */ new Set([entity.key]);
|
|
2719
2996
|
const relationships = [];
|
|
2720
2997
|
for (const relation of objects(answer["relationships"])) {
|
|
2721
|
-
const other = findEntity(roster, text
|
|
2998
|
+
const other = findEntity(roster, text(relation["with"]), "character");
|
|
2722
2999
|
if (other === void 0) {
|
|
2723
|
-
notes.push(`${entity.name}: the relationship with "${text
|
|
3000
|
+
notes.push(`${entity.name}: the relationship with "${text(relation["with"])}" names nobody in the world`);
|
|
2724
3001
|
continue;
|
|
2725
3002
|
}
|
|
2726
|
-
if (seen.has(other.key) || text
|
|
3003
|
+
if (seen.has(other.key) || text(relation["label"]) === "") continue;
|
|
2727
3004
|
seen.add(other.key);
|
|
2728
3005
|
relationships.push({
|
|
2729
3006
|
to: other.key,
|
|
2730
|
-
label: text
|
|
2731
|
-
...text
|
|
3007
|
+
label: text(relation["label"]),
|
|
3008
|
+
...text(relation["summary"]) === "" ? {} : { summary: text(relation["summary"]) }
|
|
2732
3009
|
});
|
|
2733
3010
|
}
|
|
2734
3011
|
put(document, "relationships", relationships.slice(0, 60));
|
|
@@ -2744,10 +3021,10 @@ function characterDocument(entity, answer, roster) {
|
|
|
2744
3021
|
const ways = /* @__PURE__ */ new Set();
|
|
2745
3022
|
const exits = [];
|
|
2746
3023
|
for (const way of objects(knows["ways"])) {
|
|
2747
|
-
const from = findEntity(roster, text
|
|
2748
|
-
const to = findEntity(roster, text
|
|
3024
|
+
const from = findEntity(roster, text(way["from"]), "place");
|
|
3025
|
+
const to = findEntity(roster, text(way["to"]), "place");
|
|
2749
3026
|
if (from === void 0 || to === void 0 || from.key === to.key) {
|
|
2750
|
-
notes.push(`${entity.name}: the way from "${text
|
|
3027
|
+
notes.push(`${entity.name}: the way from "${text(way["from"])}" to "${text(way["to"])}" is not between two places of the world, so they do not know of it`);
|
|
2751
3028
|
continue;
|
|
2752
3029
|
}
|
|
2753
3030
|
if (ways.has(`${from.key}>${to.key}`)) continue;
|
|
@@ -2803,30 +3080,30 @@ function placeDocument(entity, answer, roster) {
|
|
|
2803
3080
|
id: entity.key,
|
|
2804
3081
|
name: entity.name
|
|
2805
3082
|
};
|
|
2806
|
-
put(document, "description", text
|
|
2807
|
-
const named = text
|
|
3083
|
+
put(document, "description", text(answer["description"]));
|
|
3084
|
+
const named = text(answer["parent"]) === "" ? entity.parent : text(answer["parent"]);
|
|
2808
3085
|
const parent = named === void 0 ? void 0 : findEntity(roster, named, "place");
|
|
2809
3086
|
if (named !== void 0 && (parent === void 0 || parent.key === entity.key)) notes.push(`${entity.name}: the place it is in, "${named}", is not one of the world's places`);
|
|
2810
3087
|
if (parent !== void 0 && parent.key !== entity.key) document["parent"] = parent.key;
|
|
2811
|
-
const features = objects(answer["features"]).filter((feature) => text
|
|
3088
|
+
const features = objects(answer["features"]).filter((feature) => text(feature["name"]) !== "").slice(0, 30).map((feature, index) => ({
|
|
2812
3089
|
id: `feature-${index + 1}`,
|
|
2813
|
-
name: text
|
|
2814
|
-
...text
|
|
3090
|
+
name: text(feature["name"]),
|
|
3091
|
+
...text(feature["description"]) === "" ? {} : { description: text(feature["description"]) }
|
|
2815
3092
|
}));
|
|
2816
3093
|
put(document, "features", features);
|
|
2817
3094
|
const exits = [];
|
|
2818
3095
|
const to = /* @__PURE__ */ new Set();
|
|
2819
3096
|
for (const exit of objects(answer["exits"])) {
|
|
2820
|
-
const target = findEntity(roster, text
|
|
3097
|
+
const target = findEntity(roster, text(exit["to"]), "place");
|
|
2821
3098
|
if (target === void 0 || target.key === entity.key) {
|
|
2822
|
-
notes.push(`${entity.name}: the way to "${text
|
|
3099
|
+
notes.push(`${entity.name}: the way to "${text(exit["to"])}" leads to no place of the world`);
|
|
2823
3100
|
continue;
|
|
2824
3101
|
}
|
|
2825
3102
|
if (to.has(target.key)) continue;
|
|
2826
3103
|
to.add(target.key);
|
|
2827
3104
|
exits.push({
|
|
2828
3105
|
to: target.key,
|
|
2829
|
-
...text
|
|
3106
|
+
...text(exit["description"]) === "" ? {} : { description: text(exit["description"]) }
|
|
2830
3107
|
});
|
|
2831
3108
|
}
|
|
2832
3109
|
put(document, "exits", exits.slice(0, 30));
|
|
@@ -2872,25 +3149,25 @@ function factionDocument(entity, answer, roster) {
|
|
|
2872
3149
|
"summary",
|
|
2873
3150
|
"description",
|
|
2874
3151
|
"structure"
|
|
2875
|
-
]) put(document, field, text
|
|
3152
|
+
]) put(document, field, text(answer[field]));
|
|
2876
3153
|
put(document, "values", list(answer["values"]));
|
|
2877
3154
|
const start = {};
|
|
2878
|
-
put(start, "public_state", text
|
|
2879
|
-
put(start, "inner_state", text
|
|
3155
|
+
put(start, "public_state", text(answer["public_state"]));
|
|
3156
|
+
put(start, "inner_state", text(answer["inner_state"]));
|
|
2880
3157
|
put(document, "start", Object.keys(start).length === 0 ? void 0 : start);
|
|
2881
3158
|
const members = [];
|
|
2882
3159
|
const seen = /* @__PURE__ */ new Set();
|
|
2883
3160
|
for (const member of objects(answer["members"])) {
|
|
2884
|
-
const character = findEntity(roster, text
|
|
3161
|
+
const character = findEntity(roster, text(member["character"]), "character");
|
|
2885
3162
|
if (character === void 0) {
|
|
2886
|
-
notes.push(`${entity.name}: the member "${text
|
|
3163
|
+
notes.push(`${entity.name}: the member "${text(member["character"])}" is nobody in the world`);
|
|
2887
3164
|
continue;
|
|
2888
3165
|
}
|
|
2889
3166
|
if (seen.has(character.key)) continue;
|
|
2890
3167
|
seen.add(character.key);
|
|
2891
3168
|
members.push({
|
|
2892
3169
|
character: character.key,
|
|
2893
|
-
...text
|
|
3170
|
+
...text(member["role"]) === "" ? {} : { role: text(member["role"]) }
|
|
2894
3171
|
});
|
|
2895
3172
|
}
|
|
2896
3173
|
put(document, "members", members);
|
|
@@ -2918,11 +3195,11 @@ function thingDocument(entity, answer, roster) {
|
|
|
2918
3195
|
name: entity.name,
|
|
2919
3196
|
unique: true
|
|
2920
3197
|
};
|
|
2921
|
-
put(document, "description", text
|
|
2922
|
-
put(document, "quality", text
|
|
3198
|
+
put(document, "description", text(answer["description"]));
|
|
3199
|
+
put(document, "quality", text(answer["quality"]));
|
|
2923
3200
|
if (answer["notable"] === true) document["notable"] = true;
|
|
2924
|
-
const holder = text
|
|
2925
|
-
const place = text
|
|
3201
|
+
const holder = text(answer["held_by"]) === "" ? void 0 : findEntity(roster, text(answer["held_by"]), "character");
|
|
3202
|
+
const place = text(answer["location"]) === "" ? void 0 : findEntity(roster, text(answer["location"]), "place");
|
|
2926
3203
|
if (holder !== void 0) document["held_by"] = holder.key;
|
|
2927
3204
|
else if (place !== void 0) document["location"] = place.key;
|
|
2928
3205
|
else notes.push(`${entity.name}: it is nowhere in the world and nobody has it, so it is left out`);
|
|
@@ -2986,8 +3263,8 @@ const LORE_SUBJECT = {
|
|
|
2986
3263
|
};
|
|
2987
3264
|
function loreDocuments(answer, roster, taken) {
|
|
2988
3265
|
return objects(answer["entries"]).flatMap((entry) => {
|
|
2989
|
-
const title = text
|
|
2990
|
-
const body = text
|
|
3266
|
+
const title = text(entry["title"]);
|
|
3267
|
+
const body = text(entry["body"]);
|
|
2991
3268
|
if (title === "" || body === "") return [];
|
|
2992
3269
|
const notes = [];
|
|
2993
3270
|
const subjects = [];
|
|
@@ -2998,10 +3275,10 @@ function loreDocuments(answer, roster, taken) {
|
|
|
2998
3275
|
"place",
|
|
2999
3276
|
"faction",
|
|
3000
3277
|
"thing"
|
|
3001
|
-
].includes(text
|
|
3002
|
-
const found = kind === void 0 ? void 0 : findEntity(roster, text
|
|
3278
|
+
].includes(text(subject["kind"])) ? text(subject["kind"]) : void 0;
|
|
3279
|
+
const found = kind === void 0 ? void 0 : findEntity(roster, text(subject["name"]), kind);
|
|
3003
3280
|
if (found === void 0) {
|
|
3004
|
-
notes.push(`${title}: the subject "${text
|
|
3281
|
+
notes.push(`${title}: the subject "${text(subject["name"])}" is not in the world`);
|
|
3005
3282
|
continue;
|
|
3006
3283
|
}
|
|
3007
3284
|
if (!seen.has(found.key)) {
|
|
@@ -3017,7 +3294,7 @@ function loreDocuments(answer, roster, taken) {
|
|
|
3017
3294
|
id: uniqueKey(slug(title, "lore"), taken),
|
|
3018
3295
|
title,
|
|
3019
3296
|
kind,
|
|
3020
|
-
summary: text
|
|
3297
|
+
summary: text(entry["summary"]),
|
|
3021
3298
|
body
|
|
3022
3299
|
};
|
|
3023
3300
|
put(document, "subjects", subjects);
|
|
@@ -3338,9 +3615,9 @@ async function extractStyleFrom(ctx, name, pieces) {
|
|
|
3338
3615
|
persona: ctx.text("import/style", { rules: ctx.text("import/common-rules") }),
|
|
3339
3616
|
prompt,
|
|
3340
3617
|
result: STYLE_SCHEMA,
|
|
3341
|
-
check: (value) => styleProblem("roleplay/style", text
|
|
3618
|
+
check: (value) => styleProblem("roleplay/style", text(value.narration)) ?? styleProblem("roleplay/character-style", text(value.characters))
|
|
3342
3619
|
});
|
|
3343
|
-
const prompts = [["roleplay/style", text
|
|
3620
|
+
const prompts = [["roleplay/style", text(answer.narration)], ["roleplay/character-style", text(answer.characters)]].flatMap(([id, body]) => body === "" ? [] : [{
|
|
3344
3621
|
id,
|
|
3345
3622
|
text: body
|
|
3346
3623
|
}]);
|
|
@@ -3476,15 +3753,15 @@ function variableDocuments(answer, roster) {
|
|
|
3476
3753
|
const keyOf = (name) => roster.find((entity) => norm(entity.name) === norm(name) || entity.aliases.some((alias) => norm(alias) === norm(name)))?.key;
|
|
3477
3754
|
const taken = /* @__PURE__ */ new Set();
|
|
3478
3755
|
return objects(answer["variables"]).map((entry, index) => {
|
|
3479
|
-
const base = slug(text
|
|
3756
|
+
const base = slug(text(entry["key"]) || text(entry["name"]), "").replace(/-/g, "_").slice(0, 40);
|
|
3480
3757
|
const document = {
|
|
3481
3758
|
key: uniqueKey(/^[a-z][a-z0-9_]*$/.test(base) ? base : `variable_${index + 1}`, taken),
|
|
3482
|
-
name: text
|
|
3483
|
-
kind: text
|
|
3484
|
-
subject: text
|
|
3759
|
+
name: text(entry["name"]),
|
|
3760
|
+
kind: text(entry["kind"]),
|
|
3761
|
+
subject: text(entry["subject"])
|
|
3485
3762
|
};
|
|
3486
|
-
put(document, "description", text
|
|
3487
|
-
put(document, "visibility", text
|
|
3763
|
+
put(document, "description", text(entry["description"]));
|
|
3764
|
+
put(document, "visibility", text(entry["visibility"]));
|
|
3488
3765
|
put(document, "only", list(entry["only"]).flatMap((name) => keyOf(name) ?? []));
|
|
3489
3766
|
for (const field of ["min", "max"]) if (typeof entry[field] === "number") document[field] = entry[field];
|
|
3490
3767
|
if (typeof entry["integer"] === "boolean") document["integer"] = entry["integer"];
|
|
@@ -3494,9 +3771,9 @@ function variableDocuments(answer, roster) {
|
|
|
3494
3771
|
"string"
|
|
3495
3772
|
].includes(typeof entry["default"])) document["default"] = entry["default"];
|
|
3496
3773
|
put(document, "options", list(entry["options"]));
|
|
3497
|
-
put(document, "bands", objects(entry["bands"]).filter((band) => typeof band["up_to"] === "number" && text
|
|
3774
|
+
put(document, "bands", objects(entry["bands"]).filter((band) => typeof band["up_to"] === "number" && text(band["label"]) !== "").map((band) => ({
|
|
3498
3775
|
up_to: band["up_to"],
|
|
3499
|
-
label: text
|
|
3776
|
+
label: text(band["label"])
|
|
3500
3777
|
})));
|
|
3501
3778
|
return document;
|
|
3502
3779
|
});
|
|
@@ -3545,20 +3822,6 @@ async function extractVariables(ctx, card, items, classified, roster) {
|
|
|
3545
3822
|
}
|
|
3546
3823
|
}
|
|
3547
3824
|
//#endregion
|
|
3548
|
-
//#region src/host/folders.ts
|
|
3549
|
-
/**
|
|
3550
|
-
* Names of the subfolders of `dir`, sorted. Symbolic links are not followed
|
|
3551
|
-
* and a missing directory has none; any other failure is thrown.
|
|
3552
|
-
*/
|
|
3553
|
-
async function subfolders(dir) {
|
|
3554
|
-
try {
|
|
3555
|
-
return (await readdir(dir, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort((a, b) => a.localeCompare(b));
|
|
3556
|
-
} catch (error) {
|
|
3557
|
-
if (error.code === "ENOENT") return [];
|
|
3558
|
-
throw error;
|
|
3559
|
-
}
|
|
3560
|
-
}
|
|
3561
|
-
//#endregion
|
|
3562
3825
|
//#region src/host/characters/load.ts
|
|
3563
3826
|
const CHARACTERS_DIR = "characters";
|
|
3564
3827
|
/**
|
|
@@ -3885,54 +4148,6 @@ function parentsFirst(locations) {
|
|
|
3885
4148
|
return ordered;
|
|
3886
4149
|
}
|
|
3887
4150
|
//#endregion
|
|
3888
|
-
//#region src/host/lore/load.ts
|
|
3889
|
-
const LORE_DIR = "lore";
|
|
3890
|
-
async function loadLore(worldDir) {
|
|
3891
|
-
const dir = join(worldDir, LORE_DIR);
|
|
3892
|
-
const result = {
|
|
3893
|
-
lore: [],
|
|
3894
|
-
problems: []
|
|
3895
|
-
};
|
|
3896
|
-
let folders;
|
|
3897
|
-
try {
|
|
3898
|
-
folders = await subfolders(dir);
|
|
3899
|
-
} catch (error) {
|
|
3900
|
-
if (error.code !== "ENOENT") result.problems.push({
|
|
3901
|
-
path: dir,
|
|
3902
|
-
message: errorMessage(error)
|
|
3903
|
-
});
|
|
3904
|
-
return result;
|
|
3905
|
-
}
|
|
3906
|
-
const owners = /* @__PURE__ */ new Map();
|
|
3907
|
-
for (const folder of folders) {
|
|
3908
|
-
const file = join(dir, folder, LORE_FILE_NAME);
|
|
3909
|
-
try {
|
|
3910
|
-
const entry = await readDocument(file, (text) => parseLoreFile(text, folder), result.problems);
|
|
3911
|
-
if (entry === void 0) continue;
|
|
3912
|
-
const owner = owners.get(entry.id);
|
|
3913
|
-
if (owner !== void 0) {
|
|
3914
|
-
result.problems.push({
|
|
3915
|
-
path: file,
|
|
3916
|
-
message: `id "${entry.id}" is already used by ${owner}`
|
|
3917
|
-
});
|
|
3918
|
-
continue;
|
|
3919
|
-
}
|
|
3920
|
-
owners.set(entry.id, folder);
|
|
3921
|
-
result.lore.push(entry);
|
|
3922
|
-
} catch (error) {
|
|
3923
|
-
if (error.code !== "ENOENT") result.problems.push({
|
|
3924
|
-
path: file,
|
|
3925
|
-
message: errorMessage(error)
|
|
3926
|
-
});
|
|
3927
|
-
}
|
|
3928
|
-
}
|
|
3929
|
-
if (result.lore.length > 500) result.problems.push({
|
|
3930
|
-
path: dir,
|
|
3931
|
-
message: `a world has at most 500 lore entries`
|
|
3932
|
-
});
|
|
3933
|
-
return result;
|
|
3934
|
-
}
|
|
3935
|
-
//#endregion
|
|
3936
4151
|
//#region src/host/calendar/load.ts
|
|
3937
4152
|
const CALENDAR_FILE_NAME = "calendar.json";
|
|
3938
4153
|
const HOLIDAY_ID = /^[\p{L}\p{N}][\p{L}\p{N}_-]{0,59}$/u;
|
|
@@ -4189,6 +4404,11 @@ function knowledgeProblems(characters, locations, items, lore = []) {
|
|
|
4189
4404
|
];
|
|
4190
4405
|
});
|
|
4191
4406
|
}
|
|
4407
|
+
/** Whether a world's characters include the one a lore entry names by id, name or alias. */
|
|
4408
|
+
function knowsCharacter(characters, reference) {
|
|
4409
|
+
const key = reference.normalize("NFKC").toLowerCase();
|
|
4410
|
+
return characters.some((character) => character.id === reference || [character.name, ...character.aliases].some((name) => name.normalize("NFKC").toLowerCase() === key));
|
|
4411
|
+
}
|
|
4192
4412
|
function loreProblems(lore, world) {
|
|
4193
4413
|
const ids = {
|
|
4194
4414
|
character: new Set(world.characters.map((x) => x.id)),
|
|
@@ -4197,13 +4417,18 @@ function loreProblems(lore, world) {
|
|
|
4197
4417
|
item: new Set(world.items.map((x) => x.id)),
|
|
4198
4418
|
lore: new Set(lore.map((x) => x.id))
|
|
4199
4419
|
};
|
|
4200
|
-
return lore.flatMap((entry) => [
|
|
4420
|
+
return lore.flatMap((entry) => [
|
|
4421
|
+
...entry.subjects.flatMap((subject) => ids[subject.kind].has(subject.id) ? [] : [`${entry.id}: subjects: "${subject.id}" is not a ${subject.kind} of this world`]),
|
|
4422
|
+
...entry.knownBy.flatMap((reference) => knowsCharacter(world.characters, reference) ? [] : [`${entry.id}: known_by: "${reference}" is not a character of this world`]),
|
|
4423
|
+
...entry.related.flatMap((id) => id === entry.id ? [`${entry.id}: related: lore cannot relate to itself`] : ids.lore.has(id) ? [] : [`${entry.id}: related: "${id}" is not lore of this world`])
|
|
4424
|
+
]);
|
|
4201
4425
|
}
|
|
4202
4426
|
function populateLore(session, definitions) {
|
|
4203
4427
|
for (const entry of definitions) session.lore.add({
|
|
4204
4428
|
sourceId: entry.id,
|
|
4205
4429
|
title: entry.title,
|
|
4206
4430
|
kind: entry.kind,
|
|
4431
|
+
scope: entry.scope,
|
|
4207
4432
|
summary: entry.summary,
|
|
4208
4433
|
body: entry.body,
|
|
4209
4434
|
...entry.startsAt === void 0 ? {} : { startsAt: entry.startsAt },
|
|
@@ -4220,6 +4445,13 @@ function populateLore(session, definitions) {
|
|
|
4220
4445
|
subjects: entry.subjects.map(subject),
|
|
4221
4446
|
related: entry.related.map((id) => session.lore.getBySourceId(id).id)
|
|
4222
4447
|
});
|
|
4448
|
+
for (const entry of definitions) {
|
|
4449
|
+
const lore = session.lore.getBySourceId(entry.id);
|
|
4450
|
+
for (const reference of entry.knownBy) {
|
|
4451
|
+
const knower = session.characters.getBySourceId(reference) ?? session.characters.findByName(reference)[0];
|
|
4452
|
+
if (knower !== void 0) session.knowledge.learn(knower.id, "lore", lore.id, 0);
|
|
4453
|
+
}
|
|
4454
|
+
}
|
|
4223
4455
|
}
|
|
4224
4456
|
/** What is wrong with where the characters start, found before anything is created. */
|
|
4225
4457
|
function startingPlaceProblems(characters, locations) {
|
|
@@ -5712,61 +5944,6 @@ function importHooks(ctx, worlds, prompting) {
|
|
|
5712
5944
|
});
|
|
5713
5945
|
}
|
|
5714
5946
|
//#endregion
|
|
5715
|
-
|
|
5716
|
-
/** The older preset layout keeps its texts under fixed keys. */
|
|
5717
|
-
const LEGACY_KEYS = [
|
|
5718
|
-
"main_prompt",
|
|
5719
|
-
"nsfw_prompt",
|
|
5720
|
-
"jailbreak_prompt",
|
|
5721
|
-
"impersonation_prompt",
|
|
5722
|
-
"new_chat_prompt",
|
|
5723
|
-
"new_group_chat_prompt",
|
|
5724
|
-
"new_example_chat_prompt"
|
|
5725
|
-
];
|
|
5726
|
-
const MAX_PIECES = 60;
|
|
5727
|
-
const MAX_PIECE_CHARS = 8e3;
|
|
5728
|
-
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
5729
|
-
const text = (value) => typeof value === "string" ? value.trim() : "";
|
|
5730
|
-
/** The order the preset sends its prompts in: the longest list it gives, with what each entry says about being on. */
|
|
5731
|
-
function orderOf(root) {
|
|
5732
|
-
return ((Array.isArray(root["prompt_order"]) ? root["prompt_order"].flatMap((entry) => isObject(entry) && Array.isArray(entry["order"]) ? [entry["order"]] : []) : []).sort((a, b) => b.length - a.length)[0] ?? []).flatMap((entry) => isObject(entry) && typeof entry["identifier"] === "string" ? [{
|
|
5733
|
-
identifier: entry["identifier"],
|
|
5734
|
-
enabled: entry["enabled"] !== false
|
|
5735
|
-
}] : []);
|
|
5736
|
-
}
|
|
5737
|
-
/**
|
|
5738
|
-
* Reads a preset file. Markers (places where chat history or the card's fields are inserted), switched-off prompts and empty ones are left out.
|
|
5739
|
-
* @throws {ImportCardError} when the file is not a preset, with why.
|
|
5740
|
-
*/
|
|
5741
|
-
function readPreset(file, name) {
|
|
5742
|
-
let root;
|
|
5743
|
-
try {
|
|
5744
|
-
root = JSON.parse(file.toString("utf8").replace(/^/, ""));
|
|
5745
|
-
} catch {
|
|
5746
|
-
throw new ImportCardError("the file is not JSON: a preset is the .json file SillyTavern exports");
|
|
5747
|
-
}
|
|
5748
|
-
if (!isObject(root)) throw new ImportCardError("the file is not a preset: it must be a JSON object");
|
|
5749
|
-
const pieces = [];
|
|
5750
|
-
const prompts = Array.isArray(root["prompts"]) ? root["prompts"].filter(isObject) : [];
|
|
5751
|
-
if (prompts.length > 0) {
|
|
5752
|
-
const byId = new Map(prompts.flatMap((prompt) => typeof prompt["identifier"] === "string" ? [[prompt["identifier"], prompt]] : []));
|
|
5753
|
-
const ordered = orderOf(root);
|
|
5754
|
-
const chosen = ordered.length > 0 ? ordered.flatMap((entry) => entry.enabled && byId.has(entry.identifier) ? [byId.get(entry.identifier)] : []) : prompts.filter((prompt) => prompt["enabled"] !== false);
|
|
5755
|
-
for (const prompt of chosen) {
|
|
5756
|
-
const content = text(prompt["content"]);
|
|
5757
|
-
if (prompt["marker"] === true || content === "") continue;
|
|
5758
|
-
const title = text(prompt["name"]);
|
|
5759
|
-
pieces.push(`${title === "" ? "" : `[${title}]\n`}${content.slice(0, MAX_PIECE_CHARS)}`);
|
|
5760
|
-
}
|
|
5761
|
-
} else for (const key of LEGACY_KEYS) if (text(root[key]) !== "") pieces.push(`[${key}]\n${text(root[key]).slice(0, MAX_PIECE_CHARS)}`);
|
|
5762
|
-
if (pieces.length === 0) throw new ImportCardError("the file holds no instructions this importer can read: a preset has a \"prompts\" list with texts in it");
|
|
5763
|
-
const title = text(root["name"]) || text(root["preset_name"]);
|
|
5764
|
-
return {
|
|
5765
|
-
name: title === "" ? name.replace(/\.json$/i, "") : title,
|
|
5766
|
-
pieces: pieces.slice(0, MAX_PIECES)
|
|
5767
|
-
};
|
|
5768
|
-
}
|
|
5769
|
-
//#endregion
|
|
5770
|
-
export { LOCATION_FILE_NAME as $, parseDiceFile as A, FACTIONS_DIR as B, populateTriggers as C, isPng as Ct, loadTriggers as D, DICE_READINGS as Dt, TRIGGERS_FILE_NAME as E, DICE_COMPARISONS as Et, loadLore as F, extractStyleFrom as G, CHARACTERS_DIR as H, LOCATIONS_DIR as I, loadVariables as J, withPlayer as K, loadLocations as L, loadCalendar as M, parseCalendarFile as N, DICE_FILE_NAME as O, DICE_RESULTS as Ot, LORE_DIR as P, parseLoreFile as Q, ITEMS_DIR as R, populateRoutines as S, ImportCardError as St, routineProblems as T, readCard as Tt, loadCharacters as U, loadFactions as V, subfolders as W, variableProblems as X, parseVariablesFile as Y, LORE_FILE_NAME as Z, populateFactions as _, parseLoreEdit as _t, worldOf as a, CHARACTER_FILE_NAME as at, populateLocations as b, parseThingEdit as bt, isReviewing as c, ImportNotFoundError as ct, vetUrl as d, WORLD_FILE_NAME as dt, parseLocationFile as et, loadValidatedWorld as f, parseWorldFile as ft, populateDice as g, parseFactionEdit as gt, populateClock as h, parseCharacterEdit as ht, importTools as i, parseFactionFile as it, CALENDAR_FILE_NAME as j, loadDice as k, markReady as l, ImportStore as lt, populateCharacters as m, InvalidEditProblems as mt, contextOf as n, parseItemFile as nt, authoredWorldOf as o, parseCharacterFile as ot, populateCalendar as p, parseWorldInfoEdit as pt, VARIABLES_FILE_NAME as q, importHooks as r, FACTION_FILE_NAME as rt, authoringChatSessionId as s, IMPORT_FOLDER as st, readPreset as t, ITEM_FILE_NAME as tt, guardedLookup as u, parseChoices as ut, populateItems as v, parsePlaceEdit as vt, populateVariables as w, pictureOf as wt, populateLore as x, IMPORT_COMMAND as xt, populateKnowledge as y, parseRelationEdit as yt, loadItems as z };
|
|
5947
|
+
export { parseItemFile as $, parseDiceFile as A, parseFactionEdit as At, CHARACTERS_DIR as B, LORE_KINDS as Bt, populateTriggers as C, LORE_DIR as Ct, loadTriggers as D, subfolders as Dt, TRIGGERS_FILE_NAME as E, parseLoreFile as Et, loadLocations as F, IMPORT_COMMAND as Ft, withPlayer as G, extractStyleFrom as H, DICE_COMPARISONS as Ht, ITEMS_DIR as I, ImportCardError as It, parseVariablesFile as J, VARIABLES_FILE_NAME as K, loadItems as L, isPng as Lt, loadCalendar as M, parsePlaceEdit as Mt, parseCalendarFile as N, parseRelationEdit as Nt, DICE_FILE_NAME as O, InvalidEditProblems as Ot, LOCATIONS_DIR as P, parseThingEdit as Pt, ITEM_FILE_NAME as Q, FACTIONS_DIR as R, pictureOf as Rt, populateRoutines as S, writeLorebookEntry as St, routineProblems as T, LORE_FILE_NAME as Tt, cleanText as U, DICE_READINGS as Ut, loadCharacters as V, LORE_SCOPES as Vt, partsOf as W, DICE_RESULTS as Wt, LOCATION_FILE_NAME as X, variableProblems as Y, parseLocationFile as Z, populateFactions as _, loadLorebook as _t, authoredWorldOf as a, ImportNotFoundError as at, populateLocations as b, reserveLorebook as bt, markReady as c, WORLD_FILE_NAME as ct, loadValidatedWorld as d, createLorebook as dt, FACTION_FILE_NAME as et, knowsCharacter as f, deleteLorebook as ft, populateDice as g, listLorebooks as gt, populateClock as h, isLorebookName as ht, worldOf as i, IMPORT_FOLDER as it, CALENDAR_FILE_NAME as j, parseLoreEdit as jt, loadDice as k, parseCharacterEdit as kt, guardedLookup as l, parseWorldFile as lt, populateCharacters as m, entriesOf as mt, importHooks as n, CHARACTER_FILE_NAME as nt, authoringChatSessionId as o, ImportStore as ot, populateCalendar as p, deleteLorebookEntry as pt, loadVariables as q, importTools as r, parseCharacterFile as rt, isReviewing as s, parseChoices as st, contextOf as t, parseFactionFile as tt, vetUrl as u, parseWorldInfoEdit as ut, populateItems as v, lorebookDirectory as vt, populateVariables as w, loadLore as wt, populateLore as x, updateLorebookInfo as xt, populateKnowledge as y, readLorebook as yt, loadFactions as z, readCard as zt };
|
|
5771
5948
|
|
|
5772
|
-
//# sourceMappingURL=
|
|
5949
|
+
//# sourceMappingURL=tools-Dy1fgP6B.js.map
|