@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,11 +1,11 @@
1
- import { a as VARIABLE_KINDS, n as atomicWrite, o as VARIABLE_SUBJECTS, s as VARIABLE_VISIBILITIES } from "./access-Md1YTSX1.js";
2
- import "./narration-b_VBEUWn.js";
3
- import { G as readDocument, J as errorMessage, K as Reader, X as PROMPTS_FOLDER, Y as LANGUAGE_FOLDER, et as languageOf, it as shippedPromptsDirectory, nt as promptProblem, q as formatIssue, rt as shippedLanguages, tt as listFiles } from "./hooks-C2U1-8ur.js";
4
- import { i as translator, r as languageOf$1 } from "./text-C2AGl7Je.js";
5
- import { d as parseSampling } from "./child-C9nPIy9j.js";
6
- import { C as slug, S as norm, T as uniqueKey, w as trOf, x as mapLimit } from "./library-4zmCAshR.js";
1
+ import { m as parseSampling } from "./child-DzZ-aI6k.js";
2
+ import { f as parseSwitchboard } from "./narration-CDsJ5wxH.js";
3
+ import { a as VARIABLE_KINDS, n as atomicWrite, o as VARIABLE_SUBJECTS, s as VARIABLE_VISIBILITIES } from "./access-DifaiHrI.js";
4
+ import { G as readDocument, J as errorMessage, K as Reader, X as PROMPTS_FOLDER, Y as LANGUAGE_FOLDER, et as languageOf, it as shippedPromptsDirectory, nt as promptProblem, q as formatIssue, rt as shippedLanguages, tt as listFiles } from "./hooks-BdR3mBeM.js";
5
+ import { i as translator, r as languageOf$1 } from "./text-Dfv8S8eq.js";
6
+ import { C as slug, S as norm, T as uniqueKey, w as trOf, x as mapLimit } from "./library-BU2A_Dx8.js";
7
7
  import { dirname, join } from "node:path";
8
- import { MAX_ROUTINE_WINDOWS, createSessionStore, dayTokenProblems, valueIssue } from "@dsh-agentic-roleplay/state";
8
+ import { MAX_ROUTINE_WINDOWS, createSessionStore, dayTokenProblems, isTimeZone, parseInstant, valueIssue } from "@dsh-agentic-roleplay/state";
9
9
  import { existsSync, readFileSync, readdirSync } from "node:fs";
10
10
  import { createHash, randomUUID } from "node:crypto";
