@dsh-agentic-roleplay/core 0.3.5 → 0.4.0

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 (52) hide show
  1. package/lib/{preset-ClQm7KPQ.js → authoring-tools-C_8ClUkP.js} +542 -261
  2. package/lib/authoring.js +7 -5
  3. package/lib/{child-CFjnaTZt.js → child-DsixtqTw.js} +94 -2
  4. package/lib/client.js +16938 -14212
  5. package/lib/client.js.map +1 -1
  6. package/lib/compaction.js +1 -1
  7. package/lib/doctor.js +2 -4
  8. package/lib/{gallery-DIEgETzU.js → gallery-CDYKJf_O.js} +2 -2
  9. package/lib/{generator-DJ48HxPI.js → generator-BR1ugzln.js} +2 -2
  10. package/lib/{deliver-Cl6bjp7g.js → hooks-B2EhBS_-.js} +1884 -236
  11. package/lib/images.js +4 -4
  12. package/lib/index.js +1200 -242
  13. package/lib/{library-9JB9zw5a.js → library-COIktKBa.js} +4 -3
  14. package/lib/lorebook-author-tools-C-o0t4dL.js +694 -0
  15. package/lib/lorebook-authoring.js +69 -0
  16. package/lib/{settings-CA6icLL_.js → narration-BT9uvQry.js} +145 -2
  17. package/lib/orchestration.js +34 -21
  18. package/lib/{pack-jail-ClMpVc__.js → pack-jail-soI-In96.js} +170 -12
  19. package/lib/{packs-BC2A3geF.js → packs-CJPSe5LI.js} +7 -4
  20. package/lib/{presenter-agent-DnNEG_Mn.js → presenter-agent-Gu34bZwd.js} +6 -6
  21. package/lib/preset-3zn8xme7.js +242 -0
  22. package/lib/{preset-author-tools-Dibp-LY9.js → preset-author-tools-C-X8G40s.js} +24 -18
  23. package/lib/preset-authoring.js +6 -3
  24. package/lib/{presets-DNjNxQL5.js → presets-C3mhqqfz.js} +50 -28
  25. package/lib/{reflection-Bju_LPFn.js → reflection-Btsj0ZLh.js} +51 -17
  26. package/package.json +3 -2
  27. package/packs/scene/map.html +1 -0
  28. package/packs/scene/strip.html +1 -0
  29. package/prompts/en/import/lorebook.md +8 -0
  30. package/prompts/en/import/style.md +1 -0
  31. package/prompts/en/lorebook/persona.md +1 -0
  32. package/prompts/en/lorebook/procedure.md +1 -0
  33. package/prompts/en/lorebook/welcome.md +1 -0
  34. package/prompts/en/preset/persona.md +1 -1
  35. package/prompts/en/preset/procedure.md +1 -1
  36. package/prompts/en/roleplay/character-lookup.md +1 -0
  37. package/prompts/en/roleplay/game-master.md +1 -1
  38. package/prompts/en/world/procedure.md +1 -1
  39. package/prompts/zh/import/lorebook.md +8 -0
  40. package/prompts/zh/import/style.md +1 -0
  41. package/prompts/zh/lorebook/persona.md +1 -0
  42. package/prompts/zh/lorebook/procedure.md +1 -0
  43. package/prompts/zh/lorebook/welcome.md +1 -0
  44. package/prompts/zh/preset/persona.md +1 -1
  45. package/prompts/zh/preset/procedure.md +1 -1
  46. package/prompts/zh/roleplay/character-lookup.md +1 -0
  47. package/prompts/zh/roleplay/game-master.md +1 -1
  48. package/prompts/zh/world/procedure.md +1 -1
  49. package/lib/hooks-DdO_tNhu.js +0 -1060
  50. package/lib/language-BgyxtB2h.js +0 -38
  51. package/lib/load-Clkl0T7C.js +0 -486
  52. package/lib/narration-DK2kiIjE.js +0 -141
@@ -1,13 +1,15 @@
1
- import { b as INTENT_TYPES, i as isPresetName, p as PROSE_PROMPTS, v as INTENT_HORIZONS, y as INTENT_STATUSES } from "./presets-DNjNxQL5.js";
2
- import { c as VARIABLE_SUBJECTS, i as parseSwitchboard, l as VARIABLE_VISIBILITIES, s as VARIABLE_KINDS } from "./settings-CA6icLL_.js";
3
- import { S as InvalidWorldError, _ as shippedLanguages, a as readDocument, c as formatIssue, g as promptProblem, i as plotReferenceProblems, n as loadPlots, o as errorMessage, s as Reader, u as PROMPTS_FOLDER } from "./load-Clkl0T7C.js";
4
- import { a as runChild } from "./child-CFjnaTZt.js";
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";
1
+ import { a as isPresetName, b as INTENT_STATUSES, m as PROSE_PROMPTS, x as INTENT_TYPES, y as INTENT_HORIZONS } from "./presets-C3mhqqfz.js";
2
+ import { _ as VARIABLE_VISIBILITIES, f as parseSwitchboard, g as VARIABLE_SUBJECTS, h as VARIABLE_KINDS } from "./narration-BT9uvQry.js";
3
+ import { B as readDocument, G as PROMPTS_FOLDER, H as formatIssue, L as loadPlots, Q as shippedLanguages, U as errorMessage, V as Reader, Z as promptProblem, a as externalWithheld, nt as InvalidWorldError, r as externalGiven, t as externalToolLimit, z as plotReferenceProblems } from "./hooks-B2EhBS_-.js";
4
+ import { a as runChild, h as trimCharacters, s as parseSampling } from "./child-DsixtqTw.js";
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-COIktKBa.js";
6
6
  import { dirname, join } from "node:path";
7
+ import { existsSync, readFileSync } from "node:fs";
7
8
  import { createHash, randomUUID } from "node:crypto";
8
9
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
9
10
  import { inflateSync } from "node:zlib";
10
11
  import { defineTool } from "@deepseek-ai/dsh-tools";
