@dsh-agentic-roleplay/core 0.11.1 → 0.12.1

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 (61) hide show
  1. package/lib/{access-Md1YTSX1.js → access-DifaiHrI.js} +3 -15
  2. package/lib/{authoring-tools-BFdw7ahj.js → authoring-tools-VOaXzr_R.js} +58 -766
  3. package/lib/authoring.js +136 -13
  4. package/lib/{child-C9nPIy9j.js → child-DzZ-aI6k.js} +130 -2
  5. package/lib/client.js +17093 -2269
  6. package/lib/client.js.map +1 -1
  7. package/lib/compaction.js +3 -3
  8. package/lib/dev-context-Bdm-eVer.js +40 -0
  9. package/lib/doctor.js +5 -3
  10. package/lib/{gallery-BWHmjogd.js → gallery-Ctz-UoFk.js} +3 -3
  11. package/lib/{generator-QCdm8nUh.js → generator-Cv6WWmZT.js} +2 -2
  12. package/lib/helper.js +15 -1
  13. package/lib/{hooks-C2U1-8ur.js → hooks-BdR3mBeM.js} +751 -344
  14. package/lib/images.js +4 -4
  15. package/lib/index.js +342 -463
  16. package/lib/jail-Cp4zEfip.js +107 -0
  17. package/lib/{library-4zmCAshR.js → library-BU2A_Dx8.js} +3 -3
  18. package/lib/{lorebook-author-tools-Bjfjt3bg.js → lorebook-author-tools-DUKcQu8P.js} +20 -7
  19. package/lib/lorebook-authoring.js +12 -5
  20. package/lib/{narration-b_VBEUWn.js → narration-CDsJ5wxH.js} +29 -2
  21. package/lib/orchestration.js +615 -48
  22. package/lib/{pack-jail-Ci9bIeDI.js → pack-jail-CzHQu0n3.js} +559 -23
  23. package/lib/{packs-CYkozh8Q.js → packs-BZ-45J4-.js} +2 -2
  24. package/lib/{presenter-agent-CqkAL03Q.js → presenter-agent-C2ZkoxZu.js} +9 -9
  25. package/lib/{preset-B-35yUmt.js → preset-BPnRPW-1.js} +4 -4
  26. package/lib/{preset-author-tools-BUymqZM5.js → preset-author-tools-DBqPwn-o.js} +9 -8
  27. package/lib/preset-authoring.js +11 -6
  28. package/lib/{reflection-B9N0z3KY.js → reflection-Cuy0YLv0.js} +22 -16
  29. package/lib/{presets-_U-xroo0.js → serial-BZNeK57v.js} +1305 -331
  30. package/lib/service-mRKwpWjX.js +140 -0
  31. package/lib/{text-C2AGl7Je.js → text-Dfv8S8eq.js} +27 -2
  32. package/lib/{turn-guard-C0M3rXEN.js → turn-guard-xaFxYc1T.js} +3 -3
  33. package/locale/de.json +6 -0
  34. package/locale/en.json +6 -0
  35. package/locale/es.json +6 -0
  36. package/locale/fr.json +6 -0
  37. package/locale/ja.json +6 -0
  38. package/locale/pt.json +6 -0
  39. package/locale/ru.json +6 -0
  40. package/locale/zh.json +6 -0
  41. package/package.json +34 -34
  42. package/prompts/en/import/finish-ok.md +1 -1
  43. package/prompts/en/import/generator.md +1 -1
  44. package/prompts/en/import/style.md +2 -1
  45. package/prompts/en/import/variables.md +2 -1
  46. package/prompts/en/roleplay/character-lookup.md +1 -1
  47. package/prompts/en/roleplay/decide-errand.md +1 -0
  48. package/prompts/en/roleplay/decide-message.md +1 -0
  49. package/prompts/en/roleplay/dream.md +1 -0
  50. package/prompts/en/roleplay/gate-repeat.md +1 -0
  51. package/prompts/en/world/procedure.md +1 -1
  52. package/prompts/zh/import/finish-ok.md +1 -1
  53. package/prompts/zh/import/generator.md +1 -1
  54. package/prompts/zh/import/style.md +2 -1
  55. package/prompts/zh/import/variables.md +2 -1
  56. package/prompts/zh/roleplay/character-lookup.md +1 -1
  57. package/prompts/zh/roleplay/decide-errand.md +1 -0
  58. package/prompts/zh/roleplay/decide-message.md +1 -0
  59. package/prompts/zh/roleplay/dream.md +1 -0
  60. package/prompts/zh/roleplay/gate-repeat.md +1 -0
  61. package/prompts/zh/world/procedure.md +1 -1
@@ -1,15 +1,14 @@
1
- import { n as atomicWrite, r as atomicWriteJson } from "./access-Md1YTSX1.js";
2
- import { $ as IMPORT_FOLDER, A as sourcesFor, At as InvalidEditProblems, Bt as WEEKDAY_NAMES, C as inert, Ct as parseSlotsFile, D as pruneLoreSubjects, Dt as parseCharacterFile, E as pruneLinks, Et as CHARACTER_FILE_NAME, F as ROLE_TABLE, I as isLeftOut, Lt as guarded, M as classifyItems, N as findEntity, O as pruneMembers, Ot as readVariableValues, P as ROLES, Q as withPlayer, R as askYesNo, Rt as LORE_KINDS, S as extractVariables, St as parseItemFile, T as pruneKnowledge, Tt as parseFactionFile, U as yesAt, V as noAt, Vt as DEFAULT_SLOTS, X as itemise, Y as cleanText, _ as characterDocument, _t as parseLoreFile, a as isPresetName, at as readImportFolder, b as extractStyle, bt as ITEM_FILE_NAME, ft as VARIABLES_FILE_NAME, g as asWritten, gt as LORE_FILE_NAME, h as addLore, ht as variableProblems, j as buildRoster, k as pruneRelationships, kt as readIdentifier, nt as PICTURE_FILE, pt as loadVariables, rt as openingText, st as dialectOf, ut as parseImportCommand, v as emptyExtracted, vt as LOCATION_FILE_NAME, w as loreDocuments, wt as FACTION_FILE_NAME, xt as SLOTS_FILE_NAME, y as extractEntities, yt as parseLocationFile, zt as LORE_SCOPES } from "./presets-_U-xroo0.js";
3
- import { f as parseSwitchboard } from "./narration-b_VBEUWn.js";
4
- import { G as readDocument$1, J as errorMessage, K as Reader, Q as copyWorldPrompts, U as commandFlagKey, V as plotReferenceProblems, X as PROMPTS_FOLDER, _t as COMPARISONS, a as externalWithheld, at as shippedText, ct as InvalidWorldError, nt as promptProblem, q as formatIssue, r as externalGiven, rt as shippedLanguages, t as externalToolLimit, tt as listFiles, z as loadPlots } from "./hooks-C2U1-8ur.js";
5
- import { t as trimCharacters } from "./text-C2AGl7Je.js";
6
- import { S as currentTurn, c as namedModel, d as parseSampling, l as runChild, t as ChildTimeoutError } from "./child-C9nPIy9j.js";
7
- import { C as slug, S as norm, T as uniqueKey, _ as writeImageFileMetadata, b as NoEmbeddingService, i as libraryHashes, n as addToLibraryOnce, p as MEDIA_TYPES, r as imageExtensionOf, u as referenceImagePath, w as trOf, x as mapLimit } from "./library-4zmCAshR.js";
8
- import { dirname, join, relative } from "node:path";
9
- import { MINUTE, MONTH_NAMES, SEASONS, checkProblems, createSessionStore, dayTokenProblems, isTimeZone, lintWorld, parseInstant, parseTimeOfDay, readTriggerDefinition, triggerReferenceProblems, writeCalendar } from "@dsh-agentic-roleplay/state";
10
- import { existsSync, readFileSync } from "node:fs";
1
+ import { T as currentTurn, c as namedModel, l as runChild, m as parseSampling, t as ChildTimeoutError } from "./child-DzZ-aI6k.js";
2
+ import { $t as subfolders, Bt as loadLore, C as ROLE_TABLE, Ct as PICTURE_FILE, E as askYesNo, Et as readImportFolder, Ft as VARIABLES_FILE_NAME, Gt as ITEM_FILE_NAME, Ht as parseLoreFile, It as loadVariables, Jt as parseSlotsFile, Kt as SLOTS_FILE_NAME, M as WORLD_FILE_NAME, Mt as splitPanels, N as parseWorldFile, Nt as dialectOf, Qt as parseCharacterFile, R as startQuestionsToFile, Rt as variableProblems, S as ROLES, Ut as LOCATION_FILE_NAME, Vt as LORE_FILE_NAME, Wt as parseLocationFile, Xt as parseFactionFile, Yt as FACTION_FILE_NAME, Zt as CHARACTER_FILE_NAME, _ as pruneRelationships, _t as itemise, a as characterDocument, b as classifyItems, bt as IMPORT_FOLDER, c as extractStyle, d as inert, dn as DEFAULT_SLOTS, en as InvalidEditProblems, f as loreDocuments, g as pruneMembers, gt as cleanText, h as pruneLoreSubjects, i as asWritten, j as yesAt, jt as findPanel, k as noAt, kt as parseImportCommand, m as pruneLinks, o as emptyExtracted, p as pruneKnowledge, qt as parseItemFile, r as addLore, s as extractEntities, sn as guarded, t as SerialQueue, u as extractVariables, un as WEEKDAY_NAMES, v as sourcesFor, w as isLeftOut, wt as openingText, x as findEntity, y as buildRoster, yt as withPlayer, zt as LORE_DIR } from "./serial-BZNeK57v.js";
3
+ import { f as parseSwitchboard } from "./narration-CDsJ5wxH.js";
4
+ import { n as atomicWrite, r as atomicWriteJson } from "./access-DifaiHrI.js";
5
+ import { G as readDocument$1, J as errorMessage, K as Reader, Q as copyWorldPrompts, U as commandFlagKey, V as plotReferenceProblems, X as PROMPTS_FOLDER, _t as COMPARISONS, a as externalGiven, at as shippedText, ct as InvalidWorldError, nt as promptProblem, q as formatIssue, rt as shippedLanguages, s as externalWithheld, t as externalToolLimit, tt as listFiles, z as loadPlots } from "./hooks-BdR3mBeM.js";
6
+ import { t as trimCharacters } from "./text-Dfv8S8eq.js";
7
+ import { C as slug, S as norm, T as uniqueKey, _ as writeImageFileMetadata, b as NoEmbeddingService, i as libraryHashes, n as addToLibraryOnce, p as MEDIA_TYPES, r as imageExtensionOf, u as referenceImagePath, w as trOf, x as mapLimit } from "./library-BU2A_Dx8.js";
8
+ import { join, relative, sep } from "node:path";
9
+ import { MINUTE, MONTH_NAMES, SEASONS, checkProblems, createSessionStore, dayTokenProblems, lintWorld, parseTimeOfDay, readTriggerDefinition, triggerReferenceProblems, writeCalendar } from "@dsh-agentic-roleplay/state";
11
10
  import { createHash } from "node:crypto";