11
11
  import { cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
@@ -702,6 +702,19 @@ function parseRelationEdit(value) {
702
702
  if (problems.length > 0) throw new InvalidEditProblems(problems);
703
703
  return input;
704
704
  }
705
+ // src/host/folders.ts
706
+ /**
707
+ * Names of the subfolders of `dir`, sorted. Symbolic links are not followed
708
+ * and a missing directory has none; any other failure is thrown.
709
+ */
710
+ async function subfolders(dir) {
711
+ try {
712
+ return (await readdir(dir, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort((a, b) => a.localeCompare(b));
713
+ } catch (error) {
714
+ if (error.code === "ENOENT") return [];
715
+ throw error;
716
+ }
717
+ }
705
718
  /**
706
719
  * Read an `id` field. Ids are opaque strings, unique within their scope, that
707
720
  * stay the same when the file is copied or edited.
@@ -831,6 +844,8 @@ function readRoutine(reader) {
831
844
  if (location === void 0 && feature !== void 0) window.fail("feature", "needs a location");
832
845
  const flag = window.raw("interruptible");
833
846
  if (flag !== void 0 && typeof flag !== "boolean") window.fail("interruptible", "must be true or false");
847
+ const sleep = window.raw("sleep");
848
+ if (sleep !== void 0 && typeof sleep !== "boolean") window.fail("sleep", "must be true or false");
834
849
  if (from === void 0 || to === void 0 || activity === void 0) return [];
835
850
  return [{
836
851
  days,
@@ -841,7 +856,8 @@ function readRoutine(reader) {
841
856
  ...location === void 0 ? {} : { location },
842
857
  ...feature === void 0 ? {} : { feature },
843
858
  ...position === void 0 ? {} : { position },
844
- interruptible: flag !== false
859
+ interruptible: flag !== false,
860
+ ...sleep === true ? { sleep: true } : {}
845
861
  }];
846
862
  });
847
863
  if (windows.length > MAX_ROUTINE_WINDOWS) reader.fail("routine", `a character has at most ${MAX_ROUTINE_WINDOWS} windows in its day`);
@@ -1364,6 +1380,53 @@ function parseLoreFile(text, fallbackId) {
1364
1380
  issues
1365
1381
  };
1366
1382
  }
1383
+ // src/host/lore/load.ts
1384
+ const LORE_DIR = "lore";
1385
+ async function loadLore(worldDir) {
1386
+ const dir = join(worldDir, LORE_DIR);
1387
+ const result = {
1388
+ lore: [],
1389
+ problems: []
1390
+ };
1391
+ let folders;
1392
+ try {
1393
+ folders = await subfolders(dir);
1394
+ } catch (error) {
1395
+ if (error.code !== "ENOENT") result.problems.push({
1396
+ path: dir,
1397
+ message: errorMessage(error)
1398
+ });
1399
+ return result;
1400
+ }
1401
+ const owners = /* @__PURE__ */ new Map();
1402
+ for (const folder of folders) {
1403
+ const file = join(dir, folder, LORE_FILE_NAME);
1404
+ try {
1405
+ const entry = await readDocument(file, (text) => parseLoreFile(text, folder), result.problems);
1406
+ if (entry === void 0) continue;
1407
+ const owner = owners.get(entry.id);
1408
+ if (owner !== void 0) {
1409
+ result.problems.push({
1410
+ path: file,
1411
+ message: `id "${entry.id}" is already used by ${owner}`
1412
+ });
1413
+ continue;
1414
+ }
1415
+ owners.set(entry.id, folder);
1416
+ result.lore.push(entry);
1417
+ } catch (error) {
1418
+ if (error.code !== "ENOENT") result.problems.push({
1419
+ path: file,
1420
+ message: errorMessage(error)
1421
+ });
1422
+ }
1423
+ }
1424
+ if (result.lore.length > 500) result.problems.push({
1425
+ path: dir,
1426
+ message: `a world has at most 500 lore entries`
1427
+ });
1428
+ return result;
1429
+ }
1367
1430
  // src/host/variables/load.ts
1368
1431
  const VARIABLES_FILE_NAME = "variables.json";
1369
1432
  function readDefinition(reader) {
@@ -1527,34 +1590,6 @@ function variableProblems(world) {
1527
1590
  }
1528
1591
  return problems;
1529
1592
  }
1530
- // src/shared/authoring-commands.ts
1531
- /** The command a message starts with, when its name is one of `names` (not a longer word that starts with it). */
1532
- function parseAuthoringCommand(text, names) {
1533
- const value = text.trimStart();
1534
- if (!value.startsWith("/")) return void 0;
1535
- const end = value.search(/\s/u);
1536
- const word = (end < 0 ? value : value.slice(0, end)).slice(1).toLowerCase();
1537
- return names.includes(word) ? {
1538
- name: word,
1539
- rest: end < 0 ? "" : value.slice(end).trim()
1540
- } : void 0;
1541
- }
1542
- // src/shared/import-card.ts
1543
- /** The message the plugin sends on the player's behalf to start the import in the new world's authoring chat. */
1544
- const IMPORT_COMMAND = "/import-st";
1545
- /** The command in a message, with the card it names, or nothing when the message is not the command. */
1546
- function parseImportCommand(text) {
1547
- const command = parseAuthoringCommand(text, [IMPORT_COMMAND.slice(1)]);
1548
- if (command === void 0) return void 0;
1549
- const boundary = command.rest.search(/\s/u);
1550
- return boundary < 0 ? {
1551
- card: command.rest,
1552
- request: ""
1553
- } : {
1554
- card: command.rest.slice(0, boundary),
1555
- request: command.rest.slice(boundary).trim()
1556
- };
1557
- }
1558
1593
  // src/host/import/dialect.ts
1559
1594
  const MAX_NAMES = 8;
1560
1595
  const PLAIN_MACROS = /* @__PURE__ */ new Set([
@@ -1649,6 +1684,211 @@ function sourceSummary(card, language) {
1649
1684
  if (left.length > 0) lines.push(tr("Nothing runs them, so they are not carried: {parts}. Their effect is kept only where the card also says it in words.", { parts: left.join("; ") }));
1650
1685
  return lines.join(" ");
1651
1686
  }
1687
+ // src/host/import/panels.ts
1688
+ const FENCE = /```[^\n]*\n[\s\S]*?```/g;
1689
+ const TAG = /<(\/?)([\p{L}][\p{L}\p{N}_-]*)(?=[\s>/])[^>]*>/gu;
1690
+ const BLOCKS = /* @__PURE__ */ new Set([
1691
+ "div",
1692
+ "table",
1693
+ "details",
1694
+ "pre",
1695
+ "center",
1696
+ "section",
1697
+ "aside",
1698
+ "fieldset"
1699
+ ]);
1700
+ const SEPARATORS = /\s[||│]\s|[||│]\s*\S+\s*[||│]/;
1701
+ const HEADER = /(?:^|\n)[ \t]*(?:【[^】\n]{1,30}】|\[[^\]\n]{1,30}\]|#+[ \t]*[^\n]{1,30})[ \t]*\n?\s*$/;
1702
+ const MAX_HTML_TEXT_CHARS = 600;
1703
+ const MAX_CUSTOM_CHARS = 4e3;
1704
+ /** A block of tags of a card's own invention (not markup) counts as a panel from this many tags: two or three tags are a form of address or an aside, a layout is more. */
1705
+ const MIN_CUSTOM_TAGS = 6;
1706
+ const MAX_PANELS = 6;
1707
+ const collapse = (text) => text.replace(/\n{3,}/g, "\n\n").trim();
1708
+ const plain = (html) => html.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
1709
+ /** The outermost elements of block markup and of invented tags in a text, balanced by their own names, with neighbours that only whitespace separates joined into one. */
1710
+ function tagBlocks(text) {
1711
+ const found = [];
1712
+ const open = [];
1713
+ let current = {
1714
+ from: 0,
1715
+ to: 0,
1716
+ custom: false,
1717
+ tags: 0
1718
+ };
1719
+ const closed = new Set([...text.matchAll(TAG)].filter((match) => match[1] === "/").map((match) => match[2].toLowerCase()));
1720
+ for (const match of text.matchAll(TAG)) {
1721
+ const name = match[2].toLowerCase();
1722
+ const custom = !MARKUP.has(name);
1723
+ if (!custom && !BLOCKS.has(name)) continue;
1724
+ if (match[1] === "" && !closed.has(name)) continue;
1725
+ if (match[1] === "") {
1726
+ if (open.length === 0) current = {
1727
+ from: match.index,
1728
+ to: 0,
1729
+ custom: false,
1730
+ tags: 0
1731
+ };
1732
+ open.push(name);
1733
+ current.tags += 1;
1734
+ current.custom ||= custom;
1735
+ } else if (open.includes(name)) {
1736
+ while (open.pop() !== name);
1737
+ current.tags += 1;
1738
+ if (open.length === 0) {
1739
+ current.to = match.index + match[0].length;
1740
+ found.push(current);
1741
+ }
1742
+ }
1743
+ }
1744
+ const joined = [];
1745
+ for (const block of found) {
1746
+ const last = joined.at(-1);
1747
+ if (last !== void 0 && text.slice(last.to, block.from).trim() === "") {
1748
+ last.to = block.to;
1749
+ last.custom ||= block.custom;
1750
+ last.tags += block.tags;
1751
+ } else joined.push({ ...block });
1752
+ }
1753
+ return joined.map((block) => {
1754
+ const header = block.custom ? HEADER.exec(text.slice(0, block.from)) : null;
1755
+ return header === null ? block : {
1756
+ ...block,
1757
+ from: header.index + (header[0].startsWith("\n") ? 1 : 0)
1758
+ };
1759
+ });
1760
+ }
1761
+ const statusLine = (line) => SEPARATORS.test(line) && /\d/.test(line);
1762
+ /** An update call of a state-tracking framework: a block that holds one is a panel however few tags it has. */
1763
+ const CALL = /\b_\.\w+\(|\bstat_data\b|\bJSONPatch\b/;
1764
+ /** The text before a removed panel without its last line when that line only introduces the panel ("end every reply with this:"). */
1765
+ const withoutLeadIn = (before) => before.replace(/(?:^|\n)[^\n]*[::][ \t]*\n?\s*$/, "\n");
1766
+ function fencesWithoutLeadIn(text, panels) {
1767
+ let out = "";
1768
+ let last = 0;
1769
+ for (const match of text.matchAll(FENCE)) {
1770
+ panels.push(match[0].replace(/^```[^\n]*\n|```$/g, "").trim());
1771
+ out += `${withoutLeadIn(text.slice(last, match.index))}\n\n`;
1772
+ last = match.index + match[0].length;
1773
+ }
1774
+ return out + text.slice(last);
1775
+ }
1776
+ /**
1777
+ * Takes the status bars out of a message: fenced code blocks, blocks of tags of the card's own invention (a layout of nested tags, which names may be in any language), short blocks
1778
+ * of markup that carry numbers (when the message has story text besides them: a message wrapped whole in a block is only styled), and closing lines of values set apart by bars.
1779
+ * What is left is the story; the panels are what the card shows its state with.
1780
+ */
1781
+ function splitPanels(text, options = {}) {
1782
+ const panels = [];
1783
+ let rest = options.leadIn === true ? fencesWithoutLeadIn(text, panels) : text.replace(FENCE, (block) => {
1784
+ panels.push(block.replace(/^```[^\n]*\n|```$/g, "").trim());
1785
+ return "\n\n";
1786
+ });
1787
+ const blocks = tagBlocks(rest);
1788
+ const outside = blocks.reduceRight((left, { from, to }) => left.slice(0, from) + left.slice(to), rest);
1789
+ if (blocks.length > 0 && (options.alone === true || plain(outside) !== "")) for (const block of [...blocks].reverse()) {
1790
+ const body = rest.slice(block.from, block.to);
1791
+ if (!(block.custom ? (block.tags >= MIN_CUSTOM_TAGS || CALL.test(body)) && body.length <= MAX_CUSTOM_CHARS : plain(body).length <= MAX_HTML_TEXT_CHARS && /\d/.test(body))) continue;
1792
+ panels.unshift(body.trim());
1793
+ rest = (options.leadIn === true ? withoutLeadIn(rest.slice(0, block.from)) : rest.slice(0, block.from)) + "\n\n" + rest.slice(block.to);
1794
+ }
1795
+ const paragraphs = collapse(rest).split(/\n{2,}/);
1796
+ while (paragraphs.length > 1 && paragraphs.at(-1).split("\n").every(statusLine)) panels.push(paragraphs.pop().trim());
1797
+ return {
1798
+ prose: collapse(paragraphs.join("\n\n")),
1799
+ panels: panels.filter((panel) => panel !== "")
1800
+ };
1801
+ }
1802
+ /** The distinct panels in a card's own messages (openings and examples): they show which values it keeps and where they start. */
1803
+ function panelsOfCard(card) {
1804
+ const texts = [
1805
+ card.firstMessage,
1806
+ ...card.alternateGreetings,
1807
+ card.messageExample
1808
+ ];
1809
+ return [...new Set(texts.flatMap((text) => splitPanels(text).panels))].filter((panel) => panel.length <= MAX_CUSTOM_CHARS).slice(0, MAX_PANELS);
1810
+ }
1811
+ /** The sentences of one line; a full stop inside a word or a call (`_.set(`) does not end one. */
1812
+ const sentencesOf = (line) => line.match(/(?:[^.!?。!?]|[.!?](?!\s|$))+(?:[.!?]+(?=\s|$)|[。!?]+|$)\s*/gu) ?? [line];
1813
+ const MIN_LEFT_OUT_WORDS = 3;
1814
+ const ECHO_SHARE = .6;
1815
+ /** A short sentence right after a dropped one ("Never skip it.") has nothing left to refer to. */
1816
+ const MAX_TAIL_WORDS = 4;
1817
+ function wordsOf(text) {
1818
+ const words = /* @__PURE__ */ new Set();
1819
+ for (const word of text.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []) if (/[㐀-鿿]/.test(word)) for (let index = 0; index < word.length - 1; index += 1) words.add(word.slice(index, index + 2));
1820
+ else if (word.length >= 3) words.add(word);
1821
+ return words;
1822
+ }
1823
+ /**
1824
+ * The sentences of a prose prompt that repeat something the same answer lists as left out. A model that is told to drop an instruction about the shape of the reply (a status bar after
1825
+ * every message) tends to list it and keep it in the same breath; what it listed is not carried.
1826
+ */
1827
+ function withoutLeftOut(prose, leftOut) {
1828
+ const dropped = leftOut.map(wordsOf).filter((words) => words.size >= MIN_LEFT_OUT_WORDS);
1829
+ if (dropped.length === 0) return prose;
1830
+ const echoes = (sentence) => {
1831
+ const words = wordsOf(sentence);
1832
+ return dropped.some((left) => [...left].filter((word) => words.has(word)).length >= left.size * ECHO_SHARE);
1833
+ };
1834
+ const kept = (line) => {
1835
+ let after = false;
1836
+ return sentencesOf(line).filter((sentence) => {
1837
+ const echo = echoes(sentence);
1838
+ const tail = after && sentence.trim().split(/\s+/).length <= MAX_TAIL_WORDS;
1839
+ after = echo;
1840
+ return !echo && !tail;
1841
+ }).join("").trim();
1842
+ };
1843
+ return prose.split("\n").map(kept).filter((line) => line !== "").join("\n");
1844
+ }
1845
+ const OUTPUT_MARKUP = /<\/?[\p{L}][\p{L}\p{N}_-]*>|```|\b_\.\w+\(|\bstat_data\b|\{\{(?!\s*(?:user|char|bot)\s*\}\})[^{}]+\}\}/u;
1846
+ /** A text that is mostly a panel is a format specification, not a rule or a fact: it goes whole. */
1847
+ const PANEL_SHARE = .5;
1848
+ /** A standing rule without the panel it demands, the sentences that tell the game master to print markup, a code block or an update call after a reply, and the rule itself when the panel was most of it: the story shows its tracked values itself. */
1849
+ function withoutOutputMarkup(passage) {
1850
+ const { prose, panels } = splitPanels(passage, {
1851
+ alone: true,
1852
+ leadIn: true
1853
+ });
1854
+ if (panels.length > 0 && prose.length < passage.length * PANEL_SHARE) return "";
1855
+ return prose.split("\n").map((line) => sentencesOf(line).filter((sentence) => !OUTPUT_MARKUP.test(sentence)).join("").trim()).filter((line) => line !== "").join("\n");
1856
+ }
1857
+ const BARRED = /(?:\s[||│]\s[^||│\n]+){2,}/;
1858
+ /** The first status bar, panel or print-this-markup directive in a text, as written, or nothing: what a world should show with its tracked values rather than carry as text. */
1859
+ function findPanel(text) {
1860
+ const panel = splitPanels(text, { alone: true }).panels[0];
1861
+ if (panel !== void 0) return panel;
1862
+ for (const line of text.split("\n")) for (const sentence of sentencesOf(line)) if (OUTPUT_MARKUP.test(sentence) || BARRED.test(sentence) && /\d/.test(sentence)) return sentence.trim();
1863
+ }
1864
+ // src/shared/authoring-commands.ts
1865
+ /** The command a message starts with, when its name is one of `names` (not a longer word that starts with it). */
1866
+ function parseAuthoringCommand(text, names) {
1867
+ const value = text.trimStart();
1868
+ if (!value.startsWith("/")) return void 0;
1869
+ const end = value.search(/\s/u);
1870
+ const word = (end < 0 ? value : value.slice(0, end)).slice(1).toLowerCase();
1871
+ return names.includes(word) ? {
1872
+ name: word,
1873
+ rest: end < 0 ? "" : value.slice(end).trim()
1874
+ } : void 0;
1875
+ }
1876
+ // src/shared/import-card.ts
1877
+ /** The message the plugin sends on the player's behalf to start the import in the new world's authoring chat. */
1878
+ const IMPORT_COMMAND = "/import-st";
1879
+ /** The command in a message, with the card it names, or nothing when the message is not the command. */
1880
+ function parseImportCommand(text) {
1881
+ const command = parseAuthoringCommand(text, [IMPORT_COMMAND.slice(1)]);
1882
+ if (command === void 0) return void 0;
1883
+ const boundary = command.rest.search(/\s/u);
1884
+ return boundary < 0 ? {
1885
+ card: command.rest,
1886
+ request: ""
1887
+ } : {
1888
+ card: command.rest.slice(0, boundary),
1889
+ request: command.rest.slice(boundary).trim()
1890
+ };
1891
+ }
1652
1892
  // src/host/import/store.ts
1653
1893
  const IMPORT_FOLDER = ".import";
1654
1894
  const CARD_FILE = "card.json";
@@ -1883,8 +2123,8 @@ function itemise(card, choices) {
1883
2123
  ...itemsOf("field:description", "description", "", [], card.description, name),
1884
2124
  ...itemsOf("field:personality", "personality", "", [], card.personality, name),
1885
2125
  ...itemsOf("field:scenario", "scenario", "", [], card.scenario, name),
1886
- ...itemsOf("field:example", "example messages", "", [], card.messageExample, name),
1887
- ...opening === void 0 ? [] : itemsOf("field:opening", "opening", "", [], opening, name),
2126
+ ...itemsOf("field:example", "example messages", "", [], splitPanels(card.messageExample).prose, name),
2127
+ ...opening === void 0 ? [] : itemsOf("field:opening", "opening", "", [], splitPanels(opening).prose, name),
1888
2128
  ...(card.book?.entries ?? []).filter((entry) => !off.has(entry.id)).flatMap((entry) => itemsOf(entry.id, entry.title === "" ? entry.id : `entry “${entry.title}”`, entry.title, entry.keys, entry.content, name, entry.constant))
1889
2129
  ];
1890
2130
  }
@@ -1897,6 +2137,227 @@ function playerWord(text, name) {
1897
2137
  function withPlayer(text, name) {
1898
2138
  return text.replace(/\[PLAYER\]|\{\{\s*user\s*\}\}/g, playerWord(text, name));
1899
2139
  }
2140
+ // src/host/lorebooks/lorebooks.ts
2141
+ const LOREBOOKS_FOLDER = "lorebooks";
2142
+ const LOREBOOK_FILE = "lorebook.json";
2143
+ const NAME$1 = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
2144
+ const ENTRY_ID = /^[\p{L}\p{N}][\p{L}\p{N}_-]{0,79}$/u;
2145
+ const MAX_TEXT$1 = 300;
2146
+ const isLorebookName = (name) => NAME$1.test(name);
2147
+ const isEntryId = (id) => ENTRY_ID.test(id);
2148
+ const lorebooksDirectory = (root) => join(root, LOREBOOKS_FOLDER);
2149
+ function lorebookDirectory(root, name) {
2150
+ if (!isLorebookName(name)) throw new Error(`"${name}" is not a usable lorebook name (letters, digits, "-" and "_", up to 64)`);
2151
+ return join(lorebooksDirectory(root), name);
2152
+ }
2153
+ const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2154
+ function parseHeader$1(value, problems) {
2155
+ if (!isRecord$1(value)) {
2156
+ problems.push(`${LOREBOOK_FILE} must be an object`);
2157
+ return {};
2158
+ }
2159
+ const text = (key) => {
2160
+ const field = value[key];
2161
+ if (field === void 0 || field === null) return void 0;
2162
+ if (typeof field !== "string" || field.length > MAX_TEXT$1) {
2163
+ problems.push(`${LOREBOOK_FILE}: "${key}" must be text of at most ${MAX_TEXT$1} characters`);
2164
+ return;
2165
+ }
2166
+ return field.trim() || void 0;
2167
+ };
2168
+ const title = text("title");
2169
+ const description = text("description");
2170
+ return {
2171
+ ...title === void 0 ? {} : { title },
2172
+ ...description === void 0 ? {} : { description }
2173
+ };
2174
+ }
2175
+ function readHeader$1(directory, problems) {
2176
+ const file = join(directory, LOREBOOK_FILE);
2177
+ if (!existsSync(file)) return {};
2178
+ let value;
2179
+ try {
2180
+ value = JSON.parse(readFileSync(file, "utf8"));
2181
+ } catch {
2182
+ problems.push(`${LOREBOOK_FILE} is not valid JSON`);
2183
+ return {};
2184
+ }
2185
+ return parseHeader$1(value, problems);
2186
+ }
2187
+ /** 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. */
2188
+ function bookProblems(entries) {
2189
+ const ids = new Set(entries.map((entry) => entry.id));
2190
+ 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`])]);
2191
+ }
2192
+ /** Reads one lorebook folder, collecting every problem instead of stopping at the first. @throws {Error} when the folder does not exist. */
2193
+ async function readLorebook(directory, name) {
2194
+ if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
2195
+ const problems = [];
2196
+ const header = readHeader$1(directory, problems);
2197
+ const { lore, problems: found } = await loadLore(directory);
2198
+ for (const problem of found) problems.push(`${problem.path.slice(directory.length + 1)}: ${problem.message}`);
2199
+ problems.push(...bookProblems(lore));
2200
+ if (lore.length === 0 && problems.length === 0) problems.push("the lorebook has no entries");
2201
+ return {
2202
+ summary: {
2203
+ name,
2204
+ title: header.title ?? name,
2205
+ description: header.description ?? "",
2206
+ entries: lore.length,
2207
+ common: lore.filter((entry) => entry.scope === "everyone").length,
2208
+ problems
2209
+ },
2210
+ entries: lore.sort((a, b) => a.title.localeCompare(b.title))
2211
+ };
2212
+ }
2213
+ async function listLorebooks(root) {
2214
+ const folder = lorebooksDirectory(root);
2215
+ if (!existsSync(folder)) return [];
2216
+ const found = (await readdir(folder, { withFileTypes: true })).filter((entry) => entry.isDirectory() && isLorebookName(entry.name));
2217
+ return (await Promise.all(found.map((entry) => readLorebook(join(folder, entry.name), entry.name)))).sort((a, b) => a.summary.name.localeCompare(b.summary.name));
2218
+ }
2219
+ async function loadLorebook(root, name) {
2220
+ return await readLorebook(lorebookDirectory(root, name), name);
2221
+ }
2222
+ const toEntry = (definition) => ({
2223
+ id: definition.id,
2224
+ title: definition.title,
2225
+ kind: definition.kind,
2226
+ scope: definition.scope,
2227
+ knownBy: definition.knownBy,
2228
+ summary: definition.summary,
2229
+ body: definition.body,
2230
+ related: definition.related
2231
+ });
2232
+ const entriesOf = (book) => book.entries.map(toEntry);
2233
+ function headerFile$1(header) {
2234
+ return `${JSON.stringify(header, null, 2)}\n`;
2235
+ }
2236
+ async function writeAtomic(file, text) {
2237
+ await mkdir(dirname(file), { recursive: true });
2238
+ await writeFile(`${file}.tmp`, text);
2239
+ await rename(`${file}.tmp`, file);
2240
+ }
2241
+ /** Makes an empty lorebook. @throws {Error} when the name is taken or the information is not acceptable. */
2242
+ async function createLorebook(root, request) {
2243
+ const target = lorebookDirectory(root, request.name);
2244
+ if (existsSync(target)) throw new Error(`there is already a lorebook "${request.name}"`);
2245
+ const problems = [];
2246
+ const header = parseHeader$1({
2247
+ title: request.title?.trim(),
2248
+ description: request.description?.trim()
2249
+ }, problems);
2250
+ if (problems.length > 0) throw new Error(problems.join("; "));
2251
+ await writeAtomic(join(target, LOREBOOK_FILE), headerFile$1(header));
2252
+ return await readLorebook(target, request.name);
2253
+ }
2254
+ /** 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. */
2255
+ async function reserveLorebook(root, name, title) {
2256
+ const target = lorebookDirectory(root, name);
2257
+ if (existsSync(target)) throw new Error(`there is already a lorebook "${name}"`);
2258
+ await writeAtomic(join(target, LOREBOOK_FILE), headerFile$1({ title: title.trim().slice(0, MAX_TEXT$1) || name }));
2259
+ return target;
2260
+ }
2261
+ /** 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. */
2262
+ async function updateLorebookInfo(root, name, change) {
2263
+ const directory = lorebookDirectory(root, name);
2264
+ if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
2265
+ const current = readHeader$1(directory, []);
2266
+ const problems = [];
2267
+ const next = parseHeader$1({
2268
+ title: change.title ?? current.title,
2269
+ description: change.description ?? current.description
2270
+ }, problems);
2271
+ if (problems.length > 0) throw new Error(problems.join("; "));
2272
+ await writeAtomic(join(directory, LOREBOOK_FILE), headerFile$1(next));
2273
+ return await readLorebook(directory, name);
2274
+ }
2275
+ /** The file of an entry: written in the format of a world's own lore, with its scope always said. */
2276
+ function entryFile(entry) {
2277
+ return `${JSON.stringify({
2278
+ title: entry.title,
2279
+ kind: entry.kind,
2280
+ scope: entry.scope,
2281
+ ...entry.scope === "listed" && entry.knownBy.length > 0 ? { known_by: entry.knownBy } : {},
2282
+ summary: entry.summary,
2283
+ body: entry.body,
2284
+ ...entry.related.length > 0 ? { related: entry.related } : {}
2285
+ }, null, 2)}\n`;
2286
+ }
2287
+ /** Checks an entry the way a story start would, before anything is written. @returns why it cannot be used, or nothing. */
2288
+ function entryProblem(entry) {
2289
+ if (!isEntryId(entry.id)) return `"${entry.id}" is not a usable entry id (letters, digits, "-" and "_", up to 80)`;
2290
+ if (!LORE_KINDS.includes(entry.kind)) return `kind must be one of ${LORE_KINDS.join(", ")}`;
2291
+ if (!LORE_SCOPES.includes(entry.scope)) return `scope must be one of ${LORE_SCOPES.join(", ")}`;
2292
+ if (entry.title.trim() === "") return "the entry needs a title";
2293
+ if (entry.body.trim() === "" && entry.summary.trim() === "") return "the entry needs a summary or a body";
2294
+ const parsed = parseLoreFile(entryFile({
2295
+ ...entry,
2296
+ title: entry.title.trim()
2297
+ }), entry.id);
2298
+ return parsed.ok ? void 0 : parsed.issues.map((issue) => `${issue.path}: ${issue.message}`).join("; ");
2299
+ }
2300
+ /**
2301
+ * Creates several new entries of a lorebook at once, each checked as `writeLorebookEntry` checks one; none is written when any is not acceptable.
2302
+ * @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.
2303
+ */
2304
+ async function addLorebookEntries(root, name, entries) {
2305
+ const directory = lorebookDirectory(root, name);
2306
+ if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
2307
+ const book = await readLorebook(directory, name);
2308
+ if (book.entries.length + entries.length > 500) throw new Error(`a lorebook has at most 500 entries`);
2309
+ const ids = new Set(book.entries.map((entry) => entry.id));
2310
+ for (const entry of entries) {
2311
+ const problem = entryProblem(entry);
2312
+ if (problem !== void 0) throw new Error(`entry "${entry.title}": ${problem}`);
2313
+ if (ids.has(entry.id)) throw new Error(`there is already an entry "${entry.id}"`);
2314
+ ids.add(entry.id);
2315
+ }
2316
+ for (const entry of entries) await writeAtomic(join(directory, LORE_DIR, entry.id, LORE_FILE_NAME), entryFile({
2317
+ ...entry,
2318
+ title: entry.title.trim()
2319
+ }));
2320
+ return await readLorebook(directory, name);
2321
+ }
2322
+ /** 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. */
2323
+ async function writeLorebookEntry(root, name, entry) {
2324
+ const directory = lorebookDirectory(root, name);
2325
+ if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
2326
+ const problem = entryProblem(entry);
2327
+ if (problem !== void 0) throw new Error(problem);
2328
+ const file = join(directory, LORE_DIR, entry.id, LORE_FILE_NAME);
2329
+ const book = await readLorebook(directory, name);
2330
+ if (!existsSync(file) && book.entries.length >= 500) throw new Error(`a lorebook has at most 500 entries`);
2331
+ const others = book.entries.filter((other) => other.id !== entry.id);
2332
+ const missing = entry.related.filter((id) => id === entry.id || !others.some((other) => other.id === id));
2333
+ if (missing.length > 0) throw new Error(`related: ${missing.map((id) => `"${id}"`).join(", ")} ${missing.length === 1 ? "is" : "are"} not (other) entries of this book`);
2334
+ await writeAtomic(file, entryFile({
2335
+ ...entry,
2336
+ title: entry.title.trim()
2337
+ }));
2338
+ return await readLorebook(directory, name);
2339
+ }
2340
+ /** Moves an entry into the book's `.trash`. @throws {Error} when it does not exist or other entries relate to it. */
2341
+ async function deleteLorebookEntry(root, name, id, now = Date.now) {
2342
+ const directory = lorebookDirectory(root, name);
2343
+ const folder = join(directory, LORE_DIR, id);
2344
+ if (!isEntryId(id) || !existsSync(join(folder, "lore.json"))) throw new Error(`the lorebook "${name}" has no entry "${id}"`);
2345
+ const citing = (await readLorebook(directory, name)).entries.filter((entry) => entry.id !== id && entry.related.includes(id)).map((entry) => entry.id);
2346
+ if (citing.length > 0) throw new Error(`the entries ${citing.join(", ")} relate to "${id}"; change them first`);
2347
+ const aside = join(directory, ".trash", LORE_DIR, `${id}-${now()}`);
2348
+ await mkdir(dirname(aside), { recursive: true });
2349
+ await rename(folder, aside);
2350
+ return await readLorebook(directory, name);
2351
+ }
2352
+ /** Moves a lorebook out of the library into `<root>/.trash/lorebooks/`. @returns where it went. */
2353
+ async function deleteLorebook(root, name, now = Date.now) {
2354
+ const directory = lorebookDirectory(root, name);
2355
+ if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
2356
+ const aside = join(root, ".trash", LOREBOOKS_FOLDER, `${name}-${now()}`);
2357
+ await mkdir(dirname(aside), { recursive: true });
2358
+ await rename(directory, aside);
2359
+ return aside;
2360
+ }
1900
2361
  // src/host/prompts/world-prompts.ts
