@dsh-agentic-roleplay/core 0.3.4 → 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.
Files changed (40) hide show
  1. package/lib/authoring.js +5 -3
  2. package/lib/client.js +3260 -493
  3. package/lib/client.js.map +1 -1
  4. package/lib/{deliver-CpZOxBX5.js → deliver-BBgciEEK.js} +3 -2
  5. package/lib/doctor.js +3 -3
  6. package/lib/{gallery-CtFDL22W.js → gallery-DIEgETzU.js} +2 -2
  7. package/lib/generator-DJ48HxPI.js +145 -0
  8. package/lib/{hooks-KTCR3fNJ.js → hooks-DkwFGtNH.js} +3 -3
  9. package/lib/images.js +4 -3
  10. package/lib/index.js +889 -52
  11. package/lib/language-BgyxtB2h.js +38 -0
  12. package/lib/{generator-B6FxlKOV.js → library-9JB9zw5a.js} +2 -143
  13. package/lib/{language-DWVwi1R7.js → load-CVwJjIJ5.js} +11 -45
  14. package/lib/lorebook-author-tools-Bj31z1cu.js +619 -0
  15. package/lib/lorebook-authoring.js +67 -0
  16. package/lib/orchestration.js +22 -14
  17. package/lib/pack-jail-2XztyYAX.js +1980 -0
  18. package/lib/{packs-BYjrAen6.js → packs-xHRCcGdb.js} +3 -29
  19. package/lib/{presenter-agent-CiEVKcjJ.js → presenter-agent-DnNEG_Mn.js} +4 -3
  20. package/lib/preset-D0FMSeZ9.js +59 -0
  21. package/lib/preset-author-tools-BxycmoAr.js +276 -0
  22. package/lib/preset-authoring.js +53 -0
  23. package/lib/presets-gkBWAiVb.js +374 -0
  24. package/lib/{reflection-waxFg1x-.js → reflection-q0UpwXlx.js} +130 -8
  25. package/lib/{pack-jail-CybSNzxr.js → tools-Dy1fgP6B.js} +454 -2303
  26. package/package.json +4 -2
  27. package/prompts/en/import/lorebook.md +7 -0
  28. package/prompts/en/lorebook/persona.md +1 -0
  29. package/prompts/en/lorebook/procedure.md +1 -0
  30. package/prompts/en/lorebook/welcome.md +1 -0
  31. package/prompts/en/preset/persona.md +1 -0
  32. package/prompts/en/preset/procedure.md +1 -0
  33. package/prompts/en/preset/welcome.md +1 -0
  34. package/prompts/zh/import/lorebook.md +7 -0
  35. package/prompts/zh/lorebook/persona.md +1 -0
  36. package/prompts/zh/lorebook/procedure.md +1 -0
  37. package/prompts/zh/lorebook/welcome.md +1 -0
  38. package/prompts/zh/preset/persona.md +1 -0
  39. package/prompts/zh/preset/procedure.md +1 -0
  40. package/prompts/zh/preset/welcome.md +1 -0
@@ -1,15 +1,15 @@
1
- import { _ as API_PREFIX, a as packIds, b as INTENT_TYPES, d as packPath, f as readPack, h as PACK_MEDIA_TYPES, l as isPackId, v as INTENT_HORIZONS, y as INTENT_STATUSES } from "./packs-BYjrAen6.js";
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 { E as InvalidWorldError, S as shippedPromptsDirectory, b as promptProblem, c as parsePlotsFile, d as errorMessage, f as Reader, i as textLanguage, l as plotReferenceProblems, m as PROMPTS_FOLDER, n as STORY_LANGUAGES, o as PLOTS_FILE_NAME, p as formatIssue, r as isStoryLanguage, s as loadPlots, t as LANGUAGE_NAMES, u as readDocument, v as languageOf, x as shippedLanguages, y as listFiles } from "./language-DWVwi1R7.js";
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
- import { C as norm, S as mapLimit, T as uniqueKey, a as uploadReferenceImage, h as MEDIA_TYPES, o as addToLibrary, p as referenceImagePath, s as imageExtensionOf, t as generateReferenceImage, w as slug, y as writeImageFileMetadata } from "./generator-B6FxlKOV.js";
6
- import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
7
- import { existsSync, lstatSync, readFileSync, readdirSync, statSync } from "node:fs";
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
+ import { dirname, join } from "node:path";
7
+ import { existsSync, readFileSync } from "node:fs";
8
8
  import { createHash, randomUUID } from "node:crypto";
9
9
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
10
10
  import { inflateSync } from "node:zlib";
11
11
  import { defineTool } from "@deepseek-ai/dsh-tools";
