@dsh-agentic-roleplay/core 0.12.0 → 0.12.2

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 (44) hide show
  1. package/cordis.patch.yml +108 -0
  2. package/lib/{access-DAw54-NI.js → access-Csp80TFX.js} +2 -2
  3. package/lib/{authoring-tools-4NgDhIJV.js → authoring-tools-BZr4bgBy.js} +25 -771
  4. package/lib/authoring.js +136 -12
  5. package/lib/{child-D3QUNb3m.js → child-DTdY14S9.js} +54 -6
  6. package/lib/client.js +16457 -1938
  7. package/lib/client.js.map +1 -1
  8. package/lib/compaction.js +3 -3
  9. package/lib/dev-context-Cgv_wZbG.js +50 -0
  10. package/lib/doctor.js +6 -3
  11. package/lib/{gallery-Ct6nm4UQ.js → gallery-BNg0rPTp.js} +3 -3
  12. package/lib/{generator-CI8fOnXy.js → generator-9-5at9cZ.js} +2 -2
  13. package/lib/helper.js +5 -9
  14. package/lib/{hooks-BNeoGMHZ.js → hooks-Dtq5KZQX.js} +47 -16
  15. package/lib/images.js +4 -4
  16. package/lib/index.js +152 -476
  17. package/lib/{jail-BIF79PJO.js → jail-DVbPSC0R.js} +2 -2
  18. package/lib/{library-BF9ZMSFz.js → library-DTxakw0z.js} +2 -2
  19. package/lib/{lorebook-author-tools-DBk-V0hp.js → lorebook-author-tools-BjcEUo22.js} +19 -6
  20. package/lib/lorebook-authoring.js +13 -5
  21. package/lib/{narration-xvErE2yp.js → narration--K2XVIHI.js} +2 -2
  22. package/lib/orchestration.js +33 -12
  23. package/lib/{pack-jail-C8EyX9Ix.js → pack-jail-Dt0VTsu0.js} +558 -23
  24. package/lib/{packs-S0SzrVv-.js → packs-DWfR2Ted.js} +2 -2
  25. package/lib/{presenter-agent-Bc478nTA.js → presenter-agent-vFOxIuWv.js} +9 -9
  26. package/lib/{preset-SJZyw0kt.js → preset-Dv5YF2qj.js} +4 -4
  27. package/lib/{preset-author-tools-CzogjK42.js → preset-author-tools-BUzO9mTW.js} +8 -7
  28. package/lib/preset-authoring.js +12 -6
  29. package/lib/{reflection-buQiSdvq.js → reflection-Dd3pEiZB.js} +14 -15
  30. package/lib/{presets-DQ5rioMh.js → serial-BUaJGwVy.js} +1241 -390
  31. package/lib/{turn-guard-BSAba8sp.js → turn-guard-87NE-Cnp.js} +3 -3
  32. package/locale/de.json +6 -0
  33. package/locale/en.json +6 -0
  34. package/locale/es.json +6 -0
  35. package/locale/fr.json +6 -0
  36. package/locale/ja.json +6 -0
  37. package/locale/pt.json +6 -0
  38. package/locale/ru.json +6 -0
  39. package/locale/zh.json +6 -0
  40. package/package.json +34 -34
  41. package/prompts/en/import/style.md +2 -1
  42. package/prompts/en/world/procedure.md +1 -1
  43. package/prompts/zh/import/style.md +2 -1
  44. package/prompts/zh/world/procedure.md +1 -1