12
+ import { Service } from "@deepseek-ai/cordis";
11
13
  import { cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
12
14
  import { MAX_ROUTINE_WINDOWS, MINUTE, MONTH_NAMES, SEASONS, checkProblems, createSessionStore, dayTokenProblems, isTimeZone, parseInstant, parseTimeOfDay, readTriggerDefinition, triggerReferenceProblems, valueIssue, writeCalendar } from "@dsh-agentic-roleplay/state";
13
15
  import { lookup } from "node:dns";
@@ -146,6 +148,8 @@ const LORE_KINDS = [
146
148
  "legend",
147
149
  "other"
148
150
  ];
151
+ /** 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). */
152
+ const LORE_SCOPES = ["everyone", "listed"];
149
153
  const LORE_SUBJECT_KINDS = [
150
154
  "character",
151
155
  "faction",
@@ -247,7 +251,7 @@ function urlsOf(value) {
247
251
  const visit = (node, depth) => {
248
252
  if (depth > 32) return;
249
253
  if (typeof node === "string") for (const match of node.matchAll(URL_PATTERN)) {
250
- const url = match[0].replace(/[.,;:!?*_~]+$/, "");
254
+ const url = trimCharacters(match[0], ".,;:!?*_~", "end");
251
255
  if (!url.includes("$") && url.length <= 2e3) found.add(url);
252
256
  }
253
257
  else if (Array.isArray(node)) for (const entry of node) visit(entry, depth + 1);
@@ -257,7 +261,7 @@ function urlsOf(value) {
257
261
  return [...found];
258
262
  }
259
263
  const object = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
260
- const text$2 = (value) => typeof value === "string" ? value : typeof value === "number" ? String(value) : "";
264
+ const text$1 = (value) => typeof value === "string" ? value : typeof value === "number" ? String(value) : "";
261
265
  const texts = (value) => Array.isArray(value) ? value.flatMap((entry) => typeof entry === "string" ? [entry] : typeof entry === "number" ? [String(entry)] : []) : [];
262
266
  function entryOf(value, index) {
263
267
  const entry = object(value);
@@ -265,10 +269,10 @@ function entryOf(value, index) {
265
269
  const position = entry["position"];
266
270
  return {
267
271
  id: `entry:${index}`,
268
- title: text$2(entry["comment"]).trim() || text$2(entry["name"]).trim(),
272
+ title: text$1(entry["comment"]).trim() || text$1(entry["name"]).trim(),
269
273
  keys: texts(entry["keys"]),
270
274
  secondaryKeys: texts(entry["secondary_keys"]),
271
- content: text$2(entry["content"]),
275
+ content: text$1(entry["content"]),
272
276
  enabled: entry["enabled"] !== false,
273
277
  constant: entry["constant"] === true,
274
278
  selective: entry["selective"] === true,
@@ -283,10 +287,10 @@ function entryOf(value, index) {
283
287
  function readCard(file, name) {
284
288
  const root = object(jsonOf(file, name));
285
289
  const spec = root === void 0 ? void 0 : root["spec"];
286
- if (spec !== "chara_card_v2" && spec !== "chara_card_v3") throw new ImportCardError(spec === void 0 ? `${name} is not a V2 or V3 character card (it has no "spec")` : `${name} is a "${text$2(spec)}" card: only V2 and V3 cards are read`);
290
+ if (spec !== "chara_card_v2" && spec !== "chara_card_v3") throw new ImportCardError(spec === void 0 ? `${name} is not a V2 or V3 character card (it has no "spec")` : `${name} is a "${text$1(spec)}" card: only V2 and V3 cards are read`);
287
291
  const data = object(root?.["data"]);
288
292
  if (data === void 0) throw new ImportCardError(`${name} has no card data`);
289
- const cardName = text$2(data["name"]).trim();
293
+ const cardName = text$1(data["name"]).trim();
290
294
  if (cardName === "") throw new ImportCardError(`${name} has a card with no name`);
291
295
  const book = object(data["character_book"]);
292
296
  const entries = Array.isArray(book?.["entries"]) ? book["entries"].flatMap((entry, index) => entryOf(entry, index) ?? []) : [];
@@ -295,21 +299,21 @@ function readCard(file, name) {
295
299
  return {
296
300
  sourceSpec: spec,
297
301
  name: cardName,
298
- description: text$2(data["description"]),
299
- personality: text$2(data["personality"]),
300
- scenario: text$2(data["scenario"]),
301
- firstMessage: text$2(data["first_mes"]),
302
+ description: text$1(data["description"]),
303
+ personality: text$1(data["personality"]),
304
+ scenario: text$1(data["scenario"]),
305
+ firstMessage: text$1(data["first_mes"]),
302
306
  alternateGreetings: texts(data["alternate_greetings"]),
303
- messageExample: text$2(data["mes_example"]),
304
- creatorNotes: text$2(data["creator_notes"]),
305
- systemPrompt: text$2(data["system_prompt"]),
306
- postHistoryInstructions: text$2(data["post_history_instructions"]),
307
+ messageExample: text$1(data["mes_example"]),
308
+ creatorNotes: text$1(data["creator_notes"]),
309
+ systemPrompt: text$1(data["system_prompt"]),
310
+ postHistoryInstructions: text$1(data["post_history_instructions"]),
307
311
  tags: texts(data["tags"]),
308
- creator: text$2(data["creator"]),
309
- characterVersion: text$2(data["character_version"]),
312
+ creator: text$1(data["creator"]),
313
+ characterVersion: text$1(data["character_version"]),
310
314
  ...book === void 0 ? {} : { book: {
311
- name: text$2(book["name"]),
312
- description: text$2(book["description"]),
315
+ name: text$1(book["name"]),
316
+ description: text$1(book["description"]),
313
317
  entries
314
318
  } },
315
319
  ignored: {
@@ -332,10 +336,16 @@ const isPng = (file) => file.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNAT
332
336
  const IMPORT_COMMAND = "/import-st";
333
337
  /** The command in a message, with the card it names, or nothing when the message is not the command. */
334
338
  function parseImportCommand(text) {
335
- const match = /^\s*\/import-st(?=\s|$)\s*(\S*)\s*([\s\S]*)$/i.exec(text);
336
- return match === null ? void 0 : {
337
- card: match[1] ?? "",
338
- request: (match[2] ?? "").trim()
339
+ const value = text.trimStart();
340
+ if (value.slice(0, 10).toLowerCase() !== "/import-st" || value.length > 10 && !/\s/u.test(value[10])) return void 0;
341
+ const body = value.slice(10).trimStart();
342
+ const boundary = body.search(/\s/u);
343
+ return boundary < 0 ? {
344
+ card: body,
345
+ request: ""
346
+ } : {
347
+ card: body.slice(0, boundary),
348
+ request: body.slice(boundary).trim()
339
349
  };
340
350
  }
341
351
  //#endregion
@@ -701,6 +711,8 @@ function parseLoreEdit(value) {
701
711
  for (const key of Object.keys(input)) if (![
702
712
  "title",
703
713
  "kind",
714
+ "scope",
715
+ "knownBy",
704
716
  "summary",
705
717
  "body",
706
718
  "startsAt",
@@ -721,6 +733,16 @@ function parseLoreEdit(value) {
721
733
  if (typeof input["kind"] !== "string" || !LORE_KINDS.includes(input["kind"])) problems.push(`kind must be one of: ${LORE_KINDS.join(", ")}`);
722
734
  else edit.kind = input["kind"];
723
735
  }
736
+ if ("scope" in input) {
737
+ if (typeof input["scope"] !== "string" || !LORE_SCOPES.includes(input["scope"])) problems.push(`scope must be one of: ${LORE_SCOPES.join(", ")}`);
738
+ else edit.scope = input["scope"];
739
+ }
740
+ if ("knownBy" in input) {
741
+ const found = input["knownBy"];
742
+ if (!Array.isArray(found) || !found.every((entry) => typeof entry === "string" && entry.trim() !== "" && entry.length <= TEXT_LIMIT)) problems.push("knownBy must be a list of names");
743
+ else edit.knownBy = found.map((entry) => entry.trim());
744
+ }
745
+ if (edit.scope === "everyone" && (edit.knownBy?.length ?? 0) > 0) problems.push("an entry everyone knows has no list of who knows it");
724
746
  for (const key of ["startsAt", "endsAt"]) if (key in input) {
725
747
  const found = input[key];
726
748
  if (found !== null && (typeof found !== "number" || !Number.isFinite(found))) problems.push(`${key} must be a timestamp or null`);
@@ -895,6 +917,348 @@ function readIdentifier(reader, fallback) {
895
917
  if (id !== void 0 && id.length > 100) reader.fail("id", `must be at most 100 characters`);
896
918
  return id;
897
919
  }
920
+ //#endregion
921
+ //#region src/host/folders.ts
922
+ /**
923
+ * Names of the subfolders of `dir`, sorted. Symbolic links are not followed
924
+ * and a missing directory has none; any other failure is thrown.
925
+ */
926
+ async function subfolders(dir) {
927
+ try {
928
+ return (await readdir(dir, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort((a, b) => a.localeCompare(b));
929
+ } catch (error) {
930
+ if (error.code === "ENOENT") return [];
931
+ throw error;
932
+ }
933
+ }
934
+ //#endregion
935
+ //#region src/host/lore/lore-file.ts
936
+ const LORE_FILE_NAME = "lore.json";
937
+ function instant(reader, key) {
938
+ const value = reader.string(key);
939
+ if (value === void 0) return void 0;
940
+ const parsed = Date.parse(value);
941
+ if (!Number.isFinite(parsed)) {
942
+ reader.fail(key, "must be an ISO date or date-time");
943
+ return;
944
+ }
945
+ return parsed;
946
+ }
947
+ function parseLoreFile(text, fallbackId) {
948
+ const issues = [];
949
+ const reader = Reader.fromJson(text, issues);
950
+ if (reader === void 0) return {
951
+ ok: false,
952
+ issues
953
+ };
954
+ const id = readIdentifier(reader, fallbackId) ?? fallbackId;
955
+ const title = reader.string("title", { required: true }) ?? "";
956
+ const subjects = reader.objects("subjects").flatMap((entry) => {
957
+ const kind = entry.oneOf("kind", LORE_SUBJECT_KINDS, "lore");
958
+ const subjectId = entry.string("id", { required: true });
959
+ return subjectId === void 0 ? [] : [{
960
+ kind,
961
+ id: subjectId
962
+ }];
963
+ });
964
+ const startsAt = instant(reader, "starts_at");
965
+ const endsAt = instant(reader, "ends_at");
966
+ if (startsAt !== void 0 && endsAt !== void 0 && endsAt < startsAt) reader.fail("ends_at", "must not be before starts_at");
967
+ const scope = reader.oneOf("scope", LORE_SCOPES, "listed");
968
+ const knownBy = reader.strings("known_by");
969
+ if (scope === "everyone" && knownBy.length > 0) reader.fail("known_by", "applies only to lore whose scope is \"listed\"");
970
+ const value = {
971
+ id,
972
+ title,
973
+ kind: reader.oneOf("kind", LORE_KINDS, "other"),
974
+ scope,
975
+ knownBy,
976
+ summary: reader.text("summary"),
977
+ body: reader.text("body"),
978
+ subjects,
979
+ related: reader.strings("related"),
980
+ sources: reader.strings("sources"),
981
+ ...startsAt === void 0 ? {} : { startsAt },
982
+ ...endsAt === void 0 ? {} : { endsAt }
983
+ };
984
+ return issues.length === 0 ? {
985
+ ok: true,
986
+ value
987
+ } : {
988
+ ok: false,
989
+ issues
990
+ };
991
+ }
992
+ //#endregion
993
+ //#region src/host/lore/load.ts
994
+ const LORE_DIR = "lore";
995
+ async function loadLore(worldDir) {
996
+ const dir = join(worldDir, LORE_DIR);
997
+ const result = {
998
+ lore: [],
999
+ problems: []
1000
+ };
1001
+ let folders;
1002
+ try {
1003
+ folders = await subfolders(dir);
1004
+ } catch (error) {
1005
+ if (error.code !== "ENOENT") result.problems.push({
1006
+ path: dir,
1007
+ message: errorMessage(error)
1008
+ });
1009
+ return result;
1010
+ }
1011
+ const owners = /* @__PURE__ */ new Map();
1012
+ for (const folder of folders) {
1013
+ const file = join(dir, folder, LORE_FILE_NAME);
1014
+ try {
1015
+ const entry = await readDocument(file, (text) => parseLoreFile(text, folder), result.problems);
1016
+ if (entry === void 0) continue;
1017
+ const owner = owners.get(entry.id);
1018
+ if (owner !== void 0) {
1019
+ result.problems.push({
1020
+ path: file,
1021
+ message: `id "${entry.id}" is already used by ${owner}`
1022
+ });
1023
+ continue;
1024
+ }
1025
+ owners.set(entry.id, folder);
1026
+ result.lore.push(entry);
1027
+ } catch (error) {
1028
+ if (error.code !== "ENOENT") result.problems.push({
1029
+ path: file,
1030
+ message: errorMessage(error)
1031
+ });
1032
+ }
1033
+ }
1034
+ if (result.lore.length > 500) result.problems.push({
1035
+ path: dir,
1036
+ message: `a world has at most 500 lore entries`
1037
+ });
1038
+ return result;
1039
+ }
1040
+ //#endregion
1041
+ //#region src/host/lorebooks/lorebooks.ts
1042
+ const LOREBOOKS_FOLDER = "lorebooks";
1043
+ const LOREBOOK_FILE = "lorebook.json";
1044
+ const NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
1045
+ const ENTRY_ID = /^[\p{L}\p{N}][\p{L}\p{N}_-]{0,79}$/u;
1046
+ const MAX_TEXT = 300;
1047
+ const isLorebookName = (name) => NAME.test(name);
1048
+ const isEntryId = (id) => ENTRY_ID.test(id);
1049
+ const lorebooksDirectory = (root) => join(root, LOREBOOKS_FOLDER);
1050
+ function lorebookDirectory(root, name) {
1051
+ if (!isLorebookName(name)) throw new Error(`"${name}" is not a usable lorebook name (letters, digits, "-" and "_", up to 64)`);
1052
+ return join(lorebooksDirectory(root), name);
1053
+ }
1054
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1055
+ function parseHeader(value, problems) {
1056
+ if (!isRecord(value)) {
1057
+ problems.push(`${LOREBOOK_FILE} must be an object`);
1058
+ return {};
1059
+ }
1060
+ const text = (key) => {
1061
+ const field = value[key];
1062
+ if (field === void 0 || field === null) return void 0;
1063
+ if (typeof field !== "string" || field.length > MAX_TEXT) {
1064
+ problems.push(`${LOREBOOK_FILE}: "${key}" must be text of at most ${MAX_TEXT} characters`);
1065
+ return;
1066
+ }
1067
+ return field.trim() || void 0;
1068
+ };
1069
+ const title = text("title");
1070
+ const description = text("description");
1071
+ return {
1072
+ ...title === void 0 ? {} : { title },
1073
+ ...description === void 0 ? {} : { description }
1074
+ };
1075
+ }
1076
+ function readHeader(directory, problems) {
1077
+ const file = join(directory, LOREBOOK_FILE);
1078
+ if (!existsSync(file)) return {};
1079
+ let value;
1080
+ try {
1081
+ value = JSON.parse(readFileSync(file, "utf8"));
1082
+ } catch {
1083
+ problems.push(`${LOREBOOK_FILE} is not valid JSON`);
1084
+ return {};
1085
+ }
1086
+ return parseHeader(value, problems);
1087
+ }
1088
+ /** 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. */
1089
+ function bookProblems(entries) {
1090
+ const ids = new Set(entries.map((entry) => entry.id));
1091
+ 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`])]);
1092
+ }
1093
+ /** Reads one lorebook folder, collecting every problem instead of stopping at the first. @throws {Error} when the folder does not exist. */
1094
+ async function readLorebook(directory, name) {
1095
+ if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
1096
+ const problems = [];
1097
+ const header = readHeader(directory, problems);
1098
+ const { lore, problems: found } = await loadLore(directory);
1099
+ for (const problem of found) problems.push(`${problem.path.slice(directory.length + 1)}: ${problem.message}`);
1100
+ problems.push(...bookProblems(lore));
1101
+ if (lore.length === 0 && problems.length === 0) problems.push("the lorebook has no entries");
1102
+ return {
1103
+ summary: {
1104
+ name,
1105
+ title: header.title ?? name,
1106
+ description: header.description ?? "",
1107
+ entries: lore.length,
1108
+ common: lore.filter((entry) => entry.scope === "everyone").length,
1109
+ problems
1110
+ },
1111
+ entries: lore.sort((a, b) => a.title.localeCompare(b.title))
1112
+ };
1113
+ }
1114
+ async function listLorebooks(root) {
1115
+ const folder = lorebooksDirectory(root);
1116
+ if (!existsSync(folder)) return [];
1117
+ const found = (await readdir(folder, { withFileTypes: true })).filter((entry) => entry.isDirectory() && isLorebookName(entry.name));
1118
+ return (await Promise.all(found.map((entry) => readLorebook(join(folder, entry.name), entry.name)))).sort((a, b) => a.summary.name.localeCompare(b.summary.name));
1119
+ }
1120
+ async function loadLorebook(root, name) {
1121
+ return await readLorebook(lorebookDirectory(root, name), name);
1122
+ }
1123
+ const toEntry = (definition) => ({
1124
+ id: definition.id,
1125
+ title: definition.title,
1126
+ kind: definition.kind,
1127
+ scope: definition.scope,
1128
+ knownBy: definition.knownBy,
1129
+ summary: definition.summary,
1130
+ body: definition.body,
1131
+ related: definition.related
1132
+ });
1133
+ const entriesOf = (book) => book.entries.map(toEntry);
1134
+ function headerFile(header) {
1135
+ return `${JSON.stringify(header, null, 2)}\n`;
1136
+ }
1137
+ async function writeAtomic(file, text) {
1138
+ await mkdir(dirname(file), { recursive: true });
1139
+ await writeFile(`${file}.tmp`, text);
1140
+ await rename(`${file}.tmp`, file);
1141
+ }
1142
+ /** Makes an empty lorebook. @throws {Error} when the name is taken or the information is not acceptable. */
1143
+ async function createLorebook(root, request) {
1144
+ const target = lorebookDirectory(root, request.name);
1145
+ if (existsSync(target)) throw new Error(`there is already a lorebook "${request.name}"`);
1146
+ const problems = [];
1147
+ const header = parseHeader({
1148
+ title: request.title?.trim(),
1149
+ description: request.description?.trim()
1150
+ }, problems);
1151
+ if (problems.length > 0) throw new Error(problems.join("; "));
1152
+ await writeAtomic(join(target, LOREBOOK_FILE), headerFile(header));
1153
+ return await readLorebook(target, request.name);
1154
+ }
1155
+ /** 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. */
1156
+ async function reserveLorebook(root, name, title) {
1157
+ const target = lorebookDirectory(root, name);
1158
+ if (existsSync(target)) throw new Error(`there is already a lorebook "${name}"`);
1159
+ await writeAtomic(join(target, LOREBOOK_FILE), headerFile({ title: title.trim().slice(0, MAX_TEXT) || name }));
1160
+ return target;
1161
+ }
1162
+ /** 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. */
1163
+ async function updateLorebookInfo(root, name, change) {
1164
+ const directory = lorebookDirectory(root, name);
1165
+ if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
1166
+ const current = readHeader(directory, []);
1167
+ const problems = [];
1168
+ const next = parseHeader({
1169
+ title: change.title ?? current.title,
1170
+ description: change.description ?? current.description
1171
+ }, problems);
1172
+ if (problems.length > 0) throw new Error(problems.join("; "));
1173
+ await writeAtomic(join(directory, LOREBOOK_FILE), headerFile(next));
1174
+ return await readLorebook(directory, name);
1175
+ }
1176
+ /** The file of an entry: written in the format of a world's own lore, with its scope always said. */
1177
+ function entryFile(entry) {
1178
+ return `${JSON.stringify({
1179
+ title: entry.title,
1180
+ kind: entry.kind,
1181
+ scope: entry.scope,
1182
+ ...entry.scope === "listed" && entry.knownBy.length > 0 ? { known_by: entry.knownBy } : {},
1183
+ summary: entry.summary,
1184
+ body: entry.body,
1185
+ ...entry.related.length > 0 ? { related: entry.related } : {}
1186
+ }, null, 2)}\n`;
1187
+ }
1188
+ /** Checks an entry the way a story start would, before anything is written. @returns why it cannot be used, or nothing. */
1189
+ function entryProblem(entry) {
1190
+ if (!isEntryId(entry.id)) return `"${entry.id}" is not a usable entry id (letters, digits, "-" and "_", up to 80)`;
1191
+ if (!LORE_KINDS.includes(entry.kind)) return `kind must be one of ${LORE_KINDS.join(", ")}`;
1192
+ if (!LORE_SCOPES.includes(entry.scope)) return `scope must be one of ${LORE_SCOPES.join(", ")}`;
1193
+ if (entry.title.trim() === "") return "the entry needs a title";
1194
+ if (entry.body.trim() === "" && entry.summary.trim() === "") return "the entry needs a summary or a body";
1195
+ const parsed = parseLoreFile(entryFile({
1196
+ ...entry,
1197
+ title: entry.title.trim()
1198
+ }), entry.id);
1199
+ return parsed.ok ? void 0 : parsed.issues.map((issue) => `${issue.path}: ${issue.message}`).join("; ");
1200
+ }
1201
+ /**
1202
+ * Creates several new entries of a lorebook at once, each checked as `writeLorebookEntry` checks one; none is written when any is not acceptable.
1203
+ * @throws {Error} when the lorebook does not exist, an id is taken or an entry is not acceptable, or the book would have more entries than a world may.
1204
+ */
1205
+ async function addLorebookEntries(root, name, entries) {
1206
+ const directory = lorebookDirectory(root, name);
1207
+ if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
1208
+ const book = await readLorebook(directory, name);
1209
+ if (book.entries.length + entries.length > 500) throw new Error(`a lorebook has at most 500 entries`);
1210
+ const ids = new Set(book.entries.map((entry) => entry.id));
1211
+ for (const entry of entries) {
1212
+ const problem = entryProblem(entry);
1213
+ if (problem !== void 0) throw new Error(`entry "${entry.title}": ${problem}`);
1214
+ if (ids.has(entry.id)) throw new Error(`there is already an entry "${entry.id}"`);
1215
+ ids.add(entry.id);
1216
+ }
1217
+ for (const entry of entries) await writeAtomic(join(directory, LORE_DIR, entry.id, LORE_FILE_NAME), entryFile({
1218
+ ...entry,
1219
+ title: entry.title.trim()
1220
+ }));
1221
+ return await readLorebook(directory, name);
1222
+ }
1223
+ /** 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. */
1224
+ async function writeLorebookEntry(root, name, entry) {
1225
+ const directory = lorebookDirectory(root, name);
1226
+ if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
1227
+ const problem = entryProblem(entry);
1228
+ if (problem !== void 0) throw new Error(problem);
1229
+ const file = join(directory, LORE_DIR, entry.id, LORE_FILE_NAME);
1230
+ const book = await readLorebook(directory, name);
1231
+ if (!existsSync(file) && book.entries.length >= 500) throw new Error(`a lorebook has at most 500 entries`);
1232
+ const others = book.entries.filter((other) => other.id !== entry.id);
1233
+ const missing = entry.related.filter((id) => id === entry.id || !others.some((other) => other.id === id));
1234
+ if (missing.length > 0) throw new Error(`related: ${missing.map((id) => `"${id}"`).join(", ")} ${missing.length === 1 ? "is" : "are"} not (other) entries of this book`);
1235
+ await writeAtomic(file, entryFile({
1236
+ ...entry,
1237
+ title: entry.title.trim()
1238
+ }));
1239
+ return await readLorebook(directory, name);
1240
+ }
1241
+ /** Moves an entry into the book's `.trash`. @throws {Error} when it does not exist or other entries relate to it. */
1242
+ async function deleteLorebookEntry(root, name, id, now = Date.now) {
1243
+ const directory = lorebookDirectory(root, name);
1244
+ const folder = join(directory, LORE_DIR, id);
1245
+ if (!isEntryId(id) || !existsSync(join(folder, "lore.json"))) throw new Error(`the lorebook "${name}" has no entry "${id}"`);
1246
+ const citing = (await readLorebook(directory, name)).entries.filter((entry) => entry.id !== id && entry.related.includes(id)).map((entry) => entry.id);
1247
+ if (citing.length > 0) throw new Error(`the entries ${citing.join(", ")} relate to "${id}"; change them first`);
1248
+ const aside = join(directory, ".trash", LORE_DIR, `${id}-${now()}`);
1249
+ await mkdir(dirname(aside), { recursive: true });
1250
+ await rename(folder, aside);
1251
+ return await readLorebook(directory, name);
1252
+ }
1253
+ /** Moves a lorebook out of the library into `<root>/.trash/lorebooks/`. @returns where it went. */
1254
+ async function deleteLorebook(root, name, now = Date.now) {
1255
+ const directory = lorebookDirectory(root, name);
1256
+ if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
1257
+ const aside = join(root, ".trash", LOREBOOKS_FOLDER, `${name}-${now()}`);
1258
+ await mkdir(dirname(aside), { recursive: true });
1259
+ await rename(directory, aside);
1260
+ return aside;
1261
+ }
898
1262
  const MAX_OPENING_CHARS = 2e4;
899
1263
  const TEXT_FIELDS = [
900
1264
  "name",
@@ -907,14 +1271,18 @@ const TEXT_FIELDS = [
907
1271
  "version",
908
1272
  "preset"
909
1273
  ];
910
- const LIST_FIELDS = ["tags", "rules"];
1274
+ const LIST_FIELDS = [
1275
+ "tags",
1276
+ "rules",
1277
+ "lorebooks"
1278
+ ];
911
1279
  /** Reads a body that came from the browser; every field is checked and each problem is reported. */
912
1280
  function parseWorldInfoEdit(value) {
913
1281
  const problems = [];
914
1282
  const input = typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
915
1283
  if (input === void 0) throw new InvalidEditProblems(["the changes must be an object"]);
916
1284
  const edit = {};
917
- for (const key of Object.keys(input)) if (!TEXT_FIELDS.includes(key) && !LIST_FIELDS.includes(key) && key !== "alternateOpenings" && key !== "tools") problems.push(`there is no field "${key}"`);
1285
+ for (const key of Object.keys(input)) if (!TEXT_FIELDS.includes(key) && !LIST_FIELDS.includes(key) && key !== "alternateOpenings" && key !== "tools" && key !== "sampling") problems.push(`there is no field "${key}"`);
918
1286
  for (const key of TEXT_FIELDS) {
919
1287
  if (input[key] === void 0) continue;
920
1288
  if (typeof input[key] === "string") edit[key] = input[key].trim();
@@ -945,6 +1313,7 @@ function parseWorldInfoEdit(value) {
945
1313
  if (typeof board === "string") problems.push(board);
946
1314
  else edit["tools"] = board;
947
1315
  }
1316
+ if (input["sampling"] !== void 0) edit["sampling"] = parseSampling(input["sampling"], "sampling", problems);
948
1317
  if (typeof edit["version"] === "string" && edit["version"].length > 40) problems.push(`the version is longer than 40 characters`);
949
1318
  if (edit["name"] === "") problems.push("the world needs a name");
950
1319
  if (typeof edit["name"] === "string" && edit["name"].length > 200) problems.push(`the name is longer than 200 characters`);
@@ -988,6 +1357,13 @@ function readTools(reader) {
988
1357
  }
989
1358
  return Object.keys(board).length === 0 ? void 0 : board;
990
1359
  }
1360
+ /** `sampling` is an object of the controls a story's requests may carry (see `StorySampling`). */
1361
+ function readSampling(reader) {
1362
+ const problems = [];
1363
+ const sampling = parseSampling(reader.raw("sampling"), "sampling", problems);
1364
+ for (const problem of problems) reader.fail("sampling", problem.replace(/^sampling\.?/, ""));
1365
+ return Object.keys(sampling).length === 0 ? void 0 : sampling;
1366
+ }
991
1367
  /** `rules` is one rule as text, or a list of them; blank ones are left out. */
992
1368
  function readRules(reader) {
993
1369
  const value = reader.raw("rules");
@@ -1084,8 +1460,11 @@ function parseWorldFile(text) {
1084
1460
  const tools = readTools(reader);
1085
1461
  const alternateOpenings = readAlternateOpenings(reader);
1086
1462
  const narrationVoice = reader.string("narration_voice")?.trim() || void 0;
1463
+ const sampling = readSampling(reader);
1087
1464
  const preset = reader.string("preset")?.trim() || void 0;
1088
1465
  if (preset !== void 0 && !isPresetName(preset)) reader.fail("preset", "must be the name of a preset: letters, digits, \"-\" and \"_\"");
1466
+ const lorebooks = reader.strings("lorebooks").map((entry) => entry.trim()).filter((entry) => entry !== "");
1467
+ for (const [index, entry] of lorebooks.entries()) if (!isLorebookName(entry)) reader.fail(`lorebooks[${index}]`, "must be the name of a lorebook: letters, digits, \"-\" and \"_\"");
1089
1468
  if (name === void 0 || issues.length > 0) return {
1090
1469
  ok: false,
1091
1470
  issues
@@ -1107,7 +1486,9 @@ function parseWorldFile(text) {
1107
1486
  ...tools === void 0 ? {} : { tools },
1108
1487
  ...alternateOpenings === void 0 ? {} : { alternateOpenings },
1109
1488
  ...narrationVoice === void 0 ? {} : { narrationVoice },
1110
- ...preset === void 0 ? {} : { preset }
1489
+ ...sampling === void 0 ? {} : { sampling },
1490
+ ...preset === void 0 ? {} : { preset },
1491
+ ...lorebooks.length === 0 ? {} : { lorebooks: [...new Set(lorebooks)] }
1111
1492
  }
1112
1493
  };
1113
1494
  }
@@ -1879,59 +2260,6 @@ function parseLocationFile(text, fallbackId) {
1879
2260
  };
1880
2261
  }
1881
2262
  //#endregion
1882
- //#region src/host/lore/lore-file.ts
1883
- const LORE_FILE_NAME = "lore.json";
1884
- function instant(reader, key) {
1885
- const value = reader.string(key);
1886
- if (value === void 0) return void 0;
1887
- const parsed = Date.parse(value);
1888
- if (!Number.isFinite(parsed)) {
1889
- reader.fail(key, "must be an ISO date or date-time");
1890
- return;
1891
- }
1892
- return parsed;
1893
- }
1894
- function parseLoreFile(text, fallbackId) {
1895
- const issues = [];
1896
- const reader = Reader.fromJson(text, issues);
1897
- if (reader === void 0) return {
1898
- ok: false,
1899
- issues
1900
- };
1901
- const id = readIdentifier(reader, fallbackId) ?? fallbackId;
1902
- const title = reader.string("title", { required: true }) ?? "";
1903
- const subjects = reader.objects("subjects").flatMap((entry) => {
1904
- const kind = entry.oneOf("kind", LORE_SUBJECT_KINDS, "lore");
1905
- const subjectId = entry.string("id", { required: true });
1906
- return subjectId === void 0 ? [] : [{
1907
- kind,
1908
- id: subjectId
1909
- }];
1910
- });
1911
- const startsAt = instant(reader, "starts_at");
1912
- const endsAt = instant(reader, "ends_at");
1913
- if (startsAt !== void 0 && endsAt !== void 0 && endsAt < startsAt) reader.fail("ends_at", "must not be before starts_at");
1914
- const value = {
1915
- id,
1916
- title,
1917
- kind: reader.oneOf("kind", LORE_KINDS, "other"),
1918
- summary: reader.text("summary"),
1919
- body: reader.text("body"),
1920
- subjects,
1921
- related: reader.strings("related"),
1922
- sources: reader.strings("sources"),
1923
- ...startsAt === void 0 ? {} : { startsAt },
1924
- ...endsAt === void 0 ? {} : { endsAt }
1925
- };
1926
- return issues.length === 0 ? {
1927
- ok: true,
1928
- value
1929
- } : {
1930
- ok: false,
1931
- issues
1932
- };
1933
- }
1934
- //#endregion
1935
2263
  //#region src/host/variables/load.ts
1936
2264
  const VARIABLES_FILE_NAME = "variables.json";
1937
2265
  function readDefinition(reader) {
@@ -2102,7 +2430,7 @@ const MAX_ITEM_CHARS = 5e3;
2102
2430
  const PLAYER_MARKER = "[PLAYER]";
2103
2431
  /** Macros and markup of the tool that wrote the card, taken out of text a model reads: the card's own name stands for `{{char}}`; the player becomes the marker `[PLAYER]`. */
2104
2432
  function cleanText(text, cardName) {
2105
- return text.replace(/\r\n?/g, "\n").replace(/<!--[\s\S]*?-->/g, "").replace(/\{\{\s*\/\/[\s\S]*?\}\}/g, "").replace(/\{\{\s*char\s*\}\}|<char>|<bot>/gi, cardName).replace(/\{\{\s*user\s*\}\}|<user>/gi, PLAYER_MARKER).replace(/^\s*<START>\s*$/gim, "").replace(/\n{3,}/g, "\n\n").trim();
2433
+ return text.replace(/\r\n?/g, "\n").replace(/<!--[\s\S]*?-->/g, "").replace(/\{\{\s*\/\/[\s\S]*?\}\}/g, "").replace(/\{\{\s*char\s*\}\}|<char>|<bot>/gi, cardName).replace(/\{\{\s*user\s*\}\}|<user>/gi, PLAYER_MARKER).split("\n").filter((line) => line.trim().toUpperCase() !== "<START>").join("\n").replace(/\n{3,}/g, "\n\n").trim();
2106
2434
  }
2107
2435
  /** Cuts a text into parts of at most `max` characters, at the end of a paragraph, or of a line, or anywhere when there is no choice. */
2108
2436
  function partsOf(text, max = MAX_ITEM_CHARS) {
@@ -2516,7 +2844,7 @@ const SOURCE_BUDGET_CHARS = 14e3;
2516
2844
  const MAX_TAGGED = 8;
2517
2845
  const MAX_MENTIONS = 6;
2518
2846
  const MIN_MENTION_CHARS = 2;
2519
- const text$1 = (value) => typeof value === "string" ? value.trim() : "";
2847
+ const text = (value) => typeof value === "string" ? value.trim() : "";
2520
2848
  const list = (value) => Array.isArray(value) ? value.flatMap((entry) => typeof entry === "string" && entry.trim() !== "" ? [entry.trim()] : []) : [];
2521
2849
  const objects = (value) => Array.isArray(value) ? value.filter((entry) => typeof entry === "object" && entry !== null && !Array.isArray(entry)) : [];
2522
2850
  const put = (document, key, value) => {
@@ -2677,7 +3005,7 @@ function characterDocument(entity, answer, roster) {
2677
3005
  "age",
2678
3006
  "gender",
2679
3007
  "pronouns"
2680
- ]) put(document, field, text$1(answer[field]));
3008
+ ]) put(document, field, text(answer[field]));
2681
3009
  const playable = entity.player;
2682
3010
  const group = answer["kind"] === "group" && !playable;
2683
3011
  document["role"] = playable ? "playable" : "npc";
@@ -2688,10 +3016,10 @@ function characterDocument(entity, answer, roster) {
2688
3016
  "personality",
2689
3017
  "background",
2690
3018
  "appearance"
2691
- ]) document[field] = text$1(answer[field]);
3019
+ ]) document[field] = text(answer[field]);
2692
3020
  const speech = typeof answer["speech"] === "object" && answer["speech"] !== null ? answer["speech"] : {};
2693
3021
  document["speech"] = {
2694
- style: text$1(speech["style"]),
3022
+ style: text(speech["style"]),
2695
3023
  examples: list(speech["examples"]).slice(0, 8)
2696
3024
  };
2697
3025
  const start = {};
@@ -2700,17 +3028,17 @@ function characterDocument(entity, answer, roster) {
2700
3028
  ["public_state", "public_state"],
2701
3029
  ["inner_state", "inner_state"],
2702
3030
  ["activity", "activity"]
2703
- ]) put(start, to, text$1(given[from]));
2704
- const place = text$1(given["location"]) === "" ? void 0 : findEntity(roster, text$1(given["location"]), "place");
2705
- 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`);
3031
+ ]) put(start, to, text(given[from]));
3032
+ const place = text(given["location"]) === "" ? void 0 : findEntity(roster, text(given["location"]), "place");
3033
+ if (text(given["location"]) !== "" && place === void 0) notes.push(`${entity.name}: the place "${text(given["location"])}" is not one of the world's places, so the character starts nowhere`);
2706
3034
  if (place !== void 0) {
2707
3035
  start["location"] = place.key;
2708
- put(start, "position", text$1(given["position"]));
3036
+ put(start, "position", text(given["position"]));
2709
3037
  }
2710
- const goals = objects(answer["goals"]).filter((goal) => text$1(goal["name"]) !== "").map((goal) => ({
3038
+ const goals = objects(answer["goals"]).filter((goal) => text(goal["name"]) !== "").map((goal) => ({
2711
3039
  type: "agenda",
2712
- name: text$1(goal["name"]),
2713
- ...text$1(goal["description"]) === "" ? {} : { description: text$1(goal["description"]) },
3040
+ name: text(goal["name"]),
3041
+ ...text(goal["description"]) === "" ? {} : { description: text(goal["description"]) },
2714
3042
  status: "active"
2715
3043
  }));
2716
3044
  put(start, "intents", goals);
@@ -2718,17 +3046,17 @@ function characterDocument(entity, answer, roster) {
2718
3046
  const seen = /* @__PURE__ */ new Set([entity.key]);
2719
3047
  const relationships = [];
2720
3048
  for (const relation of objects(answer["relationships"])) {
2721
- const other = findEntity(roster, text$1(relation["with"]), "character");
3049
+ const other = findEntity(roster, text(relation["with"]), "character");
2722
3050
  if (other === void 0) {
2723
- notes.push(`${entity.name}: the relationship with "${text$1(relation["with"])}" names nobody in the world`);
3051
+ notes.push(`${entity.name}: the relationship with "${text(relation["with"])}" names nobody in the world`);
2724
3052
  continue;
2725
3053
  }
2726
- if (seen.has(other.key) || text$1(relation["label"]) === "") continue;
3054
+ if (seen.has(other.key) || text(relation["label"]) === "") continue;
2727
3055
  seen.add(other.key);
2728
3056
  relationships.push({
2729
3057
  to: other.key,
2730
- label: text$1(relation["label"]),
2731
- ...text$1(relation["summary"]) === "" ? {} : { summary: text$1(relation["summary"]) }
3058
+ label: text(relation["label"]),
3059
+ ...text(relation["summary"]) === "" ? {} : { summary: text(relation["summary"]) }
2732
3060
  });
2733
3061
  }
2734
3062
  put(document, "relationships", relationships.slice(0, 60));
@@ -2744,10 +3072,10 @@ function characterDocument(entity, answer, roster) {
2744
3072
  const ways = /* @__PURE__ */ new Set();
2745
3073
  const exits = [];
2746
3074
  for (const way of objects(knows["ways"])) {
2747
- const from = findEntity(roster, text$1(way["from"]), "place");
2748
- const to = findEntity(roster, text$1(way["to"]), "place");
3075
+ const from = findEntity(roster, text(way["from"]), "place");
3076
+ const to = findEntity(roster, text(way["to"]), "place");
2749
3077
  if (from === void 0 || to === void 0 || from.key === to.key) {
2750
- 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`);
3078
+ notes.push(`${entity.name}: the way from "${text(way["from"])}" to "${text(way["to"])}" is not between two places of the world, so they do not know of it`);
2751
3079
  continue;
2752
3080
  }
2753
3081
  if (ways.has(`${from.key}>${to.key}`)) continue;
@@ -2803,30 +3131,30 @@ function placeDocument(entity, answer, roster) {
2803
3131
  id: entity.key,
2804
3132
  name: entity.name
2805
3133
  };
2806
- put(document, "description", text$1(answer["description"]));
2807
- const named = text$1(answer["parent"]) === "" ? entity.parent : text$1(answer["parent"]);
3134
+ put(document, "description", text(answer["description"]));
3135
+ const named = text(answer["parent"]) === "" ? entity.parent : text(answer["parent"]);
2808
3136
  const parent = named === void 0 ? void 0 : findEntity(roster, named, "place");
2809
3137
  if (named !== void 0 && (parent === void 0 || parent.key === entity.key)) notes.push(`${entity.name}: the place it is in, "${named}", is not one of the world's places`);
2810
3138
  if (parent !== void 0 && parent.key !== entity.key) document["parent"] = parent.key;
2811
- const features = objects(answer["features"]).filter((feature) => text$1(feature["name"]) !== "").slice(0, 30).map((feature, index) => ({
3139
+ const features = objects(answer["features"]).filter((feature) => text(feature["name"]) !== "").slice(0, 30).map((feature, index) => ({
2812
3140
  id: `feature-${index + 1}`,
2813
- name: text$1(feature["name"]),
2814
- ...text$1(feature["description"]) === "" ? {} : { description: text$1(feature["description"]) }
3141
+ name: text(feature["name"]),
3142
+ ...text(feature["description"]) === "" ? {} : { description: text(feature["description"]) }
2815
3143
  }));
2816
3144
  put(document, "features", features);
2817
3145
  const exits = [];
2818
3146
  const to = /* @__PURE__ */ new Set();
2819
3147
  for (const exit of objects(answer["exits"])) {
2820
- const target = findEntity(roster, text$1(exit["to"]), "place");
3148
+ const target = findEntity(roster, text(exit["to"]), "place");
2821
3149
  if (target === void 0 || target.key === entity.key) {
2822
- notes.push(`${entity.name}: the way to "${text$1(exit["to"])}" leads to no place of the world`);
3150
+ notes.push(`${entity.name}: the way to "${text(exit["to"])}" leads to no place of the world`);
2823
3151
  continue;
2824
3152
  }
2825
3153
  if (to.has(target.key)) continue;
2826
3154
  to.add(target.key);
2827
3155
  exits.push({
2828
3156
  to: target.key,
2829
- ...text$1(exit["description"]) === "" ? {} : { description: text$1(exit["description"]) }
3157
+ ...text(exit["description"]) === "" ? {} : { description: text(exit["description"]) }
2830
3158
  });
2831
3159
  }
2832
3160
  put(document, "exits", exits.slice(0, 30));
@@ -2872,25 +3200,25 @@ function factionDocument(entity, answer, roster) {
2872
3200
  "summary",
2873
3201
  "description",
2874
3202
  "structure"
2875
- ]) put(document, field, text$1(answer[field]));
3203
+ ]) put(document, field, text(answer[field]));
2876
3204
  put(document, "values", list(answer["values"]));
2877
3205
  const start = {};
2878
- put(start, "public_state", text$1(answer["public_state"]));
2879
- put(start, "inner_state", text$1(answer["inner_state"]));
3206
+ put(start, "public_state", text(answer["public_state"]));
3207
+ put(start, "inner_state", text(answer["inner_state"]));
2880
3208
  put(document, "start", Object.keys(start).length === 0 ? void 0 : start);
2881
3209
  const members = [];
2882
3210
  const seen = /* @__PURE__ */ new Set();
2883
3211
  for (const member of objects(answer["members"])) {
2884
- const character = findEntity(roster, text$1(member["character"]), "character");
3212
+ const character = findEntity(roster, text(member["character"]), "character");
2885
3213
  if (character === void 0) {
2886
- notes.push(`${entity.name}: the member "${text$1(member["character"])}" is nobody in the world`);
3214
+ notes.push(`${entity.name}: the member "${text(member["character"])}" is nobody in the world`);
2887
3215
  continue;
2888
3216
  }
2889
3217
  if (seen.has(character.key)) continue;
2890
3218
  seen.add(character.key);
2891
3219
  members.push({
2892
3220
  character: character.key,
2893
- ...text$1(member["role"]) === "" ? {} : { role: text$1(member["role"]) }
3221
+ ...text(member["role"]) === "" ? {} : { role: text(member["role"]) }
2894
3222
  });
2895
3223
  }
2896
3224
  put(document, "members", members);
@@ -2918,11 +3246,11 @@ function thingDocument(entity, answer, roster) {
2918
3246
  name: entity.name,
2919
3247
  unique: true
2920
3248
  };
2921
- put(document, "description", text$1(answer["description"]));
2922
- put(document, "quality", text$1(answer["quality"]));
3249
+ put(document, "description", text(answer["description"]));
3250
+ put(document, "quality", text(answer["quality"]));
2923
3251
  if (answer["notable"] === true) document["notable"] = true;
2924
- const holder = text$1(answer["held_by"]) === "" ? void 0 : findEntity(roster, text$1(answer["held_by"]), "character");
2925
- const place = text$1(answer["location"]) === "" ? void 0 : findEntity(roster, text$1(answer["location"]), "place");
3252
+ const holder = text(answer["held_by"]) === "" ? void 0 : findEntity(roster, text(answer["held_by"]), "character");
3253
+ const place = text(answer["location"]) === "" ? void 0 : findEntity(roster, text(answer["location"]), "place");
2926
3254
  if (holder !== void 0) document["held_by"] = holder.key;
2927
3255
  else if (place !== void 0) document["location"] = place.key;
2928
3256
  else notes.push(`${entity.name}: it is nowhere in the world and nobody has it, so it is left out`);
@@ -2986,8 +3314,8 @@ const LORE_SUBJECT = {
2986
3314
  };
2987
3315
  function loreDocuments(answer, roster, taken) {
2988
3316
  return objects(answer["entries"]).flatMap((entry) => {
2989
- const title = text$1(entry["title"]);
2990
- const body = text$1(entry["body"]);
3317
+ const title = text(entry["title"]);
3318
+ const body = text(entry["body"]);
2991
3319
  if (title === "" || body === "") return [];
2992
3320
  const notes = [];
2993
3321
  const subjects = [];
@@ -2998,10 +3326,10 @@ function loreDocuments(answer, roster, taken) {
2998
3326
  "place",
2999
3327
  "faction",
3000
3328
  "thing"
3001
- ].includes(text$1(subject["kind"])) ? text$1(subject["kind"]) : void 0;
3002
- const found = kind === void 0 ? void 0 : findEntity(roster, text$1(subject["name"]), kind);
3329
+ ].includes(text(subject["kind"])) ? text(subject["kind"]) : void 0;
3330
+ const found = kind === void 0 ? void 0 : findEntity(roster, text(subject["name"]), kind);
3003
3331
  if (found === void 0) {
3004
- notes.push(`${title}: the subject "${text$1(subject["name"])}" is not in the world`);
3332
+ notes.push(`${title}: the subject "${text(subject["name"])}" is not in the world`);
3005
3333
  continue;
3006
3334
  }
3007
3335
  if (!seen.has(found.key)) {
@@ -3017,7 +3345,7 @@ function loreDocuments(answer, roster, taken) {
3017
3345
  id: uniqueKey(slug(title, "lore"), taken),
3018
3346
  title,
3019
3347
  kind,
3020
- summary: text$1(entry["summary"]),
3348
+ summary: text(entry["summary"]),
3021
3349
  body
3022
3350
  };
3023
3351
  put(document, "subjects", subjects);
@@ -3302,12 +3630,18 @@ const STYLE_SCHEMA = {
3302
3630
  type: "array",
3303
3631
  items: { type: "string" },
3304
3632
  description: "What the instructions contained that is not prose or behaviour guidance (rules of the game, formats, panels, scripts), one short phrase each."
3633
+ },
3634
+ persona_names: {
3635
+ type: "array",
3636
+ items: { type: "string" },
3637
+ description: "Every name the instructions give to the AI itself (a writer, narrator or assistant persona), exactly as written; empty when it has none. These names must not appear in narration or characters."
3305
3638
  }
3306
3639
  },
3307
3640
  required: [
3308
3641
  "narration",
3309
3642
  "characters",
3310
- "left_out"
3643
+ "left_out",
3644
+ "persona_names"
3311
3645
  ]
3312
3646
  };
3313
3647
  const MAX_STYLE_CHARS = 2e3;
@@ -3317,7 +3651,9 @@ function instructionPieces(card, items, classified) {
3317
3651
  const pieces = items.filter((item) => classified[item.id]?.roles[0] === "instruction").map((item) => item.text);
3318
3652
  return [...fields, ...pieces];
3319
3653
  }
3320
- function styleProblem(id, value) {
3654
+ function styleProblem(id, value, personas = []) {
3655
+ const named = personas.find((name) => name.trim() !== "" && value.toLowerCase().includes(name.trim().toLowerCase()));
3656
+ if (named !== void 0) return `${id} uses the persona name "${named}"; say "the character" or "the narrator" instead`;
3321
3657
  if (value.length > MAX_STYLE_CHARS) return `${id} is ${value.length} characters long; keep it to ${MAX_STYLE_CHARS}`;
3322
3658
  return value === "" ? void 0 : promptProblem("en", id, value);
3323
3659
  }
@@ -3338,9 +3674,9 @@ async function extractStyleFrom(ctx, name, pieces) {
3338
3674
  persona: ctx.text("import/style", { rules: ctx.text("import/common-rules") }),
3339
3675
  prompt,
3340
3676
  result: STYLE_SCHEMA,
3341
- check: (value) => styleProblem("roleplay/style", text$1(value.narration)) ?? styleProblem("roleplay/character-style", text$1(value.characters))
3677
+ check: (value) => styleProblem("roleplay/style", text(value.narration), list(value.persona_names)) ?? styleProblem("roleplay/character-style", text(value.characters), list(value.persona_names))
3342
3678
  });
3343
- const prompts = [["roleplay/style", text$1(answer.narration)], ["roleplay/character-style", text$1(answer.characters)]].flatMap(([id, body]) => body === "" ? [] : [{
3679
+ const prompts = [["roleplay/style", text(answer.narration)], ["roleplay/character-style", text(answer.characters)]].flatMap(([id, body]) => body === "" ? [] : [{
3344
3680
  id,
3345
3681
  text: body
3346
3682
  }]);
@@ -3476,15 +3812,15 @@ function variableDocuments(answer, roster) {
3476
3812
  const keyOf = (name) => roster.find((entity) => norm(entity.name) === norm(name) || entity.aliases.some((alias) => norm(alias) === norm(name)))?.key;
3477
3813
  const taken = /* @__PURE__ */ new Set();
3478
3814
  return objects(answer["variables"]).map((entry, index) => {
3479
- const base = slug(text$1(entry["key"]) || text$1(entry["name"]), "").replace(/-/g, "_").slice(0, 40);
3815
+ const base = slug(text(entry["key"]) || text(entry["name"]), "").replace(/-/g, "_").slice(0, 40);
3480
3816
  const document = {
3481
3817
  key: uniqueKey(/^[a-z][a-z0-9_]*$/.test(base) ? base : `variable_${index + 1}`, taken),
3482
- name: text$1(entry["name"]),
3483
- kind: text$1(entry["kind"]),
3484
- subject: text$1(entry["subject"])
3818
+ name: text(entry["name"]),
3819
+ kind: text(entry["kind"]),
3820
+ subject: text(entry["subject"])
3485
3821
  };
3486
- put(document, "description", text$1(entry["description"]));
3487
- put(document, "visibility", text$1(entry["visibility"]));
3822
+ put(document, "description", text(entry["description"]));
3823
+ put(document, "visibility", text(entry["visibility"]));
3488
3824
  put(document, "only", list(entry["only"]).flatMap((name) => keyOf(name) ?? []));
3489
3825
  for (const field of ["min", "max"]) if (typeof entry[field] === "number") document[field] = entry[field];
3490
3826
  if (typeof entry["integer"] === "boolean") document["integer"] = entry["integer"];
@@ -3494,9 +3830,9 @@ function variableDocuments(answer, roster) {
3494
3830
  "string"
3495
3831
  ].includes(typeof entry["default"])) document["default"] = entry["default"];
3496
3832
  put(document, "options", list(entry["options"]));
3497
- put(document, "bands", objects(entry["bands"]).filter((band) => typeof band["up_to"] === "number" && text$1(band["label"]) !== "").map((band) => ({
3833
+ put(document, "bands", objects(entry["bands"]).filter((band) => typeof band["up_to"] === "number" && text(band["label"]) !== "").map((band) => ({
3498
3834
  up_to: band["up_to"],
3499
- label: text$1(band["label"])
3835
+ label: text(band["label"])
3500
3836
  })));
3501
3837
  return document;
3502
3838
  });
@@ -3545,20 +3881,6 @@ async function extractVariables(ctx, card, items, classified, roster) {
3545
3881
  }
3546
3882
  }
3547
3883
  //#endregion
3548
- //#region src/host/folders.ts
3549
- /**
3550
- * Names of the subfolders of `dir`, sorted. Symbolic links are not followed
3551
- * and a missing directory has none; any other failure is thrown.
3552
- */
3553
- async function subfolders(dir) {
3554
- try {
3555
- return (await readdir(dir, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort((a, b) => a.localeCompare(b));
3556
- } catch (error) {
3557
- if (error.code === "ENOENT") return [];
3558
- throw error;
3559
- }
3560
- }
3561
- //#endregion
3562
3884
  //#region src/host/characters/load.ts
3563
3885
  const CHARACTERS_DIR = "characters";
3564
3886
  /**
@@ -3885,54 +4207,6 @@ function parentsFirst(locations) {
3885
4207
  return ordered;
3886
4208
  }
3887
4209
  //#endregion
3888
- //#region src/host/lore/load.ts
3889
- const LORE_DIR = "lore";
3890
- async function loadLore(worldDir) {
3891
- const dir = join(worldDir, LORE_DIR);
3892
- const result = {
3893
- lore: [],
3894
- problems: []
3895
- };
3896
- let folders;
3897
- try {
3898
- folders = await subfolders(dir);
3899
- } catch (error) {
3900
- if (error.code !== "ENOENT") result.problems.push({
3901
- path: dir,
3902
- message: errorMessage(error)
3903
- });
3904
- return result;
3905
- }
3906
- const owners = /* @__PURE__ */ new Map();
3907
- for (const folder of folders) {
3908
- const file = join(dir, folder, LORE_FILE_NAME);
3909
- try {
3910
- const entry = await readDocument(file, (text) => parseLoreFile(text, folder), result.problems);
3911
- if (entry === void 0) continue;
3912
- const owner = owners.get(entry.id);
3913
- if (owner !== void 0) {
3914
- result.problems.push({
3915
- path: file,
3916
- message: `id "${entry.id}" is already used by ${owner}`
3917
- });
3918
- continue;
3919
- }
3920
- owners.set(entry.id, folder);
3921
- result.lore.push(entry);
3922
- } catch (error) {
3923
- if (error.code !== "ENOENT") result.problems.push({
3924
- path: file,
3925
- message: errorMessage(error)
3926
- });
3927
- }
3928
- }
3929
- if (result.lore.length > 500) result.problems.push({
3930
- path: dir,
3931
- message: `a world has at most 500 lore entries`
3932
- });
3933
- return result;
3934
- }
3935
- //#endregion
3936
4210
  //#region src/host/calendar/load.ts
3937
4211
  const CALENDAR_FILE_NAME = "calendar.json";
3938
4212
  const HOLIDAY_ID = /^[\p{L}\p{N}][\p{L}\p{N}_-]{0,59}$/u;
@@ -4189,6 +4463,11 @@ function knowledgeProblems(characters, locations, items, lore = []) {
4189
4463
  ];
4190
4464
  });
4191
4465
  }
4466
+ /** Whether a world's characters include the one a lore entry names by id, name or alias. */
4467
+ function knowsCharacter(characters, reference) {
4468
+ const key = reference.normalize("NFKC").toLowerCase();
4469
+ return characters.some((character) => character.id === reference || [character.name, ...character.aliases].some((name) => name.normalize("NFKC").toLowerCase() === key));
4470
+ }
4192
4471
  function loreProblems(lore, world) {
4193
4472
  const ids = {
4194
4473
  character: new Set(world.characters.map((x) => x.id)),
@@ -4197,13 +4476,19 @@ function loreProblems(lore, world) {
4197
4476
  item: new Set(world.items.map((x) => x.id)),
4198
4477
  lore: new Set(lore.map((x) => x.id))
4199
4478
  };
4200
- 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`])]);
4479
+ return lore.flatMap((entry) => [
4480
+ ...entry.subjects.flatMap((subject) => ids[subject.kind].has(subject.id) ? [] : [`${entry.id}: subjects: "${subject.id}" is not a ${subject.kind} of this world`]),
4481
+ ...entry.knownBy.flatMap((reference) => knowsCharacter(world.characters, reference) ? [] : [`${entry.id}: known_by: "${reference}" is not a character of this world`]),
4482
+ ...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`])
4483
+ ]);
4201
4484
  }
4202
- function populateLore(session, definitions) {
4485
+ /** `turn` is when the characters that know an entry learned it: 0 at the start, the story's turn when a lorebook is added later. */
4486
+ function populateLore(session, definitions, turn = 0) {
4203
4487
  for (const entry of definitions) session.lore.add({
4204
4488
  sourceId: entry.id,
4205
4489
  title: entry.title,
4206
4490
  kind: entry.kind,
4491
+ scope: entry.scope,
4207
4492
  summary: entry.summary,
4208
4493
  body: entry.body,
4209
4494
  ...entry.startsAt === void 0 ? {} : { startsAt: entry.startsAt },
@@ -4220,6 +4505,13 @@ function populateLore(session, definitions) {
4220
4505
  subjects: entry.subjects.map(subject),
4221
4506
  related: entry.related.map((id) => session.lore.getBySourceId(id).id)
4222
4507
  });
4508
+ for (const entry of definitions) {
4509
+ const lore = session.lore.getBySourceId(entry.id);
4510
+ for (const reference of entry.knownBy) {
4511
+ const knower = session.characters.getBySourceId(reference) ?? session.characters.findByName(reference)[0];
4512
+ if (knower !== void 0) session.knowledge.learn(knower.id, "lore", lore.id, turn);
4513
+ }
4514
+ }
4223
4515
  }
4224
4516
  /** What is wrong with where the characters start, found before anything is created. */
4225
4517
  function startingPlaceProblems(characters, locations) {
@@ -4245,10 +4537,11 @@ function populateVariables(session, defs, world) {
4245
4537
  give("world", 0, world.values);
4246
4538
  }
4247
4539
  /** What is wrong with the days characters are given, found before anything is created: places that are not in the world. */
4248
- function routineProblems(characters, locations, calendar = {
4249
- hemisphere: "north",
4250
- holidays: []
4251
- }) {
4540
+ function routineProblems(characters, locations, calendar) {
4541
+ calendar ??= {
4542
+ hemisphere: "north",
4543
+ holidays: []
4544
+ };
4252
4545
  const byId = new Map(locations.map((location) => [location.id, location]));
4253
4546
  const holidays = new Set(calendar.holidays.map((holiday) => holiday.id));
4254
4547
  return characters.flatMap((character) => (character.routine ?? []).flatMap((window, index) => {
@@ -5059,8 +5352,8 @@ function isPublicAddress(address) {
5059
5352
  if (family === 4) return !blocked.check(address, "ipv4");
5060
5353
  const mapped = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i.exec(new URL(`http://[${address}]/`).hostname.replace(/^\[|\]$/g, ""));
5061
5354
  if (mapped !== null) {
5062
- const high = parseInt(mapped[1], 16);
5063
- const low = parseInt(mapped[2], 16);
5355
+ const high = Number.parseInt(mapped[1], 16);
5356
+ const low = Number.parseInt(mapped[2], 16);
5064
5357
  return isPublicAddress(`${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`);
5065
5358
  }
5066
5359
  return !blocked.check(address, "ipv6");
@@ -5712,61 +6005,49 @@ function importHooks(ctx, worlds, prompting) {
5712
6005
  });
5713
6006
  }
5714
6007
  //#endregion
5715
- //#region src/host/import/preset.ts
5716
- /** The older preset layout keeps its texts under fixed keys. */
5717
- const LEGACY_KEYS = [
5718
- "main_prompt",
5719
- "nsfw_prompt",
5720
- "jailbreak_prompt",
5721
- "impersonation_prompt",
5722
- "new_chat_prompt",
5723
- "new_group_chat_prompt",
5724
- "new_example_chat_prompt"
5725
- ];
5726
- const MAX_PIECES = 60;
5727
- const MAX_PIECE_CHARS = 8e3;
5728
- const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5729
- const text = (value) => typeof value === "string" ? value.trim() : "";
5730
- /** The order the preset sends its prompts in: the longest list it gives, with what each entry says about being on. */
5731
- function orderOf(root) {
5732
- return ((Array.isArray(root["prompt_order"]) ? root["prompt_order"].flatMap((entry) => isObject(entry) && Array.isArray(entry["order"]) ? [entry["order"]] : []) : []).sort((a, b) => b.length - a.length)[0] ?? []).flatMap((entry) => isObject(entry) && typeof entry["identifier"] === "string" ? [{
5733
- identifier: entry["identifier"],
5734
- enabled: entry["enabled"] !== false
5735
- }] : []);
5736
- }
6008
+ //#region src/shared/import-selection.ts
6009
+ const MAX_PREVIEW_TEXT = 4e3;
6010
+ //#endregion
6011
+ //#region src/host/tools/authoring-tools.ts
6012
+ /** Which of the tools other plugins registered for everyone each assistant of the authoring chats was given in the settings; read afresh, so a change applies at its next step. */
6013
+ var AuthoringTools = class extends Service {
6014
+ board;
6015
+ constructor(ctx, board) {
6016
+ super(ctx, "roleplayAuthoringTools");
6017
+ this.board = board;
6018
+ }
6019
+ /** What the assistant is given: the tools it may call on top of its own. */
6020
+ given(registry, kind) {
6021
+ return externalGiven(registry, this.board(), kind);
6022
+ }
6023
+ /** What the assistant is not given and so does not see. */
6024
+ withheld(registry, kind) {
6025
+ return externalWithheld(registry, this.board(), kind);
6026
+ }
6027
+ };
5737
6028
  /**
5738
- * Reads a preset file. Markers (places where chat history or the card's fields are inserted), switched-off prompts and empty ones are left out.
5739
- * @throws {ImportCardError} when the file is not a preset, with why.
6029
+ * Takes the tools of other plugins away from an assistant of an authoring chat unless the settings gave it that tool, before its first request and again
6030
+ * at every step (a server may connect later). Helpers the assistant starts are not touched: they have no tools but their own.
5740
6031
  */
5741
- function readPreset(file, name) {
5742
- let root;
5743
- try {
5744
- root = JSON.parse(file.toString("utf8").replace(/^/, ""));
5745
- } catch {
5746
- throw new ImportCardError("the file is not JSON: a preset is the .json file SillyTavern exports");
5747
- }
5748
- if (!isObject(root)) throw new ImportCardError("the file is not a preset: it must be a JSON object");
5749
- const pieces = [];
5750
- const prompts = Array.isArray(root["prompts"]) ? root["prompts"].filter(isObject) : [];
5751
- if (prompts.length > 0) {
5752
- const byId = new Map(prompts.flatMap((prompt) => typeof prompt["identifier"] === "string" ? [[prompt["identifier"], prompt]] : []));
5753
- const ordered = orderOf(root);
5754
- const chosen = ordered.length > 0 ? ordered.flatMap((entry) => entry.enabled && byId.has(entry.identifier) ? [byId.get(entry.identifier)] : []) : prompts.filter((prompt) => prompt["enabled"] !== false);
5755
- for (const prompt of chosen) {
5756
- const content = text(prompt["content"]);
5757
- if (prompt["marker"] === true || content === "") continue;
5758
- const title = text(prompt["name"]);
5759
- pieces.push(`${title === "" ? "" : `[${title}]\n`}${content.slice(0, MAX_PIECE_CHARS)}`);
5760
- }
5761
- } else for (const key of LEGACY_KEYS) if (text(root[key]) !== "") pieces.push(`[${key}]\n${text(root[key]).slice(0, MAX_PIECE_CHARS)}`);
5762
- if (pieces.length === 0) throw new ImportCardError("the file holds no instructions this importer can read: a preset has a \"prompts\" list with texts in it");
5763
- const title = text(root["name"]) || text(root["preset_name"]);
5764
- return {
5765
- name: title === "" ? name.replace(/\.json$/i, "") : title,
5766
- pieces: pieces.slice(0, MAX_PIECES)
6032
+ function limitAuthoringAgent(agent, kind, tools) {
6033
+ externalToolLimit(agent, tools.withheld(agent.ctx.tools, kind));
6034
+ }
6035
+ /** Installs the limit on the agents of the chats `kindOf` recognises, which a preset's listeners find among the agents of every chat of the preset and its helpers. */
6036
+ function limitAuthoringAgents(ctx, kindOf) {
6037
+ const apply = (agent) => {
6038
+ if (agent.session.header.origin === "subagent") return;
6039
+ const kind = kindOf(agent.session.id);
6040
+ if (kind !== void 0) limitAuthoringAgent(agent, kind, ctx.roleplayAuthoringTools);
5767
6041
  };
6042
+ ctx.on("agent/created", ({ agent }) => {
6043
+ apply(agent);
6044
+ });
6045
+ ctx.on("agent/pre-step", async (payload, next) => {
6046
+ apply(payload.agent);
6047
+ return await next();
6048
+ });
5768
6049
  }
5769
6050
  //#endregion
5770
- export { LOCATION_FILE_NAME as $, parseDiceFile as A, FACTIONS_DIR as B, populateTriggers as C, isPng as Ct, loadTriggers as D, DICE_READINGS as Dt, TRIGGERS_FILE_NAME as E, DICE_COMPARISONS as Et, loadLore as F, extractStyleFrom as G, CHARACTERS_DIR as H, LOCATIONS_DIR as I, loadVariables as J, withPlayer as K, loadLocations as L, loadCalendar as M, parseCalendarFile as N, DICE_FILE_NAME as O, DICE_RESULTS as Ot, LORE_DIR as P, parseLoreFile as Q, ITEMS_DIR as R, populateRoutines as S, ImportCardError as St, routineProblems as T, readCard as Tt, loadCharacters as U, loadFactions as V, subfolders as W, variableProblems as X, parseVariablesFile as Y, LORE_FILE_NAME as Z, populateFactions as _, parseLoreEdit as _t, worldOf as a, CHARACTER_FILE_NAME as at, populateLocations as b, parseThingEdit as bt, isReviewing as c, ImportNotFoundError as ct, vetUrl as d, WORLD_FILE_NAME as dt, parseLocationFile as et, loadValidatedWorld as f, parseWorldFile as ft, populateDice as g, parseFactionEdit as gt, populateClock as h, parseCharacterEdit as ht, importTools as i, parseFactionFile as it, CALENDAR_FILE_NAME as j, loadDice as k, markReady as l, ImportStore as lt, populateCharacters as m, InvalidEditProblems as mt, contextOf as n, parseItemFile as nt, authoredWorldOf as o, parseCharacterFile as ot, populateCalendar as p, parseWorldInfoEdit as pt, VARIABLES_FILE_NAME as q, importHooks as r, FACTION_FILE_NAME as rt, authoringChatSessionId as s, IMPORT_FOLDER as st, readPreset as t, ITEM_FILE_NAME as tt, guardedLookup as u, parseChoices as ut, populateItems as v, parsePlaceEdit as vt, populateVariables as w, pictureOf as wt, populateLore as x, IMPORT_COMMAND as xt, populateKnowledge as y, parseRelationEdit as yt, loadItems as z };
6051
+ export { LOCATION_FILE_NAME as $, loadTriggers as A, parseLoreFile as At, loadItems as B, ImportCardError as Bt, populateLocations as C, readLorebook as Ct, populateVariables as D, LORE_DIR as Dt, populateTriggers as E, writeLorebookEntry as Et, loadCalendar as F, parseLoreEdit as Ft, extractStyleFrom as G, LORE_SCOPES as Gt, loadFactions as H, pictureOf as Ht, parseCalendarFile as I, parsePlaceEdit as It, withPlayer as J, DICE_RESULTS as Jt, cleanText as K, DICE_COMPARISONS as Kt, LOCATIONS_DIR as L, parseRelationEdit as Lt, loadDice as M, InvalidEditProblems as Mt, parseDiceFile as N, parseCharacterEdit as Nt, routineProblems as O, loadLore as Ot, CALENDAR_FILE_NAME as P, parseFactionEdit as Pt, variableProblems as Q, loadLocations as R, parseThingEdit as Rt, populateKnowledge as S, lorebookDirectory as St, populateRoutines as T, updateLorebookInfo as Tt, CHARACTERS_DIR as U, readCard as Ut, FACTIONS_DIR as V, isPng as Vt, loadCharacters as W, LORE_KINDS as Wt, loadVariables as X, VARIABLES_FILE_NAME as Y, parseVariablesFile as Z, populateCharacters as _, deleteLorebookEntry as _t, importHooks as a, CHARACTER_FILE_NAME as at, populateFactions as b, listLorebooks as bt, authoredWorldOf as c, ImportNotFoundError as ct, markReady as d, WORLD_FILE_NAME as dt, parseLocationFile as et, guardedLookup as f, parseWorldFile as ft, populateCalendar as g, deleteLorebook as gt, knowsCharacter as h, createLorebook as ht, contextOf as i, parseFactionFile as it, DICE_FILE_NAME as j, subfolders as jt, TRIGGERS_FILE_NAME as k, LORE_FILE_NAME as kt, authoringChatSessionId as l, ImportStore as lt, loadValidatedWorld as m, addLorebookEntries as mt, limitAuthoringAgents as n, parseItemFile as nt, importTools as o, parseCharacterFile as ot, vetUrl as p, parseWorldInfoEdit as pt, partsOf as q, DICE_READINGS as qt, MAX_PREVIEW_TEXT as r, FACTION_FILE_NAME as rt, worldOf as s, IMPORT_FOLDER as st, AuthoringTools as t, ITEM_FILE_NAME as tt, isReviewing as u, parseChoices as ut, populateClock as v, entriesOf as vt, populateLore as w, reserveLorebook as wt, populateItems as x, loadLorebook as xt, populateDice as y, isLorebookName as yt, ITEMS_DIR as z, IMPORT_COMMAND as zt };
5771
6052
 
5772
- //# sourceMappingURL=preset-ClQm7KPQ.js.map
6053
+ //# sourceMappingURL=authoring-tools-C_8ClUkP.js.map