12
- import { mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
11
+ import { mkdtemp, readFile, readdir, rename, rm, stat } from "node:fs/promises";
13
12
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
14
13
  import { inflateSync } from "node:zlib";
15
14
  import { defineTool } from "@deepseek-ai/dsh-tools";
@@ -299,19 +298,6 @@ async function outputCeiling(configured, agent, named, signal) {
299
298
  }
300
299
  return autoOutputCeiling(window);
301
300
  }
302
- // src/host/folders.ts
303
- /**
304
- * Names of the subfolders of `dir`, sorted. Symbolic links are not followed
305
- * and a missing directory has none; any other failure is thrown.
306
- */
307
- async function subfolders(dir) {
308
- try {
309
- return (await readdir(dir, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort((a, b) => a.localeCompare(b));
310
- } catch (error) {
311
- if (error.code === "ENOENT") return [];
312
- throw error;
313
- }
314
- }
315
301
  // src/host/characters/load.ts
316
302
  const CHARACTERS_DIR = "characters";
317
303
  /**
@@ -426,7 +412,13 @@ async function loadCalendar(worldDir) {
426
412
  // src/host/commands/load.ts
427
413
  const COMMANDS_FILE_NAME = "commands.json";
428
414
  /** The words the game itself uses after a slash. */
429
- const RESERVED = /* @__PURE__ */ new Set(["ooc", "roll"]);
415
+ const RESERVED = /* @__PURE__ */ new Set([
416
+ "ooc",
417
+ "ask",
418
+ "roll",
419
+ "wait",
420
+ "dream"
421
+ ]);
430
422
  const WORD = /^[\p{L}\p{N}_]{1,30}$/u;
431
423
  const KEY = /^[a-z][a-z0-9_]{0,29}$/;
432
424
  const commandVariable = commandFlagKey;
@@ -858,53 +850,6 @@ function parentsFirst(locations) {
858
850
  for (const location of locations) place(location);
859
851
  return ordered;
860
852
  }
861
- // src/host/lore/load.ts
862
- const LORE_DIR = "lore";
863
- async function loadLore(worldDir) {
864
- const dir = join(worldDir, LORE_DIR);
865
- const result = {
866
- lore: [],
867
- problems: []
868
- };
869
- let folders;
870
- try {
871
- folders = await subfolders(dir);
872
- } catch (error) {
873
- if (error.code !== "ENOENT") result.problems.push({
874
- path: dir,
875
- message: errorMessage(error)
876
- });
877
- return result;
878
- }
879
- const owners = /* @__PURE__ */ new Map();
880
- for (const folder of folders) {
881
- const file = join(dir, folder, LORE_FILE_NAME);
882
- try {
883
- const entry = await readDocument$1(file, (text) => parseLoreFile(text, folder), result.problems);
884
- if (entry === void 0) continue;
885
- const owner = owners.get(entry.id);
886
- if (owner !== void 0) {
887
- result.problems.push({
888
- path: file,
889
- message: `id "${entry.id}" is already used by ${owner}`
890
- });
891
- continue;
892
- }
893
- owners.set(entry.id, folder);
894
- result.lore.push(entry);
895
- } catch (error) {
896
- if (error.code !== "ENOENT") result.problems.push({
897
- path: file,
898
- message: errorMessage(error)
899
- });
900
- }
901
- }
902
- if (result.lore.length > 500) result.problems.push({
903
- path: dir,
904
- message: `a world has at most 500 lore entries`
905
- });
906
- return result;
907
- }
908
853
  // src/host/triggers/load.ts
909
854
  const TRIGGERS_FILE_NAME = "triggers.json";
910
855
  /** Read `triggers.json`: a list of what the world does by itself when something comes true (docs/world-format.md). */
@@ -1118,6 +1063,7 @@ function populateRoutines(session, characters) {
1118
1063
  end: parseTimeOfDay(window.to),
1119
1064
  activity: window.activity,
1120
1065
  interruptible: window.interruptible,
1066
+ ...window.sleep === true ? { sleep: true } : {},
1121
1067
  ...window.location === void 0 ? {} : { locationId: session.locations.getBySourceId(window.location).id },
1122
1068
  ...window.feature === void 0 ? {} : { featureKey: window.feature },
1123
1069
  ...window.position === void 0 ? {} : { position: window.position }
@@ -1520,7 +1466,7 @@ async function checkWorld(world) {
1520
1466
  } catch (error) {
1521
1467
  if (!(error instanceof InvalidWorldError)) throw error;
1522
1468
  const problems = error.problems.map((problem) => ({
1523
- where: relative(world.directory, problem.path) || "(the world)",
1469
+ where: relative(world.directory, problem.path).split(sep).join("/") || "(the world)",
1524
1470
  message: problem.message
1525
1471
  }));
1526
1472
  return {
@@ -1781,687 +1727,6 @@ function structureOnly(card, items, _choices) {
1781
1727
  extracted
1782
1728
  };
1783
1729
  }
1784
- // src/host/lorebooks/lorebooks.ts
1785
- const LOREBOOKS_FOLDER = "lorebooks";
1786
- const LOREBOOK_FILE = "lorebook.json";
1787
- const NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
1788
- const ENTRY_ID = /^[\p{L}\p{N}][\p{L}\p{N}_-]{0,79}$/u;
1789
- const MAX_TEXT = 300;
1790
- const isLorebookName = (name) => NAME.test(name);
1791
- const isEntryId = (id) => ENTRY_ID.test(id);
1792
- const lorebooksDirectory = (root) => join(root, LOREBOOKS_FOLDER);
1793
- function lorebookDirectory(root, name) {
1794
- if (!isLorebookName(name)) throw new Error(`"${name}" is not a usable lorebook name (letters, digits, "-" and "_", up to 64)`);
1795
- return join(lorebooksDirectory(root), name);
1796
- }
1797
- const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1798
- function parseHeader(value, problems) {
1799
- if (!isRecord$1(value)) {
1800
- problems.push(`${LOREBOOK_FILE} must be an object`);
1801
- return {};
1802
- }
1803
- const text = (key) => {
1804
- const field = value[key];
1805
- if (field === void 0 || field === null) return void 0;
1806
- if (typeof field !== "string" || field.length > MAX_TEXT) {
1807
- problems.push(`${LOREBOOK_FILE}: "${key}" must be text of at most ${MAX_TEXT} characters`);
1808
- return;
1809
- }
1810
- return field.trim() || void 0;
1811
- };
1812
- const title = text("title");
1813
- const description = text("description");
1814
- return {
1815
- ...title === void 0 ? {} : { title },
1816
- ...description === void 0 ? {} : { description }
1817
- };
1818
- }
1819
- function readHeader(directory, problems) {
1820
- const file = join(directory, LOREBOOK_FILE);
1821
- if (!existsSync(file)) return {};
1822
- let value;
1823
- try {
1824
- value = JSON.parse(readFileSync(file, "utf8"));
1825
- } catch {
1826
- problems.push(`${LOREBOOK_FILE} is not valid JSON`);
1827
- return {};
1828
- }
1829
- return parseHeader(value, problems);
1830
- }
1831
- /** 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. */
1832
- function bookProblems(entries) {
1833
- const ids = new Set(entries.map((entry) => entry.id));
1834
- 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`])]);
1835
- }
1836
- /** Reads one lorebook folder, collecting every problem instead of stopping at the first. @throws {Error} when the folder does not exist. */
1837
- async function readLorebook(directory, name) {
1838
- if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
1839
- const problems = [];
1840
- const header = readHeader(directory, problems);
1841
- const { lore, problems: found } = await loadLore(directory);
1842
- for (const problem of found) problems.push(`${problem.path.slice(directory.length + 1)}: ${problem.message}`);
1843
- problems.push(...bookProblems(lore));
1844
- if (lore.length === 0 && problems.length === 0) problems.push("the lorebook has no entries");
1845
- return {
1846
- summary: {
1847
- name,
1848
- title: header.title ?? name,
1849
- description: header.description ?? "",
1850
- entries: lore.length,
1851
- common: lore.filter((entry) => entry.scope === "everyone").length,
1852
- problems
1853
- },
1854
- entries: lore.sort((a, b) => a.title.localeCompare(b.title))
1855
- };
1856
- }
1857
- async function listLorebooks(root) {
1858
- const folder = lorebooksDirectory(root);
1859
- if (!existsSync(folder)) return [];
1860
- const found = (await readdir(folder, { withFileTypes: true })).filter((entry) => entry.isDirectory() && isLorebookName(entry.name));
1861
- return (await Promise.all(found.map((entry) => readLorebook(join(folder, entry.name), entry.name)))).sort((a, b) => a.summary.name.localeCompare(b.summary.name));
1862
- }
1863
- async function loadLorebook(root, name) {
1864
- return await readLorebook(lorebookDirectory(root, name), name);
1865
- }
1866
- const toEntry = (definition) => ({
1867
- id: definition.id,
1868
- title: definition.title,
1869
- kind: definition.kind,
1870
- scope: definition.scope,
1871
- knownBy: definition.knownBy,
1872
- summary: definition.summary,
1873
- body: definition.body,
1874
- related: definition.related
1875
- });
1876
- const entriesOf = (book) => book.entries.map(toEntry);
1877
- function headerFile(header) {
1878
- return `${JSON.stringify(header, null, 2)}\n`;
1879
- }
1880
- async function writeAtomic(file, text) {
1881
- await mkdir(dirname(file), { recursive: true });
1882
- await writeFile(`${file}.tmp`, text);
1883
- await rename(`${file}.tmp`, file);
1884
- }
1885
- /** Makes an empty lorebook. @throws {Error} when the name is taken or the information is not acceptable. */
1886
- async function createLorebook(root, request) {
1887
- const target = lorebookDirectory(root, request.name);
1888
- if (existsSync(target)) throw new Error(`there is already a lorebook "${request.name}"`);
1889
- const problems = [];
1890
- const header = parseHeader({
1891
- title: request.title?.trim(),
1892
- description: request.description?.trim()
1893
- }, problems);
1894
- if (problems.length > 0) throw new Error(problems.join("; "));
1895
- await writeAtomic(join(target, LOREBOOK_FILE), headerFile(header));
1896
- return await readLorebook(target, request.name);
1897
- }
1898
- /** 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. */
1899
- async function reserveLorebook(root, name, title) {
1900
- const target = lorebookDirectory(root, name);
1901
- if (existsSync(target)) throw new Error(`there is already a lorebook "${name}"`);
1902
- await writeAtomic(join(target, LOREBOOK_FILE), headerFile({ title: title.trim().slice(0, MAX_TEXT) || name }));
1903
- return target;
1904
- }
1905
- /** 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. */
1906
- async function updateLorebookInfo(root, name, change) {
1907
- const directory = lorebookDirectory(root, name);
1908
- if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
1909
- const current = readHeader(directory, []);
1910
- const problems = [];
1911
- const next = parseHeader({
1912
- title: change.title ?? current.title,
1913
- description: change.description ?? current.description
1914
- }, problems);
1915
- if (problems.length > 0) throw new Error(problems.join("; "));
1916
- await writeAtomic(join(directory, LOREBOOK_FILE), headerFile(next));
1917
- return await readLorebook(directory, name);
1918
- }
1919
- /** The file of an entry: written in the format of a world's own lore, with its scope always said. */
1920
- function entryFile(entry) {
1921
- return `${JSON.stringify({
1922
- title: entry.title,
1923
- kind: entry.kind,
1924
- scope: entry.scope,
1925
- ...entry.scope === "listed" && entry.knownBy.length > 0 ? { known_by: entry.knownBy } : {},
1926
- summary: entry.summary,
1927
- body: entry.body,
1928
- ...entry.related.length > 0 ? { related: entry.related } : {}
1929
- }, null, 2)}\n`;
1930
- }
1931
- /** Checks an entry the way a story start would, before anything is written. @returns why it cannot be used, or nothing. */
1932
- function entryProblem(entry) {
1933
- if (!isEntryId(entry.id)) return `"${entry.id}" is not a usable entry id (letters, digits, "-" and "_", up to 80)`;
1934
- if (!LORE_KINDS.includes(entry.kind)) return `kind must be one of ${LORE_KINDS.join(", ")}`;
1935
- if (!LORE_SCOPES.includes(entry.scope)) return `scope must be one of ${LORE_SCOPES.join(", ")}`;
1936
- if (entry.title.trim() === "") return "the entry needs a title";
1937
- if (entry.body.trim() === "" && entry.summary.trim() === "") return "the entry needs a summary or a body";
1938
- const parsed = parseLoreFile(entryFile({
1939
- ...entry,
1940
- title: entry.title.trim()
1941
- }), entry.id);
1942
- return parsed.ok ? void 0 : parsed.issues.map((issue) => `${issue.path}: ${issue.message}`).join("; ");
1943
- }
1944
- /**
1945
- * Creates several new entries of a lorebook at once, each checked as `writeLorebookEntry` checks one; none is written when any is not acceptable.
1946
- * @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.
1947
- */
1948
- async function addLorebookEntries(root, name, entries) {
1949
- const directory = lorebookDirectory(root, name);
1950
- if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
1951
- const book = await readLorebook(directory, name);
1952
- if (book.entries.length + entries.length > 500) throw new Error(`a lorebook has at most 500 entries`);
1953
- const ids = new Set(book.entries.map((entry) => entry.id));
1954
- for (const entry of entries) {
1955
- const problem = entryProblem(entry);
1956
- if (problem !== void 0) throw new Error(`entry "${entry.title}": ${problem}`);
1957
- if (ids.has(entry.id)) throw new Error(`there is already an entry "${entry.id}"`);
1958
- ids.add(entry.id);
1959
- }
1960
- for (const entry of entries) await writeAtomic(join(directory, LORE_DIR, entry.id, LORE_FILE_NAME), entryFile({
1961
- ...entry,
1962
- title: entry.title.trim()
1963
- }));
1964
- return await readLorebook(directory, name);
1965
- }
1966
- /** 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. */
1967
- async function writeLorebookEntry(root, name, entry) {
1968
- const directory = lorebookDirectory(root, name);
1969
- if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
1970
- const problem = entryProblem(entry);
1971
- if (problem !== void 0) throw new Error(problem);
1972
- const file = join(directory, LORE_DIR, entry.id, LORE_FILE_NAME);
1973
- const book = await readLorebook(directory, name);
1974
- if (!existsSync(file) && book.entries.length >= 500) throw new Error(`a lorebook has at most 500 entries`);
1975
- const others = book.entries.filter((other) => other.id !== entry.id);
1976
- const missing = entry.related.filter((id) => id === entry.id || !others.some((other) => other.id === id));
1977
- if (missing.length > 0) throw new Error(`related: ${missing.map((id) => `"${id}"`).join(", ")} ${missing.length === 1 ? "is" : "are"} not (other) entries of this book`);
1978
- await writeAtomic(file, entryFile({
1979
- ...entry,
1980
- title: entry.title.trim()
1981
- }));
1982
- return await readLorebook(directory, name);
1983
- }
1984
- /** Moves an entry into the book's `.trash`. @throws {Error} when it does not exist or other entries relate to it. */
1985
- async function deleteLorebookEntry(root, name, id, now = Date.now) {
1986
- const directory = lorebookDirectory(root, name);
1987
- const folder = join(directory, LORE_DIR, id);
1988
- if (!isEntryId(id) || !existsSync(join(folder, "lore.json"))) throw new Error(`the lorebook "${name}" has no entry "${id}"`);
1989
- const citing = (await readLorebook(directory, name)).entries.filter((entry) => entry.id !== id && entry.related.includes(id)).map((entry) => entry.id);
1990
- if (citing.length > 0) throw new Error(`the entries ${citing.join(", ")} relate to "${id}"; change them first`);
1991
- const aside = join(directory, ".trash", LORE_DIR, `${id}-${now()}`);
1992
- await mkdir(dirname(aside), { recursive: true });
1993
- await rename(folder, aside);
1994
- return await readLorebook(directory, name);
1995
- }
1996
- /** Moves a lorebook out of the library into `<root>/.trash/lorebooks/`. @returns where it went. */
1997
- async function deleteLorebook(root, name, now = Date.now) {
1998
- const directory = lorebookDirectory(root, name);
1999
- if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
2000
- const aside = join(root, ".trash", LOREBOOKS_FOLDER, `${name}-${now()}`);
2001
- await mkdir(dirname(aside), { recursive: true });
2002
- await rename(directory, aside);
2003
- return aside;
2004
- }
2005
- // src/shared/start-questions.ts
2006
- const START_PLOT_STATUSES = ["dormant", "available"];
2007
- const questionView = (question) => ({
2008
- id: question.id,
2009
- text: question.text,
2010
- options: question.options.map(({ id, label, description }) => ({
2011
- id,
2012
- label,
2013
- ...description === void 0 ? {} : { description }
2014
- }))
2015
- });
2016
- /** What the answers add up to, or why they cannot be combined. A question left unanswered changes nothing. */
2017
- function combineAnswers(questions, answers) {
2018
- const problems = [];
2019
- const effect = {};
2020
- for (const id of Object.keys(answers)) if (!questions.some((question) => question.id === id)) problems.push(`the world asks no question "${id}"`);
2021
- const set = (key, value, question) => {
2022
- if (value === void 0) return;
2023
- if (effect[key] !== void 0 && effect[key] !== value) problems.push(`the answers disagree about the ${key === "startingTime" ? "starting time" : key === "clockMode" ? "clock" : key}; "${question}" changes it again`);
2024
- else effect[key] = value;
2025
- };
2026
- for (const question of questions) {
2027
- const answer = answers[question.id];
2028
- if (answer === void 0) continue;
2029
- const option = question.options.find((entry) => entry.id === answer);
2030
- if (option === void 0) {
2031
- problems.push(`"${answer}" is not an answer to "${question.id}"`);
2032
- continue;
2033
- }
2034
- const found = option.effect;
2035
- if (found.rules !== void 0) effect.rules = [...effect.rules ?? [], ...found.rules];
2036
- set("opening", found.opening, question.id);
2037
- set("startingTime", found.startingTime, question.id);
2038
- set("clockMode", found.clockMode, question.id);
2039
- for (const [agent, switches] of Object.entries(found.tools ?? {})) {
2040
- const merged = { ...effect.tools?.[agent] };
2041
- for (const [tool, value] of Object.entries(switches)) {
2042
- if (merged[tool] !== void 0 && merged[tool] !== value) problems.push(`the answers disagree about the tool "${tool}"; "${question.id}" changes it again`);
2043
- merged[tool] = value;
2044
- }
2045
- effect.tools = {
2046
- ...effect.tools,
2047
- [agent]: merged
2048
- };
2049
- }
2050
- for (const [plot, status] of Object.entries(found.plots ?? {})) {
2051
- if (effect.plots?.[plot] !== void 0 && effect.plots[plot] !== status) problems.push(`the answers disagree about the plot "${plot}"; "${question.id}" changes it again`);
2052
- effect.plots = {
2053
- ...effect.plots,
2054
- [plot]: status
2055
- };
2056
- }
2057
- }
2058
- return {
2059
- effect,
2060
- problems
2061
- };
2062
- }
2063
- /** The questions as `world.json` writes them: snake_case keys, and only what an answer sets. */
2064
- function startQuestionsToFile(questions) {
2065
- return questions.map((question) => ({
2066
- id: question.id,
2067
- text: question.text,
2068
- options: question.options.map((option) => ({
2069
- id: option.id,
2070
- label: option.label,
2071
- ...option.description === void 0 || option.description === "" ? {} : { description: option.description },
2072
- effect: {
2073
- ...option.effect.rules === void 0 || option.effect.rules.length === 0 ? {} : { rules: option.effect.rules },
2074
- ...option.effect.opening === void 0 ? {} : { opening: option.effect.opening },
2075
- ...option.effect.startingTime === void 0 || option.effect.startingTime === "" ? {} : { starting_time: option.effect.startingTime },
2076
- ...option.effect.clockMode === void 0 ? {} : { clock_mode: option.effect.clockMode },
2077
- ...option.effect.tools === void 0 ? {} : { tools: option.effect.tools },
2078
- ...option.effect.plots === void 0 ? {} : { plots: option.effect.plots }
2079
- }
2080
- }))
2081
- }));
2082
- }
2083
- const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2084
- /** Reads questions sent by the editor: the shape only, since the world file's own reader judges every value when the change is written. */
2085
- function parseStartQuestionsEdit(value, problems) {
2086
- if (!Array.isArray(value)) {
2087
- problems.push("startQuestions must be a list");
2088
- return;
2089
- }
2090
- const questions = [];
2091
- for (const entry of value) {
2092
- if (!isObject(entry) || typeof entry["id"] !== "string" || typeof entry["text"] !== "string" || !Array.isArray(entry["options"])) {
2093
- problems.push("a start question needs an id, a text and a list of options");
2094
- return;
2095
- }
2096
- const options = [];
2097
- for (const option of entry["options"]) {
2098
- if (!isObject(option) || typeof option["id"] !== "string" || typeof option["label"] !== "string" || !isObject(option["effect"]) || option["description"] !== void 0 && typeof option["description"] !== "string") {
2099
- problems.push("an answer needs an id, a label and an effect");
2100
- return;
2101
- }
2102
- const effect = option["effect"];
2103
- const known = {};
2104
- if (Array.isArray(effect["rules"])) known.rules = effect["rules"].filter((rule) => typeof rule === "string");
2105
- if (typeof effect["opening"] === "number") known.opening = effect["opening"];
2106
- if (typeof effect["startingTime"] === "string") known.startingTime = effect["startingTime"];
2107
- if (effect["clockMode"] === "simulated" || effect["clockMode"] === "real") known.clockMode = effect["clockMode"];
2108
- if (isObject(effect["tools"])) known.tools = effect["tools"];
2109
- if (isObject(effect["plots"])) known.plots = effect["plots"];
2110
- options.push({
2111
- id: option["id"].trim(),
2112
- label: option["label"].trim(),
2113
- ...typeof option["description"] === "string" && option["description"].trim() !== "" ? { description: option["description"].trim() } : {},
2114
- effect: known
2115
- });
2116
- }
2117
- questions.push({
2118
- id: entry["id"].trim(),
2119
- text: entry["text"].trim(),
2120
- options
2121
- });
2122
- }
2123
- return questions;
2124
- }
2125
- const MAX_OPENING_CHARS = 2e4;
2126
- const TEXT_FIELDS = [
2127
- "name",
2128
- "description",
2129
- "opening",
2130
- "authorName",
2131
- "authorUrl",
2132
- "timeZone",
2133
- "startingTime",
2134
- "version",
2135
- "preset"
2136
- ];
2137
- const LIST_FIELDS = [
2138
- "tags",
2139
- "rules",
2140
- "lorebooks"
2141
- ];
2142
- /** Reads a body that came from the browser; every field is checked and each problem is reported. */
2143
- function parseWorldInfoEdit(value) {
2144
- const problems = [];
2145
- const input = typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
2146
- if (input === void 0) throw new InvalidEditProblems(["the changes must be an object"]);
2147
- const edit = {};
2148
- for (const key of Object.keys(input)) if (!TEXT_FIELDS.includes(key) && !LIST_FIELDS.includes(key) && key !== "alternateOpenings" && key !== "startQuestions" && key !== "tools" && key !== "sampling") problems.push(`there is no field "${key}"`);
2149
- for (const key of TEXT_FIELDS) {
2150
- if (input[key] === void 0) continue;
2151
- if (typeof input[key] === "string") edit[key] = input[key].trim();
2152
- else problems.push(`${key} must be text`);
2153
- }
2154
- for (const key of LIST_FIELDS) {
2155
- if (input[key] === void 0) continue;
2156
- if (Array.isArray(input[key]) && input[key].every((entry) => typeof entry === "string")) edit[key] = input[key].map((entry) => entry.trim()).filter((entry) => entry !== "");
2157
- else problems.push(`${key} must be a list of text`);
2158
- }
2159
- if (input["alternateOpenings"] !== void 0) {
2160
- const list = input["alternateOpenings"];
2161
- const entries = Array.isArray(list) ? list.map((entry) => typeof entry === "object" && entry !== null ? entry : void 0) : void 0;
2162
- if (entries === void 0 || entries.some((entry) => entry === void 0 || typeof entry["text"] !== "string" || entry["title"] !== void 0 && typeof entry["title"] !== "string" || entry["character"] !== void 0 && typeof entry["character"] !== "string")) problems.push("alternateOpenings must be a list of { title, text, character? }");
2163
- else {
2164
- const kept = entries.map((entry) => ({
2165
- title: String(entry["title"] ?? "").trim(),
2166
- text: String(entry["text"]).trim(),
2167
- ...String(entry["character"] ?? "").trim() === "" ? {} : { character: String(entry["character"]).trim() }
2168
- })).filter((entry) => entry.text !== "");
2169
- if (kept.length > 30) problems.push(`there are more than 30 alternate openings`);
2170
- if (kept.some((entry) => entry.text.length > 2e4)) problems.push(`an alternate opening is longer than ${MAX_OPENING_CHARS} characters`);
2171
- edit["alternateOpenings"] = kept;
2172
- }
2173
- }
2174
- if (input["startQuestions"] !== void 0) {
2175
- const questions = parseStartQuestionsEdit(input["startQuestions"], problems);
2176
- if (questions !== void 0) edit["startQuestions"] = questions;
2177
- }
2178
- if (input["tools"] !== void 0) {
2179
- const board = parseSwitchboard(input["tools"], "tools");
2180
- if (typeof board === "string") problems.push(board);
2181
- else edit["tools"] = board;
2182
- }
2183
- if (input["sampling"] !== void 0) edit["sampling"] = parseSampling(input["sampling"], "sampling", problems);
2184
- if (typeof edit["version"] === "string" && edit["version"].length > 40) problems.push(`the version is longer than 40 characters`);
2185
- if (edit["name"] === "") problems.push("the world needs a name");
2186
- if (typeof edit["name"] === "string" && edit["name"].length > 200) problems.push(`the name is longer than 200 characters`);
2187
- if (problems.length > 0) throw new InvalidEditProblems(problems);
2188
- return edit;
2189
- }
2190
- // src/host/worlds/world-file.ts
2191
- const WORLD_FILE_NAME = "world.json";
2192
- /** `alternate_openings` is a list of `{ title, text, character? }`: other first messages the player may start with, each for any character or for one playable character. */
2193
- function readAlternateOpenings(reader) {
2194
- const value = reader.raw("alternate_openings");
2195
- if (value === void 0 || value === null) return void 0;
2196
- if (!Array.isArray(value)) {
2197
- reader.fail("alternate_openings", "must be a list");
2198
- return;
2199
- }
2200
- if (value.length > 30) reader.fail("alternate_openings", `has more than 30 openings`);
2201
- const openings = [];
2202
- for (const entry of reader.objects("alternate_openings")) {
2203
- const text = entry.string("text", { required: true })?.trim();
2204
- if (text === void 0 || text === "") continue;
2205
- if (text.length > 2e4) entry.fail("text", `is longer than ${MAX_OPENING_CHARS} characters`);
2206
- const character = entry.string("character")?.trim();
2207
- openings.push({
2208
- title: entry.string("title")?.trim() || text.slice(0, 40),
2209
- text,
2210
- ...character === void 0 || character === "" ? {} : { character }
2211
- });
2212
- }
2213
- return openings.length === 0 ? void 0 : openings;
2214
- }
2215
- const EFFECT_KEYS = [
2216
- "rules",
2217
- "opening",
2218
- "starting_time",
2219
- "clock_mode",
2220
- "tools",
2221
- "plots"
2222
- ];
2223
- /** One answer's `effect`: only the allow-listed keys, each checked; an unknown key is refused so an answer can never reach a setting it was not meant to. */
2224
- function readEffect(entry, openings) {
2225
- const raw = entry.raw("effect");
2226
- const effect = {};
2227
- if (raw === void 0 || raw === null) return effect;
2228
- if (typeof raw !== "object" || Array.isArray(raw)) {
2229
- entry.fail("effect", "must be an object");
2230
- return effect;
2231
- }
2232
- const body = raw;
2233
- for (const key of Object.keys(body)) if (!EFFECT_KEYS.includes(key)) entry.fail(`effect.${key}`, `is not something an answer can change (${EFFECT_KEYS.join(", ")})`);
2234
- if (body["rules"] !== void 0) {
2235
- const rules = Array.isArray(body["rules"]) && body["rules"].every((rule) => typeof rule === "string") ? body["rules"].map((rule) => rule.trim()).filter((rule) => rule !== "") : void 0;
2236
- if (rules === void 0) entry.fail("effect.rules", "must be a list of rules");
2237
- else if (rules.some((rule) => rule.length > 300)) entry.fail("effect.rules", `has a rule longer than 300 characters`);
2238
- else if (rules.length > 0) effect.rules = rules;
2239
- }
2240
- if (body["opening"] !== void 0) {
2241
- if (typeof body["opening"] !== "number" || !Number.isInteger(body["opening"]) || body["opening"] < 0 || body["opening"] >= openings) entry.fail("effect.opening", `must be the position of one of the ${openings} alternate openings`);
2242
- else effect.opening = body["opening"];
2243
- }
2244
- if (body["starting_time"] !== void 0) {
2245
- if (typeof body["starting_time"] !== "string" || body["starting_time"].trim() === "") entry.fail("effect.starting_time", "must be a local time like 1912-04-14T23:40:00");
2246
- else effect.startingTime = body["starting_time"].trim();
2247
- }
2248
- if (body["clock_mode"] !== void 0) {
2249
- if (body["clock_mode"] !== "simulated" && body["clock_mode"] !== "real") entry.fail("effect.clock_mode", "must be \"simulated\" or \"real\"");
2250
- else effect.clockMode = body["clock_mode"];
2251
- }
2252
- if (body["tools"] !== void 0) {
2253
- const board = parseSwitchboard(body["tools"], "tools");
2254
- if (typeof board === "string") entry.fail("effect.tools", board.replace(/^"tools"\s*/, ""));
2255
- else if (Object.keys(board).length > 0) effect.tools = board;
2256
- }
2257
- if (body["plots"] !== void 0) {
2258
- const plots = body["plots"];
2259
- if (typeof plots !== "object" || plots === null || Array.isArray(plots)) entry.fail("effect.plots", "must map plot ids to \"dormant\" or \"available\"");
2260
- else {
2261
- const kept = {};
2262
- for (const [id, status] of Object.entries(plots)) if (status !== "dormant" && status !== "available") entry.fail(`effect.plots.${id}`, `must be one of ${START_PLOT_STATUSES.join(", ")}`);
2263
- else kept[id] = status;
2264
- if (Object.keys(kept).length > 0) effect.plots = kept;
2265
- }
2266
- }
2267
- return effect;
2268
- }
2269
- /** `start_questions`: `{ id, text, options: [{ id, label, description?, effect }] }`, asked in the start dialog. */
2270
- function readStartQuestions(reader, openings) {
2271
- const value = reader.raw("start_questions");
2272
- if (value === void 0 || value === null) return void 0;
2273
- if (!Array.isArray(value)) {
2274
- reader.fail("start_questions", "must be a list");
2275
- return;
2276
- }
2277
- if (value.length > 8) reader.fail("start_questions", `has more than 8 questions`);
2278
- const questions = [];
2279
- const seen = /* @__PURE__ */ new Set();
2280
- for (const entry of reader.objects("start_questions")) {
2281
- const id = entry.string("id", { required: true })?.trim();
2282
- const text = entry.string("text", { required: true })?.trim();
2283
- if (id === void 0 || text === void 0 || id === "" || text === "") continue;
2284
- if (seen.has(id)) entry.fail("id", `repeats the question "${id}"`);
2285
- seen.add(id);
2286
- if (text.length > 200) entry.fail("text", `is longer than 200 characters`);
2287
- const raw = entry.raw("options");
2288
- if (!Array.isArray(raw) || raw.length < 2 || raw.length > 8) {
2289
- entry.fail("options", `must list 2 to 8 answers`);
2290
- continue;
2291
- }
2292
- const options = [];
2293
- const ids = /* @__PURE__ */ new Set();
2294
- for (const option of entry.objects("options")) {
2295
- const optionId = option.string("id", { required: true })?.trim();
2296
- const label = option.string("label", { required: true })?.trim();
2297
- if (optionId === void 0 || label === void 0 || optionId === "" || label === "") continue;
2298
- if (ids.has(optionId)) option.fail("id", `repeats the answer "${optionId}"`);
2299
- ids.add(optionId);
2300
- if (label.length > 200) option.fail("label", `is longer than 200 characters`);
2301
- const description = option.string("description")?.trim();
2302
- options.push({
2303
- id: optionId,
2304
- label,
2305
- ...description === void 0 || description === "" ? {} : { description },
2306
- effect: readEffect(option, openings)
2307
- });
2308
- }
2309
- questions.push({
2310
- id,
2311
- text,
2312
- options
2313
- });
2314
- }
2315
- return questions.length === 0 ? void 0 : questions;
2316
- }
2317
- /** `tools`: switches by kind of agent and tool name; a world carried from a version with other tools still loads. */
2318
- function readTools(reader) {
2319
- const value = reader.raw("tools");
2320
- if (value === void 0) return void 0;
2321
- const board = parseSwitchboard(value, "tools");
2322
- if (typeof board === "string") {
2323
- reader.fail("tools", board.replace(/^"tools"\s*/, ""));
2324
- return;
2325
- }
2326
- return Object.keys(board).length === 0 ? void 0 : board;
2327
- }
2328
- /** `sampling` is an object of the controls a story's requests may carry (see `StorySampling`). */
2329
- function readSampling(reader) {
2330
- const problems = [];
2331
- const sampling = parseSampling(reader.raw("sampling"), "sampling", problems);
2332
- for (const problem of problems) reader.fail("sampling", problem.replace(/^sampling\.?/, ""));
2333
- return Object.keys(sampling).length === 0 ? void 0 : sampling;
2334
- }
2335
- /** `rules` is one rule as text, or a list of them; blank ones are left out. */
2336
- function readRules(reader) {
2337
- const value = reader.raw("rules");
2338
- if (value === void 0 || value === null) return void 0;
2339
- const kept = (typeof value === "string" ? [value] : reader.strings("rules")).map((rule) => rule.trim()).filter((rule) => rule !== "");
2340
- if (kept.length > 30) reader.fail("rules", `has more than 30 rules`);
2341
- const long = kept.findIndex((rule) => rule.length > 300);
2342
- if (long >= 0) reader.fail("rules", `rule ${long + 1} is longer than 300 characters: keep rules short`);
2343
- return kept.length === 0 ? void 0 : kept;
2344
- }
2345
- /** `opening_message` is plain text (one narration), or a list of parts in the order the player reads them. */
2346
- function readOpening(reader) {
2347
- const value = reader.raw("opening_message");
2348
- if (value === void 0 || value === null) return void 0;
2349
- if (typeof value === "string") return value.trim() === "" ? void 0 : [{
2350
- type: "narration",
2351
- text: value.trim()
2352
- }];
2353
- if (!Array.isArray(value)) {
2354
- reader.fail("opening_message", "must be text or a list of parts");
2355
- return;
2356
- }
2357
- const parts = [];
2358
- for (const part of reader.objects("opening_message")) {
2359
- const type = part.oneOf("type", ["narration", "utterance"], "narration");
2360
- const text = part.string("text", { required: true })?.trim();
2361
- if (text === void 0 || text === "") continue;
2362
- if (type === "narration") {
2363
- parts.push({
2364
- type,
2365
- text
2366
- });
2367
- continue;
2368
- }
2369
- const character = part.string("character", { required: true });
2370
- if (character !== void 0) parts.push({
2371
- type,
2372
- character,
2373
- text
2374
- });
2375
- }
2376
- return parts.length === 0 ? void 0 : parts;
2377
- }
2378
- /** `time_zone` (an IANA name) and `starting_time` (an ISO 8601 date and time, in `time_zone` unless it carries an offset). */
2379
- function readClock(reader) {
2380
- const timeZone = reader.string("time_zone");
2381
- if (timeZone !== void 0 && !isTimeZone(timeZone)) {
2382
- reader.fail("time_zone", `"${timeZone}" is not a time zone: write it like Europe/London or UTC`);
2383
- return;
2384
- }
2385
- const text = reader.string("starting_time");
2386
- let startingTime;
2387
- if (text !== void 0) try {
2388
- startingTime = parseInstant(text, timeZone ?? "UTC");
2389
- } catch (error) {
2390
- reader.fail("starting_time", error instanceof Error ? error.message : String(error));
2391
- return;
2392
- }
2393
- return timeZone === void 0 && startingTime === void 0 ? void 0 : {
2394
- ...startingTime === void 0 ? {} : { startingTime },
2395
- ...timeZone === void 0 ? {} : { timeZone }
2396
- };
2397
- }
2398
- function readAuthor(reader) {
2399
- if (reader === void 0) return void 0;
2400
- const name = reader.string("name", { required: true });
2401
- const url = reader.string("url");
2402
- return name === void 0 ? void 0 : {
2403
- name,
2404
- ...url === void 0 ? {} : { url }
2405
- };
2406
- }
2407
- function parseWorldFile(text) {
2408
- const issues = [];
2409
- const reader = Reader.fromJson(text, issues);
2410
- if (reader === void 0) return {
2411
- ok: false,
2412
- issues
2413
- };
2414
- const id = readIdentifier(reader);
2415
- const name = reader.string("name", { required: true });
2416
- const description = reader.text("description");
2417
- const tags = reader.object("metadata")?.strings("tags") ?? [];
2418
- const author = readAuthor(reader.object("author"));
2419
- const rawVersion = reader.raw("version");
2420
- if (rawVersion !== void 0 && rawVersion !== null && typeof rawVersion !== "string" && typeof rawVersion !== "number") reader.fail("version", "must be text or a number");
2421
- const version = (typeof rawVersion === "string" || typeof rawVersion === "number" ? String(rawVersion).trim() : "") || void 0;
2422
- if (version !== void 0 && version.length > 40) reader.fail("version", `is longer than 40 characters`);
2423
- const coverMediaId = reader.string("cover_media_id");
2424
- const opening = readOpening(reader);
2425
- const clock = readClock(reader);
2426
- const variables = readVariableValues(reader);
2427
- const rules = readRules(reader);
2428
- const tools = readTools(reader);
2429
- const alternateOpenings = readAlternateOpenings(reader);
2430
- const startQuestions = readStartQuestions(reader, alternateOpenings?.length ?? 0);
2431
- const narrationVoice = reader.string("narration_voice")?.trim() || void 0;
2432
- const sampling = readSampling(reader);
2433
- const preset = reader.string("preset")?.trim() || void 0;
2434
- if (preset !== void 0 && !isPresetName(preset)) reader.fail("preset", "must be the name of a preset: letters, digits, \"-\" and \"_\"");
2435
- const lorebooks = reader.strings("lorebooks").map((entry) => entry.trim()).filter((entry) => entry !== "");
2436
- for (const [index, entry] of lorebooks.entries()) if (!isLorebookName(entry)) reader.fail(`lorebooks[${index}]`, "must be the name of a lorebook: letters, digits, \"-\" and \"_\"");
2437
- if (name === void 0 || issues.length > 0) return {
2438
- ok: false,
2439
- issues
2440
- };
2441
- return {
2442
- ok: true,
2443
- value: {
2444
- ...id === void 0 ? {} : { id },
2445
- name,
2446
- description,
2447
- tags,
2448
- ...author === void 0 ? {} : { author },
2449
- ...version === void 0 ? {} : { version },
2450
- ...coverMediaId === void 0 ? {} : { coverMediaId },
2451
- ...opening === void 0 ? {} : { opening },
2452
- ...clock === void 0 ? {} : { clock },
2453
- ...variables === void 0 ? {} : { variables },
2454
- ...rules === void 0 ? {} : { rules },
2455
- ...tools === void 0 ? {} : { tools },
2456
- ...alternateOpenings === void 0 ? {} : { alternateOpenings },
2457
- ...startQuestions === void 0 ? {} : { startQuestions },
2458
- ...narrationVoice === void 0 ? {} : { narrationVoice },
2459
- ...sampling === void 0 ? {} : { sampling },
2460
- ...preset === void 0 ? {} : { preset },
2461
- ...lorebooks.length === 0 ? {} : { lorebooks: [...new Set(lorebooks)] }
2462
- }
2463
- };
2464
- }
2465
1730
  // src/host/import/outcomes.ts
2466
1731
  /**
2467
1732
  * What became of one piece of a card: `carried` is kept word for word (an opening), `converted` made characters, places, things or other entries of the world, `guidance`
@@ -2999,19 +2264,13 @@ async function repairFields(directory, problems) {
2999
2264
  return repairs;
3000
2265
  }
3001
2266
  // src/host/worlds/world-file-io.ts
3002
- const queues = /* @__PURE__ */ new Map();
2267
+ const queue = new SerialQueue();
3003
2268
  /**
3004
2269
  * Runs `work` after everything asked for the same folder before it has finished. The import, the editor and the assistant each read `world.json`, change a field and write it
3005
2270
  * back; run side by side, the last one to write would take back what the others changed.
3006
2271
  */
3007
2272
  function serialized(directory, work) {
3008
- const run = (queues.get(directory) ?? Promise.resolve()).then(work, work);
3009
- const tail = run.then(() => void 0, () => void 0);
3010
- queues.set(directory, tail);
3011
- tail.then(() => {
3012
- if (queues.get(directory) === tail) queues.delete(directory);
3013
- });
3014
- return run;
2273
+ return queue.run(directory, work);
3015
2274
  }
3016
2275
  /** Changes `world.json` in place: read, `update`, written back in one step with the indentation the file had, nothing else moving in between. @returns the document as written. */
3017
2276
  function updateWorldFile(directory, update) {
@@ -3110,7 +2369,7 @@ async function writePortrait(directory, picture, characters, cardName) {
3110
2369
  }
3111
2370
  /** The card's opening as the world's opening message: plain paragraphs, without the markup the card's tool read as emphasis. */
3112
2371
  function openingMessage(raw, cardName, player) {
3113
- const text = cleanText(raw, cardName).replace(/<\/?[a-z][^>\n]*>/gi, "").replace(/```[a-z]*\n?|```/g, "").replace(/\*\*([^*\n]+)\*\*/g, "$1").replace(/(^|[^*])\*(?!\s)([^*\n]+?)(?<!\s)\*(?!\*)/g, "$1$2").replace(/\n{3,}/g, "\n\n").trim();
2372
+ const text = cleanText(splitPanels(raw).prose, cardName).replace(/<\/?[a-z][^>\n]*>/gi, "").replace(/```[a-z]*\n?|```/g, "").replace(/\*\*([^*\n]+)\*\*/g, "$1").replace(/(^|[^*])\*(?!\s)([^*\n]+?)(?<!\s)\*(?!\*)/g, "$1$2").replace(/\n{3,}/g, "\n\n").trim();
3114
2373
  return withPlayer(text, player);
3115
2374
  }
3116
2375
  /** Every player marker in the strings of a value, replaced by the player's character or a plain word for the player; the value is changed in place. */
@@ -3369,6 +2628,7 @@ async function finishImport(ctx, input) {
3369
2628
  };
3370
2629
  if (opening !== void 0) world["opening_message"] = openingMessage(opening, card.name, player === void 0 ? void 0 : String(player["name"]));
3371
2630
  if (alternates.length > 0) world["alternate_openings"] = alternates;
2631
+ if (extracted.rules.length > 0 && world["rules"] === void 0) world["rules"] = extracted.rules.slice(0, 30);
3372
2632
  if (card.creator.trim() !== "" && world["author"] === void 0) world["author"] = { name: card.creator.trim() };
3373
2633
  if (cover) world["cover_media_id"] = "cover";
3374
2634
  });
@@ -4138,6 +3398,7 @@ function infoOf(document, startQuestions = []) {
4138
3398
  version: typeof document["version"] === "number" ? String(document["version"]) : textOf(document["version"]),
4139
3399
  sampling: parseSampling(document["sampling"], "sampling", []),
4140
3400
  tools: toolsOf(document["tools"]),
3401
+ autonomy: document["autonomy"] === true,
4141
3402
  startQuestions,
4142
3403
  alternateOpenings: Array.isArray(document["alternate_openings"]) ? document["alternate_openings"].flatMap((entry) => typeof entry === "object" && entry !== null && typeof entry["text"] === "string" ? [{
4143
3404
  title: textOf(entry["title"]),
@@ -4225,6 +3486,10 @@ async function changeWorldInfo(directory, edit) {
4225
3486
  if (Object.keys(edit.sampling).length === 0) delete document["sampling"];
4226
3487
  else document["sampling"] = edit.sampling;
4227
3488
  }
3489
+ if (edit.autonomy !== void 0) {
3490
+ if (edit.autonomy) document["autonomy"] = true;
3491
+ else delete document["autonomy"];
3492
+ }
4228
3493
  if (edit.tools !== void 0) {
4229
3494
  if (Object.keys(edit.tools).length === 0) delete document["tools"];
4230
3495
  else document["tools"] = edit.tools;
@@ -4837,7 +4102,7 @@ function worldFieldChanges(before, after) {
4837
4102
  field: "authorName",
4838
4103
  because: `the card\'s creator is now “${after.card.creator}”`
4839
4104
  });
4840
- if (differ(openingText(before.card, before.choices.opening) ?? "", openingText(after.card, after.choices.opening) ?? "")) changes.push({
4105
+ if (differ(splitPanels(openingText(before.card, before.choices.opening) ?? "").prose, splitPanels(openingText(after.card, after.choices.opening) ?? "").prose)) changes.push({
4841
4106
  field: "opening",
4842
4107
  because: "the greeting the world opens with changed; suggested is the new greeting as the import writes an opening (plain paragraphs, the card's markup removed, the player named by the world's player character where the card says {{user}})",
4843
4108
  suggested: openingMessage(openingText(after.card, after.choices.opening) ?? "", after.card.name)
@@ -5981,6 +5246,31 @@ const about = {
5981
5246
  return foundBy("quality-world", found);
5982
5247
  }
5983
5248
  };
5249
+ const PANEL_QUOTE_CHARS = 120;
5250
+ const panels = {
5251
+ id: "quality-panels",
5252
+ kit: "quality",
5253
+ mode: "code",
5254
+ needs: [],
5255
+ description: "Status bars, panels and update blocks written into the opening, the prompts, the lore or the characters: a story shows its tracked values itself, and a game master that is told to print one writes it into the narration.",
5256
+ async run(input) {
5257
+ const { texts } = await loaded.text(input);
5258
+ const found = [];
5259
+ for (const [where, body] of texts) {
5260
+ const panel = findPanel(body);
5261
+ if (panel === void 0) continue;
5262
+ const quote = panel.replace(/\s+/g, " ").slice(0, PANEL_QUOTE_CHARS);
5263
+ found.push({
5264
+ severity: "warning",
5265
+ code: "output-panel",
5266
+ where,
5267
+ message: `${where} holds a status bar or markup a story would print: ${quote}`,
5268
+ hint: "Take it out with the editing tools; keeping it is never intended. Declare the values it shows in variables.json (the story shows them) and do not keep the layout or an instruction to print it."
5269
+ });
5270
+ }
5271
+ return foundBy("quality-panels", found);
5272
+ }
5273
+ };
5984
5274
  const SHEET_SCHEMA = {
5985
5275
  type: "object",
5986
5276
  properties: {
@@ -6059,6 +5349,7 @@ const qualityChecks = [
6059
5349
  cast,
6060
5350
  places,
6061
5351
  about,
5352
+ panels,
6062
5353
  sheets,
6063
5354
  {
6064
5355
  id: "world-gaps",
@@ -6419,6 +5710,7 @@ async function build(ctx, world) {
6419
5710
  const extracted = await extractEntities(ctx, card, items.filter((item) => !isLeftOut(classified[item.id])), classified, roster);
6420
5711
  const style = await extractStyle(ctx, card, items, classified);
6421
5712
  extracted.prompts.push(...style.prompts);
5713
+ extracted.rules.push(...style.rules);
6422
5714
  extracted.notes.push(...style.notes);
6423
5715
  extracted.derived.push(...style.derived);
6424
5716
  const tracked = await extractVariables(ctx, card, items, classified, roster);
@@ -6927,6 +6219,6 @@ function limitAuthoringAgents(ctx, kindOf) {
6927
6219
  return await next();
6928
6220
  });
6929
6221
  }
6930
- export { readSource as $, subfolders as $t, editsSince as A, populateLore as At, addressesToFetch as B, loadLocations as Bt, worldFieldChanges as C, populateCharacters as Ct, loadCardEvidence as D, populateItems as Dt, loadWorldParts as E, populateFactions as Et, localChanges as F, TRIGGERS_FILE_NAME as Ft, vetUrl as G, DICE_FILE_NAME as Gt, fetchPictures as H, loadItems as Ht, readOrigin as I, loadTriggers as It, UPDATE_FOLDER as J, CALENDAR_FILE_NAME as Jt, cardCharacter as K, loadDice as Kt, writeOrigin as L, LORE_DIR as Lt, describeChanges as M, populateTriggers as Mt, hashWorld as N, populateVariables as Nt, CHECK_COMMANDS as O, populateKnowledge as Ot, isUnchanged as P, routineProblems as Pt, entitiesByPiece as Q, loadCharacters as Qt, CatalogueError as R, loadLore as Rt, pictureChange as S, populateCalendar as St, readWorldInfo as T, populateDice as Tt, guardedLookup as U, FACTIONS_DIR as Ut, candidateUrls as V, ITEMS_DIR as Vt, mergeReports as W, loadFactions as Wt, cardPieces as X, parseCalendarFile as Xt, baseId as Y, loadCalendar as Yt, cardTools as Z, CHARACTERS_DIR as Zt, runChecks as _, writeLorebookEntry as _t, importHooks as a, readCard as an, addLorebookEntries as at, diffText as b, withScratchStory as bt, importPhase as c, DICE_RESULTS as cn, deleteLorebookEntry as ct, markReady as d, listLorebooks as dt, knownOutputCeiling as en, WORLD_FILE_NAME as et, settleDraft as f, loadLorebook as ft, CHECKS as g, updateLorebookInfo as gt, presentReport as h, reserveLorebook as ht, contextOf as i, pictureOf as in, questionView as it, writeSnapshot as j, populateRoutines as jt, recordProvenance as k, populateLocations as kt, isReviewing as l, authoredWorldOf as ln, entriesOf as lt, checkImported as m, readLorebook as mt, limitAuthoringAgents as n, cardFormat as nn, parseWorldInfoEdit as nt, importTools as o, DICE_COMPARISONS as on, createLorebook as ot, structureImport as p, lorebookDirectory as pt, writePortrait as q, parseDiceFile as qt, MAX_PREVIEW_TEXT as r, isPng as rn, combineAnswers as rt, worldOf as s, DICE_READINGS as sn, deleteLorebook as st, AuthoringTools as t, ImportCardError as tn, parseWorldFile as tt, keepDraft as u, authoringChatSessionId as un, isLorebookName as ut, addressChanges as v, checkWorld as vt, editWorldInfo as w, populateClock as wt, matchPieces as x, knowsCharacter as xt, cardChanges as y, loadValidatedWorld as yt, addressKey as z, LOCATIONS_DIR as zt };
6222
+ export { readSource as $, editsSince as A, loadCommands as At, addressesToFetch as B, isPng as Bt, worldFieldChanges as C, FACTIONS_DIR as Ct, loadCardEvidence as D, parseDiceFile as Dt, loadWorldParts as E, loadDice as Et, localChanges as F, CHARACTERS_DIR as Ft, vetUrl as G, DICE_RESULTS as Gt, fetchPictures as H, readCard as Ht, readOrigin as I, loadCharacters as It, UPDATE_FOLDER as J, cardCharacter as K, authoredWorldOf as Kt, writeOrigin as L, knownOutputCeiling as Lt, describeChanges as M, CALENDAR_FILE_NAME as Mt, hashWorld as N, loadCalendar as Nt, CHECK_COMMANDS as O, COMMANDS_FILE_NAME as Ot, isUnchanged as P, parseCalendarFile as Pt, entitiesByPiece as Q, CatalogueError as R, ImportCardError as Rt, pictureChange as S, loadItems as St, readWorldInfo as T, DICE_FILE_NAME as Tt, guardedLookup as U, DICE_COMPARISONS as Ut, candidateUrls as V, pictureOf as Vt, mergeReports as W, DICE_READINGS as Wt, cardPieces as X, baseId as Y, cardTools as Z, runChecks as _, TRIGGERS_FILE_NAME as _t, importHooks as a, populateCharacters as at, diffText as b, loadLocations as bt, importPhase as c, populateFactions as ct, markReady as d, populateLocations as dt, checkWorld as et, settleDraft as f, populateLore as ft, CHECKS as g, routineProblems as gt, presentReport as h, populateVariables as ht, contextOf as i, populateCalendar as it, writeSnapshot as j, parseCommandsFile as jt, recordProvenance as k, commandVariable as kt, isReviewing as l, populateItems as lt, checkImported as m, populateTriggers as mt, limitAuthoringAgents as n, withScratchStory as nt, importTools as o, populateClock as ot, structureImport as p, populateRoutines as pt, writePortrait as q, authoringChatSessionId as qt, MAX_PREVIEW_TEXT as r, knowsCharacter as rt, worldOf as s, populateDice as st, AuthoringTools as t, loadValidatedWorld as tt, keepDraft as u, populateKnowledge as ut, addressChanges as v, loadTriggers as vt, editWorldInfo as w, loadFactions as wt, matchPieces as x, ITEMS_DIR as xt, cardChanges as y, LOCATIONS_DIR as yt, addressKey as z, cardFormat as zt };
6931
6223
 
6932
- //# sourceMappingURL=authoring-tools-BFdw7ahj.js.map
6224
+ //# sourceMappingURL=authoring-tools-VOaXzr_R.js.map