1901
2362
  /** The prompts that decide how the story is written and who the models are (prose and persona); every other prompt holds rules of the game. */
1902
2363
  const PROSE_PROMPTS = [
@@ -1962,38 +2423,761 @@ async function deleteWorldPrompt(directory, language, id, shipped = shippedPromp
1962
2423
  await rm(dirname(file), { recursive: false }).catch(() => void 0);
1963
2424
  return aside;
1964
2425
  }
1965
- // src/host/decisions/route.ts
1966
- /** The probability from which a yes is taken as a yes, for the confidence a chat asks. */
1967
- const yesAt = (confidence) => (1 + confidence) / 2;
1968
- /** The probability up to which a no is taken as a no. */
1969
- const noAt = (confidence) => (1 - confidence) / 2;
1970
- const clip = (text) => text.length > 120 ? `${text.slice(0, 119)}…` : text;
1971
- const reportOf = (mode, items) => ({
1972
- mode,
1973
- items,
1974
- decided: 0,
1975
- escalated: 0,
1976
- fallbacks: 0,
1977
- agreed: 0,
1978
- disagreed: 0,
1979
- decisionMs: 0,
1980
- llmMs: 0,
1981
- samples: []
1982
- });
1983
- async function timed(run) {
1984
- const started = performance.now();
2426
+ // src/host/presets/presets.ts
2427
+ const PRESETS_FOLDER = "presets";
2428
+ const PRESET_FILE = "preset.json";
2429
+ const NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
2430
+ const MAX_TEXT = 300;
2431
+ const isPresetName = (name) => NAME.test(name);
2432
+ const presetsDirectory = (root) => join(root, PRESETS_FOLDER);
2433
+ function presetDirectory(root, name) {
2434
+ if (!isPresetName(name)) throw new Error(`"${name}" is not a usable preset name (letters, digits, "-" and "_", up to 64)`);
2435
+ return join(presetsDirectory(root), name);
2436
+ }
2437
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2438
+ function parseHeader(value, problems) {
2439
+ if (!isRecord(value)) {
2440
+ problems.push(`${PRESET_FILE} must be an object`);
2441
+ return { sampling: {} };
2442
+ }
2443
+ const text = (key) => {
2444
+ const field = value[key];
2445
+ if (field === void 0 || field === null) return void 0;
2446
+ if (typeof field !== "string" || field.length > MAX_TEXT) {
2447
+ problems.push(`${PRESET_FILE}: "${key}" must be text of at most ${MAX_TEXT} characters`);
2448
+ return;
2449
+ }
2450
+ return field.trim() || void 0;
2451
+ };
2452
+ const sampling = parseSampling(value["sampling"], `${PRESET_FILE}: sampling`, problems);
2453
+ const title = text("title");
2454
+ const description = text("description");
1985
2455
  return {
1986
- value: await run(),
1987
- ms: Math.round(performance.now() - started)
2456
+ ...title === void 0 ? {} : { title },
2457
+ ...description === void 0 ? {} : { description },
2458
+ sampling
1988
2459
  };
1989
2460
  }
1990
- /**
1991
- * Gives each key a verdict the way its site is set to: from the language model, from the decision model, from the decision model where it
1992
- * is confident and the language model elsewhere, or from the language model while comparing it with the decision model. A decision model
1993
- * that cannot be used never stops a story: its keys go to the language model and the report says why.
1994
- */
1995
- async function routeVerdicts(route, signal) {
1996
- const { mode, keys } = route;
2461
+ function readHeader(directory, problems) {
2462
+ const file = join(directory, PRESET_FILE);
2463
+ if (!existsSync(file)) return { sampling: {} };
2464
+ let value;
2465
+ try {
2466
+ value = JSON.parse(readFileSync(file, "utf8"));
2467
+ } catch {
2468
+ problems.push(`${PRESET_FILE} is not valid JSON`);
2469
+ return { sampling: {} };
2470
+ }
2471
+ return parseHeader(value, problems);
2472
+ }
2473
+ /** Reads one preset folder, collecting every problem instead of stopping at the first. @throws {Error} when the folder does not exist. */
2474
+ function readPreset(directory, name, shipped = shippedPromptsDirectory()) {
2475
+ if (!existsSync(directory)) throw new Error(`there is no preset "${name}"`);
2476
+ const problems = [];
2477
+ const header = readHeader(directory, problems);
2478
+ const files = /* @__PURE__ */ new Map();
2479
+ const base = join(directory, PROMPTS_FOLDER);
2480
+ if (existsSync(base)) for (const entry of readdirSync(base, { withFileTypes: true })) {
2481
+ if (!entry.isDirectory() || !LANGUAGE_FOLDER.test(entry.name)) {
2482
+ problems.push(`prompts/${entry.name}: prompts are kept in a folder named by the language, such as en or zh`);
2483
+ continue;
2484
+ }
2485
+ for (const id of listFiles(join(base, entry.name))) {
2486
+ const path = `${entry.name}/${id}.md`;
2487
+ const text = readFileSync(join(base, path), "utf8");
2488
+ const problem = id.startsWith("roleplay/") ? promptProblem(entry.name, id, text, shipped) : `"${id}" is not a prompt of the story`;
2489
+ if (problem !== void 0) problems.push(`prompts/${path}: ${problem}`);
2490
+ else files.set(path, text);
2491
+ }
2492
+ }
2493
+ if (files.size === 0 && problems.length === 0) problems.push("the preset carries no prompts");
2494
+ const paths = [...files.keys()];
2495
+ const ids = [...new Set(paths.map((path) => path.slice(path.indexOf("/") + 1, -3)))].sort((a, b) => a.localeCompare(b));
2496
+ return {
2497
+ summary: {
2498
+ name,
2499
+ title: header.title ?? name,
2500
+ description: header.description ?? "",
2501
+ languages: [...new Set(paths.map((path) => path.split("/")[0]))].sort((a, b) => a.localeCompare(b)),
2502
+ prompts: ids,
2503
+ rules: ids.filter((id) => !PROSE_PROMPTS.includes(id)),
2504
+ sampling: header.sampling,
2505
+ problems
2506
+ },
2507
+ files
2508
+ };
2509
+ }
2510
+ /** Every preset in the library; one that cannot be read is listed with its problems. */
2511
+ function listPresets(root) {
2512
+ const folder = presetsDirectory(root);
2513
+ if (!existsSync(folder)) return [];
2514
+ return readdirSync(folder, { withFileTypes: true }).filter((entry) => entry.isDirectory() && isPresetName(entry.name)).map((entry) => readPreset(join(folder, entry.name), entry.name)).sort((a, b) => a.summary.name.localeCompare(b.summary.name));
2515
+ }
2516
+ function loadPreset(root, name) {
2517
+ return readPreset(presetDirectory(root, name), name);
2518
+ }
2519
+ const sha = (text) => createHash("sha256").update(text).digest("hex");
2520
+ /**
2521
+ * Makes a preset of the prose prompts a world carries. Nothing is overwritten.
2522
+ * @throws {Error} when the name is taken, the world carries no prose prompt, or what it carries is not acceptable.
2523
+ */
2524
+ async function savePresetFromWorld(root, worldDirectory, request) {
2525
+ const target = presetDirectory(root, request.name);
2526
+ if (existsSync(target)) throw new Error(`there is already a preset "${request.name}"`);
2527
+ const source = join(worldDirectory, PROMPTS_FOLDER);
2528
+ const found = [];
2529
+ if (existsSync(source)) {
2530
+ for (const entry of readdirSync(source, { withFileTypes: true })) if (entry.isDirectory() && LANGUAGE_FOLDER.test(entry.name)) {
2531
+ for (const id of listFiles(join(source, entry.name))) if (PROSE_PROMPTS.includes(id)) found.push({
2532
+ language: entry.name,
2533
+ id
2534
+ });
2535
+ }
2536
+ }
2537
+ if (found.length === 0) throw new Error("the world carries no prose prompts to make a preset of");
2538
+ const staging = join(root, ".install", `preset-${request.name}-${Date.now()}`);
2539
+ try {
2540
+ for (const { language, id } of found) {
2541
+ const to = join(staging, PROMPTS_FOLDER, language, `${id}.md`);
2542
+ await mkdir(dirname(to), { recursive: true });
2543
+ await writeFile(to, readFileSync(join(source, language, `${id}.md`), "utf8"));
2544
+ }
2545
+ const header = {
2546
+ ...request.title === void 0 || request.title.trim() === "" ? {} : { title: request.title.trim() },
2547
+ ...request.description === void 0 || request.description.trim() === "" ? {} : { description: request.description.trim() },
2548
+ ...request.sampling === void 0 || Object.keys(request.sampling).length === 0 ? {} : { sampling: request.sampling }
2549
+ };
2550
+ await writeFile(join(staging, PRESET_FILE), JSON.stringify(header, null, 2));
2551
+ const loaded = readPreset(staging, request.name);
2552
+ if (loaded.summary.problems.length > 0) throw new Error(`the preset would have problems: ${loaded.summary.problems.join("; ")}`);
2553
+ await mkdir(presetsDirectory(root), { recursive: true });
2554
+ await rename(staging, target);
2555
+ return readPreset(target, request.name);
2556
+ } finally {
2557
+ await rm(staging, {
2558
+ recursive: true,
2559
+ force: true
2560
+ });
2561
+ }
2562
+ }
2563
+ /** Moves a preset out of the library into `<root>/.trash/presets/`. @returns where it went. */
2564
+ async function deletePreset(root, name, now = Date.now) {
2565
+ const directory = presetDirectory(root, name);
2566
+ if (!existsSync(directory)) throw new Error(`there is no preset "${name}"`);
2567
+ const aside = join(root, ".trash", PRESETS_FOLDER, `${name}-${now()}`);
2568
+ await mkdir(dirname(aside), { recursive: true });
2569
+ await rename(directory, aside);
2570
+ return aside;
2571
+ }
2572
+ function headerFile(title, description, sampling) {
2573
+ return `${JSON.stringify({
2574
+ ...title === void 0 ? {} : { title },
2575
+ ...description === void 0 ? {} : { description },
2576
+ ...Object.keys(sampling).length === 0 ? {} : { sampling }
2577
+ }, null, 2)}\n`;
2578
+ }
2579
+ async function writeHeader(directory, text) {
2580
+ const file = join(directory, PRESET_FILE);
2581
+ await writeFile(`${file}.tmp`, text);
2582
+ await rename(`${file}.tmp`, file);
2583
+ }
2584
+ /** Changes what a preset says about itself. @throws {Error} when the preset does not exist or the change is not acceptable; nothing is written then. */
2585
+ async function updatePresetInfo(root, name, change) {
2586
+ const directory = presetDirectory(root, name);
2587
+ if (!existsSync(directory)) throw new Error(`there is no preset "${name}"`);
2588
+ const current = readHeader(directory, []);
2589
+ const problems = [];
2590
+ const next = parseHeader({
2591
+ title: change.title ?? current.title,
2592
+ description: change.description ?? current.description,
2593
+ sampling: change.sampling ?? current.sampling
2594
+ }, problems);
2595
+ if (problems.length > 0) throw new Error(problems.join("; "));
2596
+ await writeHeader(directory, headerFile(next.title, next.description, next.sampling));
2597
+ return readPreset(directory, name);
2598
+ }
2599
+ /**
2600
+ * Makes a preset holding the shipped prose prompts of every language, as a starting point to edit. Nothing is overwritten.
2601
+ * @throws {Error} when the name is taken or the information is not acceptable.
2602
+ */
2603
+ async function createPresetFromShipped(root, request, shipped = shippedPromptsDirectory()) {
2604
+ const target = presetDirectory(root, request.name);
2605
+ if (existsSync(target)) throw new Error(`there is already a preset "${request.name}"`);
2606
+ const problems = [];
2607
+ const header = parseHeader({
2608
+ title: request.title?.trim(),
2609
+ description: request.description?.trim(),
2610
+ sampling: request.sampling
2611
+ }, problems);
2612
+ if (problems.length > 0) throw new Error(problems.join("; "));
2613
+ const staging = join(root, ".install", `preset-${request.name}-${Date.now()}`);
2614
+ try {
2615
+ for (const language of shippedLanguages(shipped)) for (const id of PROSE_PROMPTS) {
2616
+ const from = join(shipped, language, `${id}.md`);
2617
+ if (!existsSync(from)) continue;
2618
+ const to = join(staging, PROMPTS_FOLDER, language, `${id}.md`);
2619
+ await mkdir(dirname(to), { recursive: true });
2620
+ await writeFile(to, readFileSync(from, "utf8"));
2621
+ }
2622
+ await mkdir(staging, { recursive: true });
2623
+ await writeHeader(staging, headerFile(header.title, header.description, header.sampling));
2624
+ const loaded = readPreset(staging, request.name);
2625
+ if (loaded.summary.problems.length > 0) throw new Error(`the preset would have problems: ${loaded.summary.problems.join("; ")}`);
2626
+ await mkdir(presetsDirectory(root), { recursive: true });
2627
+ await rename(staging, target);
2628
+ return readPreset(target, request.name);
2629
+ } finally {
2630
+ await rm(staging, {
2631
+ recursive: true,
2632
+ force: true
2633
+ });
2634
+ }
2635
+ }
2636
+ /** Makes an empty preset folder that the import is about to fill; it has no prompts yet, so it reads as having problems until it does. */
2637
+ async function reservePreset(root, name, title, sampling = {}) {
2638
+ const target = presetDirectory(root, name);
2639
+ if (existsSync(target)) throw new Error(`there is already a preset "${name}"`);
2640
+ await mkdir(target, { recursive: true });
2641
+ await writeHeader(target, headerFile(title.trim().slice(0, MAX_TEXT) || void 0, void 0, sampling));
2642
+ return target;
2643
+ }
2644
+ /**
2645
+ * Makes a preset that adds guidance to the shipped prompts, in every language the program ships: each prompt keeps its shipped text and the guidance follows it, so that
2646
+ * the prompt keeps naming the tools and values it needs. The guidance is the importer's, in the language it was written in.
2647
+ * @throws {Error} when the name is taken, there is no guidance, or a prompt would not be acceptable; nothing is made then.
2648
+ */
2649
+ async function createPresetFromGuidance(root, request, guidance, shipped = shippedPromptsDirectory()) {
2650
+ const target = presetDirectory(root, request.name);
2651
+ if (existsSync(target)) throw new Error(`there is already a preset "${request.name}"`);
2652
+ const ids = Object.keys(guidance).filter((id) => (guidance[id]?.length ?? 0) > 0);
2653
+ if (ids.length === 0) throw new Error("there is no guidance to make a preset of");
2654
+ const problems = [];
2655
+ const header = parseHeader({
2656
+ title: request.title?.trim(),
2657
+ description: request.description?.trim()
2658
+ }, problems);
2659
+ if (problems.length > 0) throw new Error(problems.join("; "));
2660
+ const staging = join(root, ".install", `preset-${request.name}-${Date.now()}`);
2661
+ try {
2662
+ for (const language of shippedLanguages(shipped)) for (const id of ids) {
2663
+ const base = readWorldPrompt(join(staging, "none"), language, id, shipped).text.trimEnd();
2664
+ const to = join(staging, PROMPTS_FOLDER, language, `${id}.md`);
2665
+ await mkdir(dirname(to), { recursive: true });
2666
+ await writeFile(to, `${base}\n\n${(guidance[id] ?? []).join("\n")}\n`);
2667
+ }
2668
+ await writeHeader(staging, headerFile(header.title, header.description, {}));
2669
+ const loaded = readPreset(staging, request.name);
2670
+ if (loaded.summary.problems.length > 0) throw new Error(`the preset would have problems: ${loaded.summary.problems.join("; ")}`);
2671
+ await mkdir(presetsDirectory(root), { recursive: true });
2672
+ await rename(staging, target);
2673
+ return readPreset(target, request.name);
2674
+ } finally {
2675
+ await rm(staging, {
2676
+ recursive: true,
2677
+ force: true
2678
+ });
2679
+ }
2680
+ }
2681
+ // src/shared/start-questions.ts
2682
+ const START_PLOT_STATUSES = ["dormant", "available"];
2683
+ const questionView = (question) => ({
2684
+ id: question.id,
2685
+ text: question.text,
2686
+ options: question.options.map(({ id, label, description }) => ({
2687
+ id,
2688
+ label,
2689
+ ...description === void 0 ? {} : { description }
2690
+ }))
2691
+ });
2692
+ /** What the answers add up to, or why they cannot be combined. A question left unanswered changes nothing. */
2693
+ function combineAnswers(questions, answers) {
2694
+ const problems = [];
2695
+ const effect = {};
2696
+ for (const id of Object.keys(answers)) if (!questions.some((question) => question.id === id)) problems.push(`the world asks no question "${id}"`);
2697
+ const set = (key, value, question) => {
2698
+ if (value === void 0) return;
2699
+ 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`);
2700
+ else effect[key] = value;
2701
+ };
2702
+ for (const question of questions) {
2703
+ const answer = answers[question.id];
2704
+ if (answer === void 0) continue;
2705
+ const option = question.options.find((entry) => entry.id === answer);
2706
+ if (option === void 0) {
2707
+ problems.push(`"${answer}" is not an answer to "${question.id}"`);
2708
+ continue;
2709
+ }
2710
+ const found = option.effect;
2711
+ if (found.rules !== void 0) effect.rules = [...effect.rules ?? [], ...found.rules];
2712
+ set("opening", found.opening, question.id);
2713
+ set("startingTime", found.startingTime, question.id);
2714
+ set("clockMode", found.clockMode, question.id);
2715
+ for (const [agent, switches] of Object.entries(found.tools ?? {})) {
2716
+ const merged = { ...effect.tools?.[agent] };
2717
+ for (const [tool, value] of Object.entries(switches)) {
2718
+ if (merged[tool] !== void 0 && merged[tool] !== value) problems.push(`the answers disagree about the tool "${tool}"; "${question.id}" changes it again`);
2719
+ merged[tool] = value;
2720
+ }
2721
+ effect.tools = {
2722
+ ...effect.tools,
2723
+ [agent]: merged
2724
+ };
2725
+ }
2726
+ for (const [plot, status] of Object.entries(found.plots ?? {})) {
2727
+ if (effect.plots?.[plot] !== void 0 && effect.plots[plot] !== status) problems.push(`the answers disagree about the plot "${plot}"; "${question.id}" changes it again`);
2728
+ effect.plots = {
2729
+ ...effect.plots,
2730
+ [plot]: status
2731
+ };
2732
+ }
2733
+ }
2734
+ return {
2735
+ effect,
2736
+ problems
2737
+ };
2738
+ }
2739
+ /** The questions as `world.json` writes them: snake_case keys, and only what an answer sets. */
2740
+ function startQuestionsToFile(questions) {
2741
+ return questions.map((question) => ({
2742
+ id: question.id,
2743
+ text: question.text,
2744
+ options: question.options.map((option) => ({
2745
+ id: option.id,
2746
+ label: option.label,
2747
+ ...option.description === void 0 || option.description === "" ? {} : { description: option.description },
2748
+ effect: {
2749
+ ...option.effect.rules === void 0 || option.effect.rules.length === 0 ? {} : { rules: option.effect.rules },
2750
+ ...option.effect.opening === void 0 ? {} : { opening: option.effect.opening },
2751
+ ...option.effect.startingTime === void 0 || option.effect.startingTime === "" ? {} : { starting_time: option.effect.startingTime },
2752
+ ...option.effect.clockMode === void 0 ? {} : { clock_mode: option.effect.clockMode },
2753
+ ...option.effect.tools === void 0 ? {} : { tools: option.effect.tools },
2754
+ ...option.effect.plots === void 0 ? {} : { plots: option.effect.plots }
2755
+ }
2756
+ }))
2757
+ }));
2758
+ }
2759
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2760
+ /** Reads questions sent by the editor: the shape only, since the world file's own reader judges every value when the change is written. */
2761
+ function parseStartQuestionsEdit(value, problems) {
2762
+ if (!Array.isArray(value)) {
2763
+ problems.push("startQuestions must be a list");
2764
+ return;
2765
+ }
2766
+ const questions = [];
2767
+ for (const entry of value) {
2768
+ if (!isObject(entry) || typeof entry["id"] !== "string" || typeof entry["text"] !== "string" || !Array.isArray(entry["options"])) {
2769
+ problems.push("a start question needs an id, a text and a list of options");
2770
+ return;
2771
+ }
2772
+ const options = [];
2773
+ for (const option of entry["options"]) {
2774
+ if (!isObject(option) || typeof option["id"] !== "string" || typeof option["label"] !== "string" || !isObject(option["effect"]) || option["description"] !== void 0 && typeof option["description"] !== "string") {
2775
+ problems.push("an answer needs an id, a label and an effect object, such as {\"id\": \"morning\", \"label\": \"Morning\", \"effect\": {\"startingTime\": \"07:00\"}} (the effect may hold rules, opening, startingTime, clockMode, tools, plots; {} changes nothing)");
2776
+ return;
2777
+ }
2778
+ const effect = option["effect"];
2779
+ const known = {};
2780
+ if (Array.isArray(effect["rules"])) known.rules = effect["rules"].filter((rule) => typeof rule === "string");
2781
+ if (typeof effect["opening"] === "number") known.opening = effect["opening"];
2782
+ if (typeof effect["startingTime"] === "string") known.startingTime = effect["startingTime"];
2783
+ if (effect["clockMode"] === "simulated" || effect["clockMode"] === "real") known.clockMode = effect["clockMode"];
2784
+ if (isObject(effect["tools"])) known.tools = effect["tools"];
2785
+ if (isObject(effect["plots"])) known.plots = effect["plots"];
2786
+ options.push({
2787
+ id: option["id"].trim(),
2788
+ label: option["label"].trim(),
2789
+ ...typeof option["description"] === "string" && option["description"].trim() !== "" ? { description: option["description"].trim() } : {},
2790
+ effect: known
2791
+ });
2792
+ }
2793
+ questions.push({
2794
+ id: entry["id"].trim(),
2795
+ text: entry["text"].trim(),
2796
+ options
2797
+ });
2798
+ }
2799
+ return questions;
2800
+ }
2801
+ const MAX_OPENING_CHARS = 2e4;
2802
+ const TEXT_FIELDS = [
2803
+ "name",
2804
+ "description",
2805
+ "opening",
2806
+ "authorName",
2807
+ "authorUrl",
2808
+ "timeZone",
2809
+ "startingTime",
2810
+ "version",
2811
+ "preset"
2812
+ ];
2813
+ const LIST_FIELDS = [
2814
+ "tags",
2815
+ "rules",
2816
+ "lorebooks"
2817
+ ];
2818
+ /** Reads a body that came from the browser; every field is checked and each problem is reported. */
2819
+ function parseWorldInfoEdit(value) {
2820
+ const problems = [];
2821
+ const input = typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
2822
+ if (input === void 0) throw new InvalidEditProblems(["the changes must be an object"]);
2823
+ const edit = {};
2824
+ 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}"`);
2825
+ for (const key of TEXT_FIELDS) {
2826
+ if (input[key] === void 0) continue;
2827
+ if (typeof input[key] === "string") edit[key] = input[key].trim();
2828
+ else problems.push(`${key} must be text`);
2829
+ }
2830
+ for (const key of LIST_FIELDS) {
2831
+ if (input[key] === void 0) continue;
2832
+ if (Array.isArray(input[key]) && input[key].every((entry) => typeof entry === "string")) edit[key] = input[key].map((entry) => entry.trim()).filter((entry) => entry !== "");
2833
+ else problems.push(`${key} must be a list of text`);
2834
+ }
2835
+ if (input["alternateOpenings"] !== void 0) {
2836
+ const list = input["alternateOpenings"];
2837
+ const entries = Array.isArray(list) ? list.map((entry) => typeof entry === "object" && entry !== null ? entry : void 0) : void 0;
2838
+ 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? }");
2839
+ else {
2840
+ const kept = entries.map((entry) => ({
2841
+ title: String(entry["title"] ?? "").trim(),
2842
+ text: String(entry["text"]).trim(),
2843
+ ...String(entry["character"] ?? "").trim() === "" ? {} : { character: String(entry["character"]).trim() }
2844
+ })).filter((entry) => entry.text !== "");
2845
+ if (kept.length > 30) problems.push(`there are more than 30 alternate openings`);
2846
+ if (kept.some((entry) => entry.text.length > 2e4)) problems.push(`an alternate opening is longer than ${MAX_OPENING_CHARS} characters`);
2847
+ edit["alternateOpenings"] = kept;
2848
+ }
2849
+ }
2850
+ if (input["startQuestions"] !== void 0) {
2851
+ const questions = parseStartQuestionsEdit(input["startQuestions"], problems);
2852
+ if (questions !== void 0) edit["startQuestions"] = questions;
2853
+ }
2854
+ if (input["tools"] !== void 0) {
2855
+ const board = parseSwitchboard(input["tools"], "tools");
2856
+ if (typeof board === "string") problems.push(board);
2857
+ else edit["tools"] = board;
2858
+ }
2859
+ if (input["autonomy"] !== void 0) {
2860
+ if (typeof input["autonomy"] === "boolean") edit["autonomy"] = input["autonomy"];
2861
+ else problems.push("autonomy must be true or false");
2862
+ }
2863
+ if (input["sampling"] !== void 0) edit["sampling"] = parseSampling(input["sampling"], "sampling", problems);
2864
+ if (typeof edit["version"] === "string" && edit["version"].length > 40) problems.push(`the version is longer than 40 characters`);
2865
+ if (edit["name"] === "") problems.push("the world needs a name");
2866
+ if (typeof edit["name"] === "string" && edit["name"].length > 200) problems.push(`the name is longer than 200 characters`);
2867
+ if (problems.length > 0) throw new InvalidEditProblems(problems);
2868
+ return edit;
2869
+ }
2870
+ // src/host/worlds/world-file.ts
2871
+ const WORLD_FILE_NAME = "world.json";
2872
+ /** `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. */
2873
+ function readAlternateOpenings(reader) {
2874
+ const value = reader.raw("alternate_openings");
2875
+ if (value === void 0 || value === null) return void 0;
2876
+ if (!Array.isArray(value)) {
2877
+ reader.fail("alternate_openings", "must be a list");
2878
+ return;
2879
+ }
2880
+ if (value.length > 30) reader.fail("alternate_openings", `has more than 30 openings`);
2881
+ const openings = [];
2882
+ for (const entry of reader.objects("alternate_openings")) {
2883
+ const text = entry.string("text", { required: true })?.trim();
2884
+ if (text === void 0 || text === "") continue;
2885
+ if (text.length > 2e4) entry.fail("text", `is longer than ${MAX_OPENING_CHARS} characters`);
2886
+ const character = entry.string("character")?.trim();
2887
+ openings.push({
2888
+ title: entry.string("title")?.trim() || text.slice(0, 40),
2889
+ text,
2890
+ ...character === void 0 || character === "" ? {} : { character }
2891
+ });
2892
+ }
2893
+ return openings.length === 0 ? void 0 : openings;
2894
+ }
2895
+ const EFFECT_KEYS = [
2896
+ "rules",
2897
+ "opening",
2898
+ "starting_time",
2899
+ "clock_mode",
2900
+ "tools",
2901
+ "plots"
2902
+ ];
2903
+ /** 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. */
2904
+ function readEffect(entry, openings) {
2905
+ const raw = entry.raw("effect");
2906
+ const effect = {};
2907
+ if (raw === void 0 || raw === null) return effect;
2908
+ if (typeof raw !== "object" || Array.isArray(raw)) {
2909
+ entry.fail("effect", "must be an object");
2910
+ return effect;
2911
+ }
2912
+ const body = raw;
2913
+ 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(", ")})`);
2914
+ if (body["rules"] !== void 0) {
2915
+ const rules = Array.isArray(body["rules"]) && body["rules"].every((rule) => typeof rule === "string") ? body["rules"].map((rule) => rule.trim()).filter((rule) => rule !== "") : void 0;
2916
+ if (rules === void 0) entry.fail("effect.rules", "must be a list of rules");
2917
+ else if (rules.some((rule) => rule.length > 300)) entry.fail("effect.rules", `has a rule longer than 300 characters`);
2918
+ else if (rules.length > 0) effect.rules = rules;
2919
+ }
2920
+ if (body["opening"] !== void 0) {
2921
+ 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`);
2922
+ else effect.opening = body["opening"];
2923
+ }
2924
+ if (body["starting_time"] !== void 0) {
2925
+ 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");
2926
+ else effect.startingTime = body["starting_time"].trim();
2927
+ }
2928
+ if (body["clock_mode"] !== void 0) {
2929
+ if (body["clock_mode"] !== "simulated" && body["clock_mode"] !== "real") entry.fail("effect.clock_mode", "must be \"simulated\" or \"real\"");
2930
+ else effect.clockMode = body["clock_mode"];
2931
+ }
2932
+ if (body["tools"] !== void 0) {
2933
+ const board = parseSwitchboard(body["tools"], "tools");
2934
+ if (typeof board === "string") entry.fail("effect.tools", board.replace(/^"tools"\s*/, ""));
2935
+ else if (Object.keys(board).length > 0) effect.tools = board;
2936
+ }
2937
+ if (body["plots"] !== void 0) {
2938
+ const plots = body["plots"];
2939
+ if (typeof plots !== "object" || plots === null || Array.isArray(plots)) entry.fail("effect.plots", "must map plot ids to \"dormant\" or \"available\"");
2940
+ else {
2941
+ const kept = {};
2942
+ 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(", ")}`);
2943
+ else kept[id] = status;
2944
+ if (Object.keys(kept).length > 0) effect.plots = kept;
2945
+ }
2946
+ }
2947
+ return effect;
2948
+ }
2949
+ /** `start_questions`: `{ id, text, options: [{ id, label, description?, effect }] }`, asked in the start dialog. */
2950
+ function readStartQuestions(reader, openings) {
2951
+ const value = reader.raw("start_questions");
2952
+ if (value === void 0 || value === null) return void 0;
2953
+ if (!Array.isArray(value)) {
2954
+ reader.fail("start_questions", "must be a list");
2955
+ return;
2956
+ }
2957
+ if (value.length > 8) reader.fail("start_questions", `has more than 8 questions`);
2958
+ const questions = [];
2959
+ const seen = /* @__PURE__ */ new Set();
2960
+ for (const entry of reader.objects("start_questions")) {
2961
+ const id = entry.string("id", { required: true })?.trim();
2962
+ const text = entry.string("text", { required: true })?.trim();
2963
+ if (id === void 0 || text === void 0 || id === "" || text === "") continue;
2964
+ if (seen.has(id)) entry.fail("id", `repeats the question "${id}"`);
2965
+ seen.add(id);
2966
+ if (text.length > 200) entry.fail("text", `is longer than 200 characters`);
2967
+ const raw = entry.raw("options");
2968
+ if (!Array.isArray(raw) || raw.length < 2 || raw.length > 8) {
2969
+ entry.fail("options", `must list 2 to 8 answers`);
2970
+ continue;
2971
+ }
2972
+ const options = [];
2973
+ const ids = /* @__PURE__ */ new Set();
2974
+ for (const option of entry.objects("options")) {
2975
+ const optionId = option.string("id", { required: true })?.trim();
2976
+ const label = option.string("label", { required: true })?.trim();
2977
+ if (optionId === void 0 || label === void 0 || optionId === "" || label === "") continue;
2978
+ if (ids.has(optionId)) option.fail("id", `repeats the answer "${optionId}"`);
2979
+ ids.add(optionId);
2980
+ if (label.length > 200) option.fail("label", `is longer than 200 characters`);
2981
+ const description = option.string("description")?.trim();
2982
+ options.push({
2983
+ id: optionId,
2984
+ label,
2985
+ ...description === void 0 || description === "" ? {} : { description },
2986
+ effect: readEffect(option, openings)
2987
+ });
2988
+ }
2989
+ questions.push({
2990
+ id,
2991
+ text,
2992
+ options
2993
+ });
2994
+ }
2995
+ return questions.length === 0 ? void 0 : questions;
2996
+ }
2997
+ /** `tools`: switches by kind of agent and tool name; a world carried from a version with other tools still loads. */
2998
+ function readTools(reader) {
2999
+ const value = reader.raw("tools");
3000
+ if (value === void 0) return void 0;
3001
+ const board = parseSwitchboard(value, "tools");
3002
+ if (typeof board === "string") {
3003
+ reader.fail("tools", board.replace(/^"tools"\s*/, ""));
3004
+ return;
3005
+ }
3006
+ return Object.keys(board).length === 0 ? void 0 : board;
3007
+ }
3008
+ /** `sampling` is an object of the controls a story's requests may carry (see `StorySampling`). */
3009
+ function readSampling(reader) {
3010
+ const problems = [];
3011
+ const sampling = parseSampling(reader.raw("sampling"), "sampling", problems);
3012
+ for (const problem of problems) reader.fail("sampling", problem.replace(/^sampling\.?/, ""));
3013
+ return Object.keys(sampling).length === 0 ? void 0 : sampling;
3014
+ }
3015
+ /** `rules` is one rule as text, or a list of them; blank ones are left out. */
3016
+ function readRules(reader) {
3017
+ const value = reader.raw("rules");
3018
+ if (value === void 0 || value === null) return void 0;
3019
+ const kept = (typeof value === "string" ? [value] : reader.strings("rules")).map((rule) => rule.trim()).filter((rule) => rule !== "");
3020
+ if (kept.length > 30) reader.fail("rules", `has more than 30 rules`);
3021
+ const long = kept.findIndex((rule) => rule.length > 300);
3022
+ if (long >= 0) reader.fail("rules", `rule ${long + 1} is longer than 300 characters: keep rules short`);
3023
+ return kept.length === 0 ? void 0 : kept;
3024
+ }
3025
+ /** `opening_message` is plain text (one narration), or a list of parts in the order the player reads them. */
3026
+ function readOpening(reader) {
3027
+ const value = reader.raw("opening_message");
3028
+ if (value === void 0 || value === null) return void 0;
3029
+ if (typeof value === "string") return value.trim() === "" ? void 0 : [{
3030
+ type: "narration",
3031
+ text: value.trim()
3032
+ }];
3033
+ if (!Array.isArray(value)) {
3034
+ reader.fail("opening_message", "must be text or a list of parts");
3035
+ return;
3036
+ }
3037
+ const parts = [];
3038
+ for (const part of reader.objects("opening_message")) {
3039
+ const type = part.oneOf("type", ["narration", "utterance"], "narration");
3040
+ const text = part.string("text", { required: true })?.trim();
3041
+ if (text === void 0 || text === "") continue;
3042
+ if (type === "narration") {
3043
+ parts.push({
3044
+ type,
3045
+ text
3046
+ });
3047
+ continue;
3048
+ }
3049
+ const character = part.string("character", { required: true });
3050
+ if (character !== void 0) parts.push({
3051
+ type,
3052
+ character,
3053
+ text
3054
+ });
3055
+ }
3056
+ return parts.length === 0 ? void 0 : parts;
3057
+ }
3058
+ /** `time_zone` (an IANA name) and `starting_time` (an ISO 8601 date and time, in `time_zone` unless it carries an offset). */
3059
+ function readClock(reader) {
3060
+ const timeZone = reader.string("time_zone");
3061
+ if (timeZone !== void 0 && !isTimeZone(timeZone)) {
3062
+ reader.fail("time_zone", `"${timeZone}" is not a time zone: write it like Europe/London or UTC`);
3063
+ return;
3064
+ }
3065
+ const text = reader.string("starting_time");
3066
+ let startingTime;
3067
+ if (text !== void 0) try {
3068
+ startingTime = parseInstant(text, timeZone ?? "UTC");
3069
+ } catch (error) {
3070
+ reader.fail("starting_time", error instanceof Error ? error.message : String(error));
3071
+ return;
3072
+ }
3073
+ return timeZone === void 0 && startingTime === void 0 ? void 0 : {
3074
+ ...startingTime === void 0 ? {} : { startingTime },
3075
+ ...timeZone === void 0 ? {} : { timeZone }
3076
+ };
3077
+ }
3078
+ function readAuthor(reader) {
3079
+ if (reader === void 0) return void 0;
3080
+ const name = reader.string("name", { required: true });
3081
+ const url = reader.string("url");
3082
+ return name === void 0 ? void 0 : {
3083
+ name,
3084
+ ...url === void 0 ? {} : { url }
3085
+ };
3086
+ }
3087
+ function parseWorldFile(text) {
3088
+ const issues = [];
3089
+ const reader = Reader.fromJson(text, issues);
3090
+ if (reader === void 0) return {
3091
+ ok: false,
3092
+ issues
3093
+ };
3094
+ const id = readIdentifier(reader);
3095
+ const name = reader.string("name", { required: true });
3096
+ const description = reader.text("description");
3097
+ const tags = reader.object("metadata")?.strings("tags") ?? [];
3098
+ const author = readAuthor(reader.object("author"));
3099
+ const rawVersion = reader.raw("version");
3100
+ if (rawVersion !== void 0 && rawVersion !== null && typeof rawVersion !== "string" && typeof rawVersion !== "number") reader.fail("version", "must be text or a number");
3101
+ const version = (typeof rawVersion === "string" || typeof rawVersion === "number" ? String(rawVersion).trim() : "") || void 0;
3102
+ if (version !== void 0 && version.length > 40) reader.fail("version", `is longer than 40 characters`);
3103
+ const coverMediaId = reader.string("cover_media_id");
3104
+ const opening = readOpening(reader);
3105
+ const clock = readClock(reader);
3106
+ const variables = readVariableValues(reader);
3107
+ const rules = readRules(reader);
3108
+ const tools = readTools(reader);
3109
+ const autonomyValue = reader.raw("autonomy");
3110
+ if (autonomyValue !== void 0 && autonomyValue !== null && typeof autonomyValue !== "boolean") reader.fail("autonomy", "must be true or false");
3111
+ const autonomy = autonomyValue === true ? true : void 0;
3112
+ const alternateOpenings = readAlternateOpenings(reader);
3113
+ const startQuestions = readStartQuestions(reader, alternateOpenings?.length ?? 0);
3114
+ const narrationVoice = reader.string("narration_voice")?.trim() || void 0;
3115
+ const sampling = readSampling(reader);
3116
+ const preset = reader.string("preset")?.trim() || void 0;
3117
+ if (preset !== void 0 && !isPresetName(preset)) reader.fail("preset", "must be the name of a preset: letters, digits, \"-\" and \"_\"");
3118
+ const lorebooks = reader.strings("lorebooks").map((entry) => entry.trim()).filter((entry) => entry !== "");
3119
+ for (const [index, entry] of lorebooks.entries()) if (!isLorebookName(entry)) reader.fail(`lorebooks[${index}]`, "must be the name of a lorebook: letters, digits, \"-\" and \"_\"");
3120
+ if (name === void 0 || issues.length > 0) return {
3121
+ ok: false,
3122
+ issues
3123
+ };
3124
+ return {
3125
+ ok: true,
3126
+ value: {
3127
+ ...id === void 0 ? {} : { id },
3128
+ name,
3129
+ description,
3130
+ tags,
3131
+ ...author === void 0 ? {} : { author },
3132
+ ...version === void 0 ? {} : { version },
3133
+ ...coverMediaId === void 0 ? {} : { coverMediaId },
3134
+ ...opening === void 0 ? {} : { opening },
3135
+ ...clock === void 0 ? {} : { clock },
3136
+ ...variables === void 0 ? {} : { variables },
3137
+ ...rules === void 0 ? {} : { rules },
3138
+ ...tools === void 0 ? {} : { tools },
3139
+ ...autonomy === void 0 ? {} : { autonomy },
3140
+ ...alternateOpenings === void 0 ? {} : { alternateOpenings },
3141
+ ...startQuestions === void 0 ? {} : { startQuestions },
3142
+ ...narrationVoice === void 0 ? {} : { narrationVoice },
3143
+ ...sampling === void 0 ? {} : { sampling },
3144
+ ...preset === void 0 ? {} : { preset },
3145
+ ...lorebooks.length === 0 ? {} : { lorebooks: [...new Set(lorebooks)] }
3146
+ }
3147
+ };
3148
+ }
3149
+ // src/host/decisions/route.ts
3150
+ /** The probability from which a yes is taken as a yes, for the confidence a chat asks. */
3151
+ const yesAt = (confidence) => (1 + confidence) / 2;
3152
+ /** The probability up to which a no is taken as a no. */
3153
+ const noAt = (confidence) => (1 - confidence) / 2;
3154
+ const clip = (text) => text.length > 120 ? `${text.slice(0, 119)}…` : text;
3155
+ const reportOf = (mode, items) => ({
3156
+ mode,
3157
+ items,
3158
+ decided: 0,
3159
+ escalated: 0,
3160
+ fallbacks: 0,
3161
+ agreed: 0,
3162
+ disagreed: 0,
3163
+ decisionMs: 0,
3164
+ llmMs: 0,
3165
+ samples: []
3166
+ });
3167
+ async function timed(run) {
3168
+ const started = performance.now();
3169
+ return {
3170
+ value: await run(),
3171
+ ms: Math.round(performance.now() - started)
3172
+ };
3173
+ }
3174
+ /**
3175
+ * Gives each key a verdict the way its site is set to: from the language model, from the decision model, from the decision model where it
3176
+ * is confident and the language model elsewhere, or from the language model while comparing it with the decision model. A decision model
3177
+ * that cannot be used never stops a story: its keys go to the language model and the report says why.
3178
+ */
3179
+ async function routeVerdicts(route, signal) {
3180
+ const { mode, keys } = route;
1997
3181
  const report = reportOf(mode, keys.length);
1998
3182
  const verdicts = /* @__PURE__ */ new Map();
1999
3183
  if (keys.length === 0) return {
@@ -2586,6 +3770,7 @@ const emptyExtracted = () => ({
2586
3770
  items: [],
2587
3771
  lore: [],
2588
3772
  prompts: [],
3773
+ rules: [],
2589
3774
  variables: [],
2590
3775
  casting: [],
2591
3776
  commands: [],
@@ -3135,7 +4320,7 @@ const LORE_SUBJECT = {
3135
4320
  function loreDocuments(answer, roster, taken) {
3136
4321
  return objects(answer["entries"]).flatMap((entry) => {
3137
4322
  const title = text(entry["title"]);
3138
- const body = text(entry["body"]);
4323
+ const body = withoutOutputMarkup(text(entry["body"]));
3139
4324
  if (title === "" || body === "") return [];
3140
4325
  const notes = [];
3141
4326
  const subjects = [];
@@ -3165,7 +4350,7 @@ function loreDocuments(answer, roster, taken) {
3165
4350
  id: uniqueKey(slug(title, "lore"), taken),
3166
4351
  title,
3167
4352
  kind,
3168
- summary: text(entry["summary"]),
4353
+ summary: withoutOutputMarkup(text(entry["summary"])),
3169
4354
  body
3170
4355
  };
3171
4356
  put(document, "subjects", subjects);
@@ -3508,7 +4693,7 @@ async function extractEntities(ctx, card, items, classified, roster) {
3508
4693
  result: GUIDANCE_SCHEMA,
3509
4694
  check: (value) => passageProblem(value, item.text)
3510
4695
  });
3511
- const passages = (field) => answer[field].filter((passage) => passage.trim() !== "");
4696
+ const passages = (field) => answer[field].map(withoutOutputMarkup).filter((passage) => passage.trim() !== "");
3512
4697
  return {
3513
4698
  item,
3514
4699
  casting: passages("casting"),
@@ -3578,6 +4763,11 @@ const STYLE_SCHEMA = {
3578
4763
  items: { type: "string" },
3579
4764
  description: "What the instructions contained that is not prose or behaviour guidance (rules of the game, formats, panels, scripts), one short phrase each."
3580
4765
  },
4766
+ world_rules: {
4767
+ type: "array",
4768
+ items: { type: "string" },
4769
+ description: "The rules of the world the instructions lay down: what exists, does not exist or may not happen in the story (for example \"there are no firearms\"), one short sentence each, in the language of the instructions, as faithfully as they say it. Not style, not formats, not anything about the player or tools. Empty when there are none."
4770
+ },
3581
4771
  persona_names: {
3582
4772
  type: "array",
3583
4773
  items: { type: "string" },
@@ -3587,6 +4777,7 @@ const STYLE_SCHEMA = {
3587
4777
  required: [
3588
4778
  "narration",
3589
4779
  "characters",
4780
+ "world_rules",
3590
4781
  "left_out",
3591
4782
  "persona_names"
3592
4783
  ]
@@ -3598,6 +4789,11 @@ function instructionPieces(card, items, classified) {
3598
4789
  const pieces = items.filter((item) => mainRole(classified[item.id] ?? { roles: [] }) === "instruction").map((item) => item.text);
3599
4790
  return [...fields, ...pieces];
3600
4791
  }
4792
+ function ruleProblem(rules) {
4793
+ if (rules.length > 30) return `world_rules has ${rules.length} rules; keep the 30 that matter most`;
4794
+ const long = rules.find((rule) => rule.length > 300);
4795
+ return long === void 0 ? void 0 : `a world rule is ${long.length} characters long; each is one sentence of at most 300`;
4796
+ }
3601
4797
  function styleProblem(id, value, personas = []) {
3602
4798
  const named = personas.find((name) => name.trim() !== "" && value.toLowerCase().includes(name.trim().toLowerCase()));
3603
4799
  if (named !== void 0) return `${id} uses the persona name "${named}"; say "the character" or "the narrator" instead`;
@@ -3611,17 +4807,22 @@ async function extractStyle(ctx, card, items, classified) {
3611
4807
  const pieces = piecesOfTexts(card, items, texts);
3612
4808
  return {
3613
4809
  ...made,
3614
- derived: made.prompts.map((prompt) => ({
4810
+ derived: [...made.prompts.map((prompt) => ({
3615
4811
  kind: "prompt",
3616
4812
  name: prompt.id,
3617
4813
  pieces
3618
- }))
4814
+ })), ...made.rules.length === 0 ? [] : [{
4815
+ kind: "rules",
4816
+ name: "world rules",
4817
+ pieces
4818
+ }]]
3619
4819
  };
3620
4820
  }
3621
4821
  /** The prose prompts that instruction texts become, and what was left out of them. */
3622
4822
  async function extractStyleFrom(ctx, name, pieces) {
3623
4823
  if (pieces.length === 0) return {
3624
4824
  prompts: [],
4825
+ rules: [],
3625
4826
  notes: []
3626
4827
  };
3627
4828
  ctx.say("writing the style prompts");
@@ -3633,20 +4834,23 @@ async function extractStyleFrom(ctx, name, pieces) {
3633
4834
  maxTokens: 8e3,
3634
4835
  prompt,
3635
4836
  result: STYLE_SCHEMA,
3636
- check: (value) => styleProblem("roleplay/style", text(value.narration), list(value.persona_names)) ?? styleProblem("roleplay/character-style", text(value.characters), list(value.persona_names))
4837
+ check: (value) => styleProblem("roleplay/style", text(value.narration), list(value.persona_names)) ?? styleProblem("roleplay/character-style", text(value.characters), list(value.persona_names)) ?? ruleProblem(list(value.world_rules))
3637
4838
  });
3638
- const prompts = [["roleplay/style", text(answer.narration)], ["roleplay/character-style", text(answer.characters)]].flatMap(([id, body]) => body === "" ? [] : [{
4839
+ const leftOut = list(answer.left_out);
4840
+ const prompts = [["roleplay/style", withoutLeftOut(text(answer.narration), leftOut)], ["roleplay/character-style", withoutLeftOut(text(answer.characters), leftOut)]].flatMap(([id, body]) => body === "" ? [] : [{
3639
4841
  id,
3640
4842
  text: body
3641
4843
  }]);
3642
4844
  if (!prompts.every((entry) => PROSE_PROMPTS.includes(entry.id))) throw new Error("only prose prompts can be made");
3643
4845
  return {
3644
4846
  prompts,
3645
- notes: list(answer.left_out).map((entry) => `instructions not carried: ${entry}`)
4847
+ rules: list(answer.world_rules).map(withoutOutputMarkup).filter((rule) => rule.trim() !== ""),
4848
+ notes: list(answer.left_out).map((entry) => `instructions left out on purpose: ${entry}`)
3646
4849
  };
3647
4850
  } catch (error) {
3648
4851
  return {
3649
4852
  prompts: [],
4853
+ rules: [],
3650
4854
  notes: [`the instructions of the card were not carried over: ${error instanceof Error ? error.message : String(error)}`]
3651
4855
  };
3652
4856
  }
@@ -3770,12 +4974,14 @@ const VARIABLES_SCHEMA = {
3770
4974
  /** The pieces that may describe what a card tracks: its panels and formats, and its instructions. */
3771
4975
  /** What a card that keeps its game state in variables says of them: the tool that updates them names itself in the text, whatever role the piece was given. */
3772
4976
  const STATE_SPEC = /stat_data|\[mvu_|<UpdateVariable>|<initvar>|JSON ?Patch/i;
3773
- function trackingPieces(card, items, classified) {
4977
+ function trackingPieces(card, items, classified, tr) {
3774
4978
  const specs = items.filter((item) => mainRole(classified[item.id] ?? { roles: [] }) !== "irrelevant" && STATE_SPEC.test(item.text)).map((item) => item.text);
4979
+ const panels = panelsOfCard(card).map((panel) => `${tr("A status panel from one of the card's own messages (it shows which values the card keeps and where they start):")}\n${panel}`);
3775
4980
  return [.../* @__PURE__ */ new Set([
3776
4981
  ...items.filter((item) => mainRole(classified[item.id] ?? { roles: [] }) === "template").map((item) => item.text),
3777
4982
  ...instructionPieces(card, items, classified),
3778
- ...specs
4983
+ ...specs,
4984
+ ...panels
3779
4985
  ])];
3780
4986
  }
3781
4987
  /** The documents of `variables.json` an answer describes, with the roster's names turned into keys. */
@@ -3846,7 +5052,8 @@ const MAX_VARIABLE_ROUNDS = 12;
3846
5052
  const TOKENS_PER_VARIABLE = 600;
3847
5053
  /** Finds what the card keeps track of, such as status panels and meters, and writes it as the world's tracked variables. Each group of the card's tracking text is read on its own, a request declares at most `variablesPerRequest` values and is asked again, told what is declared already, while it fills its share; the first declaration of a key stands. */
3848
5054
  async function extractVariables(ctx, card, items, classified, roster) {
3849
- const groups = trackingGroups(trackingPieces(card, items, classified));
5055
+ const tr = trOf(ctx);
5056
+ const groups = trackingGroups(trackingPieces(card, items, classified, tr));
3850
5057
  if (groups.length === 0) return {
3851
5058
  variables: [],
3852
5059
  notes: [],
@@ -3854,7 +5061,6 @@ async function extractVariables(ctx, card, items, classified, roster) {
3854
5061
  };
3855
5062
  const perRequest = ctx.variablesPerRequest ?? DEFAULT_VARIABLES_PER_REQUEST;
3856
5063
  const names = (kind) => roster.filter((entity) => entity.kind === kind).map((entity) => entity.name).join(", ");
3857
- const tr = trOf(ctx);
3858
5064
  const found = await mapLimit(groups, ctx.concurrency, async (pieces, index) => {
3859
5065
  const documents = [];
3860
5066
  const notes = [];
@@ -3909,261 +5115,29 @@ async function extractVariables(ctx, card, items, classified, roster) {
3909
5115
  derived
3910
5116
  };
3911
5117
  }
3912
- // src/host/presets/presets.ts
3913
- const PRESETS_FOLDER = "presets";
3914
- const PRESET_FILE = "preset.json";
3915
- const NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
3916
- const MAX_TEXT = 300;
3917
- const isPresetName = (name) => NAME.test(name);
3918
- const presetsDirectory = (root) => join(root, PRESETS_FOLDER);
3919
- function presetDirectory(root, name) {
3920
- if (!isPresetName(name)) throw new Error(`"${name}" is not a usable preset name (letters, digits, "-" and "_", up to 64)`);
3921
- return join(presetsDirectory(root), name);
3922
- }
3923
- const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3924
- function parseHeader(value, problems) {
3925
- if (!isRecord(value)) {
3926
- problems.push(`${PRESET_FILE} must be an object`);
3927
- return { sampling: {} };
3928
- }
3929
- const text = (key) => {
3930
- const field = value[key];
3931
- if (field === void 0 || field === null) return void 0;
3932
- if (typeof field !== "string" || field.length > MAX_TEXT) {
3933
- problems.push(`${PRESET_FILE}: "${key}" must be text of at most ${MAX_TEXT} characters`);
3934
- return;
3935
- }
3936
- return field.trim() || void 0;
3937
- };
3938
- const sampling = parseSampling(value["sampling"], `${PRESET_FILE}: sampling`, problems);
3939
- const title = text("title");
3940
- const description = text("description");
3941
- return {
3942
- ...title === void 0 ? {} : { title },
3943
- ...description === void 0 ? {} : { description },
3944
- sampling
3945
- };
3946
- }
3947
- function readHeader(directory, problems) {
3948
- const file = join(directory, PRESET_FILE);
3949
- if (!existsSync(file)) return { sampling: {} };
3950
- let value;
3951
- try {
3952
- value = JSON.parse(readFileSync(file, "utf8"));
3953
- } catch {
3954
- problems.push(`${PRESET_FILE} is not valid JSON`);
3955
- return { sampling: {} };
3956
- }
3957
- return parseHeader(value, problems);
3958
- }
3959
- /** Reads one preset folder, collecting every problem instead of stopping at the first. @throws {Error} when the folder does not exist. */
3960
- function readPreset(directory, name, shipped = shippedPromptsDirectory()) {
3961
- if (!existsSync(directory)) throw new Error(`there is no preset "${name}"`);
3962
- const problems = [];
3963
- const header = readHeader(directory, problems);
3964
- const files = /* @__PURE__ */ new Map();
3965
- const base = join(directory, PROMPTS_FOLDER);
3966
- if (existsSync(base)) for (const entry of readdirSync(base, { withFileTypes: true })) {
3967
- if (!entry.isDirectory() || !LANGUAGE_FOLDER.test(entry.name)) {
3968
- problems.push(`prompts/${entry.name}: prompts are kept in a folder named by the language, such as en or zh`);
3969
- continue;
3970
- }
3971
- for (const id of listFiles(join(base, entry.name))) {
3972
- const path = `${entry.name}/${id}.md`;
3973
- const text = readFileSync(join(base, path), "utf8");
3974
- const problem = id.startsWith("roleplay/") ? promptProblem(entry.name, id, text, shipped) : `"${id}" is not a prompt of the story`;
3975
- if (problem !== void 0) problems.push(`prompts/${path}: ${problem}`);
3976
- else files.set(path, text);
3977
- }
3978
- }
3979
- if (files.size === 0 && problems.length === 0) problems.push("the preset carries no prompts");
3980
- const paths = [...files.keys()];
3981
- const ids = [...new Set(paths.map((path) => path.slice(path.indexOf("/") + 1, -3)))].sort((a, b) => a.localeCompare(b));
3982
- return {
3983
- summary: {
3984
- name,
3985
- title: header.title ?? name,
3986
- description: header.description ?? "",
3987
- languages: [...new Set(paths.map((path) => path.split("/")[0]))].sort((a, b) => a.localeCompare(b)),
3988
- prompts: ids,
3989
- rules: ids.filter((id) => !PROSE_PROMPTS.includes(id)),
3990
- sampling: header.sampling,
3991
- problems
3992
- },
3993
- files
3994
- };
3995
- }
3996
- /** Every preset in the library; one that cannot be read is listed with its problems. */
3997
- function listPresets(root) {
3998
- const folder = presetsDirectory(root);
3999
- if (!existsSync(folder)) return [];
4000
- return readdirSync(folder, { withFileTypes: true }).filter((entry) => entry.isDirectory() && isPresetName(entry.name)).map((entry) => readPreset(join(folder, entry.name), entry.name)).sort((a, b) => a.summary.name.localeCompare(b.summary.name));
4001
- }
4002
- function loadPreset(root, name) {
4003
- return readPreset(presetDirectory(root, name), name);
4004
- }
4005
- const sha = (text) => createHash("sha256").update(text).digest("hex");
4006
- /**
4007
- * Makes a preset of the prose prompts a world carries. Nothing is overwritten.
4008
- * @throws {Error} when the name is taken, the world carries no prose prompt, or what it carries is not acceptable.
4009
- */
4010
- async function savePresetFromWorld(root, worldDirectory, request) {
4011
- const target = presetDirectory(root, request.name);
4012
- if (existsSync(target)) throw new Error(`there is already a preset "${request.name}"`);
4013
- const source = join(worldDirectory, PROMPTS_FOLDER);
4014
- const found = [];
4015
- if (existsSync(source)) {
4016
- for (const entry of readdirSync(source, { withFileTypes: true })) if (entry.isDirectory() && LANGUAGE_FOLDER.test(entry.name)) {
4017
- for (const id of listFiles(join(source, entry.name))) if (PROSE_PROMPTS.includes(id)) found.push({
4018
- language: entry.name,
4019
- id
4020
- });
4021
- }
4022
- }
4023
- if (found.length === 0) throw new Error("the world carries no prose prompts to make a preset of");
4024
- const staging = join(root, ".install", `preset-${request.name}-${Date.now()}`);
4025
- try {
4026
- for (const { language, id } of found) {
4027
- const to = join(staging, PROMPTS_FOLDER, language, `${id}.md`);
4028
- await mkdir(dirname(to), { recursive: true });
4029
- await writeFile(to, readFileSync(join(source, language, `${id}.md`), "utf8"));
4030
- }
4031
- const header = {
4032
- ...request.title === void 0 || request.title.trim() === "" ? {} : { title: request.title.trim() },
4033
- ...request.description === void 0 || request.description.trim() === "" ? {} : { description: request.description.trim() },
4034
- ...request.sampling === void 0 || Object.keys(request.sampling).length === 0 ? {} : { sampling: request.sampling }
4035
- };
4036
- await writeFile(join(staging, PRESET_FILE), JSON.stringify(header, null, 2));
4037
- const loaded = readPreset(staging, request.name);
4038
- if (loaded.summary.problems.length > 0) throw new Error(`the preset would have problems: ${loaded.summary.problems.join("; ")}`);
4039
- await mkdir(presetsDirectory(root), { recursive: true });
4040
- await rename(staging, target);
4041
- return readPreset(target, request.name);
4042
- } finally {
4043
- await rm(staging, {
4044
- recursive: true,
4045
- force: true
4046
- });
4047
- }
4048
- }
4049
- /** Moves a preset out of the library into `<root>/.trash/presets/`. @returns where it went. */
4050
- async function deletePreset(root, name, now = Date.now) {
4051
- const directory = presetDirectory(root, name);
4052
- if (!existsSync(directory)) throw new Error(`there is no preset "${name}"`);
4053
- const aside = join(root, ".trash", PRESETS_FOLDER, `${name}-${now()}`);
4054
- await mkdir(dirname(aside), { recursive: true });
4055
- await rename(directory, aside);
4056
- return aside;
4057
- }
4058
- function headerFile(title, description, sampling) {
4059
- return `${JSON.stringify({
4060
- ...title === void 0 ? {} : { title },
4061
- ...description === void 0 ? {} : { description },
4062
- ...Object.keys(sampling).length === 0 ? {} : { sampling }
4063
- }, null, 2)}\n`;
4064
- }
4065
- async function writeHeader(directory, text) {
4066
- const file = join(directory, PRESET_FILE);
4067
- await writeFile(`${file}.tmp`, text);
4068
- await rename(`${file}.tmp`, file);
4069
- }
4070
- /** Changes what a preset says about itself. @throws {Error} when the preset does not exist or the change is not acceptable; nothing is written then. */
4071
- async function updatePresetInfo(root, name, change) {
4072
- const directory = presetDirectory(root, name);
4073
- if (!existsSync(directory)) throw new Error(`there is no preset "${name}"`);
4074
- const current = readHeader(directory, []);
4075
- const problems = [];
4076
- const next = parseHeader({
4077
- title: change.title ?? current.title,
4078
- description: change.description ?? current.description,
4079
- sampling: change.sampling ?? current.sampling
4080
- }, problems);
4081
- if (problems.length > 0) throw new Error(problems.join("; "));
4082
- await writeHeader(directory, headerFile(next.title, next.description, next.sampling));
4083
- return readPreset(directory, name);
4084
- }
5118
+ // src/host/serial.ts
4085
5119
  /**
4086
- * Makes a preset holding the shipped prose prompts of every language, as a starting point to edit. Nothing is overwritten.
4087
- * @throws {Error} when the name is taken or the information is not acceptable.
5120
+ * One job at a time per key. Everything asked for a key runs after what was asked before it, and a failure does not stop
5121
+ * the work that follows: the next caller is told about its own failure, not the previous one. The key is forgotten once
5122
+ * nothing is waiting, so a host that has seen many sessions does not keep them all.
4088
5123
  */
4089
- async function createPresetFromShipped(root, request, shipped = shippedPromptsDirectory()) {
4090
- const target = presetDirectory(root, request.name);
4091
- if (existsSync(target)) throw new Error(`there is already a preset "${request.name}"`);
4092
- const problems = [];
4093
- const header = parseHeader({
4094
- title: request.title?.trim(),
4095
- description: request.description?.trim(),
4096
- sampling: request.sampling
4097
- }, problems);
4098
- if (problems.length > 0) throw new Error(problems.join("; "));
4099
- const staging = join(root, ".install", `preset-${request.name}-${Date.now()}`);
4100
- try {
4101
- for (const language of shippedLanguages(shipped)) for (const id of PROSE_PROMPTS) {
4102
- const from = join(shipped, language, `${id}.md`);
4103
- if (!existsSync(from)) continue;
4104
- const to = join(staging, PROMPTS_FOLDER, language, `${id}.md`);
4105
- await mkdir(dirname(to), { recursive: true });
4106
- await writeFile(to, readFileSync(from, "utf8"));
4107
- }
4108
- await mkdir(staging, { recursive: true });
4109
- await writeHeader(staging, headerFile(header.title, header.description, header.sampling));
4110
- const loaded = readPreset(staging, request.name);
4111
- if (loaded.summary.problems.length > 0) throw new Error(`the preset would have problems: ${loaded.summary.problems.join("; ")}`);
4112
- await mkdir(presetsDirectory(root), { recursive: true });
4113
- await rename(staging, target);
4114
- return readPreset(target, request.name);
4115
- } finally {
4116
- await rm(staging, {
4117
- recursive: true,
4118
- force: true
5124
+ var SerialQueue = class {
5125
+ tails = /* @__PURE__ */ new Map();
5126
+ /** Runs `work` after the work asked for `key` before it, and resolves with its result. */
5127
+ run(key, work) {
5128
+ const run = (this.tails.get(key) ?? Promise.resolve()).then(work, work);
5129
+ const tail = run.then(() => void 0, () => void 0);
5130
+ this.tails.set(key, tail);
5131
+ tail.then(() => {
5132
+ if (this.tails.get(key) === tail) this.tails.delete(key);
4119
5133
  });
5134
+ return run;
4120
5135
  }
4121
- }
4122
- /** Makes an empty preset folder that the import is about to fill; it has no prompts yet, so it reads as having problems until it does. */
4123
- async function reservePreset(root, name, title, sampling = {}) {
4124
- const target = presetDirectory(root, name);
4125
- if (existsSync(target)) throw new Error(`there is already a preset "${name}"`);
4126
- await mkdir(target, { recursive: true });
4127
- await writeHeader(target, headerFile(title.trim().slice(0, MAX_TEXT) || void 0, void 0, sampling));
4128
- return target;
4129
- }
4130
- /**
4131
- * Makes a preset that adds guidance to the shipped prompts, in every language the program ships: each prompt keeps its shipped text and the guidance follows it, so that
4132
- * the prompt keeps naming the tools and values it needs. The guidance is the importer's, in the language it was written in.
4133
- * @throws {Error} when the name is taken, there is no guidance, or a prompt would not be acceptable; nothing is made then.
4134
- */
4135
- async function createPresetFromGuidance(root, request, guidance, shipped = shippedPromptsDirectory()) {
4136
- const target = presetDirectory(root, request.name);
4137
- if (existsSync(target)) throw new Error(`there is already a preset "${request.name}"`);
4138
- const ids = Object.keys(guidance).filter((id) => (guidance[id]?.length ?? 0) > 0);
4139
- if (ids.length === 0) throw new Error("there is no guidance to make a preset of");
4140
- const problems = [];
4141
- const header = parseHeader({
4142
- title: request.title?.trim(),
4143
- description: request.description?.trim()
4144
- }, problems);
4145
- if (problems.length > 0) throw new Error(problems.join("; "));
4146
- const staging = join(root, ".install", `preset-${request.name}-${Date.now()}`);
4147
- try {
4148
- for (const language of shippedLanguages(shipped)) for (const id of ids) {
4149
- const base = readWorldPrompt(join(staging, "none"), language, id, shipped).text.trimEnd();
4150
- const to = join(staging, PROMPTS_FOLDER, language, `${id}.md`);
4151
- await mkdir(dirname(to), { recursive: true });
4152
- await writeFile(to, `${base}\n\n${(guidance[id] ?? []).join("\n")}\n`);
4153
- }
4154
- await writeHeader(staging, headerFile(header.title, header.description, {}));
4155
- const loaded = readPreset(staging, request.name);
4156
- if (loaded.summary.problems.length > 0) throw new Error(`the preset would have problems: ${loaded.summary.problems.join("; ")}`);
4157
- await mkdir(presetsDirectory(root), { recursive: true });
4158
- await rename(staging, target);
4159
- return readPreset(target, request.name);
4160
- } finally {
4161
- await rm(staging, {
4162
- recursive: true,
4163
- force: true
4164
- });
5136
+ /** How many keys have work waiting or running; for tests and diagnostics. */
5137
+ get pending() {
5138
+ return this.tails.size;
4165
5139
  }
4166
- }
4167
- export { IMPORT_FOLDER as $, sourcesFor as A, InvalidEditProblems as At, modeFor as B, WEEKDAY_NAMES as Bt, inert as C, parseSlotsFile as Ct, pruneLoreSubjects as D, parseCharacterFile as Dt, pruneLinks as E, CHARACTER_FILE_NAME as Et, ROLE_TABLE as F, parseRelationEdit as Ft, deleteWorldPrompt as G, routeVerdicts as H, INTENT_STATUSES as Ht, isLeftOut as I, parseThingEdit as It, writeWorldPrompt as J, listWorldPrompts as K, announceProblem as L, guarded as Lt, classifyItems as M, parseFactionEdit as Mt, findEntity as N, parseLoreEdit as Nt, pruneMembers as O, readVariableValues as Ot, ROLES as P, parsePlaceEdit as Pt, withPlayer as Q, askYesNo as R, LORE_KINDS as Rt, extractVariables as S, parseItemFile as St, pruneKnowledge as T, parseFactionFile as Tt, yesAt as U, noAt as V, DEFAULT_SLOTS as Vt, PROSE_PROMPTS as W, itemise as X, cleanText as Y, partsOf as Z, characterDocument as _, parseLoreFile as _t, isPresetName as a, readImportFolder as at, extractStyle as b, ITEM_FILE_NAME as bt, presetDirectory as c, sourceSummary as ct, savePresetFromWorld as d, parseAuthoringCommand as dt, ImportNotFoundError as et, sha as f, VARIABLES_FILE_NAME as ft, asWritten as g, LORE_FILE_NAME as gt, addLore as h, variableProblems as ht, deletePreset as i, parseChoices as it, buildRoster as j, parseCharacterEdit as jt, pruneRelationships as k, readIdentifier as kt, readPreset as l, IMPORT_COMMAND as lt, STANDING_PROMPT as m, parseVariablesFile as mt, createPresetFromGuidance as n, PICTURE_FILE as nt, listPresets as o, writeChoices as ot, updatePresetInfo as p, loadVariables as pt, readWorldPrompt as q, createPresetFromShipped as r, openingText as rt, loadPreset as s, dialectOf as st, PRESET_FILE as t, ImportStore as tt, reservePreset as u, parseImportCommand as ut, emptyExtracted as v, LOCATION_FILE_NAME as vt, loreDocuments as w, FACTION_FILE_NAME as wt, extractStyleFrom as x, SLOTS_FILE_NAME as xt, extractEntities as y, parseLocationFile as yt, mergeReports as z, LORE_SCOPES as zt };
5140
+ };
5141
+ export { deleteWorldPrompt as $, subfolders as $t, routeVerdicts as A, parseAuthoringCommand as At, createPresetFromGuidance as B, loadLore as Bt, ROLE_TABLE as C, PICTURE_FILE as Ct, mergeReports as D, writeChoices as Dt, askYesNo as E, readImportFolder as Et, parseWorldInfoEdit as F, VARIABLES_FILE_NAME as Ft, loadPreset as G, ITEM_FILE_NAME as Gt, deletePreset as H, parseLoreFile as Ht, combineAnswers as I, loadVariables as It, reservePreset as J, parseSlotsFile as Jt, presetDirectory as K, SLOTS_FILE_NAME as Kt, questionView as L, parseVariablesFile as Lt, WORLD_FILE_NAME as M, splitPanels as Mt, parseWorldFile as N, dialectOf as Nt, modeFor as O, IMPORT_COMMAND as Ot, MAX_OPENING_CHARS as P, sourceSummary as Pt, PROSE_PROMPTS as Q, parseCharacterFile as Qt, startQuestionsToFile as R, variableProblems as Rt, ROLES as S, ImportStore as St, announceProblem as T, parseChoices as Tt, isPresetName as U, LOCATION_FILE_NAME as Ut, createPresetFromShipped as V, LORE_FILE_NAME as Vt, listPresets as W, parseLocationFile as Wt, sha as X, parseFactionFile as Xt, savePresetFromWorld as Y, FACTION_FILE_NAME as Yt, updatePresetInfo as Z, CHARACTER_FILE_NAME as Zt, pruneRelationships as _, itemise as _t, characterDocument as a, parseRelationEdit as an, deleteLorebook as at, classifyItems as b, IMPORT_FOLDER as bt, extractStyle as c, LORE_KINDS as cn, isLorebookName as ct, inert as d, DEFAULT_SLOTS as dn, lorebookDirectory as dt, InvalidEditProblems as en, listWorldPrompts as et, loreDocuments as f, INTENT_STATUSES as fn, readLorebook as ft, pruneMembers as g, cleanText as gt, pruneLoreSubjects as h, writeLorebookEntry as ht, asWritten as i, parsePlaceEdit as in, createLorebook as it, yesAt as j, findPanel as jt, noAt as k, parseImportCommand as kt, extractStyleFrom as l, LORE_SCOPES as ln, listLorebooks as lt, pruneLinks as m, updateLorebookInfo as mt, STANDING_PROMPT as n, parseFactionEdit as nn, writeWorldPrompt as nt, emptyExtracted as o, parseThingEdit as on, deleteLorebookEntry as ot, pruneKnowledge as p, reserveLorebook as pt, readPreset as q, parseItemFile as qt, addLore as r, parseLoreEdit as rn, addLorebookEntries as rt, extractEntities as s, guarded as sn, entriesOf as st, SerialQueue as t, parseCharacterEdit as tn, readWorldPrompt as tt, extractVariables as u, WEEKDAY_NAMES as un, loadLorebook as ut, sourcesFor as v, partsOf as vt, isLeftOut as w, openingText as wt, findEntity as x, ImportNotFoundError as xt, buildRoster as y, withPlayer as yt, PRESET_FILE as z, LORE_DIR as zt };
4168
5142
 
4169
- //# sourceMappingURL=presets-_U-xroo0.js.map
5143
+ //# sourceMappingURL=serial-BZNeK57v.js.map