@@ -1,15 +1,14 @@
1
- import { T as currentTurn, c as namedModel, l as runChild, m as parseSampling, t as ChildTimeoutError } from "./child-D3QUNb3m.js";
2
- import { $ as IMPORT_FOLDER, A as sourcesFor, At as readVariableValues, Bt as LORE_KINDS, C as inert, Ct as SLOTS_FILE_NAME, D as pruneLoreSubjects, Dt as parseFactionFile, E as pruneLinks, Et as FACTION_FILE_NAME, F as ROLE_TABLE, Ht as WEEKDAY_NAMES, I as isLeftOut, M as classifyItems, Mt as InvalidEditProblems, N as findEntity, O as pruneMembers, Ot as CHARACTER_FILE_NAME, P as ROLES, Q as withPlayer, R as askYesNo, S as extractVariables, St as ITEM_FILE_NAME, T as pruneKnowledge, Tt as parseSlotsFile, U as yesAt, Ut as DEFAULT_SLOTS, V as noAt, Vt as LORE_SCOPES, X as itemise, Y as cleanText, _ as characterDocument, _t as variableProblems, a as isPresetName, at as readImportFolder, b as extractStyle, bt as LOCATION_FILE_NAME, ct as parseImportCommand, dt as splitPanels, ft as dialectOf, g as asWritten, h as addLore, ht as loadVariables, j as buildRoster, jt as readIdentifier, k as pruneRelationships, kt as parseCharacterFile, mt as VARIABLES_FILE_NAME, nt as PICTURE_FILE, rt as openingText, ut as findPanel, v as emptyExtracted, vt as LORE_FILE_NAME, w as loreDocuments, wt as parseItemFile, xt as parseLocationFile, y as extractEntities, yt as parseLoreFile, zt as guarded } from "./presets-DQ5rioMh.js";
3
- import { f as parseSwitchboard } from "./narration-xvErE2yp.js";
4
- import { n as atomicWrite, r as atomicWriteJson } from "./access-DAw54-NI.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-BNeoGMHZ.js";
1
+ import { T as currentTurn, c as namedModel, l as runChild, m as parseSampling, t as ChildTimeoutError } from "./child-DTdY14S9.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-BUaJGwVy.js";
3
+ import { f as parseSwitchboard } from "./narration--K2XVIHI.js";
4
+ import { n as atomicWrite, r as atomicWriteJson } from "./access-Csp80TFX.js";
5
+ import { $ as copyWorldPrompts, G as readDocument$1, J as errorMessage, K as Reader, U as commandFlagKey, V as plotReferenceProblems, Z as PROMPTS_FOLDER, a as externalGiven, it as shippedLanguages, lt as InvalidWorldError, nt as listFiles, ot as shippedText, q as formatIssue, rt as promptProblem, s as externalWithheld, t as externalToolLimit, vt as COMPARISONS, z as loadPlots } from "./hooks-Dtq5KZQX.js";
6
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-BF9ZMSFz.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";
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-DTxakw0z.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). */
@@ -1521,7 +1466,7 @@ async function checkWorld(world) {
1521
1466
  } catch (error) {
1522
1467
  if (!(error instanceof InvalidWorldError)) throw error;
1523
1468
  const problems = error.problems.map((problem) => ({
1524
- where: relative(world.directory, problem.path) || "(the world)",
1469
+ where: relative(world.directory, problem.path).split(sep).join("/") || "(the world)",
1525
1470
  message: problem.message
1526
1471
  }));
1527
1472
  return {
@@ -1782,695 +1727,6 @@ function structureOnly(card, items, _choices) {
1782
1727
  extracted
1783
1728
  };
1784
1729
  }
1785
- // src/host/lorebooks/lorebooks.ts
1786
- const LOREBOOKS_FOLDER = "lorebooks";
1787
- const LOREBOOK_FILE = "lorebook.json";
1788
- const NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
1789
- const ENTRY_ID = /^[\p{L}\p{N}][\p{L}\p{N}_-]{0,79}$/u;
1790
- const MAX_TEXT = 300;
1791
- const isLorebookName = (name) => NAME.test(name);
1792
- const isEntryId = (id) => ENTRY_ID.test(id);
1793
- const lorebooksDirectory = (root) => join(root, LOREBOOKS_FOLDER);
1794
- function lorebookDirectory(root, name) {
1795
- if (!isLorebookName(name)) throw new Error(`"${name}" is not a usable lorebook name (letters, digits, "-" and "_", up to 64)`);
1796
- return join(lorebooksDirectory(root), name);
1797
- }
1798
- const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1799
- function parseHeader(value, problems) {
1800
- if (!isRecord$1(value)) {
1801
- problems.push(`${LOREBOOK_FILE} must be an object`);
1802
- return {};
1803
- }
1804
- const text = (key) => {
1805
- const field = value[key];
1806
- if (field === void 0 || field === null) return void 0;
1807
- if (typeof field !== "string" || field.length > MAX_TEXT) {
1808
- problems.push(`${LOREBOOK_FILE}: "${key}" must be text of at most ${MAX_TEXT} characters`);
1809
- return;
1810
- }
1811
- return field.trim() || void 0;
1812
- };
1813
- const title = text("title");
1814
- const description = text("description");
1815
- return {
1816
- ...title === void 0 ? {} : { title },
1817
- ...description === void 0 ? {} : { description }
1818
- };
1819
- }
1820
- function readHeader(directory, problems) {
1821
- const file = join(directory, LOREBOOK_FILE);
1822
- if (!existsSync(file)) return {};
1823
- let value;
1824
- try {
1825
- value = JSON.parse(readFileSync(file, "utf8"));
1826
- } catch {
1827
- problems.push(`${LOREBOOK_FILE} is not valid JSON`);
1828
- return {};
1829
- }
1830
- return parseHeader(value, problems);
1831
- }
1832
- /** 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. */
1833
- function bookProblems(entries) {
1834
- const ids = new Set(entries.map((entry) => entry.id));
1835
- 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`])]);
1836
- }
1837
- /** Reads one lorebook folder, collecting every problem instead of stopping at the first. @throws {Error} when the folder does not exist. */
1838
- async function readLorebook(directory, name) {
1839
- if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
1840
- const problems = [];
1841
- const header = readHeader(directory, problems);
1842
- const { lore, problems: found } = await loadLore(directory);
1843
- for (const problem of found) problems.push(`${problem.path.slice(directory.length + 1)}: ${problem.message}`);
1844
- problems.push(...bookProblems(lore));
1845
- if (lore.length === 0 && problems.length === 0) problems.push("the lorebook has no entries");
1846
- return {
1847
- summary: {
1848
- name,
1849
- title: header.title ?? name,
1850
- description: header.description ?? "",
1851
- entries: lore.length,
1852
- common: lore.filter((entry) => entry.scope === "everyone").length,
1853
- problems
1854
- },
1855
- entries: lore.sort((a, b) => a.title.localeCompare(b.title))
1856
- };
1857
- }
1858
- async function listLorebooks(root) {
1859
- const folder = lorebooksDirectory(root);
1860
- if (!existsSync(folder)) return [];
1861
- const found = (await readdir(folder, { withFileTypes: true })).filter((entry) => entry.isDirectory() && isLorebookName(entry.name));
1862
- return (await Promise.all(found.map((entry) => readLorebook(join(folder, entry.name), entry.name)))).sort((a, b) => a.summary.name.localeCompare(b.summary.name));
1863
- }
1864
- async function loadLorebook(root, name) {
1865
- return await readLorebook(lorebookDirectory(root, name), name);
1866
- }
1867
- const toEntry = (definition) => ({
1868
- id: definition.id,
1869
- title: definition.title,
1870
- kind: definition.kind,
1871
- scope: definition.scope,
1872
- knownBy: definition.knownBy,
1873
- summary: definition.summary,
1874
- body: definition.body,
1875
- related: definition.related
1876
- });
1877
- const entriesOf = (book) => book.entries.map(toEntry);
1878
- function headerFile(header) {
1879
- return `${JSON.stringify(header, null, 2)}\n`;
1880
- }
1881
- async function writeAtomic(file, text) {
1882
- await mkdir(dirname(file), { recursive: true });
1883
- await writeFile(`${file}.tmp`, text);
1884
- await rename(`${file}.tmp`, file);
1885
- }
1886
- /** Makes an empty lorebook. @throws {Error} when the name is taken or the information is not acceptable. */
1887
- async function createLorebook(root, request) {
1888
- const target = lorebookDirectory(root, request.name);
1889
- if (existsSync(target)) throw new Error(`there is already a lorebook "${request.name}"`);
1890
- const problems = [];
1891
- const header = parseHeader({
1892
- title: request.title?.trim(),
1893
- description: request.description?.trim()
1894
- }, problems);
1895
- if (problems.length > 0) throw new Error(problems.join("; "));
1896
- await writeAtomic(join(target, LOREBOOK_FILE), headerFile(header));
1897
- return await readLorebook(target, request.name);
1898
- }
1899
- /** 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. */
1900
- async function reserveLorebook(root, name, title) {
1901
- const target = lorebookDirectory(root, name);
1902
- if (existsSync(target)) throw new Error(`there is already a lorebook "${name}"`);
1903
- await writeAtomic(join(target, LOREBOOK_FILE), headerFile({ title: title.trim().slice(0, MAX_TEXT) || name }));
1904
- return target;
1905
- }
1906
- /** 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. */
1907
- async function updateLorebookInfo(root, name, change) {
1908
- const directory = lorebookDirectory(root, name);
1909
- if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
1910
- const current = readHeader(directory, []);
1911
- const problems = [];
1912
- const next = parseHeader({
1913
- title: change.title ?? current.title,
1914
- description: change.description ?? current.description
1915
- }, problems);
1916
- if (problems.length > 0) throw new Error(problems.join("; "));
1917
- await writeAtomic(join(directory, LOREBOOK_FILE), headerFile(next));
1918
- return await readLorebook(directory, name);
1919
- }
1920
- /** The file of an entry: written in the format of a world's own lore, with its scope always said. */
1921
- function entryFile(entry) {
1922
- return `${JSON.stringify({
1923
- title: entry.title,
1924
- kind: entry.kind,
1925
- scope: entry.scope,
1926
- ...entry.scope === "listed" && entry.knownBy.length > 0 ? { known_by: entry.knownBy } : {},
1927
- summary: entry.summary,
1928
- body: entry.body,
1929
- ...entry.related.length > 0 ? { related: entry.related } : {}
1930
- }, null, 2)}\n`;
1931
- }
1932
- /** Checks an entry the way a story start would, before anything is written. @returns why it cannot be used, or nothing. */
1933
- function entryProblem(entry) {
1934
- if (!isEntryId(entry.id)) return `"${entry.id}" is not a usable entry id (letters, digits, "-" and "_", up to 80)`;
1935
- if (!LORE_KINDS.includes(entry.kind)) return `kind must be one of ${LORE_KINDS.join(", ")}`;
1936
- if (!LORE_SCOPES.includes(entry.scope)) return `scope must be one of ${LORE_SCOPES.join(", ")}`;
1937
- if (entry.title.trim() === "") return "the entry needs a title";
1938
- if (entry.body.trim() === "" && entry.summary.trim() === "") return "the entry needs a summary or a body";
1939
- const parsed = parseLoreFile(entryFile({
1940
- ...entry,
1941
- title: entry.title.trim()
1942
- }), entry.id);
1943
- return parsed.ok ? void 0 : parsed.issues.map((issue) => `${issue.path}: ${issue.message}`).join("; ");
1944
- }
1945
- /**
1946
- * Creates several new entries of a lorebook at once, each checked as `writeLorebookEntry` checks one; none is written when any is not acceptable.
1947
- * @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.
1948
- */
1949
- async function addLorebookEntries(root, name, entries) {
1950
- const directory = lorebookDirectory(root, name);
1951
- if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
1952
- const book = await readLorebook(directory, name);
1953
- if (book.entries.length + entries.length > 500) throw new Error(`a lorebook has at most 500 entries`);
1954
- const ids = new Set(book.entries.map((entry) => entry.id));
1955
- for (const entry of entries) {
1956
- const problem = entryProblem(entry);
1957
- if (problem !== void 0) throw new Error(`entry "${entry.title}": ${problem}`);
1958
- if (ids.has(entry.id)) throw new Error(`there is already an entry "${entry.id}"`);
1959
- ids.add(entry.id);
1960
- }
1961
- for (const entry of entries) await writeAtomic(join(directory, LORE_DIR, entry.id, LORE_FILE_NAME), entryFile({
1962
- ...entry,
1963
- title: entry.title.trim()
1964
- }));
1965
- return await readLorebook(directory, name);
1966
- }
1967
- /** 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. */
1968
- async function writeLorebookEntry(root, name, entry) {
1969
- const directory = lorebookDirectory(root, name);
1970
- if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
1971
- const problem = entryProblem(entry);
1972
- if (problem !== void 0) throw new Error(problem);
1973
- const file = join(directory, LORE_DIR, entry.id, LORE_FILE_NAME);
1974
- const book = await readLorebook(directory, name);
1975
- if (!existsSync(file) && book.entries.length >= 500) throw new Error(`a lorebook has at most 500 entries`);
1976
- const others = book.entries.filter((other) => other.id !== entry.id);
1977
- const missing = entry.related.filter((id) => id === entry.id || !others.some((other) => other.id === id));
1978
- if (missing.length > 0) throw new Error(`related: ${missing.map((id) => `"${id}"`).join(", ")} ${missing.length === 1 ? "is" : "are"} not (other) entries of this book`);
1979
- await writeAtomic(file, entryFile({
1980
- ...entry,
1981
- title: entry.title.trim()
1982
- }));
1983
- return await readLorebook(directory, name);
1984
- }
1985
- /** Moves an entry into the book's `.trash`. @throws {Error} when it does not exist or other entries relate to it. */
1986
- async function deleteLorebookEntry(root, name, id, now = Date.now) {
1987
- const directory = lorebookDirectory(root, name);
1988
- const folder = join(directory, LORE_DIR, id);
1989
- if (!isEntryId(id) || !existsSync(join(folder, "lore.json"))) throw new Error(`the lorebook "${name}" has no entry "${id}"`);
1990
- const citing = (await readLorebook(directory, name)).entries.filter((entry) => entry.id !== id && entry.related.includes(id)).map((entry) => entry.id);
1991
- if (citing.length > 0) throw new Error(`the entries ${citing.join(", ")} relate to "${id}"; change them first`);
1992
- const aside = join(directory, ".trash", LORE_DIR, `${id}-${now()}`);
1993
- await mkdir(dirname(aside), { recursive: true });
1994
- await rename(folder, aside);
1995
- return await readLorebook(directory, name);
1996
- }
1997
- /** Moves a lorebook out of the library into `<root>/.trash/lorebooks/`. @returns where it went. */
1998
- async function deleteLorebook(root, name, now = Date.now) {
1999
- const directory = lorebookDirectory(root, name);
2000
- if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
2001
- const aside = join(root, ".trash", LOREBOOKS_FOLDER, `${name}-${now()}`);
2002
- await mkdir(dirname(aside), { recursive: true });
2003
- await rename(directory, aside);
2004
- return aside;
2005
- }
2006
- // src/shared/start-questions.ts
2007
- const START_PLOT_STATUSES = ["dormant", "available"];
2008
- const questionView = (question) => ({
2009
- id: question.id,
2010
- text: question.text,
2011
- options: question.options.map(({ id, label, description }) => ({
2012
- id,
2013
- label,
2014
- ...description === void 0 ? {} : { description }
2015
- }))
2016
- });
2017
- /** What the answers add up to, or why they cannot be combined. A question left unanswered changes nothing. */
2018
- function combineAnswers(questions, answers) {
2019
- const problems = [];
2020
- const effect = {};
2021
- for (const id of Object.keys(answers)) if (!questions.some((question) => question.id === id)) problems.push(`the world asks no question "${id}"`);
2022
- const set = (key, value, question) => {
2023
- if (value === void 0) return;
2024
- 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`);
2025
- else effect[key] = value;
2026
- };
2027
- for (const question of questions) {
2028
- const answer = answers[question.id];
2029
- if (answer === void 0) continue;
2030
- const option = question.options.find((entry) => entry.id === answer);
2031
- if (option === void 0) {
2032
- problems.push(`"${answer}" is not an answer to "${question.id}"`);
2033
- continue;
2034
- }
2035
- const found = option.effect;
2036
- if (found.rules !== void 0) effect.rules = [...effect.rules ?? [], ...found.rules];
2037
- set("opening", found.opening, question.id);
2038
- set("startingTime", found.startingTime, question.id);
2039
- set("clockMode", found.clockMode, question.id);
2040
- for (const [agent, switches] of Object.entries(found.tools ?? {})) {
2041
- const merged = { ...effect.tools?.[agent] };
2042
- for (const [tool, value] of Object.entries(switches)) {
2043
- if (merged[tool] !== void 0 && merged[tool] !== value) problems.push(`the answers disagree about the tool "${tool}"; "${question.id}" changes it again`);
2044
- merged[tool] = value;
2045
- }
2046
- effect.tools = {
2047
- ...effect.tools,
2048
- [agent]: merged
2049
- };
2050
- }
2051
- for (const [plot, status] of Object.entries(found.plots ?? {})) {
2052
- if (effect.plots?.[plot] !== void 0 && effect.plots[plot] !== status) problems.push(`the answers disagree about the plot "${plot}"; "${question.id}" changes it again`);
2053
- effect.plots = {
2054
- ...effect.plots,
2055
- [plot]: status
2056
- };
2057
- }
2058
- }
2059
- return {
2060
- effect,
2061
- problems
2062
- };
2063
- }
2064
- /** The questions as `world.json` writes them: snake_case keys, and only what an answer sets. */
2065
- function startQuestionsToFile(questions) {
2066
- return questions.map((question) => ({
2067
- id: question.id,
2068
- text: question.text,
2069
- options: question.options.map((option) => ({
2070
- id: option.id,
2071
- label: option.label,
2072
- ...option.description === void 0 || option.description === "" ? {} : { description: option.description },
2073
- effect: {
2074
- ...option.effect.rules === void 0 || option.effect.rules.length === 0 ? {} : { rules: option.effect.rules },
2075
- ...option.effect.opening === void 0 ? {} : { opening: option.effect.opening },
2076
- ...option.effect.startingTime === void 0 || option.effect.startingTime === "" ? {} : { starting_time: option.effect.startingTime },
2077
- ...option.effect.clockMode === void 0 ? {} : { clock_mode: option.effect.clockMode },
2078
- ...option.effect.tools === void 0 ? {} : { tools: option.effect.tools },
2079
- ...option.effect.plots === void 0 ? {} : { plots: option.effect.plots }
2080
- }
2081
- }))
2082
- }));
2083
- }
2084
- const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2085
- /** Reads questions sent by the editor: the shape only, since the world file's own reader judges every value when the change is written. */
2086
- function parseStartQuestionsEdit(value, problems) {
2087
- if (!Array.isArray(value)) {
2088
- problems.push("startQuestions must be a list");
2089
- return;
2090
- }
2091
- const questions = [];
2092
- for (const entry of value) {
2093
- if (!isObject(entry) || typeof entry["id"] !== "string" || typeof entry["text"] !== "string" || !Array.isArray(entry["options"])) {
2094
- problems.push("a start question needs an id, a text and a list of options");
2095
- return;
2096
- }
2097
- const options = [];
2098
- for (const option of entry["options"]) {
2099
- if (!isObject(option) || typeof option["id"] !== "string" || typeof option["label"] !== "string" || !isObject(option["effect"]) || option["description"] !== void 0 && typeof option["description"] !== "string") {
2100
- problems.push("an answer needs an id, a label and an effect");
2101
- return;
2102
- }
2103
- const effect = option["effect"];
2104
- const known = {};
2105
- if (Array.isArray(effect["rules"])) known.rules = effect["rules"].filter((rule) => typeof rule === "string");
2106
- if (typeof effect["opening"] === "number") known.opening = effect["opening"];
2107
- if (typeof effect["startingTime"] === "string") known.startingTime = effect["startingTime"];
2108
- if (effect["clockMode"] === "simulated" || effect["clockMode"] === "real") known.clockMode = effect["clockMode"];
2109
- if (isObject(effect["tools"])) known.tools = effect["tools"];
2110
- if (isObject(effect["plots"])) known.plots = effect["plots"];
2111
- options.push({
2112
- id: option["id"].trim(),
2113
- label: option["label"].trim(),
2114
- ...typeof option["description"] === "string" && option["description"].trim() !== "" ? { description: option["description"].trim() } : {},
2115
- effect: known
2116
- });
2117
- }
2118
- questions.push({
2119
- id: entry["id"].trim(),
2120
- text: entry["text"].trim(),
2121
- options
2122
- });
2123
- }
2124
- return questions;
2125
- }
2126
- const MAX_OPENING_CHARS = 2e4;
2127
- const TEXT_FIELDS = [
2128
- "name",
2129
- "description",
2130
- "opening",
2131
- "authorName",
2132
- "authorUrl",
2133
- "timeZone",
2134
- "startingTime",
2135
- "version",
2136
- "preset"
2137
- ];
2138
- const LIST_FIELDS = [
2139
- "tags",
2140
- "rules",
2141
- "lorebooks"
2142
- ];
2143
- /** Reads a body that came from the browser; every field is checked and each problem is reported. */
2144
- function parseWorldInfoEdit(value) {
2145
- const problems = [];
2146
- const input = typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
2147
- if (input === void 0) throw new InvalidEditProblems(["the changes must be an object"]);
2148
- const edit = {};
2149
- for (const key of Object.keys(input)) if (!TEXT_FIELDS.includes(key) && !LIST_FIELDS.includes(key) && key !== "alternateOpenings" && key !== "startQuestions" && key !== "tools" && key !== "sampling" && key !== "autonomy") problems.push(`there is no field "${key}"`);
2150
- for (const key of TEXT_FIELDS) {
2151
- if (input[key] === void 0) continue;
2152
- if (typeof input[key] === "string") edit[key] = input[key].trim();
2153
- else problems.push(`${key} must be text`);
2154
- }
2155
- for (const key of LIST_FIELDS) {
2156
- if (input[key] === void 0) continue;
2157
- if (Array.isArray(input[key]) && input[key].every((entry) => typeof entry === "string")) edit[key] = input[key].map((entry) => entry.trim()).filter((entry) => entry !== "");
2158
- else problems.push(`${key} must be a list of text`);
2159
- }
2160
- if (input["alternateOpenings"] !== void 0) {
2161
- const list = input["alternateOpenings"];
2162
- const entries = Array.isArray(list) ? list.map((entry) => typeof entry === "object" && entry !== null ? entry : void 0) : void 0;
2163
- 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? }");
2164
- else {
2165
- const kept = entries.map((entry) => ({
2166
- title: String(entry["title"] ?? "").trim(),
2167
- text: String(entry["text"]).trim(),
2168
- ...String(entry["character"] ?? "").trim() === "" ? {} : { character: String(entry["character"]).trim() }
2169
- })).filter((entry) => entry.text !== "");
2170
- if (kept.length > 30) problems.push(`there are more than 30 alternate openings`);
2171
- if (kept.some((entry) => entry.text.length > 2e4)) problems.push(`an alternate opening is longer than ${MAX_OPENING_CHARS} characters`);
2172
- edit["alternateOpenings"] = kept;
2173
- }
2174
- }
2175
- if (input["startQuestions"] !== void 0) {
2176
- const questions = parseStartQuestionsEdit(input["startQuestions"], problems);
2177
- if (questions !== void 0) edit["startQuestions"] = questions;
2178
- }
2179
- if (input["tools"] !== void 0) {
2180
- const board = parseSwitchboard(input["tools"], "tools");
2181
- if (typeof board === "string") problems.push(board);
2182
- else edit["tools"] = board;
2183
- }
2184
- if (input["autonomy"] !== void 0) {
2185
- if (typeof input["autonomy"] === "boolean") edit["autonomy"] = input["autonomy"];
2186
- else problems.push("autonomy must be true or false");
2187
- }
2188
- if (input["sampling"] !== void 0) edit["sampling"] = parseSampling(input["sampling"], "sampling", problems);
2189
- if (typeof edit["version"] === "string" && edit["version"].length > 40) problems.push(`the version is longer than 40 characters`);
2190
- if (edit["name"] === "") problems.push("the world needs a name");
2191
- if (typeof edit["name"] === "string" && edit["name"].length > 200) problems.push(`the name is longer than 200 characters`);
2192
- if (problems.length > 0) throw new InvalidEditProblems(problems);
2193
- return edit;
2194
- }
2195
- // src/host/worlds/world-file.ts
2196
- const WORLD_FILE_NAME = "world.json";
2197
- /** `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. */
2198
- function readAlternateOpenings(reader) {
2199
- const value = reader.raw("alternate_openings");
2200
- if (value === void 0 || value === null) return void 0;
2201
- if (!Array.isArray(value)) {
2202
- reader.fail("alternate_openings", "must be a list");
2203
- return;
2204
- }
2205
- if (value.length > 30) reader.fail("alternate_openings", `has more than 30 openings`);
2206
- const openings = [];
2207
- for (const entry of reader.objects("alternate_openings")) {
2208
- const text = entry.string("text", { required: true })?.trim();
2209
- if (text === void 0 || text === "") continue;
2210
- if (text.length > 2e4) entry.fail("text", `is longer than ${MAX_OPENING_CHARS} characters`);
2211
- const character = entry.string("character")?.trim();
2212
- openings.push({
2213
- title: entry.string("title")?.trim() || text.slice(0, 40),
2214
- text,
2215
- ...character === void 0 || character === "" ? {} : { character }
2216
- });
2217
- }
2218
- return openings.length === 0 ? void 0 : openings;
2219
- }
2220
- const EFFECT_KEYS = [
2221
- "rules",
2222
- "opening",
2223
- "starting_time",
2224
- "clock_mode",
2225
- "tools",
2226
- "plots"
2227
- ];
2228
- /** 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. */
2229
- function readEffect(entry, openings) {
2230
- const raw = entry.raw("effect");
2231
- const effect = {};
2232
- if (raw === void 0 || raw === null) return effect;
2233
- if (typeof raw !== "object" || Array.isArray(raw)) {
2234
- entry.fail("effect", "must be an object");
2235
- return effect;
2236
- }
2237
- const body = raw;
2238
- 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(", ")})`);
2239
- if (body["rules"] !== void 0) {
2240
- const rules = Array.isArray(body["rules"]) && body["rules"].every((rule) => typeof rule === "string") ? body["rules"].map((rule) => rule.trim()).filter((rule) => rule !== "") : void 0;
2241
- if (rules === void 0) entry.fail("effect.rules", "must be a list of rules");
2242
- else if (rules.some((rule) => rule.length > 300)) entry.fail("effect.rules", `has a rule longer than 300 characters`);
2243
- else if (rules.length > 0) effect.rules = rules;
2244
- }
2245
- if (body["opening"] !== void 0) {
2246
- 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`);
2247
- else effect.opening = body["opening"];
2248
- }
2249
- if (body["starting_time"] !== void 0) {
2250
- 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");
2251
- else effect.startingTime = body["starting_time"].trim();
2252
- }
2253
- if (body["clock_mode"] !== void 0) {
2254
- if (body["clock_mode"] !== "simulated" && body["clock_mode"] !== "real") entry.fail("effect.clock_mode", "must be \"simulated\" or \"real\"");
2255
- else effect.clockMode = body["clock_mode"];
2256
- }
2257
- if (body["tools"] !== void 0) {
2258
- const board = parseSwitchboard(body["tools"], "tools");
2259
- if (typeof board === "string") entry.fail("effect.tools", board.replace(/^"tools"\s*/, ""));
2260
- else if (Object.keys(board).length > 0) effect.tools = board;
2261
- }
2262
- if (body["plots"] !== void 0) {
2263
- const plots = body["plots"];
2264
- if (typeof plots !== "object" || plots === null || Array.isArray(plots)) entry.fail("effect.plots", "must map plot ids to \"dormant\" or \"available\"");
2265
- else {
2266
- const kept = {};
2267
- 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(", ")}`);
2268
- else kept[id] = status;
2269
- if (Object.keys(kept).length > 0) effect.plots = kept;
2270
- }
2271
- }
2272
- return effect;
2273
- }
2274
- /** `start_questions`: `{ id, text, options: [{ id, label, description?, effect }] }`, asked in the start dialog. */
2275
- function readStartQuestions(reader, openings) {
2276
- const value = reader.raw("start_questions");
2277
- if (value === void 0 || value === null) return void 0;
2278
- if (!Array.isArray(value)) {
2279
- reader.fail("start_questions", "must be a list");
2280
- return;
2281
- }
2282
- if (value.length > 8) reader.fail("start_questions", `has more than 8 questions`);
2283
- const questions = [];
2284
- const seen = /* @__PURE__ */ new Set();
2285
- for (const entry of reader.objects("start_questions")) {
2286
- const id = entry.string("id", { required: true })?.trim();
2287
- const text = entry.string("text", { required: true })?.trim();
2288
- if (id === void 0 || text === void 0 || id === "" || text === "") continue;
2289
- if (seen.has(id)) entry.fail("id", `repeats the question "${id}"`);
2290
- seen.add(id);
2291
- if (text.length > 200) entry.fail("text", `is longer than 200 characters`);
2292
- const raw = entry.raw("options");
2293
- if (!Array.isArray(raw) || raw.length < 2 || raw.length > 8) {
2294
- entry.fail("options", `must list 2 to 8 answers`);
2295
- continue;
2296
- }
2297
- const options = [];
2298
- const ids = /* @__PURE__ */ new Set();
2299
- for (const option of entry.objects("options")) {
2300
- const optionId = option.string("id", { required: true })?.trim();
2301
- const label = option.string("label", { required: true })?.trim();
2302
- if (optionId === void 0 || label === void 0 || optionId === "" || label === "") continue;
2303
- if (ids.has(optionId)) option.fail("id", `repeats the answer "${optionId}"`);
2304
- ids.add(optionId);
2305
- if (label.length > 200) option.fail("label", `is longer than 200 characters`);
2306
- const description = option.string("description")?.trim();
2307
- options.push({
2308
- id: optionId,
2309
- label,
2310
- ...description === void 0 || description === "" ? {} : { description },
2311
- effect: readEffect(option, openings)
2312
- });
2313
- }
2314
- questions.push({
2315
- id,
2316
- text,
2317
- options
2318
- });
2319
- }
2320
- return questions.length === 0 ? void 0 : questions;
2321
- }
2322
- /** `tools`: switches by kind of agent and tool name; a world carried from a version with other tools still loads. */
2323
- function readTools(reader) {
2324
- const value = reader.raw("tools");
2325
- if (value === void 0) return void 0;
2326
- const board = parseSwitchboard(value, "tools");
2327
- if (typeof board === "string") {
2328
- reader.fail("tools", board.replace(/^"tools"\s*/, ""));
2329
- return;
2330
- }
2331
- return Object.keys(board).length === 0 ? void 0 : board;
2332
- }
2333
- /** `sampling` is an object of the controls a story's requests may carry (see `StorySampling`). */
2334
- function readSampling(reader) {
2335
- const problems = [];
2336
- const sampling = parseSampling(reader.raw("sampling"), "sampling", problems);
2337
- for (const problem of problems) reader.fail("sampling", problem.replace(/^sampling\.?/, ""));
2338
- return Object.keys(sampling).length === 0 ? void 0 : sampling;
2339
- }
2340
- /** `rules` is one rule as text, or a list of them; blank ones are left out. */
2341
- function readRules(reader) {
2342
- const value = reader.raw("rules");
2343
- if (value === void 0 || value === null) return void 0;
2344
- const kept = (typeof value === "string" ? [value] : reader.strings("rules")).map((rule) => rule.trim()).filter((rule) => rule !== "");
2345
- if (kept.length > 30) reader.fail("rules", `has more than 30 rules`);
2346
- const long = kept.findIndex((rule) => rule.length > 300);
2347
- if (long >= 0) reader.fail("rules", `rule ${long + 1} is longer than 300 characters: keep rules short`);
2348
- return kept.length === 0 ? void 0 : kept;
2349
- }
2350
- /** `opening_message` is plain text (one narration), or a list of parts in the order the player reads them. */
2351
- function readOpening(reader) {
2352
- const value = reader.raw("opening_message");
2353
- if (value === void 0 || value === null) return void 0;
2354
- if (typeof value === "string") return value.trim() === "" ? void 0 : [{
2355
- type: "narration",
2356
- text: value.trim()
2357
- }];
2358
- if (!Array.isArray(value)) {
2359
- reader.fail("opening_message", "must be text or a list of parts");
2360
- return;
2361
- }
2362
- const parts = [];
2363
- for (const part of reader.objects("opening_message")) {
2364
- const type = part.oneOf("type", ["narration", "utterance"], "narration");
2365
- const text = part.string("text", { required: true })?.trim();
2366
- if (text === void 0 || text === "") continue;
2367
- if (type === "narration") {
2368
- parts.push({
2369
- type,
2370
- text
2371
- });
2372
- continue;
2373
- }
2374
- const character = part.string("character", { required: true });
2375
- if (character !== void 0) parts.push({
2376
- type,
2377
- character,
2378
- text
2379
- });
2380
- }
2381
- return parts.length === 0 ? void 0 : parts;
2382
- }
2383
- /** `time_zone` (an IANA name) and `starting_time` (an ISO 8601 date and time, in `time_zone` unless it carries an offset). */
2384
- function readClock(reader) {
2385
- const timeZone = reader.string("time_zone");
2386
- if (timeZone !== void 0 && !isTimeZone(timeZone)) {
2387
- reader.fail("time_zone", `"${timeZone}" is not a time zone: write it like Europe/London or UTC`);
2388
- return;
2389
- }
2390
- const text = reader.string("starting_time");
2391
- let startingTime;
2392
- if (text !== void 0) try {
2393
- startingTime = parseInstant(text, timeZone ?? "UTC");
2394
- } catch (error) {
2395
- reader.fail("starting_time", error instanceof Error ? error.message : String(error));
2396
- return;
2397
- }
2398
- return timeZone === void 0 && startingTime === void 0 ? void 0 : {
2399
- ...startingTime === void 0 ? {} : { startingTime },
2400
- ...timeZone === void 0 ? {} : { timeZone }
2401
- };
2402
- }
2403
- function readAuthor(reader) {
2404
- if (reader === void 0) return void 0;
2405
- const name = reader.string("name", { required: true });
2406
- const url = reader.string("url");
2407
- return name === void 0 ? void 0 : {
2408
- name,
2409
- ...url === void 0 ? {} : { url }
2410
- };
2411
- }
2412
- function parseWorldFile(text) {
2413
- const issues = [];
2414
- const reader = Reader.fromJson(text, issues);
2415
- if (reader === void 0) return {
2416
- ok: false,
2417
- issues
2418
- };
2419
- const id = readIdentifier(reader);
2420
- const name = reader.string("name", { required: true });
2421
- const description = reader.text("description");
2422
- const tags = reader.object("metadata")?.strings("tags") ?? [];
2423
- const author = readAuthor(reader.object("author"));
2424
- const rawVersion = reader.raw("version");
2425
- if (rawVersion !== void 0 && rawVersion !== null && typeof rawVersion !== "string" && typeof rawVersion !== "number") reader.fail("version", "must be text or a number");
2426
- const version = (typeof rawVersion === "string" || typeof rawVersion === "number" ? String(rawVersion).trim() : "") || void 0;
2427
- if (version !== void 0 && version.length > 40) reader.fail("version", `is longer than 40 characters`);
2428
- const coverMediaId = reader.string("cover_media_id");
2429
- const opening = readOpening(reader);
2430
- const clock = readClock(reader);
2431
- const variables = readVariableValues(reader);
2432
- const rules = readRules(reader);
2433
- const tools = readTools(reader);
2434
- const autonomyValue = reader.raw("autonomy");
2435
- if (autonomyValue !== void 0 && autonomyValue !== null && typeof autonomyValue !== "boolean") reader.fail("autonomy", "must be true or false");
2436
- const autonomy = autonomyValue === true ? true : void 0;
2437
- const alternateOpenings = readAlternateOpenings(reader);
2438
- const startQuestions = readStartQuestions(reader, alternateOpenings?.length ?? 0);
2439
- const narrationVoice = reader.string("narration_voice")?.trim() || void 0;
2440
- const sampling = readSampling(reader);
2441
- const preset = reader.string("preset")?.trim() || void 0;
2442
- if (preset !== void 0 && !isPresetName(preset)) reader.fail("preset", "must be the name of a preset: letters, digits, \"-\" and \"_\"");
2443
- const lorebooks = reader.strings("lorebooks").map((entry) => entry.trim()).filter((entry) => entry !== "");
2444
- for (const [index, entry] of lorebooks.entries()) if (!isLorebookName(entry)) reader.fail(`lorebooks[${index}]`, "must be the name of a lorebook: letters, digits, \"-\" and \"_\"");
2445
- if (name === void 0 || issues.length > 0) return {
2446
- ok: false,
2447
- issues
2448
- };
2449
- return {
2450
- ok: true,
2451
- value: {
2452
- ...id === void 0 ? {} : { id },
2453
- name,
2454
- description,
2455
- tags,
2456
- ...author === void 0 ? {} : { author },
2457
- ...version === void 0 ? {} : { version },
2458
- ...coverMediaId === void 0 ? {} : { coverMediaId },
2459
- ...opening === void 0 ? {} : { opening },
2460
- ...clock === void 0 ? {} : { clock },
2461
- ...variables === void 0 ? {} : { variables },
2462
- ...rules === void 0 ? {} : { rules },
2463
- ...tools === void 0 ? {} : { tools },
2464
- ...autonomy === void 0 ? {} : { autonomy },
2465
- ...alternateOpenings === void 0 ? {} : { alternateOpenings },
2466
- ...startQuestions === void 0 ? {} : { startQuestions },
2467
- ...narrationVoice === void 0 ? {} : { narrationVoice },
2468
- ...sampling === void 0 ? {} : { sampling },
2469
- ...preset === void 0 ? {} : { preset },
2470
- ...lorebooks.length === 0 ? {} : { lorebooks: [...new Set(lorebooks)] }
2471
- }
2472
- };
2473
- }
2474
1730
  // src/host/import/outcomes.ts
2475
1731
  /**
2476
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`
@@ -3008,19 +2264,13 @@ async function repairFields(directory, problems) {
3008
2264
  return repairs;
3009
2265
  }
3010
2266
  // src/host/worlds/world-file-io.ts
3011
- const queues = /* @__PURE__ */ new Map();
2267
+ const queue = new SerialQueue();
3012
2268
  /**
3013
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
3014
2270
  * back; run side by side, the last one to write would take back what the others changed.
3015
2271
  */
3016
2272
  function serialized(directory, work) {
3017
- const run = (queues.get(directory) ?? Promise.resolve()).then(work, work);
3018
- const tail = run.then(() => void 0, () => void 0);
3019
- queues.set(directory, tail);
3020
- tail.then(() => {
3021
- if (queues.get(directory) === tail) queues.delete(directory);
3022
- });
3023
- return run;
2273
+ return queue.run(directory, work);
3024
2274
  }
3025
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. */
3026
2276
  function updateWorldFile(directory, update) {
@@ -3378,6 +2628,7 @@ async function finishImport(ctx, input) {
3378
2628
  };
3379
2629
  if (opening !== void 0) world["opening_message"] = openingMessage(opening, card.name, player === void 0 ? void 0 : String(player["name"]));
3380
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);
3381
2632
  if (card.creator.trim() !== "" && world["author"] === void 0) world["author"] = { name: card.creator.trim() };
3382
2633
  if (cover) world["cover_media_id"] = "cover";
3383
2634
  });