12
- import { chmod, cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
12
+ import { cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
13
13
  import { MAX_ROUTINE_WINDOWS, MINUTE, MONTH_NAMES, SEASONS, checkProblems, createSessionStore, dayTokenProblems, isTimeZone, parseInstant, parseTimeOfDay, readTriggerDefinition, triggerReferenceProblems, valueIssue, writeCalendar } from "@dsh-agentic-roleplay/state";
14
14
  import { lookup } from "node:dns";
15
15
  import { request } from "node:http";
@@ -147,6 +147,8 @@ const LORE_KINDS = [
147
147
  "legend",
148
148
  "other"
149
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"];
150
152
  const LORE_SUBJECT_KINDS = [
151
153
  "character",
152
154
  "faction",
@@ -192,7 +194,7 @@ function chunksOf(file) {
192
194
  return chunks;
193
195
  }
194
196
  /** The keyword and text of a PNG text chunk. */
195
- function textOf$1(chunk) {
197
+ function textOf(chunk) {
196
198
  const end = chunk.data.indexOf(0);
197
199
  if (end < 0) return void 0;
198
200
  const keyword = chunk.data.toString("latin1", 0, end);
@@ -224,7 +226,7 @@ function jsonOf(file, name) {
224
226
  const found = /* @__PURE__ */ new Map();
225
227
  for (const chunk of chunksOf(file)) {
226
228
  if (!TEXT_CHUNKS.has(chunk.type)) continue;
227
- const text = textOf$1(chunk);
229
+ const text = textOf(chunk);
228
230
  if (text !== void 0 && CARD_KEYWORDS.includes(text.keyword) && !found.has(text.keyword)) found.set(text.keyword, text.text);
229
231
  }
230
232
  const keyword = CARD_KEYWORDS.find((candidate) => found.has(candidate));
@@ -257,19 +259,19 @@ function urlsOf(value) {
257
259
  visit(value, 0);
258
260
  return [...found];
259
261
  }
260
- const object$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
261
- const text$2 = (value) => typeof value === "string" ? value : typeof value === "number" ? String(value) : "";
262
+ const object = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
263
+ const text$1 = (value) => typeof value === "string" ? value : typeof value === "number" ? String(value) : "";
262
264
  const texts = (value) => Array.isArray(value) ? value.flatMap((entry) => typeof entry === "string" ? [entry] : typeof entry === "number" ? [String(entry)] : []) : [];
263
265
  function entryOf(value, index) {
264
- const entry = object$1(value);
266
+ const entry = object(value);
265
267
  if (entry === void 0) return void 0;
266
268
  const position = entry["position"];
267
269
  return {
268
270
  id: `entry:${index}`,
269
- title: text$2(entry["comment"]).trim() || text$2(entry["name"]).trim(),
271
+ title: text$1(entry["comment"]).trim() || text$1(entry["name"]).trim(),
270
272
  keys: texts(entry["keys"]),
271
273
  secondaryKeys: texts(entry["secondary_keys"]),
272
- content: text$2(entry["content"]),
274
+ content: text$1(entry["content"]),
273
275
  enabled: entry["enabled"] !== false,
274
276
  constant: entry["constant"] === true,
275
277
  selective: entry["selective"] === true,
@@ -282,35 +284,35 @@ function entryOf(value, index) {
282
284
  * @throws {ImportCardError} when the file is not such a card.
283
285
  */
284
286
  function readCard(file, name) {
285
- const root = object$1(jsonOf(file, name));
287
+ const root = object(jsonOf(file, name));
286
288
  const spec = root === void 0 ? void 0 : root["spec"];
287
- 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$2(spec)}" card: only V2 and V3 cards are read`);
288
- const data = object$1(root?.["data"]);
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`);
290
+ const data = object(root?.["data"]);
289
291
  if (data === void 0) throw new ImportCardError(`${name} has no card data`);
290
- const cardName = text$2(data["name"]).trim();
292
+ const cardName = text$1(data["name"]).trim();
291
293
  if (cardName === "") throw new ImportCardError(`${name} has a card with no name`);
292
- const book = object$1(data["character_book"]);
294
+ const book = object(data["character_book"]);
293
295
  const entries = Array.isArray(book?.["entries"]) ? book["entries"].flatMap((entry, index) => entryOf(entry, index) ?? []) : [];
294
- const extensions = object$1(data["extensions"]) ?? {};
295
- const scripts = [extensions["regex_scripts"], object$1(extensions["tavern_helper"])?.["scripts"]].reduce((count, list) => count + (Array.isArray(list) ? list.length : 0), 0);
296
+ const extensions = object(data["extensions"]) ?? {};
297
+ const scripts = [extensions["regex_scripts"], object(extensions["tavern_helper"])?.["scripts"]].reduce((count, list) => count + (Array.isArray(list) ? list.length : 0), 0);
296
298
  return {
297
299
  sourceSpec: spec,
298
300
  name: cardName,
299
- description: text$2(data["description"]),
300
- personality: text$2(data["personality"]),
301
- scenario: text$2(data["scenario"]),
302
- firstMessage: text$2(data["first_mes"]),
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"]),
303
305
  alternateGreetings: texts(data["alternate_greetings"]),
304
- messageExample: text$2(data["mes_example"]),
305
- creatorNotes: text$2(data["creator_notes"]),
306
- systemPrompt: text$2(data["system_prompt"]),
307
- postHistoryInstructions: text$2(data["post_history_instructions"]),
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"]),
308
310
  tags: texts(data["tags"]),
309
- creator: text$2(data["creator"]),
310
- characterVersion: text$2(data["character_version"]),
311
+ creator: text$1(data["creator"]),
312
+ characterVersion: text$1(data["character_version"]),
311
313
  ...book === void 0 ? {} : { book: {
312
- name: text$2(book["name"]),
313
- description: text$2(book["description"]),
314
+ name: text$1(book["name"]),
315
+ description: text$1(book["description"]),
314
316
  entries
315
317
  } },
316
318
  ignored: {
@@ -896,6 +898,326 @@ function readIdentifier(reader, fallback) {
896
898
  if (id !== void 0 && id.length > 100) reader.fail("id", `must be at most 100 characters`);
897
899
  return id;
898
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
+ }
899
1221
  const MAX_OPENING_CHARS = 2e4;
900
1222
  const TEXT_FIELDS = [
901
1223
  "name",
@@ -905,9 +1227,14 @@ const TEXT_FIELDS = [
905
1227
  "authorUrl",
906
1228
  "timeZone",
907
1229
  "startingTime",
908
- "version"
1230
+ "version",
1231
+ "preset"
1232
+ ];
1233
+ const LIST_FIELDS = [
1234
+ "tags",
1235
+ "rules",
1236
+ "lorebooks"
909
1237
  ];
910
- const LIST_FIELDS = ["tags", "rules"];
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 = [];
@@ -1084,6 +1411,10 @@ function parseWorldFile(text) {
1084
1411
  const tools = readTools(reader);
1085
1412
  const alternateOpenings = readAlternateOpenings(reader);
1086
1413
  const narrationVoice = reader.string("narration_voice")?.trim() || void 0;
1414
+ const preset = reader.string("preset")?.trim() || void 0;
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 \"_\"");
1087
1418
  if (name === void 0 || issues.length > 0) return {
1088
1419
  ok: false,
1089
1420
  issues
@@ -1104,7 +1435,9 @@ function parseWorldFile(text) {
1104
1435
  ...rules === void 0 ? {} : { rules },
1105
1436
  ...tools === void 0 ? {} : { tools },
1106
1437
  ...alternateOpenings === void 0 ? {} : { alternateOpenings },
1107
- ...narrationVoice === void 0 ? {} : { narrationVoice }
1438
+ ...narrationVoice === void 0 ? {} : { narrationVoice },
1439
+ ...preset === void 0 ? {} : { preset },
1440
+ ...lorebooks.length === 0 ? {} : { lorebooks: [...new Set(lorebooks)] }
1108
1441
  }
1109
1442
  };
1110
1443
  }
@@ -1876,59 +2209,6 @@ function parseLocationFile(text, fallbackId) {
1876
2209
  };
1877
2210
  }
1878
2211
  //#endregion
1879
- //#region src/host/lore/lore-file.ts
1880
- const LORE_FILE_NAME = "lore.json";
1881
- function instant(reader, key) {
1882
- const value = reader.string(key);
1883
- if (value === void 0) return void 0;
1884
- const parsed = Date.parse(value);
1885
- if (!Number.isFinite(parsed)) {
1886
- reader.fail(key, "must be an ISO date or date-time");
1887
- return;
1888
- }
1889
- return parsed;
1890
- }
1891
- function parseLoreFile(text, fallbackId) {
1892
- const issues = [];
1893
- const reader = Reader.fromJson(text, issues);
1894
- if (reader === void 0) return {
1895
- ok: false,
1896
- issues
1897
- };
1898
- const id = readIdentifier(reader, fallbackId) ?? fallbackId;
1899
- const title = reader.string("title", { required: true }) ?? "";
1900
- const subjects = reader.objects("subjects").flatMap((entry) => {
1901
- const kind = entry.oneOf("kind", LORE_SUBJECT_KINDS, "lore");
1902
- const subjectId = entry.string("id", { required: true });
1903
- return subjectId === void 0 ? [] : [{
1904
- kind,
1905
- id: subjectId
1906
- }];
1907
- });
1908
- const startsAt = instant(reader, "starts_at");
1909
- const endsAt = instant(reader, "ends_at");
1910
- if (startsAt !== void 0 && endsAt !== void 0 && endsAt < startsAt) reader.fail("ends_at", "must not be before starts_at");
1911
- const value = {
1912
- id,
1913
- title,
1914
- kind: reader.oneOf("kind", LORE_KINDS, "other"),
1915
- summary: reader.text("summary"),
1916
- body: reader.text("body"),
1917
- subjects,
1918
- related: reader.strings("related"),
1919
- sources: reader.strings("sources"),
1920
- ...startsAt === void 0 ? {} : { startsAt },
1921
- ...endsAt === void 0 ? {} : { endsAt }
1922
- };
1923
- return issues.length === 0 ? {
1924
- ok: true,
1925
- value
1926
- } : {
1927
- ok: false,
1928
- issues
1929
- };
1930
- }
1931
- //#endregion
1932
2212
  //#region src/host/variables/load.ts
1933
2213
  const VARIABLES_FILE_NAME = "variables.json";
1934
2214
  function readDefinition(reader) {
@@ -2154,72 +2434,6 @@ function withPlayer(text, name) {
2154
2434
  return text.replace(/\[PLAYER\]|\{\{\s*user\s*\}\}/g, playerWord(text, name));
2155
2435
  }
2156
2436
  //#endregion
2157
- //#region src/host/prompts/world-prompts.ts
2158
- /** The prompts that decide how the story is written and who the models are (prose and persona); every other prompt holds rules of the game. */
2159
- const PROSE_PROMPTS = [
2160
- "roleplay/persona",
2161
- "roleplay/style",
2162
- "roleplay/character-style"
2163
- ];
2164
- function shippedFile(shipped, language, id) {
2165
- return [language, "en"].map((name) => join(shipped, name, `${id}.md`)).find((path) => existsSync(path));
2166
- }
2167
- function fileOf(directory, language, id, shipped) {
2168
- const problem = promptProblem(language, id, "x", shipped);
2169
- if (!id.startsWith("roleplay/")) throw new Error(`"${id}" is not a prompt of the story; the ones that can be carried are listed by list_world_prompts`);
2170
- if (problem !== void 0 && problem.startsWith("there is no prompt")) throw new Error(problem);
2171
- return join(directory, PROMPTS_FOLDER, language, `${id}.md`);
2172
- }
2173
- /** Every prompt of the story, in a language, and whether the world carries its own version. */
2174
- function listWorldPrompts(directory, language, shipped = shippedPromptsDirectory()) {
2175
- const tag = languageOf(language);
2176
- return readdirSync(join(shipped, "en"), { withFileTypes: true }).filter((entry) => entry.isDirectory() && entry.name !== "import" && entry.name !== "world").flatMap((entry) => listFiles(join(shipped, "en", entry.name), `${entry.name}/`)).sort().map((id) => ({
2177
- id,
2178
- kind: PROSE_PROMPTS.includes(id) ? "prose" : "rules",
2179
- carried: existsSync(join(directory, PROMPTS_FOLDER, tag, `${id}.md`))
2180
- }));
2181
- }
2182
- /** A prompt as sessions of the world get it: the world's own version, else the shipped text. */
2183
- function readWorldPrompt(directory, language, id, shipped = shippedPromptsDirectory()) {
2184
- const tag = languageOf(language);
2185
- const own = fileOf(directory, tag, id, shipped);
2186
- if (existsSync(own)) return {
2187
- id,
2188
- language: tag,
2189
- carried: true,
2190
- text: readFileSync(own, "utf8")
2191
- };
2192
- const original = shippedFile(shipped, tag, id);
2193
- return {
2194
- id,
2195
- language: tag,
2196
- carried: false,
2197
- text: original === void 0 ? "" : readFileSync(original, "utf8")
2198
- };
2199
- }
2200
- /** @throws {Error} when the text is not acceptable for the prompt: see `promptProblem`. */
2201
- async function writeWorldPrompt(directory, language, id, text, shipped = shippedPromptsDirectory()) {
2202
- const tag = languageOf(language);
2203
- const file = fileOf(directory, tag, id, shipped);
2204
- const problem = promptProblem(tag, id, text, shipped);
2205
- if (problem !== void 0) throw new Error(problem);
2206
- await mkdir(dirname(file), { recursive: true });
2207
- const temporary = `${file}.tmp`;
2208
- await writeFile(temporary, text.endsWith("\n") ? text : `${text}\n`);
2209
- await rename(temporary, file);
2210
- }
2211
- /** Moves the world's own version into its `.trash`, so sessions use the shipped one again. @returns where it went. */
2212
- async function deleteWorldPrompt(directory, language, id, shipped = shippedPromptsDirectory()) {
2213
- const tag = languageOf(language);
2214
- const file = fileOf(directory, tag, id, shipped);
2215
- if (!existsSync(file)) throw new Error(`the world carries no prompt "${id}" in ${tag}`);
2216
- const aside = join(directory, ".trash", PROMPTS_FOLDER, tag, `${id}.${Date.now()}.md`);
2217
- await mkdir(dirname(aside), { recursive: true });
2218
- await rename(file, aside);
2219
- await rm(dirname(file), { recursive: false }).catch(() => void 0);
2220
- return aside;
2221
- }
2222
- //#endregion
2223
2437
  //#region src/host/import/survey.ts
2224
2438
  const ROLES = [
2225
2439
  "character",
@@ -2579,7 +2793,7 @@ const SOURCE_BUDGET_CHARS = 14e3;
2579
2793
  const MAX_TAGGED = 8;
2580
2794
  const MAX_MENTIONS = 6;
2581
2795
  const MIN_MENTION_CHARS = 2;
2582
- const text$1 = (value) => typeof value === "string" ? value.trim() : "";
2796
+ const text = (value) => typeof value === "string" ? value.trim() : "";
2583
2797
  const list = (value) => Array.isArray(value) ? value.flatMap((entry) => typeof entry === "string" && entry.trim() !== "" ? [entry.trim()] : []) : [];
2584
2798
  const objects = (value) => Array.isArray(value) ? value.filter((entry) => typeof entry === "object" && entry !== null && !Array.isArray(entry)) : [];
2585
2799
  const put = (document, key, value) => {
@@ -2740,7 +2954,7 @@ function characterDocument(entity, answer, roster) {
2740
2954
  "age",
2741
2955
  "gender",
2742
2956
  "pronouns"
2743
- ]) put(document, field, text$1(answer[field]));
2957
+ ]) put(document, field, text(answer[field]));
2744
2958
  const playable = entity.player;
2745
2959
  const group = answer["kind"] === "group" && !playable;
2746
2960
  document["role"] = playable ? "playable" : "npc";
@@ -2751,10 +2965,10 @@ function characterDocument(entity, answer, roster) {
2751
2965
  "personality",
2752
2966
  "background",
2753
2967
  "appearance"
2754
- ]) document[field] = text$1(answer[field]);
2968
+ ]) document[field] = text(answer[field]);
2755
2969
  const speech = typeof answer["speech"] === "object" && answer["speech"] !== null ? answer["speech"] : {};
2756
2970
  document["speech"] = {
2757
- style: text$1(speech["style"]),
2971
+ style: text(speech["style"]),
2758
2972
  examples: list(speech["examples"]).slice(0, 8)
2759
2973
  };
2760
2974
  const start = {};
@@ -2763,17 +2977,17 @@ function characterDocument(entity, answer, roster) {
2763
2977
  ["public_state", "public_state"],
2764
2978
  ["inner_state", "inner_state"],
2765
2979
  ["activity", "activity"]
2766
- ]) put(start, to, text$1(given[from]));
2767
- const place = text$1(given["location"]) === "" ? void 0 : findEntity(roster, text$1(given["location"]), "place");
2768
- if (text$1(given["location"]) !== "" && place === void 0) notes.push(`${entity.name}: the place "${text$1(given["location"])}" is not one of the world's places, so the character starts nowhere`);
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`);
2769
2983
  if (place !== void 0) {
2770
2984
  start["location"] = place.key;
2771
- put(start, "position", text$1(given["position"]));
2985
+ put(start, "position", text(given["position"]));
2772
2986
  }
2773
- const goals = objects(answer["goals"]).filter((goal) => text$1(goal["name"]) !== "").map((goal) => ({
2987
+ const goals = objects(answer["goals"]).filter((goal) => text(goal["name"]) !== "").map((goal) => ({
2774
2988
  type: "agenda",
2775
- name: text$1(goal["name"]),
2776
- ...text$1(goal["description"]) === "" ? {} : { description: text$1(goal["description"]) },
2989
+ name: text(goal["name"]),
2990
+ ...text(goal["description"]) === "" ? {} : { description: text(goal["description"]) },
2777
2991
  status: "active"
2778
2992
  }));
2779
2993
  put(start, "intents", goals);
@@ -2781,17 +2995,17 @@ function characterDocument(entity, answer, roster) {
2781
2995
  const seen = /* @__PURE__ */ new Set([entity.key]);
2782
2996
  const relationships = [];
2783
2997
  for (const relation of objects(answer["relationships"])) {
2784
- const other = findEntity(roster, text$1(relation["with"]), "character");
2998
+ const other = findEntity(roster, text(relation["with"]), "character");
2785
2999
  if (other === void 0) {
2786
- notes.push(`${entity.name}: the relationship with "${text$1(relation["with"])}" names nobody in the world`);
3000
+ notes.push(`${entity.name}: the relationship with "${text(relation["with"])}" names nobody in the world`);
2787
3001
  continue;
2788
3002
  }
2789
- if (seen.has(other.key) || text$1(relation["label"]) === "") continue;
3003
+ if (seen.has(other.key) || text(relation["label"]) === "") continue;
2790
3004
  seen.add(other.key);
2791
3005
  relationships.push({
2792
3006
  to: other.key,
2793
- label: text$1(relation["label"]),
2794
- ...text$1(relation["summary"]) === "" ? {} : { summary: text$1(relation["summary"]) }
3007
+ label: text(relation["label"]),
3008
+ ...text(relation["summary"]) === "" ? {} : { summary: text(relation["summary"]) }
2795
3009
  });
2796
3010
  }
2797
3011
  put(document, "relationships", relationships.slice(0, 60));
@@ -2807,10 +3021,10 @@ function characterDocument(entity, answer, roster) {
2807
3021
  const ways = /* @__PURE__ */ new Set();
2808
3022
  const exits = [];
2809
3023
  for (const way of objects(knows["ways"])) {
2810
- const from = findEntity(roster, text$1(way["from"]), "place");
2811
- const to = findEntity(roster, text$1(way["to"]), "place");
3024
+ const from = findEntity(roster, text(way["from"]), "place");
3025
+ const to = findEntity(roster, text(way["to"]), "place");
2812
3026
  if (from === void 0 || to === void 0 || from.key === to.key) {
2813
- notes.push(`${entity.name}: the way from "${text$1(way["from"])}" to "${text$1(way["to"])}" is not between two places of the world, so they do not know of it`);
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`);
2814
3028
  continue;
2815
3029
  }
2816
3030
  if (ways.has(`${from.key}>${to.key}`)) continue;
@@ -2866,30 +3080,30 @@ function placeDocument(entity, answer, roster) {
2866
3080
  id: entity.key,
2867
3081
  name: entity.name
2868
3082
  };
2869
- put(document, "description", text$1(answer["description"]));
2870
- const named = text$1(answer["parent"]) === "" ? entity.parent : text$1(answer["parent"]);
3083
+ put(document, "description", text(answer["description"]));
3084
+ const named = text(answer["parent"]) === "" ? entity.parent : text(answer["parent"]);
2871
3085
  const parent = named === void 0 ? void 0 : findEntity(roster, named, "place");
2872
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`);
2873
3087
  if (parent !== void 0 && parent.key !== entity.key) document["parent"] = parent.key;
2874
- const features = objects(answer["features"]).filter((feature) => text$1(feature["name"]) !== "").slice(0, 30).map((feature, index) => ({
3088
+ const features = objects(answer["features"]).filter((feature) => text(feature["name"]) !== "").slice(0, 30).map((feature, index) => ({
2875
3089
  id: `feature-${index + 1}`,
2876
- name: text$1(feature["name"]),
2877
- ...text$1(feature["description"]) === "" ? {} : { description: text$1(feature["description"]) }
3090
+ name: text(feature["name"]),
3091
+ ...text(feature["description"]) === "" ? {} : { description: text(feature["description"]) }
2878
3092
  }));
2879
3093
  put(document, "features", features);
2880
3094
  const exits = [];
2881
3095
  const to = /* @__PURE__ */ new Set();
2882
3096
  for (const exit of objects(answer["exits"])) {
2883
- const target = findEntity(roster, text$1(exit["to"]), "place");
3097
+ const target = findEntity(roster, text(exit["to"]), "place");
2884
3098
  if (target === void 0 || target.key === entity.key) {
2885
- notes.push(`${entity.name}: the way to "${text$1(exit["to"])}" leads to no place of the world`);
3099
+ notes.push(`${entity.name}: the way to "${text(exit["to"])}" leads to no place of the world`);
2886
3100
  continue;
2887
3101
  }
2888
3102
  if (to.has(target.key)) continue;
2889
3103
  to.add(target.key);
2890
3104
  exits.push({
2891
3105
  to: target.key,
2892
- ...text$1(exit["description"]) === "" ? {} : { description: text$1(exit["description"]) }
3106
+ ...text(exit["description"]) === "" ? {} : { description: text(exit["description"]) }
2893
3107
  });
2894
3108
  }
2895
3109
  put(document, "exits", exits.slice(0, 30));
@@ -2935,25 +3149,25 @@ function factionDocument(entity, answer, roster) {
2935
3149
  "summary",
2936
3150
  "description",
2937
3151
  "structure"
2938
- ]) put(document, field, text$1(answer[field]));
3152
+ ]) put(document, field, text(answer[field]));
2939
3153
  put(document, "values", list(answer["values"]));
2940
3154
  const start = {};
2941
- put(start, "public_state", text$1(answer["public_state"]));
2942
- put(start, "inner_state", text$1(answer["inner_state"]));
3155
+ put(start, "public_state", text(answer["public_state"]));
3156
+ put(start, "inner_state", text(answer["inner_state"]));
2943
3157
  put(document, "start", Object.keys(start).length === 0 ? void 0 : start);
2944
3158
  const members = [];
2945
3159
  const seen = /* @__PURE__ */ new Set();
2946
3160
  for (const member of objects(answer["members"])) {
2947
- const character = findEntity(roster, text$1(member["character"]), "character");
3161
+ const character = findEntity(roster, text(member["character"]), "character");
2948
3162
  if (character === void 0) {
2949
- notes.push(`${entity.name}: the member "${text$1(member["character"])}" is nobody in the world`);
3163
+ notes.push(`${entity.name}: the member "${text(member["character"])}" is nobody in the world`);
2950
3164
  continue;
2951
3165
  }
2952
3166
  if (seen.has(character.key)) continue;
2953
3167
  seen.add(character.key);
2954
3168
  members.push({
2955
3169
  character: character.key,
2956
- ...text$1(member["role"]) === "" ? {} : { role: text$1(member["role"]) }
3170
+ ...text(member["role"]) === "" ? {} : { role: text(member["role"]) }
2957
3171
  });
2958
3172
  }
2959
3173
  put(document, "members", members);
@@ -2981,11 +3195,11 @@ function thingDocument(entity, answer, roster) {
2981
3195
  name: entity.name,
2982
3196
  unique: true
2983
3197
  };
2984
- put(document, "description", text$1(answer["description"]));
2985
- put(document, "quality", text$1(answer["quality"]));
3198
+ put(document, "description", text(answer["description"]));
3199
+ put(document, "quality", text(answer["quality"]));
2986
3200
  if (answer["notable"] === true) document["notable"] = true;
2987
- const holder = text$1(answer["held_by"]) === "" ? void 0 : findEntity(roster, text$1(answer["held_by"]), "character");
2988
- const place = text$1(answer["location"]) === "" ? void 0 : findEntity(roster, text$1(answer["location"]), "place");
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");
2989
3203
  if (holder !== void 0) document["held_by"] = holder.key;
2990
3204
  else if (place !== void 0) document["location"] = place.key;
2991
3205
  else notes.push(`${entity.name}: it is nowhere in the world and nobody has it, so it is left out`);
@@ -3049,8 +3263,8 @@ const LORE_SUBJECT = {
3049
3263
  };
3050
3264
  function loreDocuments(answer, roster, taken) {
3051
3265
  return objects(answer["entries"]).flatMap((entry) => {
3052
- const title = text$1(entry["title"]);
3053
- const body = text$1(entry["body"]);
3266
+ const title = text(entry["title"]);
3267
+ const body = text(entry["body"]);
3054
3268
  if (title === "" || body === "") return [];
3055
3269
  const notes = [];
3056
3270
  const subjects = [];
@@ -3061,10 +3275,10 @@ function loreDocuments(answer, roster, taken) {
3061
3275
  "place",
3062
3276
  "faction",
3063
3277
  "thing"
3064
- ].includes(text$1(subject["kind"])) ? text$1(subject["kind"]) : void 0;
3065
- const found = kind === void 0 ? void 0 : findEntity(roster, text$1(subject["name"]), kind);
3278
+ ].includes(text(subject["kind"])) ? text(subject["kind"]) : void 0;
3279
+ const found = kind === void 0 ? void 0 : findEntity(roster, text(subject["name"]), kind);
3066
3280
  if (found === void 0) {
3067
- notes.push(`${title}: the subject "${text$1(subject["name"])}" is not in the world`);
3281
+ notes.push(`${title}: the subject "${text(subject["name"])}" is not in the world`);
3068
3282
  continue;
3069
3283
  }
3070
3284
  if (!seen.has(found.key)) {
@@ -3080,7 +3294,7 @@ function loreDocuments(answer, roster, taken) {
3080
3294
  id: uniqueKey(slug(title, "lore"), taken),
3081
3295
  title,
3082
3296
  kind,
3083
- summary: text$1(entry["summary"]),
3297
+ summary: text(entry["summary"]),
3084
3298
  body
3085
3299
  };
3086
3300
  put(document, "subjects", subjects);
@@ -3401,9 +3615,9 @@ async function extractStyleFrom(ctx, name, pieces) {
3401
3615
  persona: ctx.text("import/style", { rules: ctx.text("import/common-rules") }),
3402
3616
  prompt,
3403
3617
  result: STYLE_SCHEMA,
3404
- check: (value) => styleProblem("roleplay/style", text$1(value.narration)) ?? styleProblem("roleplay/character-style", text$1(value.characters))
3618
+ check: (value) => styleProblem("roleplay/style", text(value.narration)) ?? styleProblem("roleplay/character-style", text(value.characters))
3405
3619
  });
3406
- const prompts = [["roleplay/style", text$1(answer.narration)], ["roleplay/character-style", text$1(answer.characters)]].flatMap(([id, body]) => body === "" ? [] : [{
3620
+ const prompts = [["roleplay/style", text(answer.narration)], ["roleplay/character-style", text(answer.characters)]].flatMap(([id, body]) => body === "" ? [] : [{
3407
3621
  id,
3408
3622
  text: body
3409
3623
  }]);
@@ -3539,15 +3753,15 @@ function variableDocuments(answer, roster) {
3539
3753
  const keyOf = (name) => roster.find((entity) => norm(entity.name) === norm(name) || entity.aliases.some((alias) => norm(alias) === norm(name)))?.key;
3540
3754
  const taken = /* @__PURE__ */ new Set();
3541
3755
  return objects(answer["variables"]).map((entry, index) => {
3542
- const base = slug(text$1(entry["key"]) || text$1(entry["name"]), "").replace(/-/g, "_").slice(0, 40);
3756
+ const base = slug(text(entry["key"]) || text(entry["name"]), "").replace(/-/g, "_").slice(0, 40);
3543
3757
  const document = {
3544
3758
  key: uniqueKey(/^[a-z][a-z0-9_]*$/.test(base) ? base : `variable_${index + 1}`, taken),
3545
- name: text$1(entry["name"]),
3546
- kind: text$1(entry["kind"]),
3547
- subject: text$1(entry["subject"])
3759
+ name: text(entry["name"]),
3760
+ kind: text(entry["kind"]),
3761
+ subject: text(entry["subject"])
3548
3762
  };
3549
- put(document, "description", text$1(entry["description"]));
3550
- put(document, "visibility", text$1(entry["visibility"]));
3763
+ put(document, "description", text(entry["description"]));
3764
+ put(document, "visibility", text(entry["visibility"]));
3551
3765
  put(document, "only", list(entry["only"]).flatMap((name) => keyOf(name) ?? []));
3552
3766
  for (const field of ["min", "max"]) if (typeof entry[field] === "number") document[field] = entry[field];
3553
3767
  if (typeof entry["integer"] === "boolean") document["integer"] = entry["integer"];
@@ -3557,9 +3771,9 @@ function variableDocuments(answer, roster) {
3557
3771
  "string"
3558
3772
  ].includes(typeof entry["default"])) document["default"] = entry["default"];
3559
3773
  put(document, "options", list(entry["options"]));
3560
- put(document, "bands", objects(entry["bands"]).filter((band) => typeof band["up_to"] === "number" && text$1(band["label"]) !== "").map((band) => ({
3774
+ put(document, "bands", objects(entry["bands"]).filter((band) => typeof band["up_to"] === "number" && text(band["label"]) !== "").map((band) => ({
3561
3775
  up_to: band["up_to"],
3562
- label: text$1(band["label"])
3776
+ label: text(band["label"])
3563
3777
  })));
3564
3778
  return document;
3565
3779
  });
@@ -3608,20 +3822,6 @@ async function extractVariables(ctx, card, items, classified, roster) {
3608
3822
  }
3609
3823
  }
3610
3824
  //#endregion
3611
- //#region src/host/folders.ts
3612
- /**
3613
- * Names of the subfolders of `dir`, sorted. Symbolic links are not followed
3614
- * and a missing directory has none; any other failure is thrown.
3615
- */
3616
- async function subfolders(dir) {
3617
- try {
3618
- return (await readdir(dir, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort((a, b) => a.localeCompare(b));
3619
- } catch (error) {
3620
- if (error.code === "ENOENT") return [];
3621
- throw error;
3622
- }
3623
- }
3624
- //#endregion
3625
3825
  //#region src/host/characters/load.ts
3626
3826
  const CHARACTERS_DIR = "characters";
3627
3827
  /**
@@ -3948,67 +4148,19 @@ function parentsFirst(locations) {
3948
4148
  return ordered;
3949
4149
  }
3950
4150
  //#endregion
3951
- //#region src/host/lore/load.ts
3952
- const LORE_DIR = "lore";
3953
- async function loadLore(worldDir) {
3954
- const dir = join(worldDir, LORE_DIR);
3955
- const result = {
3956
- lore: [],
3957
- problems: []
3958
- };
3959
- let folders;
3960
- try {
3961
- folders = await subfolders(dir);
3962
- } catch (error) {
3963
- if (error.code !== "ENOENT") result.problems.push({
3964
- path: dir,
3965
- message: errorMessage(error)
3966
- });
3967
- return result;
3968
- }
3969
- const owners = /* @__PURE__ */ new Map();
3970
- for (const folder of folders) {
3971
- const file = join(dir, folder, LORE_FILE_NAME);
3972
- try {
3973
- const entry = await readDocument(file, (text) => parseLoreFile(text, folder), result.problems);
3974
- if (entry === void 0) continue;
3975
- const owner = owners.get(entry.id);
3976
- if (owner !== void 0) {
3977
- result.problems.push({
3978
- path: file,
3979
- message: `id "${entry.id}" is already used by ${owner}`
3980
- });
3981
- continue;
3982
- }
3983
- owners.set(entry.id, folder);
3984
- result.lore.push(entry);
3985
- } catch (error) {
3986
- if (error.code !== "ENOENT") result.problems.push({
3987
- path: file,
3988
- message: errorMessage(error)
3989
- });
3990
- }
3991
- }
3992
- if (result.lore.length > 500) result.problems.push({
3993
- path: dir,
3994
- message: `a world has at most 500 lore entries`
3995
- });
3996
- return result;
3997
- }
3998
- //#endregion
3999
- //#region src/host/calendar/load.ts
4000
- const CALENDAR_FILE_NAME = "calendar.json";
4001
- const HOLIDAY_ID = /^[\p{L}\p{N}][\p{L}\p{N}_-]{0,59}$/u;
4002
- /**
4003
- * Read `calendar.json`: the holidays of the world and the hemisphere its seasons follow (docs/world-format.md). A holiday is told by days (`12-25`,
4004
- * `09-21..09-22`, `nth:mon:1`, `season:winter`, a month, a weekday); it cannot name another holiday.
4005
- */
4006
- function parseCalendarFile(text) {
4007
- const issues = [];
4008
- const reader = Reader.fromJson(text, issues);
4009
- if (reader === void 0) return {
4010
- ok: false,
4011
- issues
4151
+ //#region src/host/calendar/load.ts
4152
+ const CALENDAR_FILE_NAME = "calendar.json";
4153
+ const HOLIDAY_ID = /^[\p{L}\p{N}][\p{L}\p{N}_-]{0,59}$/u;
4154
+ /**
4155
+ * Read `calendar.json`: the holidays of the world and the hemisphere its seasons follow (docs/world-format.md). A holiday is told by days (`12-25`,
4156
+ * `09-21..09-22`, `nth:mon:1`, `season:winter`, a month, a weekday); it cannot name another holiday.
4157
+ */
4158
+ function parseCalendarFile(text) {
4159
+ const issues = [];
4160
+ const reader = Reader.fromJson(text, issues);
4161
+ if (reader === void 0) return {
4162
+ ok: false,
4163
+ issues
4012
4164
  };
4013
4165
  const hemisphere = reader.oneOf("hemisphere", ["north", "south"], "north");
4014
4166
  const seen = /* @__PURE__ */ new Set();
@@ -4252,6 +4404,11 @@ function knowledgeProblems(characters, locations, items, lore = []) {
4252
4404
  ];
4253
4405
  });
4254
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
+ }
4255
4412
  function loreProblems(lore, world) {
4256
4413
  const ids = {
4257
4414
  character: new Set(world.characters.map((x) => x.id)),
@@ -4260,13 +4417,18 @@ function loreProblems(lore, world) {
4260
4417
  item: new Set(world.items.map((x) => x.id)),
4261
4418
  lore: new Set(lore.map((x) => x.id))
4262
4419
  };
4263
- return lore.flatMap((entry) => [...entry.subjects.flatMap((subject) => ids[subject.kind].has(subject.id) ? [] : [`${entry.id}: subjects: "${subject.id}" is not a ${subject.kind} of this world`]), ...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`])]);
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
+ ]);
4264
4425
  }
4265
4426
  function populateLore(session, definitions) {
4266
4427
  for (const entry of definitions) session.lore.add({
4267
4428
  sourceId: entry.id,
4268
4429
  title: entry.title,
4269
4430
  kind: entry.kind,
4431
+ scope: entry.scope,
4270
4432
  summary: entry.summary,
4271
4433
  body: entry.body,
4272
4434
  ...entry.startsAt === void 0 ? {} : { startsAt: entry.startsAt },
@@ -4283,6 +4445,13 @@ function populateLore(session, definitions) {
4283
4445
  subjects: entry.subjects.map(subject),
4284
4446
  related: entry.related.map((id) => session.lore.getBySourceId(id).id)
4285
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
+ }
4286
4455
  }
4287
4456
  /** What is wrong with where the characters start, found before anything is created. */
4288
4457
  function startingPlaceProblems(characters, locations) {
@@ -5554,559 +5723,6 @@ async function finish(ctx, world) {
5554
5723
  return result;
5555
5724
  }
5556
5725
  //#endregion
5557
- //#region src/host/translate/terms.ts
5558
- const STOP = /* @__PURE__ */ new Set([
5559
- "the",
5560
- "and",
5561
- "for",
5562
- "with",
5563
- "from",
5564
- "that",
5565
- "this",
5566
- "his",
5567
- "her",
5568
- "their",
5569
- "she",
5570
- "he",
5571
- "they",
5572
- "you",
5573
- "your",
5574
- "but",
5575
- "not",
5576
- "when",
5577
- "where",
5578
- "what",
5579
- "who",
5580
- "one",
5581
- "two",
5582
- "its",
5583
- "has",
5584
- "had",
5585
- "was",
5586
- "were",
5587
- "are",
5588
- "there",
5589
- "then",
5590
- "now",
5591
- "at",
5592
- "in",
5593
- "on",
5594
- "of",
5595
- "to",
5596
- "a",
5597
- "an"
5598
- ]);
5599
- const MAX_TERMS = 40;
5600
- const MIN_USES = 3;
5601
- const capitalised = (word) => /^\p{Lu}[\p{L}'’-]{2,}$/u.test(word) && !STOP.has(word.toLowerCase());
5602
- /** The parts of a name written "Place - Room": each part is a name of its own, and so is the whole. */
5603
- function partsOfName(name) {
5604
- return name.split(/\s+[-–—]\s+/).map((part) => part.trim()).filter((part) => part !== "");
5605
- }
5606
- /**
5607
- * Words of the world that recur inside other names and texts and so have to be rendered once: the parts of names ("Iron Stag Inn" in "Iron Stag Inn - Bar") and capitalised
5608
- * phrases of two or three words that the texts use again and again ("Iron Stag"). The most used come first; names are not repeated here.
5609
- */
5610
- function recurringTerms(names, texts) {
5611
- const known = new Set(names);
5612
- const found = /* @__PURE__ */ new Map();
5613
- const add = (term, uses) => {
5614
- if (!known.has(term)) found.set(term, (found.get(term) ?? 0) + uses);
5615
- };
5616
- for (const name of names) for (const part of partsOfName(name)) if (part !== name) add(part, MIN_USES);
5617
- const counts = /* @__PURE__ */ new Map();
5618
- for (const text of [...names, ...texts]) {
5619
- const words = text.split(/[^\p{L}'’-]+/u);
5620
- for (let at = 0; at < words.length; at += 1) for (const size of [2, 3]) {
5621
- const phrase = words.slice(at, at + size);
5622
- if (phrase.length !== size || !phrase.every((word) => capitalised(word.replace(/['’]s$/, "")))) continue;
5623
- const key = phrase.join(" ").replace(/['’]s$/, "");
5624
- counts.set(key, (counts.get(key) ?? 0) + 1);
5625
- }
5626
- }
5627
- for (const [phrase, uses] of counts) if (uses >= MIN_USES) add(phrase, uses);
5628
- return [...found].sort((a, b) => b[1] - a[1]).slice(0, MAX_TERMS).map(([term]) => term);
5629
- }
5630
- /** Whether `text` uses `term` as a word of its own (case as written). */
5631
- function usesTerm(text, term) {
5632
- const escaped = term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5633
- return new RegExp(`(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`, "u").test(text);
5634
- }
5635
- //#endregion
5636
- //#region src/host/translate/prose.ts
5637
- const rooted = (roots, paths) => roots.flatMap((root) => paths.map((path) => `${root}${path}`));
5638
- const INTENT = [
5639
- ".name",
5640
- ".description",
5641
- ".plan[]",
5642
- ".open_threads[]",
5643
- ".constraints[]"
5644
- ];
5645
- const FIELDS$1 = {
5646
- world: {
5647
- names: ["name"],
5648
- text: [
5649
- "description",
5650
- "rules[]",
5651
- "metadata.tags[]",
5652
- "opening_message",
5653
- "opening_message[].text",
5654
- "alternate_openings[].title",
5655
- "alternate_openings[].text"
5656
- ]
5657
- },
5658
- calendar: {
5659
- names: ["holidays[].name"],
5660
- text: []
5661
- },
5662
- variables: {
5663
- names: [],
5664
- text: rooted(["[]", "variables[]"], [
5665
- ".name",
5666
- ".description",
5667
- ".bands[].label"
5668
- ])
5669
- },
5670
- triggers: {
5671
- names: [],
5672
- text: rooted(["[]", "triggers[]"], [
5673
- ".name",
5674
- ".announce.text",
5675
- ".effects[].text",
5676
- ".effects[].edit.events[].text"
5677
- ])
5678
- },
5679
- plots: {
5680
- names: [],
5681
- text: [
5682
- "plots[].name",
5683
- "plots[].premise",
5684
- "plots[].themes[]",
5685
- "plots[].stakes[]",
5686
- "plots[].resolutions[]",
5687
- ...["hooks", "developments"].flatMap((list) => [
5688
- `plots[].${list}[].text`,
5689
- `plots[].${list}[].prerequisites[]`,
5690
- `plots[].${list}[].guidance`,
5691
- `plots[].${list}[].avoid[]`
5692
- ])
5693
- ]
5694
- },
5695
- character: {
5696
- names: ["name", "aliases[]"],
5697
- text: [
5698
- "age",
5699
- "gender",
5700
- "summary",
5701
- "personality",
5702
- "background",
5703
- "appearance",
5704
- "speech.style",
5705
- "speech.examples[]",
5706
- "start.public_state",
5707
- "start.inner_state",
5708
- "start.activity",
5709
- ...INTENT.map((path) => `start.intents[]${path}`),
5710
- "relationships[].label",
5711
- "relationships[].summary",
5712
- "routine[].activity",
5713
- "visual_identity.description"
5714
- ]
5715
- },
5716
- location: {
5717
- names: ["name", "features[].name"],
5718
- text: [
5719
- "description",
5720
- "features[].description",
5721
- "exits[].description",
5722
- "exits[].note",
5723
- "exits[].back_description",
5724
- "visual_identity.description"
5725
- ]
5726
- },
5727
- item: {
5728
- names: ["name"],
5729
- text: [
5730
- "description",
5731
- "quality",
5732
- "visual_identity.description"
5733
- ]
5734
- },
5735
- faction: {
5736
- names: ["name", "aliases[]"],
5737
- text: [
5738
- "summary",
5739
- "description",
5740
- "values[]",
5741
- "structure",
5742
- "start.public_state",
5743
- "start.inner_state",
5744
- ...INTENT.map((path) => `start.goals[]${path}`),
5745
- "members[].role",
5746
- "members[].rank",
5747
- "relationships[].label",
5748
- "relationships[].summary"
5749
- ]
5750
- },
5751
- lore: {
5752
- names: [],
5753
- text: [
5754
- "title",
5755
- "summary",
5756
- "body"
5757
- ]
5758
- }
5759
- };
5760
- /** The strings of a document that are words for a reader, in document order; strings with no letters need no translation and are left out. */
5761
- function leavesOf(kind, document) {
5762
- const fields = FIELDS$1[kind];
5763
- const names = new Set(fields.names);
5764
- const text = new Set(fields.text);
5765
- const leaves = [];
5766
- const visit = (value, pattern, path) => {
5767
- if (typeof value === "string") {
5768
- const name = names.has(pattern);
5769
- if ((name || text.has(pattern)) && /\p{L}/u.test(value)) leaves.push({
5770
- path,
5771
- text: value,
5772
- name
5773
- });
5774
- } else if (Array.isArray(value)) value.forEach((entry, index) => {
5775
- visit(entry, `${pattern}[]`, [...path, index]);
5776
- });
5777
- else if (typeof value === "object" && value !== null) for (const [key, entry] of Object.entries(value)) visit(entry, pattern === "" ? key : `${pattern}.${key}`, [...path, key]);
5778
- };
5779
- visit(document, "", []);
5780
- return leaves;
5781
- }
5782
- /** Puts `text` where `path` points in the document. */
5783
- function setLeaf(document, path, text) {
5784
- let at = document;
5785
- for (const step of path.slice(0, -1)) at = at[step];
5786
- at[path[path.length - 1]] = text;
5787
- }
5788
- const ROOT_FILES = [
5789
- ["world.json", "world"],
5790
- ["calendar.json", "calendar"],
5791
- ["variables.json", "variables"],
5792
- ["triggers.json", "triggers"],
5793
- ["plots.json", "plots"]
5794
- ];
5795
- const ENTITIES = [
5796
- [
5797
- "characters",
5798
- "character.json",
5799
- "character"
5800
- ],
5801
- [
5802
- "locations",
5803
- "location.json",
5804
- "location"
5805
- ],
5806
- [
5807
- "items",
5808
- "item.json",
5809
- "item"
5810
- ],
5811
- [
5812
- "factions",
5813
- "faction.json",
5814
- "faction"
5815
- ],
5816
- [
5817
- "lore",
5818
- "lore.json",
5819
- "lore"
5820
- ]
5821
- ];
5822
- async function readIfThere(file) {
5823
- try {
5824
- return JSON.parse(await readFile(file, "utf8"));
5825
- } catch (error) {
5826
- if (error.code === "ENOENT") return void 0;
5827
- throw new Error(`${file} cannot be read: ${error instanceof Error ? error.message : String(error)}`);
5828
- }
5829
- }
5830
- /** Every file of a world that holds words for a reader. A file that does not parse stops the read: a world with a broken file is not translated. */
5831
- async function readWorldDocuments(directory) {
5832
- const found = [];
5833
- for (const [file, kind] of ROOT_FILES) {
5834
- const document = await readIfThere(join(directory, file));
5835
- if (document !== void 0) found.push({
5836
- file,
5837
- kind,
5838
- document
5839
- });
5840
- }
5841
- for (const [folder, name, kind] of ENTITIES) {
5842
- let entries;
5843
- try {
5844
- entries = (await readdir(join(directory, folder), { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
5845
- } catch (error) {
5846
- if (error.code === "ENOENT") continue;
5847
- throw error;
5848
- }
5849
- for (const entry of entries) {
5850
- const file = join(folder, entry, name);
5851
- const document = await readIfThere(join(directory, file));
5852
- if (document !== void 0) found.push({
5853
- file,
5854
- kind,
5855
- document
5856
- });
5857
- }
5858
- }
5859
- return found;
5860
- }
5861
- //#endregion
5862
- //#region src/host/translate/translate-world.ts
5863
- /** What is not carried over to a translation: the removed things of the editor and the card import's working files. */
5864
- const NOT_COPIED = /* @__PURE__ */ new Set([".trash", ".import"]);
5865
- const TERMS_PER_JOB = 40;
5866
- const TEXTS_PER_JOB = 30;
5867
- const CHARS_PER_JOB = 5e3;
5868
- const GLOSSARY_SHOWN = 60;
5869
- /** A text with fewer letters than this is too short to check which language it came out in. */
5870
- const CHECKED_LETTERS = 40;
5871
- /** A name shorter than this is too likely to be an ordinary word to be held to the glossary. */
5872
- const MIN_TERM = 4;
5873
- var TranslationRefusedError = class extends Error {};
5874
- const STRINGS = {
5875
- type: "array",
5876
- items: { type: "string" }
5877
- };
5878
- const GLOSSARY_SCHEMA = {
5879
- type: "object",
5880
- properties: { terms: {
5881
- type: "array",
5882
- items: {
5883
- type: "object",
5884
- properties: {
5885
- source: { type: "string" },
5886
- target: { type: "string" }
5887
- },
5888
- required: ["source", "target"],
5889
- additionalProperties: false
5890
- },
5891
- description: "One entry for each name given, in the same order, with the source exactly as given."
5892
- } },
5893
- required: ["terms"],
5894
- additionalProperties: false
5895
- };
5896
- const TEXTS_SCHEMA = {
5897
- type: "object",
5898
- properties: { translations: {
5899
- ...STRINGS,
5900
- description: "The translation of each text, in the order given."
5901
- } },
5902
- required: ["translations"],
5903
- additionalProperties: false
5904
- };
5905
- const BRACED = /\$?\{[^{}]*\}/g;
5906
- const braces = (text) => (text.match(BRACED) ?? []).sort().join("\0");
5907
- const letters = (text) => text.match(/\p{L}/gu)?.length ?? 0;
5908
- /** The language the world is written in, from the words of all its files; nothing when there are too few to tell. */
5909
- function languageOfDocuments(documents) {
5910
- return textLanguage(documents.flatMap((entry) => leavesOf(entry.kind, entry.document).map((leaf) => leaf.text)).join("\n"));
5911
- }
5912
- function batches(items, size, maxItems, maxSize) {
5913
- const out = [];
5914
- let current = [];
5915
- let used = 0;
5916
- for (const item of items) {
5917
- if (current.length > 0 && (current.length >= maxItems || used + size(item) > maxSize)) {
5918
- out.push(current);
5919
- current = [];
5920
- used = 0;
5921
- }
5922
- current.push(item);
5923
- used += size(item);
5924
- }
5925
- if (current.length > 0) out.push(current);
5926
- return out;
5927
- }
5928
- /** Why a set of translations cannot be used, or nothing. A text left in the language it was written in is not a translation. */
5929
- function problemWith(sources, from, translations, glossary) {
5930
- if (translations.length !== sources.length) return `${sources.length} texts were given and ${translations.length} translations came back: give exactly one for each, in order`;
5931
- for (const [index, source] of sources.entries()) {
5932
- const text = translations[index];
5933
- if (text.trim() === "") return `translation ${index + 1} is empty`;
5934
- if (braces(source) !== braces(text)) return `translation ${index + 1} must keep the text in curly braces exactly as it is: ${(source.match(BRACED) ?? []).join(" ")}`;
5935
- if (letters(source) >= CHECKED_LETTERS && textLanguage(source) === from && textLanguage(text) === from) return `translation ${index + 1} is still in the original language`;
5936
- for (const [term, rendering] of glossary) if (term.length >= MIN_TERM && rendering !== term && !rendering.includes(term) && usesTerm(source, term) && usesTerm(text, term)) return `translation ${index + 1} still has "${term}": the glossary renders it "${rendering}"`;
5937
- }
5938
- }
5939
- async function glossaryOf(ctx, names, vars, known = /* @__PURE__ */ new Map()) {
5940
- const jobs = batches(names, () => 1, TERMS_PER_JOB, TERMS_PER_JOB);
5941
- const parts = await mapLimit(jobs, ctx.concurrency, async (terms) => {
5942
- const job = {
5943
- persona: ctx.text("translate/glossary", vars),
5944
- prompt: JSON.stringify({
5945
- known: Object.fromEntries([...known].filter(([source]) => terms.some((term) => term.toLowerCase().includes(source.toLowerCase())))),
5946
- names: terms
5947
- }),
5948
- result: GLOSSARY_SCHEMA,
5949
- check: (value) => {
5950
- if (value.terms.length !== terms.length) return `${terms.length} names were given and ${value.terms.length} came back: one for each, in order`;
5951
- const wrong = terms.findIndex((term, index) => value.terms[index].source !== term || value.terms[index].target.trim() === "");
5952
- return wrong === -1 ? void 0 : `entry ${wrong + 1} must repeat "${terms[wrong]}" exactly and have a translation`;
5953
- }
5954
- };
5955
- return (await ctx.run(job)).terms;
5956
- });
5957
- return new Map(parts.flat().map((term) => [term.source, term.target.trim()]));
5958
- }
5959
- async function translated(ctx, texts, glossary, from, vars) {
5960
- return (await mapLimit(batches(texts, (text) => text.length, TEXTS_PER_JOB, CHARS_PER_JOB), ctx.concurrency, async (group) => {
5961
- const haystack = group.join("\n").toLowerCase();
5962
- const shown = [...glossary].filter(([source]) => haystack.includes(source.toLowerCase())).slice(0, GLOSSARY_SHOWN);
5963
- const relevant = new Map(shown);
5964
- const job = {
5965
- persona: ctx.text("translate/document", vars),
5966
- prompt: JSON.stringify({
5967
- glossary: Object.fromEntries(shown),
5968
- texts: group.map((text, index) => ({
5969
- n: index + 1,
5970
- text
5971
- }))
5972
- }),
5973
- result: TEXTS_SCHEMA,
5974
- check: (value) => problemWith(group, from, value.translations, relevant)
5975
- };
5976
- return (await ctx.run(job)).translations;
5977
- })).flat();
5978
- }
5979
- async function freeFolder(directory, suffix) {
5980
- for (let n = 1;; n += 1) {
5981
- const candidate = join(dirname(directory), `${basename(directory)} ${suffix}${n === 1 ? "" : ` ${n}`}`);
5982
- try {
5983
- await stat(candidate);
5984
- } catch (error) {
5985
- if (error.code === "ENOENT") return candidate;
5986
- throw error;
5987
- }
5988
- }
5989
- }
5990
- /** The ids of the Markdown prompt files under a world's prompt folder for one language (`roleplay/style`), or none when it has none. */
5991
- async function promptIds(folder, prefix = "") {
5992
- let entries;
5993
- try {
5994
- entries = await readdir(join(folder, prefix), { withFileTypes: true });
5995
- } catch (error) {
5996
- if (error.code === "ENOENT") return [];
5997
- throw error;
5998
- }
5999
- const ids = [];
6000
- for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
6001
- const id = prefix === "" ? entry.name : `${prefix}/${entry.name}`;
6002
- if (entry.isDirectory()) ids.push(...await promptIds(folder, id));
6003
- else if (entry.isFile() && entry.name.endsWith(".md")) ids.push(id.slice(0, -3));
6004
- }
6005
- return ids;
6006
- }
6007
- async function listedIn(directory, names) {
6008
- const present = new Set(await readdir(directory));
6009
- return names.filter((name) => present.has(name));
6010
- }
6011
- /**
6012
- * Makes a copy of a world in another language, next to it: the names first, so that every file calls each person, place and thing the same, then the words of each file.
6013
- * The original is never changed. The copy gets an id of its own and is checked as a story start would check it.
6014
- */
6015
- async function translateWorld(ctx, worlds, source, to, told) {
6016
- const documents = await readWorldDocuments(source.directory);
6017
- const from = languageOfDocuments(documents);
6018
- if (from === void 0) throw new TranslationRefusedError("there is too little text in this world to tell which language it is written in");
6019
- if (from === to) throw new TranslationRefusedError(`this world is already written in ${LANGUAGE_NAMES[to].en}`);
6020
- const vars = {
6021
- from: LANGUAGE_NAMES[from][told],
6022
- to: LANGUAGE_NAMES[to][told]
6023
- };
6024
- const leaves = documents.map((entry) => ({
6025
- entry,
6026
- leaves: leavesOf(entry.kind, entry.document)
6027
- }));
6028
- const names = [...new Set(leaves.flatMap((item) => item.leaves.filter((leaf) => leaf.name).map((leaf) => leaf.text)))];
6029
- ctx.say(`translating ${names.length} names`);
6030
- const prose = leaves.flatMap((item) => item.leaves.filter((leaf) => !leaf.name).map((leaf) => leaf.text));
6031
- const recurring = from === "en" ? recurringTerms(names, prose) : [];
6032
- const parts = await glossaryOf(ctx, recurring, vars);
6033
- const glossary = await glossaryOf(ctx, names, vars, parts);
6034
- for (const [term, rendering] of parts) glossary.set(term, rendering);
6035
- let texts = 0;
6036
- for (const { entry, leaves: own } of leaves) {
6037
- const words = own.filter((leaf) => !leaf.name);
6038
- for (const leaf of own.filter((item) => item.name)) setLeaf(entry.document, leaf.path, glossary.get(leaf.text) ?? leaf.text);
6039
- if (words.length === 0) continue;
6040
- ctx.say(`translating ${entry.file}`);
6041
- const result = await translated(ctx, words.map((leaf) => leaf.text), glossary, from, vars);
6042
- for (const [index, leaf] of words.entries()) setLeaf(entry.document, leaf.path, result[index]);
6043
- texts += words.length;
6044
- }
6045
- for (const { entry, leaves: own } of leaves) {
6046
- const document = entry.document;
6047
- if (entry.kind !== "character" && entry.kind !== "faction") continue;
6048
- const original = own.find((leaf) => leaf.name && leaf.path.length === 1 && leaf.path[0] === "name")?.text;
6049
- const aliases = Array.isArray(document["aliases"]) ? document["aliases"] : [];
6050
- if (original !== void 0 && original !== document["name"] && !aliases.includes(original)) document["aliases"] = [...aliases, original];
6051
- }
6052
- const own = await promptIds(join(source.directory, "prompts", from));
6053
- const present = new Set(await promptIds(join(source.directory, "prompts", to)));
6054
- const owed = own.filter((prompt) => !present.has(prompt));
6055
- const written = [];
6056
- if (owed.length > 0) {
6057
- ctx.say(`translating ${owed.length} prompt files`);
6058
- const result = await translated(ctx, await Promise.all(owed.map((prompt) => readFile(join(source.directory, "prompts", from, `${prompt}.md`), "utf8"))), glossary, from, vars);
6059
- for (const [index, prompt] of owed.entries()) written.push({
6060
- id: prompt,
6061
- text: result[index]
6062
- });
6063
- }
6064
- const id = randomUUID();
6065
- const destination = await freeFolder(source.directory, to);
6066
- await cp(source.directory, destination, {
6067
- recursive: true,
6068
- filter: (path) => !NOT_COPIED.has(relative(source.directory, path).split(sep)[0])
6069
- });
6070
- for (const entry of documents) {
6071
- const document = entry.kind === "world" ? (({ id: _old, ...rest }) => ({
6072
- id,
6073
- ...rest
6074
- }))(entry.document) : entry.document;
6075
- await writeFile(join(destination, entry.file), `${JSON.stringify(document, null, 2)}\n`);
6076
- }
6077
- for (const prompt of written) {
6078
- const file = join(destination, "prompts", to, `${prompt.id}.md`);
6079
- await mkdir(dirname(file), { recursive: true });
6080
- await writeFile(file, prompt.text.endsWith("\n") ? prompt.text : `${prompt.text}\n`);
6081
- }
6082
- const payload = await worlds.list({ refresh: true });
6083
- const made = payload.worlds.find((world) => world.id === id);
6084
- if (made === void 0) throw new Error(`the translated world was written to ${destination} but the catalogue does not list it: ${payload.problems.map((problem) => problem.message).join("; ")}`);
6085
- const record = await worlds.find(id);
6086
- const problems = [];
6087
- if (record !== void 0) try {
6088
- await loadValidatedWorld(record);
6089
- } catch (error) {
6090
- if (!(error instanceof InvalidWorldError)) throw error;
6091
- problems.push(...error.problems.map((problem) => `${relative(destination, problem.path) || "."}: ${problem.message}`));
6092
- }
6093
- return {
6094
- worldId: id,
6095
- name: made.name,
6096
- folder: basename(destination),
6097
- documents: documents.length,
6098
- texts,
6099
- names: names.length + recurring.length,
6100
- problems,
6101
- prompts: written.map((prompt) => prompt.id),
6102
- copiedAsIs: await listedIn(source.directory, [
6103
- "ui",
6104
- "images",
6105
- "media"
6106
- ])
6107
- };
6108
- }
6109
- //#endregion
6110
5726
  //#region src/shared/authoring-chat.ts
6111
5727
  const PREFIX = "world-author-";
6112
5728
  /** Stable DSH chat identity for the authoring conversation of one world. */
@@ -6328,1471 +5944,6 @@ function importHooks(ctx, worlds, prompting) {
6328
5944
  });
6329
5945
  }
6330
5946
  //#endregion
6331
- //#region src/host/translate/tools.ts
6332
- const TRANSLATE_TOOL = "translate_world";
6333
- /** The message that has the authoring chat translate its world, in the language of the person who asked. */
6334
- function translateMessage(text, to, language) {
6335
- return text("translate/notice", {
6336
- tool: TRANSLATE_TOOL,
6337
- code: to,
6338
- to: to === "zh" ? language === "zh" ? "中文" : "Chinese" : language === "zh" ? "英文" : "English"
6339
- });
6340
- }
6341
- /** The tool of the authoring chat that translates the chat's world into a copy in another language. */
6342
- function translateTools(worlds, settings, prompting) {
6343
- return [defineTool({
6344
- name: TRANSLATE_TOOL,
6345
- description: "Makes a translated copy of this world, next to it, in another language: its names first, so every file calls each person, place and thing the same, then the words of every file. The world itself is not changed. Takes several minutes. Use it only when the person asked for a translation.",
6346
- parameters: { language: {
6347
- type: "string",
6348
- required: true,
6349
- enum: [...STORY_LANGUAGES],
6350
- description: "The language to translate into: en or zh."
6351
- } },
6352
- output: {
6353
- schema: { type: "json" },
6354
- render: (_args, value) => [{
6355
- type: "text",
6356
- text: JSON.stringify(value, null, 1)
6357
- }]
6358
- },
6359
- isConcurrencySafe: () => false,
6360
- async execute(args, exec) {
6361
- if (!isStoryLanguage(args.language)) throw new Error(`language must be one of: ${STORY_LANGUAGES.join(", ")}`);
6362
- const world = await worldOf(worlds, exec);
6363
- const told = prompting.languages().get(world.id);
6364
- const text = (id, variables) => prompting.prompts().text(id, told, variables);
6365
- const report = await translateWorld(contextOf(exec, settings(), text), worlds, world, args.language, told.startsWith("zh") ? "zh" : "en");
6366
- return JSON.parse(JSON.stringify(report));
6367
- }
6368
- })];
6369
- }
6370
- //#endregion
6371
- //#region src/host/import/preset.ts
6372
- /** The older preset layout keeps its texts under fixed keys. */
6373
- const LEGACY_KEYS = [
6374
- "main_prompt",
6375
- "nsfw_prompt",
6376
- "jailbreak_prompt",
6377
- "impersonation_prompt",
6378
- "new_chat_prompt",
6379
- "new_group_chat_prompt",
6380
- "new_example_chat_prompt"
6381
- ];
6382
- const MAX_PIECES = 60;
6383
- const MAX_PIECE_CHARS = 8e3;
6384
- const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6385
- const text = (value) => typeof value === "string" ? value.trim() : "";
6386
- /** The order the preset sends its prompts in: the longest list it gives, with what each entry says about being on. */
6387
- function orderOf(root) {
6388
- 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" ? [{
6389
- identifier: entry["identifier"],
6390
- enabled: entry["enabled"] !== false
6391
- }] : []);
6392
- }
6393
- /**
6394
- * 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.
6395
- * @throws {ImportCardError} when the file is not a preset, with why.
6396
- */
6397
- function readPreset(file, name) {
6398
- let root;
6399
- try {
6400
- root = JSON.parse(file.toString("utf8").replace(/^/, ""));
6401
- } catch {
6402
- throw new ImportCardError("the file is not JSON: a preset is the .json file SillyTavern exports");
6403
- }
6404
- if (!isObject(root)) throw new ImportCardError("the file is not a preset: it must be a JSON object");
6405
- const pieces = [];
6406
- const prompts = Array.isArray(root["prompts"]) ? root["prompts"].filter(isObject) : [];
6407
- if (prompts.length > 0) {
6408
- const byId = new Map(prompts.flatMap((prompt) => typeof prompt["identifier"] === "string" ? [[prompt["identifier"], prompt]] : []));
6409
- const ordered = orderOf(root);
6410
- const chosen = ordered.length > 0 ? ordered.flatMap((entry) => entry.enabled && byId.has(entry.identifier) ? [byId.get(entry.identifier)] : []) : prompts.filter((prompt) => prompt["enabled"] !== false);
6411
- for (const prompt of chosen) {
6412
- const content = text(prompt["content"]);
6413
- if (prompt["marker"] === true || content === "") continue;
6414
- const title = text(prompt["name"]);
6415
- pieces.push(`${title === "" ? "" : `[${title}]\n`}${content.slice(0, MAX_PIECE_CHARS)}`);
6416
- }
6417
- } else for (const key of LEGACY_KEYS) if (text(root[key]) !== "") pieces.push(`[${key}]\n${text(root[key]).slice(0, MAX_PIECE_CHARS)}`);
6418
- 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");
6419
- const title = text(root["name"]) || text(root["preset_name"]);
6420
- return {
6421
- name: title === "" ? name.replace(/\.json$/i, "") : title,
6422
- pieces: pieces.slice(0, MAX_PIECES)
6423
- };
6424
- }
6425
- //#endregion
6426
- //#region src/host/import/preset-tools.ts
6427
- const PRESET_TOOL = "import_preset";
6428
- const PRESET_FILE = "preset.json";
6429
- const PRESET_PATH = `${IMPORT_FOLDER}/${PRESET_FILE}`;
6430
- /** The command that has the authoring chat apply a preset that was uploaded to the world. */
6431
- const presetMessage = () => `Apply the narration preset I uploaded to this world: call ${PRESET_TOOL} with file ${PRESET_PATH}.`;
6432
- /** The tool that turns an uploaded narration preset into the world's prose prompts; every call asks the person first. */
6433
- function presetTools(worlds, settings, prompting) {
6434
- return [defineTool({
6435
- name: PRESET_TOOL,
6436
- description: `Turn the narration preset the person uploaded to this world (${PRESET_PATH}) into the world's prose prompts: how the narration is written and how the characters speak and behave. Rules of the game, formats and scripts in the preset are not carried. It replaces the world's own versions of those prompts, so the person is asked first.`,
6437
- parameters: { file: {
6438
- type: "string",
6439
- required: true,
6440
- description: `The preset: ${PRESET_PATH}.`
6441
- } },
6442
- output: {
6443
- schema: { type: "json" },
6444
- render: (_args, value) => [{
6445
- type: "text",
6446
- text: JSON.stringify(value, null, 1)
6447
- }]
6448
- },
6449
- isConcurrencySafe: () => false,
6450
- async execute(args, exec) {
6451
- if (args.file.trim() !== PRESET_PATH) throw new Error(`the preset is ${PRESET_PATH}`);
6452
- const world = await worldOf(worlds, exec);
6453
- const file = join(world.directory, IMPORT_FOLDER, PRESET_FILE);
6454
- const preset = readPreset(await readFile(file).catch(() => {
6455
- throw new Error("no preset was uploaded to this world");
6456
- }), "preset");
6457
- const language = prompting.languages().get(world.id);
6458
- const text = (id, variables) => prompting.prompts().text(id, language, variables);
6459
- const made = await extractStyleFrom(contextOf(exec, settings(), text), preset.name, preset.pieces);
6460
- for (const { id, text: body } of made.prompts) for (const tag of shippedLanguages()) await writeWorldPrompt(world.directory, tag, id, withPlayer(body));
6461
- await rm(file, { force: true });
6462
- const written = made.prompts.map((entry) => entry.id);
6463
- return JSON.parse(JSON.stringify({
6464
- preset: preset.name,
6465
- written,
6466
- folder: `${PROMPTS_FOLDER}/<language>/`,
6467
- notes: made.notes,
6468
- next: written.length === 0 ? "Nothing in the preset was about how to write the story, so no prompt was changed: tell the person." : "Tell the person which prompts were written (they can read and edit them in the world's Prompts section) and what was not carried over."
6469
- }));
6470
- }
6471
- })];
6472
- }
6473
- //#endregion
6474
- //#region src/host/triggers/parts.ts
6475
- /** What the files of a world say it has, for checking what a trigger names. @throws {InvalidEditProblems} when those files have problems of their own: they are fixed first. */
6476
- async function loadWorldParts(directory) {
6477
- const { characters, problems: characterProblems } = await loadCharacters(directory);
6478
- const { locations, problems: locationProblems } = await loadLocations(directory);
6479
- const { items, slots, problems: itemProblems } = await loadItems(directory, {
6480
- characters: characters.map((character) => character.id),
6481
- locations
6482
- });
6483
- const { defs, problems: variableProblems } = await loadVariables(directory);
6484
- const { calendar, problems: calendarProblems } = await loadCalendar(directory);
6485
- const problems = [
6486
- ...characterProblems,
6487
- ...locationProblems,
6488
- ...itemProblems,
6489
- ...variableProblems,
6490
- ...calendarProblems
6491
- ];
6492
- if (problems.length > 0) throw new InvalidEditProblems([`the world's other files have problems that come first: ${problems.map((problem) => `${problem.path}: ${problem.message}`).join("; ")}`]);
6493
- return {
6494
- characters,
6495
- locations,
6496
- items,
6497
- slots,
6498
- variables: defs,
6499
- calendar
6500
- };
6501
- }
6502
- //#endregion
6503
- //#region src/host/triggers/check.ts
6504
- /**
6505
- * What each trigger names that the world does not have (a character, place, item or variable in its condition, its cues or the words of a
6506
- * cue), found as a session start finds it: against a scratch story made from the world's files. Triggers that wait for each other count
6507
- * as there. @returns the problems by trigger key; a trigger with none is not in it.
6508
- */
6509
- function triggerProblemsOf(parts, definitions) {
6510
- const found = /* @__PURE__ */ new Map();
6511
- if (definitions.length === 0) return found;
6512
- const scratch = createSessionStore(":memory:", {
6513
- id: "scratch",
6514
- name: "scratch",
6515
- world: {
6516
- id: "scratch",
6517
- name: "scratch"
6518
- }
6519
- }, { vectors: false });
6520
- try {
6521
- const session = scratch;
6522
- if (parts.calendar !== void 0) writeCalendar(scratch.metadata, parts.calendar);
6523
- populateLocations(session, parts.locations);
6524
- populateCharacters(session, parts.characters, parts.characters.find((character) => character.role === "playable")?.id ?? "");
6525
- populateItems(session, parts.items, parts.slots, parts.locations);
6526
- populateVariables(session, parts.variables, {
6527
- characters: parts.characters,
6528
- items: parts.items,
6529
- locations: parts.locations,
6530
- values: void 0
6531
- });
6532
- const keys = definitions.map((definition) => definition.key);
6533
- for (const definition of definitions) {
6534
- const problems = triggerReferenceProblems(scratch, definition, keys).map((problem) => problem.slice(definition.key.length + 2));
6535
- if (problems.length > 0) found.set(definition.key, problems);
6536
- }
6537
- } finally {
6538
- scratch.close();
6539
- }
6540
- return found;
6541
- }
6542
- //#endregion
6543
- //#region src/host/triggers/files.ts
6544
- /** The fields of a trigger in the file; any other is a mistake that would otherwise be dropped without a word. */
6545
- const FIELDS = /* @__PURE__ */ new Set([
6546
- "key",
6547
- "name",
6548
- "when",
6549
- "effects",
6550
- "repeat",
6551
- "cooldown_seconds",
6552
- "chance",
6553
- "priority",
6554
- "expires",
6555
- "announce"
6556
- ]);
6557
- const isDocument = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6558
- /** The documents of `<world>/triggers.json` as written; none when the file is not there. @throws {InvalidEditProblems} when it is not a list of objects. */
6559
- async function readTriggerDocuments(directory) {
6560
- let text;
6561
- try {
6562
- text = await readFile(join(directory, TRIGGERS_FILE_NAME), "utf8");
6563
- } catch (error) {
6564
- if (error.code === "ENOENT") return [];
6565
- throw error;
6566
- }
6567
- let data;
6568
- try {
6569
- data = JSON.parse(text.replace(/^/, ""));
6570
- } catch (error) {
6571
- throw new InvalidEditProblems([`triggers.json is not valid JSON: ${error instanceof Error ? error.message : String(error)}`]);
6572
- }
6573
- if (!Array.isArray(data) || !data.every(isDocument)) throw new InvalidEditProblems(["triggers.json is not a list of triggers"]);
6574
- return data;
6575
- }
6576
- async function writeDocuments(directory, documents) {
6577
- const file = join(directory, TRIGGERS_FILE_NAME);
6578
- const temporary = join(dirname(file), `.${basename(file)}.${process.pid}.${randomUUID()}.tmp`);
6579
- try {
6580
- const mode = await stat(file).then((value) => value.mode, () => void 0);
6581
- await writeFile(temporary, `${JSON.stringify(documents, null, 2)}\n`, mode === void 0 ? {} : { mode });
6582
- await rename(temporary, file);
6583
- } catch (error) {
6584
- await rm(temporary, { force: true });
6585
- throw error;
6586
- }
6587
- }
6588
- /** The keys of the triggers a condition waits for. */
6589
- function waitsFor(condition) {
6590
- switch (condition.type) {
6591
- case "fired": return [condition.trigger];
6592
- case "all":
6593
- case "any": return condition.conditions.flatMap(waitsFor);
6594
- case "not": return waitsFor(condition.condition);
6595
- default: return [];
6596
- }
6597
- }
6598
- /**
6599
- * Makes or replaces one trigger of the world, by key, from a complete document in the file format. It is read as a session start reads it, and
6600
- * what it names that the world does not have is refused, with every problem; nothing is written then.
6601
- * @throws {InvalidEditProblems}
6602
- */
6603
- async function writeTriggerDocument(directory, parts, key, document) {
6604
- if (!isDocument(document)) throw new InvalidEditProblems(["document must be a JSON object"]);
6605
- const unknown = Object.keys(document).filter((field) => !FIELDS.has(field));
6606
- if (unknown.length > 0) throw new InvalidEditProblems(unknown.map((field) => `"${field}" is not a field of a trigger (${[...FIELDS].join(", ")})`));
6607
- const written = {
6608
- ...document,
6609
- key
6610
- };
6611
- const parsed = readTriggerDefinition(written, "trigger");
6612
- if ("problems" in parsed) throw new InvalidEditProblems(parsed.problems);
6613
- const documents = await readTriggerDocuments(directory);
6614
- const at = documents.findIndex((entry) => entry["key"] === key);
6615
- const problems = triggerProblemsOf(parts, [...documents.filter((_, index) => index !== at).flatMap((entry) => {
6616
- const read = readTriggerDefinition(entry, "trigger");
6617
- return "definition" in read ? [read.definition] : [];
6618
- }), parsed.definition]).get(key) ?? [];
6619
- if (problems.length > 0) throw new InvalidEditProblems(problems);
6620
- await writeDocuments(directory, at < 0 ? [...documents, written] : documents.map((entry, index) => index === at ? written : entry));
6621
- return at < 0 ? "created" : "replaced";
6622
- }
6623
- /**
6624
- * Removes one trigger from the world's file, keeping its document in `.trash/triggers` so that it can be put back. A trigger that others wait for
6625
- * cannot be removed.
6626
- * @returns where the document was kept.
6627
- * @throws {InvalidEditProblems}
6628
- */
6629
- async function deleteTriggerDocument(directory, key) {
6630
- const documents = await readTriggerDocuments(directory);
6631
- const found = documents.find((entry) => entry["key"] === key);
6632
- if (found === void 0) throw new InvalidEditProblems([`there is no trigger "${key}"`]);
6633
- const waiting = documents.flatMap((entry) => {
6634
- const read = readTriggerDefinition(entry, "trigger");
6635
- return "definition" in read && read.definition.key !== key && waitsFor(read.definition.condition).includes(key) ? [read.definition.key] : [];
6636
- });
6637
- if (waiting.length > 0) throw new InvalidEditProblems([`${waiting.join(", ")} wait${waiting.length === 1 ? "s" : ""} for "${key}" to fire; change ${waiting.length === 1 ? "it" : "them"} first`]);
6638
- const trash = join(directory, ".trash", "triggers");
6639
- await mkdir(trash, { recursive: true });
6640
- const kept = join(trash, `${key}-${Date.now()}-${randomUUID()}.json`);
6641
- await writeFile(kept, `${JSON.stringify(found, null, 2)}\n`, { flag: "wx" });
6642
- await writeDocuments(directory, documents.filter((entry) => entry !== found));
6643
- return kept;
6644
- }
6645
- //#endregion
6646
- //#region src/host/worlds/world-editor.ts
6647
- function stateOf(world, definition, names) {
6648
- const { start } = definition;
6649
- const portrait = referenceImagePath(world.directory, {
6650
- kind: "character",
6651
- localId: definition.id,
6652
- ...definition.visualIdentity?.globalId === void 0 ? {} : { globalId: definition.visualIdentity.globalId }
6653
- });
6654
- return {
6655
- key: definition.id,
6656
- name: definition.name,
6657
- aliases: definition.aliases,
6658
- role: definition.role,
6659
- tier: definition.tier,
6660
- kind: definition.kind,
6661
- control: definition.role === "playable" ? "player" : "agent",
6662
- ...definition.age === void 0 ? {} : { age: definition.age },
6663
- ...definition.gender === void 0 ? {} : { gender: definition.gender },
6664
- ...definition.pronouns === void 0 ? {} : { pronouns: definition.pronouns },
6665
- summary: definition.summary,
6666
- personality: definition.personality,
6667
- background: definition.background,
6668
- appearance: definition.appearance,
6669
- speech: definition.speech,
6670
- ...definition.voice === void 0 ? {} : { voice: definition.voice },
6671
- ...definition.visualIdentity === void 0 ? {} : { visualIdentity: definition.visualIdentity },
6672
- ...existsSync(portrait) ? { portrait: `/${API_PREFIX}/worlds/state/character/portrait/file?id=${encodeURIComponent(world.id)}&key=${encodeURIComponent(definition.id)}&v=${statSync(portrait).mtimeMs}` } : {},
6673
- state: {
6674
- publicState: start.publicState,
6675
- innerState: start.innerState,
6676
- activity: start.activity
6677
- },
6678
- ...start.place === void 0 ? {} : { place: {
6679
- key: start.place.location,
6680
- name: names.get(start.place.location) ?? start.place.location,
6681
- ...start.place.position === void 0 ? {} : { position: start.place.position }
6682
- } },
6683
- goals: start.intents.map((intent, index) => ({
6684
- ref: String(index),
6685
- name: intent.name,
6686
- description: intent.description,
6687
- status: intent.status,
6688
- priority: intent.priority
6689
- }))
6690
- };
6691
- }
6692
- /** The triggers of the world's file as the editor shows them, with what each names that the world does not have; or why the file cannot be shown. */
6693
- function triggersOf(parts, scripted) {
6694
- if (scripted.problems.length > 0) return {
6695
- triggers: [],
6696
- triggersProblem: scripted.problems.map((problem) => problem.message).join("; ")
6697
- };
6698
- const view = (problems) => scripted.triggers.map((definition) => ({
6699
- key: definition.key,
6700
- name: definition.name,
6701
- when: definition.condition,
6702
- effects: definition.effects,
6703
- repeat: definition.repeat,
6704
- priority: definition.priority,
6705
- ...definition.cooldownSeconds === void 0 ? {} : { cooldownSeconds: definition.cooldownSeconds },
6706
- ...definition.chance === void 0 ? {} : { chance: definition.chance },
6707
- ...definition.expires === void 0 ? {} : { expires: definition.expires },
6708
- announced: definition.announce !== void 0,
6709
- problems: problems.get(definition.key) ?? []
6710
- }));
6711
- try {
6712
- return { triggers: view(triggerProblemsOf(parts, scripted.triggers)) };
6713
- } catch (error) {
6714
- return {
6715
- triggers: view(/* @__PURE__ */ new Map()),
6716
- triggersProblem: `what the triggers name could not be checked, because the rest of the world has a problem: ${error instanceof Error ? error.message : String(error)}`
6717
- };
6718
- }
6719
- }
6720
- /** The characters of a world as they start, and the places they can start in. */
6721
- async function readWorldEditor(world) {
6722
- const [{ characters }, { locations }, { factions }, { lore }, { plots }] = await Promise.all([
6723
- loadCharacters(world.directory),
6724
- loadLocations(world.directory),
6725
- loadFactions(world.directory),
6726
- loadLore(world.directory),
6727
- loadPlots(world.directory)
6728
- ]);
6729
- const { items, slots } = await loadItems(world.directory, {
6730
- characters: characters.map((character) => character.id),
6731
- locations
6732
- });
6733
- const scripted = await loadTriggers(world.directory);
6734
- const declared = await loadVariables(world.directory);
6735
- const { calendar } = await loadCalendar(world.directory);
6736
- const { triggers, triggersProblem } = triggersOf({
6737
- characters,
6738
- locations,
6739
- items,
6740
- slots,
6741
- variables: declared.defs,
6742
- calendar
6743
- }, scripted);
6744
- const names = new Map(locations.map((location) => [location.id, location.name]));
6745
- const characterNames = new Map(characters.map((character) => [character.id, character.name]));
6746
- const itemNames = new Map(items.map((item) => [item.id, item.name]));
6747
- const holder = (item) => item.start.kind === "location" ? names.get(item.start.location) ?? item.start.location : item.start.kind === "inside" ? itemNames.get(item.start.item) ?? item.start.item : characterNames.get(item.start.character) ?? item.start.character;
6748
- const entity = (kind, key, name) => ({
6749
- kind,
6750
- key,
6751
- name
6752
- });
6753
- const characterEntity = (key) => entity("character", key, characterNames.get(key) ?? key);
6754
- const factionNames = new Map(factions.map((faction) => [faction.id, faction.name]));
6755
- const relations = [];
6756
- for (const character of characters) {
6757
- for (const relation of character.relationships ?? []) relations.push({
6758
- key: relationKey("character", character.id, relation.to),
6759
- kind: "character",
6760
- from: characterEntity(character.id),
6761
- to: characterEntity(relation.to),
6762
- label: relation.label,
6763
- summary: relation.summary,
6764
- familiarity: relation.familiarity,
6765
- trust: relation.trust,
6766
- affinity: relation.affinity,
6767
- tension: relation.tension
6768
- });
6769
- for (const location of character.knowledge?.locations ?? []) relations.push({
6770
- key: relationKey("knowledge", character.id, "location", location),
6771
- kind: "knowledge",
6772
- from: characterEntity(character.id),
6773
- to: entity("location", location, names.get(location) ?? location),
6774
- observed: false
6775
- });
6776
- for (const item of character.knowledge?.items ?? []) relations.push({
6777
- key: relationKey("knowledge", character.id, "item", item),
6778
- kind: "knowledge",
6779
- from: characterEntity(character.id),
6780
- to: entity("item", item, itemNames.get(item) ?? item),
6781
- observed: false
6782
- });
6783
- for (const exit of character.knowledge?.exits ?? []) relations.push({
6784
- key: relationKey("knowledge", character.id, "exit", exit.from, exit.to),
6785
- kind: "knowledge",
6786
- from: characterEntity(character.id),
6787
- to: entity("exit", `${exit.from}>${exit.to}`, `${names.get(exit.from) ?? exit.from} → ${names.get(exit.to) ?? exit.to}`),
6788
- observed: false
6789
- });
6790
- }
6791
- for (const location of locations) for (const exit of location.exits) relations.push({
6792
- key: relationKey("exit", location.id, exit.to),
6793
- kind: "exit",
6794
- from: entity("location", location.id, location.name),
6795
- to: entity("location", exit.to, names.get(exit.to) ?? exit.to),
6796
- description: exit.description,
6797
- ...exit.travelSeconds === void 0 ? {} : { travelSeconds: exit.travelSeconds },
6798
- state: exit.state,
6799
- note: exit.note,
6800
- oneWay: exit.oneWay
6801
- });
6802
- for (const faction of factions) {
6803
- for (const member of faction.members) relations.push({
6804
- key: relationKey("membership", faction.id, member.character),
6805
- kind: "membership",
6806
- from: characterEntity(member.character),
6807
- to: entity("faction", faction.id, faction.name),
6808
- role: member.role,
6809
- rank: member.rank,
6810
- status: member.status,
6811
- public: member.public,
6812
- commitment: member.commitment
6813
- });
6814
- for (const relation of faction.relationships) {
6815
- const targetName = relation.to.kind === "faction" ? factionNames.get(relation.to.id) ?? relation.to.id : characterNames.get(relation.to.id) ?? relation.to.id;
6816
- relations.push({
6817
- key: relationKey("social", "faction", faction.id, relation.to.kind, relation.to.id),
6818
- kind: "social",
6819
- from: entity("faction", faction.id, faction.name),
6820
- to: entity(relation.to.kind, relation.to.id, targetName),
6821
- label: relation.label,
6822
- summary: relation.summary ?? "",
6823
- familiarity: relation.familiarity ?? 0,
6824
- trust: relation.trust ?? 0,
6825
- affinity: relation.affinity ?? 0,
6826
- tension: relation.tension ?? 0
6827
- });
6828
- }
6829
- }
6830
- const worldDocument = JSON.parse(await readFile(join(world.directory, "world.json"), "utf8"));
6831
- const narrationVoice = typeof worldDocument["narration_voice"] === "string" ? worldDocument["narration_voice"] : void 0;
6832
- return {
6833
- ...narrationVoice === void 0 ? {} : { narrationVoice },
6834
- characters: characters.map((character) => stateOf(world, character, names)),
6835
- places: locations.map((location) => ({
6836
- key: location.id,
6837
- name: location.name,
6838
- description: location.description,
6839
- ...imageOf(world, "place", location.id, location.visualIdentity?.globalId),
6840
- ...location.parent === void 0 ? {} : { parent: {
6841
- key: location.parent,
6842
- name: names.get(location.parent) ?? location.parent
6843
- } },
6844
- features: location.features,
6845
- ...location.visualIdentity === void 0 ? {} : { visualIdentity: location.visualIdentity }
6846
- })),
6847
- things: items.map((item) => ({
6848
- key: item.id,
6849
- name: item.name,
6850
- description: item.description,
6851
- ...imageOf(world, "thing", item.id, item.visualIdentity?.globalId),
6852
- quantity: item.quantity,
6853
- unique: item.unique,
6854
- quality: item.quality,
6855
- notable: item.notable,
6856
- hidden: item.hidden,
6857
- ...item.wearable === void 0 ? {} : { wearable: item.wearable },
6858
- ...item.container === void 0 ? {} : { containerState: item.container.state },
6859
- ...item.owner === void 0 ? {} : { owner: {
6860
- key: item.owner,
6861
- name: characterNames.get(item.owner) ?? item.owner
6862
- } },
6863
- holder: holder(item),
6864
- ...item.visualIdentity === void 0 ? {} : { visualIdentity: item.visualIdentity }
6865
- })),
6866
- factions: factions.map((faction) => ({
6867
- key: faction.id,
6868
- name: faction.name,
6869
- aliases: faction.aliases,
6870
- summary: faction.summary,
6871
- description: faction.description,
6872
- values: faction.values,
6873
- structure: faction.structure,
6874
- state: {
6875
- publicState: faction.start.publicState,
6876
- innerState: faction.start.innerState
6877
- },
6878
- goals: faction.start.goals.map((goal, index) => ({
6879
- ref: String(index),
6880
- name: goal.name,
6881
- description: goal.description,
6882
- status: goal.status,
6883
- priority: goal.priority
6884
- })),
6885
- members: faction.members.map((member) => ({
6886
- ...member,
6887
- name: characterNames.get(member.character) ?? member.character
6888
- })),
6889
- relationships: faction.relationships.map((relationship) => ({
6890
- target: `${relationship.to.kind}:${relationship.to.id}`,
6891
- label: relationship.label,
6892
- summary: relationship.summary ?? ""
6893
- }))
6894
- })),
6895
- lore: lore.map((entry) => ({
6896
- key: entry.id,
6897
- title: entry.title,
6898
- kind: entry.kind,
6899
- summary: entry.summary,
6900
- body: entry.body,
6901
- ...entry.startsAt === void 0 ? {} : { startsAt: entry.startsAt },
6902
- ...entry.endsAt === void 0 ? {} : { endsAt: entry.endsAt },
6903
- subjects: entry.subjects.map((subject) => ({
6904
- kind: subject.kind,
6905
- key: subject.id,
6906
- name: subject.kind === "character" ? characterNames.get(subject.id) ?? subject.id : subject.kind === "faction" ? factionNames.get(subject.id) ?? subject.id : subject.kind === "location" ? names.get(subject.id) ?? subject.id : subject.kind === "item" ? itemNames.get(subject.id) ?? subject.id : lore.find((candidate) => candidate.id === subject.id)?.title ?? subject.id
6907
- })),
6908
- related: entry.related.map((key) => ({
6909
- key,
6910
- title: lore.find((candidate) => candidate.id === key)?.title ?? key
6911
- })),
6912
- sources: entry.sources
6913
- })),
6914
- triggers,
6915
- ...triggersProblem === void 0 ? {} : { triggersProblem },
6916
- plots: plots.map((definition) => ({ definition })),
6917
- relations
6918
- };
6919
- }
6920
- async function editWorldPlots(world, edit) {
6921
- const parsed = parsePlotsFile(JSON.stringify(edit.plots));
6922
- if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
6923
- const state = await readWorldEditor(world);
6924
- const references = plotReferenceProblems(parsed.value, [
6925
- ...state.characters.map((entry) => entry.key),
6926
- ...state.factions.map((entry) => entry.key),
6927
- ...state.places.map((entry) => entry.key),
6928
- ...state.things.map((entry) => entry.key),
6929
- ...(state.lore ?? []).map((entry) => entry.key)
6930
- ]);
6931
- if (references.length > 0) throw new InvalidEditProblems(references);
6932
- const document = parsed.value.map((plot) => ({
6933
- ...plot,
6934
- pacing: {
6935
- quiet_turns: plot.pacing.quietTurns,
6936
- cooldown_turns: plot.pacing.cooldownTurns,
6937
- cooldown_days: plot.pacing.cooldownDays
6938
- }
6939
- }));
6940
- await replaceFile$1(join(world.directory, PLOTS_FILE_NAME), JSON.stringify(document, null, 2) + "\n");
6941
- return await readWorldEditor(world);
6942
- }
6943
- async function editWorldLore(world, key, edit) {
6944
- return await editEntityFile(world, LORE_DIR, LORE_FILE_NAME, key, parseLoreFile, (document) => {
6945
- if (edit.title !== void 0) document["title"] = edit.title;
6946
- if (edit.kind !== void 0) document["kind"] = edit.kind;
6947
- if (edit.summary !== void 0) setOptional(document, "summary", edit.summary);
6948
- if (edit.body !== void 0) setOptional(document, "body", edit.body);
6949
- if (edit.sources !== void 0) document["sources"] = edit.sources;
6950
- if (edit.startsAt !== void 0) {
6951
- if (edit.startsAt === null) delete document["starts_at"];
6952
- else document["starts_at"] = new Date(edit.startsAt).toISOString();
6953
- }
6954
- if (edit.endsAt !== void 0) {
6955
- if (edit.endsAt === null) delete document["ends_at"];
6956
- else document["ends_at"] = new Date(edit.endsAt).toISOString();
6957
- }
6958
- });
6959
- }
6960
- async function editWorldNarrationVoice(world, voice) {
6961
- const file = join(world.directory, "world.json");
6962
- const text = await readFile(file, "utf8");
6963
- const document = JSON.parse(text);
6964
- if (voice.trim() === "") delete document["narration_voice"];
6965
- else document["narration_voice"] = voice.trim();
6966
- await replaceFile$1(file, JSON.stringify(document, null, /^([ \t]+)"/m.exec(text)?.[1] ?? " ") + (text.endsWith("\n") ? "\n" : ""));
6967
- return await readWorldEditor(world);
6968
- }
6969
- const relationKey = (...parts) => parts.map((part) => encodeURIComponent(part)).join(":");
6970
- const relationParts = (key) => key.split(":").map((part) => decodeURIComponent(part));
6971
- /** The folder of a character by its id: the id is the folder's name unless the file says another. */
6972
- async function folderOf$1(worldDirectory, key) {
6973
- const root = join(worldDirectory, CHARACTERS_DIR);
6974
- for (const folder of await subfolders(root)) try {
6975
- const parsed = parseCharacterFile(await readFile(join(root, folder, CHARACTER_FILE_NAME), "utf8"), folder);
6976
- if (parsed.ok && parsed.value.id === key) return folder;
6977
- } catch (error) {
6978
- if (error.code !== "ENOENT") throw error;
6979
- }
6980
- }
6981
- const object = (parent, key) => {
6982
- const found = parent[key];
6983
- if (typeof found === "object" && found !== null && !Array.isArray(found)) return found;
6984
- const made = {};
6985
- parent[key] = made;
6986
- return made;
6987
- };
6988
- /** A blank optional text is taken out of the file instead of being written empty. */
6989
- function setOptional(target, key, value) {
6990
- if (value === void 0) return;
6991
- if (value.trim() === "") delete target[key];
6992
- else target[key] = value.trim();
6993
- }
6994
- /** Puts the edit into the document of a character file; the fields it does not name, and every field the editor does not know, stay as they are. */
6995
- function apply(document, edit, problems) {
6996
- if (edit.name !== void 0) document["name"] = edit.name;
6997
- if (edit.aliases !== void 0) document["aliases"] = edit.aliases.map((alias) => alias.trim()).filter((alias) => alias !== "");
6998
- for (const key of [
6999
- "age",
7000
- "gender",
7001
- "pronouns"
7002
- ]) setOptional(document, key, edit[key]);
7003
- for (const key of [
7004
- "role",
7005
- "tier",
7006
- "kind",
7007
- "summary",
7008
- "personality",
7009
- "background",
7010
- "appearance"
7011
- ]) if (edit[key] !== void 0) document[key] = edit[key];
7012
- if (edit.visualIdentity === null) delete document["visual_identity"];
7013
- else if (edit.visualIdentity !== void 0) document["visual_identity"] = {
7014
- description: edit.visualIdentity.description,
7015
- tags: edit.visualIdentity.tags,
7016
- negative_tags: edit.visualIdentity.negativeTags,
7017
- ...edit.visualIdentity.globalId === void 0 ? {} : { global_id: edit.visualIdentity.globalId }
7018
- };
7019
- if (edit.speech !== void 0) {
7020
- const speech = object(document, "speech");
7021
- if (edit.speech.style !== void 0) speech["style"] = edit.speech.style;
7022
- if (edit.speech.examples !== void 0) speech["examples"] = edit.speech.examples.map((example) => example.trim()).filter((example) => example !== "");
7023
- }
7024
- setOptional(document, "voice", edit.voice);
7025
- const start = object(document, "start");
7026
- if (edit.state !== void 0) {
7027
- if (edit.state.publicState !== void 0) start["public_state"] = edit.state.publicState;
7028
- if (edit.state.innerState !== void 0) start["inner_state"] = edit.state.innerState;
7029
- if (edit.state.activity !== void 0) start["activity"] = edit.state.activity;
7030
- }
7031
- if (edit.place !== void 0) {
7032
- if (start["location"] !== edit.place.location) delete start["feature"];
7033
- start["location"] = edit.place.location;
7034
- setOptional(start, "position", edit.place.position ?? "");
7035
- }
7036
- if (edit.goals !== void 0) {
7037
- const intents = Array.isArray(start["intents"]) ? start["intents"] : [];
7038
- for (const goal of edit.goals) {
7039
- const intent = intents[Number(goal.ref)];
7040
- if (intent === void 0 || typeof intent !== "object" || intent === null) {
7041
- problems.push(`there is no goal "${goal.ref}"`);
7042
- continue;
7043
- }
7044
- if (goal.name !== void 0) intent["name"] = goal.name;
7045
- if (goal.description !== void 0) intent["description"] = goal.description;
7046
- if (goal.status !== void 0) intent["status"] = goal.status;
7047
- if (goal.priority !== void 0) intent["priority"] = goal.priority;
7048
- }
7049
- }
7050
- }
7051
- /** Written in one step, so an interruption cannot leave a character file half written. */
7052
- async function replaceFile$1(file, text) {
7053
- const temporary = join(dirname(file), `.${basename(file)}.${process.pid}.${randomUUID()}.tmp`);
7054
- try {
7055
- const mode = await stat(file).then((value) => value.mode, (error) => {
7056
- if (error.code === "ENOENT") return 420;
7057
- throw error;
7058
- });
7059
- await writeFile(temporary, text, { mode });
7060
- await chmod(temporary, mode);
7061
- await rename(temporary, file);
7062
- } catch (error) {
7063
- await rm(temporary, { force: true });
7064
- throw error;
7065
- }
7066
- }
7067
- /**
7068
- * Change a character in a world's files: the file is read, changed and checked as a whole (it has to read as a valid character, and the place has to be a place of
7069
- * the world) before it is written, so a refused edit changes nothing. Whatever the file holds that the editor does not know stays.
7070
- * @throws {InvalidEditProblems} when the character is not there, or the result would not be a valid character.
7071
- */
7072
- async function editWorldCharacter(world, key, edit) {
7073
- const folder = await folderOf$1(world.directory, key);
7074
- if (folder === void 0) throw new InvalidEditProblems([`there is no character "${key}"`]);
7075
- const file = join(world.directory, CHARACTERS_DIR, folder, CHARACTER_FILE_NAME);
7076
- const text = (await readFile(file, "utf8")).replace(/^/, "");
7077
- const document = JSON.parse(text);
7078
- const problems = [];
7079
- if (edit.place !== void 0) {
7080
- const { locations } = await loadLocations(world.directory);
7081
- if (!locations.some((location) => location.id === edit.place?.location)) problems.push(`there is no place "${edit.place.location}"`);
7082
- }
7083
- apply(document, edit, problems);
7084
- const next = JSON.stringify(document, null, /^([ \t]+)"/m.exec(text)?.[1] ?? " ") + (text.endsWith("\n") ? "\n" : "");
7085
- const parsed = parseCharacterFile(next, folder);
7086
- if (!parsed.ok) problems.push(...parsed.issues.map(formatIssue));
7087
- if (problems.length > 0) throw new InvalidEditProblems(problems);
7088
- await replaceFile$1(file, next);
7089
- return await readWorldEditor(world);
7090
- }
7091
- async function entityFolder(worldDirectory, directory, fileName, key, parse) {
7092
- for (const folder of await subfolders(join(worldDirectory, directory))) try {
7093
- const parsed = parse(await readFile(join(worldDirectory, directory, folder, fileName), "utf8"), folder);
7094
- if (parsed.ok && parsed.value?.id === key) return folder;
7095
- } catch (error) {
7096
- if (error.code !== "ENOENT") throw error;
7097
- }
7098
- }
7099
- function setVisualIdentity(document, identity) {
7100
- if (identity === null) delete document["visual_identity"];
7101
- else if (identity !== void 0) document["visual_identity"] = {
7102
- description: identity.description,
7103
- tags: identity.tags,
7104
- negative_tags: identity.negativeTags,
7105
- ...identity.globalId === void 0 ? {} : { global_id: identity.globalId }
7106
- };
7107
- }
7108
- async function editEntityFile(world, directory, fileName, key, parse, mutate) {
7109
- const folder = await entityFolder(world.directory, directory, fileName, key, parse);
7110
- if (folder === void 0) throw new InvalidEditProblems([`there is no entity "${key}"`]);
7111
- const file = join(world.directory, directory, folder, fileName);
7112
- const text = (await readFile(file, "utf8")).replace(/^/, "");
7113
- const document = JSON.parse(text);
7114
- mutate(document);
7115
- const next = JSON.stringify(document, null, /^([ \t]+)"/m.exec(text)?.[1] ?? " ") + (text.endsWith("\n") ? "\n" : "");
7116
- const parsed = parse(next, folder);
7117
- if (!parsed.ok) throw new InvalidEditProblems((parsed.issues ?? []).map(formatIssue));
7118
- await replaceFile$1(file, next);
7119
- return await readWorldEditor(world);
7120
- }
7121
- async function editWorldPlace(world, key, edit) {
7122
- if (edit.parent !== void 0 && edit.parent !== null) {
7123
- const places = (await readWorldEditor(world)).places;
7124
- if (!places.some((place) => place.key === edit.parent)) throw new InvalidEditProblems([`there is no place "${edit.parent}" to put it in`]);
7125
- const parents = new Map(places.map((place) => [place.key, place.parent?.key]));
7126
- for (let at = edit.parent; at !== void 0; at = parents.get(at)) if (at === key) throw new InvalidEditProblems(["a place cannot be inside itself or a place within it"]);
7127
- }
7128
- return await editEntityFile(world, LOCATIONS_DIR, LOCATION_FILE_NAME, key, parseLocationFile, (document) => {
7129
- if (edit.name !== void 0) document["name"] = edit.name;
7130
- if (edit.description !== void 0) document["description"] = edit.description;
7131
- if (edit.features !== void 0) document["features"] = edit.features.map((feature) => ({
7132
- id: feature.key,
7133
- name: feature.name,
7134
- description: feature.description
7135
- }));
7136
- if (edit.parent === null) delete document["parent"];
7137
- else if (edit.parent !== void 0) document["parent"] = edit.parent;
7138
- setVisualIdentity(document, edit.visualIdentity);
7139
- });
7140
- }
7141
- async function editWorldThing(world, key, edit) {
7142
- if (edit.owner !== void 0 && edit.owner !== null && !(await readWorldEditor(world)).characters.some((character) => character.key === edit.owner)) throw new InvalidEditProblems([`there is no character "${edit.owner}" to own it`]);
7143
- return await editEntityFile(world, ITEMS_DIR, ITEM_FILE_NAME, key, parseItemFile, (document) => {
7144
- for (const field of [
7145
- "name",
7146
- "description",
7147
- "quantity",
7148
- "quality",
7149
- "notable",
7150
- "hidden"
7151
- ]) if (edit[field] !== void 0) document[field] = edit[field];
7152
- if (edit.containerState !== void 0) object(document, "container")["state"] = edit.containerState;
7153
- if (edit.owner === null) delete document["owner"];
7154
- else if (edit.owner !== void 0) document["owner"] = edit.owner;
7155
- setVisualIdentity(document, edit.visualIdentity);
7156
- });
7157
- }
7158
- async function editWorldFaction(world, key, edit) {
7159
- return await editEntityFile(world, FACTIONS_DIR, FACTION_FILE_NAME, key, parseFactionFile, (document) => {
7160
- for (const field of [
7161
- "name",
7162
- "aliases",
7163
- "summary",
7164
- "description",
7165
- "values",
7166
- "structure"
7167
- ]) if (edit[field] !== void 0) document[field] = edit[field];
7168
- const start = object(document, "start");
7169
- if (edit.state?.publicState !== void 0) start["public_state"] = edit.state.publicState;
7170
- if (edit.state?.innerState !== void 0) start["inner_state"] = edit.state.innerState;
7171
- if (edit.goals !== void 0) {
7172
- const goals = Array.isArray(start["goals"]) ? start["goals"] : [];
7173
- for (const goal of edit.goals) {
7174
- const target = goals[Number(goal.ref)];
7175
- if (target === void 0) continue;
7176
- for (const field of [
7177
- "name",
7178
- "description",
7179
- "status",
7180
- "priority"
7181
- ]) if (goal[field] !== void 0) target[field] = goal[field];
7182
- }
7183
- }
7184
- });
7185
- }
7186
- async function createWorldRelation(world, edit) {
7187
- if (edit.kind === "character" || edit.kind === "knowledge") return await editEntityFile(world, CHARACTERS_DIR, CHARACTER_FILE_NAME, edit.from, parseCharacterFile, (document) => {
7188
- if (edit.kind === "character") {
7189
- const relationships = Array.isArray(document["relationships"]) ? document["relationships"] : [];
7190
- if (relationships.some((entry) => entry?.["to"] === edit.to)) throw new InvalidEditProblems(["that relationship already exists"]);
7191
- relationships.push({
7192
- to: edit.to,
7193
- label: edit.label,
7194
- summary: edit.summary ?? "",
7195
- familiarity: edit.familiarity ?? 0,
7196
- trust: edit.trust ?? 0,
7197
- affinity: edit.affinity ?? 0,
7198
- tension: edit.tension ?? 0
7199
- });
7200
- document["relationships"] = relationships;
7201
- } else {
7202
- const knowledge = object(document, "knowledge");
7203
- const field = edit.toKind === "location" ? "locations" : edit.toKind === "item" ? "items" : "exits";
7204
- const entries = Array.isArray(knowledge[field]) ? knowledge[field] : [];
7205
- if (edit.toKind === "exit") {
7206
- const [from, to] = edit.to.split(">");
7207
- if (from === void 0 || to === void 0) throw new InvalidEditProblems(["the route key is invalid"]);
7208
- if (entries.some((entry) => typeof entry === "object" && entry !== null && entry["from"] === from && entry["to"] === to)) throw new InvalidEditProblems(["that knowledge relation already exists"]);
7209
- entries.push({
7210
- from,
7211
- to
7212
- });
7213
- } else {
7214
- if (entries.includes(edit.to)) throw new InvalidEditProblems(["that knowledge relation already exists"]);
7215
- entries.push(edit.to);
7216
- }
7217
- knowledge[field] = entries;
7218
- }
7219
- });
7220
- if (edit.kind === "exit") return await editEntityFile(world, LOCATIONS_DIR, LOCATION_FILE_NAME, edit.from, parseLocationFile, (document) => {
7221
- const exits = Array.isArray(document["exits"]) ? document["exits"] : [];
7222
- if (exits.some((entry) => entry?.["to"] === edit.to)) throw new InvalidEditProblems(["that route already exists"]);
7223
- exits.push({
7224
- to: edit.to,
7225
- description: edit.description,
7226
- ...edit.travelSeconds === void 0 ? {} : { travel_time_seconds: edit.travelSeconds },
7227
- state: edit.state ?? "open",
7228
- note: edit.note ?? ""
7229
- });
7230
- document["exits"] = exits;
7231
- });
7232
- const faction = edit.kind === "membership" ? edit.to : edit.from;
7233
- if (edit.kind === "social" && edit.fromKind !== "faction") throw new InvalidEditProblems(["authored social relationships must start from a faction"]);
7234
- return await editEntityFile(world, FACTIONS_DIR, FACTION_FILE_NAME, faction, parseFactionFile, (document) => {
7235
- if (edit.kind === "membership") {
7236
- const members = Array.isArray(document["members"]) ? document["members"] : [];
7237
- if (members.some((entry) => entry?.["character"] === edit.from)) throw new InvalidEditProblems(["that membership already exists"]);
7238
- members.push({
7239
- character: edit.from,
7240
- role: edit.role,
7241
- rank: edit.rank ?? "",
7242
- status: edit.status ?? "active",
7243
- public: edit.public ?? true,
7244
- commitment: edit.commitment ?? .5
7245
- });
7246
- document["members"] = members;
7247
- } else {
7248
- const relationships = Array.isArray(document["relationships"]) ? document["relationships"] : [];
7249
- if (relationships.some((entry) => typeof entry?.["to"] === "object" && entry["to"] !== null && entry["to"]["kind"] === edit.toKind && entry["to"]["id"] === edit.to)) throw new InvalidEditProblems(["that relationship already exists"]);
7250
- relationships.push({
7251
- to: {
7252
- kind: edit.toKind,
7253
- id: edit.to
7254
- },
7255
- label: edit.label,
7256
- summary: edit.summary ?? "",
7257
- familiarity: edit.familiarity ?? 0,
7258
- trust: edit.trust ?? 0,
7259
- affinity: edit.affinity ?? 0,
7260
- tension: edit.tension ?? 0
7261
- });
7262
- document["relationships"] = relationships;
7263
- }
7264
- });
7265
- }
7266
- const isNewRelation = (edit) => "create" in edit && edit.create === true;
7267
- async function editWorldRelation(world, edit) {
7268
- if (isNewRelation(edit)) return await createWorldRelation(world, edit);
7269
- const parts = relationParts(edit.key);
7270
- if (parts[0] !== edit.kind) throw new InvalidEditProblems([`the relation key "${edit.key}" is not a ${edit.kind} key: copy it exactly from list_relationships ("${edit.kind}:..."), or to make a new one send create: true with from and to and no key`]);
7271
- if (edit.kind === "character" || edit.kind === "knowledge") {
7272
- const character = parts[1];
7273
- if (character === void 0) throw new InvalidEditProblems(["the relation key is invalid"]);
7274
- if (await folderOf$1(world.directory, character) === void 0) throw new InvalidEditProblems([`there is no character "${character}"`]);
7275
- return await editEntityFile(world, CHARACTERS_DIR, CHARACTER_FILE_NAME, character, parseCharacterFile, (document) => {
7276
- if (edit.kind === "character") {
7277
- const target = parts[2];
7278
- const relationships = Array.isArray(document["relationships"]) ? document["relationships"] : [];
7279
- const index = relationships.findIndex((entry) => entry?.["to"] === target);
7280
- if (index < 0) throw new InvalidEditProblems(["the relationship no longer exists"]);
7281
- if (edit.remove === true) relationships.splice(index, 1);
7282
- else for (const field of [
7283
- "label",
7284
- "summary",
7285
- "familiarity",
7286
- "trust",
7287
- "affinity",
7288
- "tension"
7289
- ]) if (edit[field] !== void 0) relationships[index][field] = edit[field];
7290
- document["relationships"] = relationships;
7291
- } else {
7292
- const subjectKind = parts[2];
7293
- const one = parts[3];
7294
- const two = parts[4];
7295
- const knowledge = object(document, "knowledge");
7296
- const field = subjectKind === "location" ? "locations" : subjectKind === "item" ? "items" : "exits";
7297
- const entries = Array.isArray(knowledge[field]) ? knowledge[field] : [];
7298
- const index = subjectKind === "exit" ? entries.findIndex((entry) => typeof entry === "object" && entry !== null && entry["from"] === one && entry["to"] === two) : entries.indexOf(one);
7299
- if (index < 0) throw new InvalidEditProblems(["the knowledge relation no longer exists"]);
7300
- entries.splice(index, 1);
7301
- knowledge[field] = entries;
7302
- }
7303
- });
7304
- }
7305
- if (edit.kind === "exit") {
7306
- const from = parts[1];
7307
- const to = parts[2];
7308
- if (from === void 0 || to === void 0) throw new InvalidEditProblems(["the exit key is invalid"]);
7309
- return await editEntityFile(world, LOCATIONS_DIR, LOCATION_FILE_NAME, from, parseLocationFile, (document) => {
7310
- const exits = Array.isArray(document["exits"]) ? document["exits"] : [];
7311
- const index = exits.findIndex((entry) => entry?.["to"] === to);
7312
- if (index < 0) throw new InvalidEditProblems(["the exit no longer exists"]);
7313
- if (edit.remove === true) exits.splice(index, 1);
7314
- else {
7315
- for (const field of [
7316
- "description",
7317
- "state",
7318
- "note"
7319
- ]) if (edit[field] !== void 0) exits[index][field] = edit[field];
7320
- if (edit.travelSeconds === null) delete exits[index]["travel_time_seconds"];
7321
- else if (edit.travelSeconds !== void 0) exits[index]["travel_time_seconds"] = edit.travelSeconds;
7322
- }
7323
- document["exits"] = exits;
7324
- });
7325
- }
7326
- const faction = edit.kind === "membership" ? parts[1] : parts[2];
7327
- if (faction === void 0) throw new InvalidEditProblems(["the relation key is invalid"]);
7328
- return await editEntityFile(world, FACTIONS_DIR, FACTION_FILE_NAME, faction, parseFactionFile, (document) => {
7329
- if (edit.kind === "membership") {
7330
- const character = parts[2];
7331
- const members = Array.isArray(document["members"]) ? document["members"] : [];
7332
- const index = members.findIndex((entry) => entry?.["character"] === character);
7333
- if (index < 0) throw new InvalidEditProblems(["the membership no longer exists"]);
7334
- if (edit.remove === true) members.splice(index, 1);
7335
- else for (const field of [
7336
- "role",
7337
- "rank",
7338
- "status",
7339
- "public",
7340
- "commitment"
7341
- ]) if (edit[field] !== void 0) members[index][field] = edit[field];
7342
- document["members"] = members;
7343
- } else {
7344
- const targetKind = parts[3];
7345
- const target = parts[4];
7346
- const relationships = Array.isArray(document["relationships"]) ? document["relationships"] : [];
7347
- const index = relationships.findIndex((entry) => typeof entry?.["to"] === "object" && entry["to"] !== null && entry["to"]["kind"] === targetKind && entry["to"]["id"] === target);
7348
- if (index < 0) throw new InvalidEditProblems(["the relationship no longer exists"]);
7349
- if (edit.remove === true) relationships.splice(index, 1);
7350
- else for (const field of [
7351
- "label",
7352
- "summary",
7353
- "familiarity",
7354
- "trust",
7355
- "affinity",
7356
- "tension"
7357
- ]) if (edit[field] !== void 0) relationships[index][field] = edit[field];
7358
- document["relationships"] = relationships;
7359
- }
7360
- });
7361
- }
7362
- async function characterOf(world, key) {
7363
- const { characters } = await loadCharacters(world.directory);
7364
- const character = characters.find((candidate) => candidate.id === key);
7365
- if (character === void 0) throw new InvalidEditProblems([`there is no character "${key}"`]);
7366
- return character;
7367
- }
7368
- /** What kinds of things besides characters have a reference picture, and what the images call them. */
7369
- const IMAGE_SUBJECT = {
7370
- place: "location",
7371
- thing: "item"
7372
- };
7373
- function imageOf(world, kind, id, globalId) {
7374
- const file = referenceImagePath(world.directory, {
7375
- kind: IMAGE_SUBJECT[kind],
7376
- localId: id,
7377
- ...globalId === void 0 ? {} : { globalId }
7378
- });
7379
- return existsSync(file) ? { image: `/${API_PREFIX}/worlds/state/${kind}/image/file?id=${encodeURIComponent(world.id)}&key=${encodeURIComponent(id)}&v=${statSync(file).mtimeMs}` } : {};
7380
- }
7381
- async function imageSubjectOf(world, kind, key) {
7382
- if (kind === "place") {
7383
- const { locations } = await loadLocations(world.directory);
7384
- const found = locations.find((candidate) => candidate.id === key);
7385
- if (found === void 0) throw new InvalidEditProblems([`there is no place "${key}"`]);
7386
- return {
7387
- id: found.id,
7388
- name: found.name,
7389
- ...found.visualIdentity === void 0 ? {} : { identity: found.visualIdentity }
7390
- };
7391
- }
7392
- const { characters } = await loadCharacters(world.directory);
7393
- const { locations } = await loadLocations(world.directory);
7394
- const { items } = await loadItems(world.directory, {
7395
- characters: characters.map((character) => character.id),
7396
- locations
7397
- });
7398
- const found = items.find((candidate) => candidate.id === key);
7399
- if (found === void 0) throw new InvalidEditProblems([`there is no thing "${key}"`]);
7400
- return {
7401
- id: found.id,
7402
- name: found.name,
7403
- ...found.visualIdentity === void 0 ? {} : { identity: found.visualIdentity }
7404
- };
7405
- }
7406
- /** Generate or replace the reference picture of an authored place or thing from its visual identity. */
7407
- async function generateWorldEntityImage(world, kind, key, service) {
7408
- const subject = await imageSubjectOf(world, kind, key);
7409
- if (subject.identity === void 0) throw new InvalidEditProblems([`${subject.name} needs a visual identity before a picture can be generated`]);
7410
- await generateReferenceImage(service, {
7411
- root: world.directory,
7412
- subject: {
7413
- kind: IMAGE_SUBJECT[kind],
7414
- localId: subject.id,
7415
- name: subject.name,
7416
- ...subject.identity.globalId === void 0 ? {} : { globalId: subject.identity.globalId }
7417
- },
7418
- identity: {
7419
- ...subject.identity,
7420
- subjectKind: IMAGE_SUBJECT[kind],
7421
- subjectId: 0,
7422
- version: 1,
7423
- updatedAt: ""
7424
- }
7425
- });
7426
- return await readWorldEditor(world);
7427
- }
7428
- /** The picture the author brought becomes the place's or thing's reference picture. */
7429
- async function uploadWorldEntityImage(world, kind, key, png, originalName) {
7430
- const subject = await imageSubjectOf(world, kind, key);
7431
- try {
7432
- await uploadReferenceImage({
7433
- root: world.directory,
7434
- subject: {
7435
- kind: IMAGE_SUBJECT[kind],
7436
- localId: subject.id,
7437
- name: subject.name,
7438
- ...subject.identity?.globalId === void 0 ? {} : { globalId: subject.identity.globalId }
7439
- },
7440
- png,
7441
- ...originalName === void 0 ? {} : { originalName }
7442
- });
7443
- } catch (error) {
7444
- throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
7445
- }
7446
- return await readWorldEditor(world);
7447
- }
7448
- /** Resolve the picture through authored data so request parameters cannot select arbitrary files. */
7449
- async function worldEntityImageFile(world, kind, key) {
7450
- const subject = await imageSubjectOf(world, kind, key);
7451
- const file = referenceImagePath(world.directory, {
7452
- kind: IMAGE_SUBJECT[kind],
7453
- localId: subject.id,
7454
- ...subject.identity?.globalId === void 0 ? {} : { globalId: subject.identity.globalId }
7455
- });
7456
- return {
7457
- file,
7458
- size: (await stat(file)).size
7459
- };
7460
- }
7461
- /** Generate or replace the authored character's stable reference portrait. */
7462
- async function generateWorldCharacterPortrait(world, key, service) {
7463
- const character = await characterOf(world, key);
7464
- const identity = character.visualIdentity;
7465
- if (identity === void 0) throw new InvalidEditProblems([`${character.name} needs a visual identity before a portrait can be generated`]);
7466
- await generateReferenceImage(service, {
7467
- root: world.directory,
7468
- subject: {
7469
- kind: "character",
7470
- localId: character.id,
7471
- name: character.name,
7472
- ...identity.globalId === void 0 ? {} : { globalId: identity.globalId }
7473
- },
7474
- identity: {
7475
- ...identity,
7476
- subjectKind: "character",
7477
- subjectId: 0,
7478
- version: 1,
7479
- updatedAt: ""
7480
- }
7481
- });
7482
- return await readWorldEditor(world);
7483
- }
7484
- /** The picture the author brought becomes the character's portrait. */
7485
- async function uploadWorldCharacterPortrait(world, key, png, originalName) {
7486
- const character = await characterOf(world, key);
7487
- try {
7488
- await uploadReferenceImage({
7489
- root: world.directory,
7490
- subject: {
7491
- kind: "character",
7492
- localId: character.id,
7493
- name: character.name,
7494
- ...character.visualIdentity?.globalId === void 0 ? {} : { globalId: character.visualIdentity.globalId }
7495
- },
7496
- png,
7497
- ...originalName === void 0 ? {} : { originalName }
7498
- });
7499
- } catch (error) {
7500
- throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
7501
- }
7502
- return await readWorldEditor(world);
7503
- }
7504
- /** Resolve a portrait through authored data so request parameters cannot select arbitrary files. */
7505
- async function worldCharacterPortraitFile(world, key) {
7506
- const character = await characterOf(world, key);
7507
- const file = referenceImagePath(world.directory, {
7508
- kind: "character",
7509
- localId: character.id,
7510
- ...character.visualIdentity?.globalId === void 0 ? {} : { globalId: character.visualIdentity.globalId }
7511
- });
7512
- return {
7513
- file,
7514
- size: (await stat(file)).size
7515
- };
7516
- }
7517
- /** The document of one trigger as the world's file has it, for editing. */
7518
- async function readWorldTrigger(world, key) {
7519
- const found = (await readTriggerDocuments(world.directory)).find((entry) => entry["key"] === key);
7520
- if (found === void 0) throw new InvalidEditProblems([`there is no trigger "${key}"`]);
7521
- return found;
7522
- }
7523
- /** Makes or replaces one trigger from a complete document, checked as a story start checks it, and answers the world as it stands. */
7524
- async function writeWorldTrigger(world, key, document) {
7525
- await writeTriggerDocument(world.directory, await loadWorldParts(world.directory), key, document);
7526
- return await readWorldEditor(world);
7527
- }
7528
- /** Removes one trigger, keeping its document in the world's trash, and answers the world as it stands. */
7529
- async function removeWorldTrigger(world, key) {
7530
- await deleteTriggerDocument(world.directory, key);
7531
- return await readWorldEditor(world);
7532
- }
7533
- //#endregion
7534
- //#region src/host/authoring/documents.ts
7535
- const AUTHORED_ENTITY_KINDS = [
7536
- "character",
7537
- "location",
7538
- "item",
7539
- "faction",
7540
- "lore"
7541
- ];
7542
- const formats = {
7543
- character: {
7544
- directory: CHARACTERS_DIR,
7545
- file: CHARACTER_FILE_NAME,
7546
- parse: parseCharacterFile
7547
- },
7548
- location: {
7549
- directory: LOCATIONS_DIR,
7550
- file: LOCATION_FILE_NAME,
7551
- parse: parseLocationFile
7552
- },
7553
- item: {
7554
- directory: ITEMS_DIR,
7555
- file: ITEM_FILE_NAME,
7556
- parse: parseItemFile
7557
- },
7558
- faction: {
7559
- directory: FACTIONS_DIR,
7560
- file: FACTION_FILE_NAME,
7561
- parse: parseFactionFile
7562
- },
7563
- lore: {
7564
- directory: LORE_DIR,
7565
- file: LORE_FILE_NAME,
7566
- parse: parseLoreFile
7567
- }
7568
- };
7569
- /** Keys become folder names and image paths: letters (any script), digits, marks, `.`, `_` and `-`, starting with a letter or digit. */
7570
- const NEW_KEY = /^[\p{L}\p{N}][\p{L}\p{N}\p{M}._-]{0,99}$/u;
7571
- function validNewKey(key) {
7572
- return NEW_KEY.test(key);
7573
- }
7574
- async function find(world, kind, key) {
7575
- const format = formats[kind];
7576
- const root = join(world.directory, format.directory);
7577
- for (const folder of await subfolders(root)) {
7578
- const file = join(root, folder, format.file);
7579
- try {
7580
- const parsed = format.parse(await readFile(file, "utf8"), folder);
7581
- if (parsed.ok && parsed.value.id === key) return {
7582
- folder,
7583
- file
7584
- };
7585
- } catch (error) {
7586
- if (error.code !== "ENOENT") throw error;
7587
- }
7588
- }
7589
- }
7590
- function serializeDocument(kind, key, value) {
7591
- if (typeof value !== "object" || value === null || Array.isArray(value)) throw new InvalidEditProblems(["document must be a JSON object"]);
7592
- const document = {
7593
- ...value,
7594
- id: key
7595
- };
7596
- const text = `${JSON.stringify(document, null, 2)}\n`;
7597
- const parsed = formats[kind].parse(text, key);
7598
- if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
7599
- return text;
7600
- }
7601
- async function replaceFile(file, text) {
7602
- const temporary = join(dirname(file), `.${basename(file)}.${process.pid}.${randomUUID()}.tmp`);
7603
- try {
7604
- const mode = await stat(file).then((value) => value.mode);
7605
- await writeFile(temporary, text, { mode });
7606
- await rename(temporary, file);
7607
- } catch (error) {
7608
- await rm(temporary, { force: true });
7609
- throw error;
7610
- }
7611
- }
7612
- async function readAuthoredEntityDocument(world, kind, key) {
7613
- const found = await find(world, kind, key);
7614
- if (found === void 0) throw new InvalidEditProblems([`there is no ${kind} "${key}"`]);
7615
- return JSON.parse((await readFile(found.file, "utf8")).replace(/^/, ""));
7616
- }
7617
- async function createAuthoredEntity(world, kind, key, document) {
7618
- if (!validNewKey(key)) throw new InvalidEditProblems(["key must be letters (any script), digits, \".\", \"_\" or \"-\", starting with a letter or digit, at most 100 characters (no brackets, spaces or slashes)"]);
7619
- if (await find(world, kind, key) !== void 0) throw new InvalidEditProblems([`the ${kind} "${key}" already exists`]);
7620
- const format = formats[kind];
7621
- const root = join(world.directory, format.directory);
7622
- const folder = join(root, key);
7623
- const text = serializeDocument(kind, key, document);
7624
- await mkdir(root, { recursive: true });
7625
- await mkdir(folder, { recursive: false });
7626
- try {
7627
- await writeFile(join(folder, format.file), text, { flag: "wx" });
7628
- } catch (error) {
7629
- await rm(folder, {
7630
- recursive: true,
7631
- force: true
7632
- });
7633
- throw error;
7634
- }
7635
- }
7636
- async function replaceAuthoredEntity(world, kind, key, document) {
7637
- const found = await find(world, kind, key);
7638
- if (found === void 0) throw new InvalidEditProblems([`there is no ${kind} "${key}"`]);
7639
- await replaceFile(found.file, serializeDocument(kind, key, document));
7640
- }
7641
- /** Deletions remain recoverable without making the trash visible to the world loaders. */
7642
- async function deleteAuthoredEntity(world, kind, key) {
7643
- const found = await find(world, kind, key);
7644
- if (found === void 0) throw new InvalidEditProblems([`there is no ${kind} "${key}"`]);
7645
- const trash = join(world.directory, ".trash", formats[kind].directory);
7646
- await mkdir(trash, { recursive: true });
7647
- const destination = join(trash, `${found.folder}-${Date.now()}-${randomUUID()}`);
7648
- await rename(dirname(found.file), destination);
7649
- return destination;
7650
- }
7651
- //#endregion
7652
- //#region src/host/interface/world-packs.ts
7653
- /** The kinds of file an assistant may write, as text. */
7654
- const TEXT_EXTENSIONS = [
7655
- "html",
7656
- "css",
7657
- "js",
7658
- "json",
7659
- "txt",
7660
- "svg"
7661
- ];
7662
- const folderOf = (directory, pack) => join(directory, "ui", pack);
7663
- function checked(directory, pack) {
7664
- if (!isPackId(pack)) throw new Error(`"${pack}" is not a usable pack name (letters, digits, "-" and "_")`);
7665
- return folderOf(directory, pack);
7666
- }
7667
- /** What every pack the world carries holds and what is wrong with it. */
7668
- function listWorldPacks(directory) {
7669
- return packIds(directory).map((id) => {
7670
- const { pack, problems } = readPack(folderOf(directory, id), id, (file) => file);
7671
- const files = pack === void 0 ? [] : [...pack.files.keys()];
7672
- return {
7673
- id,
7674
- name: pack?.manifest.name ?? id,
7675
- problems,
7676
- files
7677
- };
7678
- });
7679
- }
7680
- /** What is wrong with a pack (nothing when it can be used). */
7681
- function checkWorldPack(directory, pack) {
7682
- const folder = checked(directory, pack);
7683
- if (!existsSync(folder)) throw new Error(`the world carries no pack "${pack}"`);
7684
- return readPack(folder, pack, (file) => file).problems;
7685
- }
7686
- /** Moves a file of a pack into the world's `.trash`. @returns where it went, and what is wrong with the pack now. */
7687
- async function deleteWorldPackFile(directory, pack, path) {
7688
- const relative = packPath(path);
7689
- if (relative === void 0 || !(extname(relative).slice(1).toLowerCase() in PACK_MEDIA_TYPES)) throw new Error(`"${path}" is not a file of a pack`);
7690
- const folder = checked(directory, pack);
7691
- const file = join(folder, ...relative.split("/"));
7692
- if (!existsSync(file)) throw new Error(`the pack "${pack}" has no file "${path}"`);
7693
- const aside = join(directory, ".trash", "ui", pack, `${relative.replaceAll("/", "__")}.${Date.now()}`);
7694
- await mkdir(dirname(aside), { recursive: true });
7695
- await rename(file, aside);
7696
- return {
7697
- trashPath: aside,
7698
- problems: existsSync(join(folder, "pack.json")) ? readPack(folder, pack, (address) => address).problems : [{
7699
- file: "pack.json",
7700
- message: "the pack has no pack.json"
7701
- }]
7702
- };
7703
- }
7704
- //#endregion
7705
- //#region src/host/authoring/pack-jail.ts
7706
- /** DSH's own file tools, which the world authoring chat uses on the interface packs and nothing else. */
7707
- const PACK_FILE_TOOLS = [
7708
- "read",
7709
- "write",
7710
- "edit"
7711
- ];
7712
- const WRITING = ["write", "edit"];
7713
- /** The most text a call may carry. */
7714
- const MAX_PACK_TEXT = 204800;
7715
- function unsafePath(ui, path) {
7716
- const parts = relative(ui, path).split(sep);
7717
- let current = ui;
7718
- for (const part of ["", ...parts]) {
7719
- if (part !== "") current = join(current, part);
7720
- try {
7721
- if (lstatSync(current).isSymbolicLink()) return `the path passes through the symbolic link ${current}`;
7722
- } catch (error) {
7723
- if (error.code === "ENOENT") break;
7724
- if (error.code === "ENOTDIR") return `${current} cannot be traversed as a folder`;
7725
- throw error;
7726
- }
7727
- }
7728
- }
7729
- /**
7730
- * Why a call of a file tool is not one on an interface pack of the world, or nothing when it is: the file must be a text
7731
- * file of a pack folder `<world>/ui/<pack>/`, and a write must not carry more text than a pack file may hold.
7732
- * @param path - the absolute path asked for.
7733
- * @param world - the world's folder.
7734
- */
7735
- function packFileProblem(tool, path, world, texts = []) {
7736
- const ui = join(world, "ui");
7737
- const inside = relative(ui, path);
7738
- const segments = inside.split(sep);
7739
- const hint = `in this chat the file tools reach only the text files of the world's interface packs, ${join(ui, "<pack>", "<file>")}. Nothing, not another path and not sandbox_permissions, lifts that: do not try again for this file, tell the person that it cannot be changed from here`;
7740
- if (inside === "" || inside.startsWith("..") || isAbsolute(inside) || segments.length < 2) return `${path} is not a file of an interface pack: ${hint}`;
7741
- if (!isPackId(segments[0])) return `"${segments[0]}" is not a usable pack name (letters, digits, "-" and "_"): ${hint}`;
7742
- if (segments.some((segment) => segment.startsWith("."))) return `${path}: names may not start with a dot`;
7743
- if (!TEXT_EXTENSIONS.includes(extname(path).slice(1).toLowerCase())) return `${path} is not a text file of a pack (${TEXT_EXTENSIONS.join(", ")}); pictures and other files are added by hand`;
7744
- const unsafe = unsafePath(ui, path);
7745
- if (unsafe !== void 0) return `${path}: ${unsafe}; file tools do not follow symbolic links in interface packs`;
7746
- if (WRITING.includes(tool) && texts.some((text) => Buffer.byteLength(text) > 204800)) return `a call may carry at most ${MAX_PACK_TEXT / 1024} KB of text`;
7747
- }
7748
- const textOf = (value) => typeof value === "string" ? [value] : [];
7749
- /**
7750
- * Keeps DSH's `read`, `write` and `edit` on the interface packs of the world in an authoring chat, and asks the person before
7751
- * any change. It stands first in the chain, so that what it refuses cannot be let through by a listener after it; and what a
7752
- * later listener decides still stands: a plugin that denies or asks keeps doing so, and only a plain allow becomes an ask.
7753
- */
7754
- async function packJail(exec, next, deps) {
7755
- const chat = exec.agent?.session.id;
7756
- if (!PACK_FILE_TOOLS.includes(exec.name) || chat === void 0 || authoredWorldOf(chat) === void 0) return await next();
7757
- const world = await deps.worldDirectory(chat);
7758
- if (world === void 0) return {
7759
- kind: "deny",
7760
- reason: "the world of this chat no longer exists"
7761
- };
7762
- const args = exec.arguments;
7763
- const requested = args["file_path"];
7764
- if (typeof requested !== "string" || requested === "" || requested.startsWith("~")) return {
7765
- kind: "deny",
7766
- reason: "file_path must be a path of an interface pack of this world"
7767
- };
7768
- const path = resolve(exec.agent?.session.header.cwd ?? world, requested);
7769
- const problem = packFileProblem(exec.name, path, world, [...textOf(args["content"]), ...textOf(args["new_string"])]);
7770
- if (problem !== void 0) return {
7771
- kind: "deny",
7772
- reason: problem
7773
- };
7774
- const writing = WRITING.includes(exec.name);
7775
- if (writing && await deps.reviewing(chat)) return {
7776
- kind: "deny",
7777
- reason: "an import does not write interface packs; they are left to the person"
7778
- };
7779
- const decision = await next();
7780
- if (!writing || decision.kind !== "allow") return decision;
7781
- const target = `“${relative(join(world, "ui"), path)}”`;
7782
- return {
7783
- kind: "ask",
7784
- reason: `${exec.name} interface pack file ${target}`,
7785
- displayReason: {
7786
- en: `${exec.name === "write" ? "Write" : "Edit"} ${target} of an interface pack in the world files?`,
7787
- zh: `${exec.name === "write" ? "写入" : "编辑"}世界文件中界面包的文件${target}?`
7788
- }
7789
- };
7790
- }
7791
- /** Puts the jail first in the chain of `tools/pre-execute`: what it refuses cannot be let through by a listener after it. */
7792
- function registerPackJail(ctx, deps) {
7793
- ctx.on("tools/pre-execute", (exec, next) => packJail(exec, next, deps), { prepend: true });
7794
- }
7795
- //#endregion
7796
- export { populateCalendar as $, readCard as $t, worldEntityImageFile as A, loadVariables as At, translateMessage as B, parseWorldFile as Bt, readWorldEditor as C, subfolders as Ct, uploadWorldCharacterPortrait as D, readWorldPrompt as Dt, replaceFile$1 as E, listWorldPrompts as Et, loadWorldParts as F, IMPORT_FOLDER as Ft, authoringChatSessionId as G, parseLoreEdit as Gt, importHooks as H, InvalidEditProblems as Ht, PRESET_FILE as I, ImportNotFoundError as It, isReviewing as J, parseThingEdit as Jt, languageOfDocuments as K, parsePlaceEdit as Kt, presetMessage as L, ImportStore as Lt, deleteTriggerDocument as M, variableProblems as Mt, readTriggerDocuments as N, CHARACTER_FILE_NAME as Nt, uploadWorldEntityImage as O, writeWorldPrompt as Ot, writeTriggerDocument as P, parseCharacterFile as Pt, loadValidatedWorld as Q, pictureOf as Qt, presetTools as R, parseChoices as Rt, generateWorldEntityImage as S, loadCharacters as St, removeWorldTrigger as T, deleteWorldPrompt as Tt, importTools as U, parseCharacterEdit as Ut, translateTools as V, parseWorldInfoEdit as Vt, authoredWorldOf as W, parseFactionEdit as Wt, guardedLookup as X, ImportCardError as Xt, markReady as Y, IMPORT_COMMAND as Yt, vetUrl as Z, isPng as Zt, editWorldPlots as _, loadCalendar as _t, deleteWorldPackFile as a, populateKnowledge as at, entityFolder as b, loadItems as bt, createAuthoredEntity as c, populateRoutines as ct, replaceAuthoredEntity as d, routineProblems as dt, DICE_COMPARISONS as en, populateCharacters as et, editWorldCharacter as f, TRIGGERS_FILE_NAME as ft, editWorldPlace as g, CALENDAR_FILE_NAME as gt, editWorldNarrationVoice as h, parseDiceFile as ht, checkWorldPack as i, populateItems as it, writeWorldTrigger as j, parseVariablesFile as jt, worldCharacterPortraitFile as k, VARIABLES_FILE_NAME as kt, deleteAuthoredEntity as l, populateTriggers as lt, editWorldLore as m, loadDice as mt, packFileProblem as n, DICE_RESULTS as nn, populateDice as nt, listWorldPacks as o, populateLocations as ot, editWorldFaction as p, DICE_FILE_NAME as pt, readWorldDocuments as q, parseRelationEdit as qt, registerPackJail as r, populateFactions as rt, AUTHORED_ENTITY_KINDS as s, populateLore as st, MAX_PACK_TEXT as t, DICE_READINGS as tn, populateClock as tt, readAuthoredEntityDocument as u, populateVariables as ut, editWorldRelation as v, parseCalendarFile as vt, readWorldTrigger as w, PROSE_PROMPTS as wt, generateWorldCharacterPortrait as x, CHARACTERS_DIR as xt, editWorldThing as y, loadLocations as yt, readPreset as z, WORLD_FILE_NAME as zt };
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 };
7797
5948
 
7798
- //# sourceMappingURL=pack-jail-CybSNzxr.js.map
5949
+ //# sourceMappingURL=tools-Dy1fgP6B.js.map