@@ -4142,6 +3393,7 @@ function infoOf(document, startQuestions = []) {
4142
3393
  authorUrl: textOf(author["url"]),
4143
3394
  timeZone: textOf(document["time_zone"]),
4144
3395
  startingTime: textOf(document["starting_time"]),
3396
+ language: textOf(document["language"]),
4145
3397
  preset: textOf(document["preset"]),
4146
3398
  lorebooks: Array.isArray(document["lorebooks"]) ? document["lorebooks"].filter((name) => typeof name === "string") : [],
4147
3399
  version: typeof document["version"] === "number" ? String(document["version"]) : textOf(document["version"]),
@@ -4218,6 +3470,7 @@ async function changeWorldInfo(directory, edit) {
4218
3470
  if (edit.timeZone !== void 0) setOrRemove(document, "time_zone", edit.timeZone);
4219
3471
  if (edit.startingTime !== void 0) setOrRemove(document, "starting_time", edit.startingTime);
4220
3472
  if (edit.version !== void 0) setOrRemove(document, "version", edit.version);
3473
+ if (edit.language !== void 0) setOrRemove(document, "language", edit.language);
4221
3474
  if (edit.preset !== void 0) setOrRemove(document, "preset", edit.preset);
4222
3475
  if (edit.lorebooks !== void 0) {
4223
3476
  if (edit.lorebooks.length === 0) delete document["lorebooks"];
@@ -6459,6 +5712,7 @@ async function build(ctx, world) {
6459
5712
  const extracted = await extractEntities(ctx, card, items.filter((item) => !isLeftOut(classified[item.id])), classified, roster);
6460
5713
  const style = await extractStyle(ctx, card, items, classified);
6461
5714
  extracted.prompts.push(...style.prompts);
5715
+ extracted.rules.push(...style.rules);
6462
5716
  extracted.notes.push(...style.notes);
6463
5717
  extracted.derived.push(...style.derived);
6464
5718
  const tracked = await extractVariables(ctx, card, items, classified, roster);
@@ -6967,6 +6221,6 @@ function limitAuthoringAgents(ctx, kindOf) {
6967
6221
  return await next();
6968
6222
  });
6969
6223
  }
6970
- 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 };
6224
+ 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 };
6971
6225
 
6972
- //# sourceMappingURL=authoring-tools-4NgDhIJV.js.map
6226
+ //# sourceMappingURL=authoring-tools-BZr4bgBy.js.map