@dsh-agentic-roleplay/core 0.3.4 → 0.3.5

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.
@@ -1,15 +1,14 @@
1
- import { _ as API_PREFIX, a as packIds, b as INTENT_TYPES, d as packPath, f as readPack, h as PACK_MEDIA_TYPES, l as isPackId, v as INTENT_HORIZONS, y as INTENT_STATUSES } from "./packs-BYjrAen6.js";
1
+ import { b as INTENT_TYPES, i as isPresetName, p as PROSE_PROMPTS, v as INTENT_HORIZONS, y as INTENT_STATUSES } from "./presets-DNjNxQL5.js";
2
2
  import { c as VARIABLE_SUBJECTS, i as parseSwitchboard, l as VARIABLE_VISIBILITIES, s as VARIABLE_KINDS } from "./settings-CA6icLL_.js";
3
- import { E as InvalidWorldError, S as shippedPromptsDirectory, b as promptProblem, c as parsePlotsFile, d as errorMessage, f as Reader, i as textLanguage, l as plotReferenceProblems, m as PROMPTS_FOLDER, n as STORY_LANGUAGES, o as PLOTS_FILE_NAME, p as formatIssue, r as isStoryLanguage, s as loadPlots, t as LANGUAGE_NAMES, u as readDocument, v as languageOf, x as shippedLanguages, y as listFiles } from "./language-DWVwi1R7.js";
3
+ import { S as InvalidWorldError, _ as shippedLanguages, a as readDocument, c as formatIssue, g as promptProblem, i as plotReferenceProblems, n as loadPlots, o as errorMessage, s as Reader, u as PROMPTS_FOLDER } from "./load-Clkl0T7C.js";
4
4
  import { a as runChild } from "./child-CFjnaTZt.js";
5
- import { C as norm, S as mapLimit, T as uniqueKey, a as uploadReferenceImage, h as MEDIA_TYPES, o as addToLibrary, p as referenceImagePath, s as imageExtensionOf, t as generateReferenceImage, w as slug, y as writeImageFileMetadata } from "./generator-B6FxlKOV.js";
6
- import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
7
- import { existsSync, lstatSync, readFileSync, readdirSync, statSync } from "node:fs";
5
+ import { b as slug, c as referenceImagePath, d as MEDIA_TYPES, h as writeImageFileMetadata, n as imageExtensionOf, t as addToLibrary, v as mapLimit, x as uniqueKey, y as norm } from "./library-9JB9zw5a.js";
6
+ import { dirname, join } from "node:path";
8
7
  import { createHash, randomUUID } from "node:crypto";
9
8
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
10
9
  import { inflateSync } from "node:zlib";
11
10
  import { defineTool } from "@deepseek-ai/dsh-tools";
12
- import { chmod, cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
11
+ import { cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
13
12
  import { MAX_ROUTINE_WINDOWS, MINUTE, MONTH_NAMES, SEASONS, checkProblems, createSessionStore, dayTokenProblems, isTimeZone, parseInstant, parseTimeOfDay, readTriggerDefinition, triggerReferenceProblems, valueIssue, writeCalendar } from "@dsh-agentic-roleplay/state";
14
13
  import { lookup } from "node:dns";
15
14
  import { request } from "node:http";
@@ -192,7 +191,7 @@ function chunksOf(file) {
192
191
  return chunks;
193
192
  }
194
193
  /** The keyword and text of a PNG text chunk. */
195
- function textOf$1(chunk) {
194
+ function textOf(chunk) {
196
195
  const end = chunk.data.indexOf(0);
197
196
  if (end < 0) return void 0;
198
197
  const keyword = chunk.data.toString("latin1", 0, end);
@@ -224,7 +223,7 @@ function jsonOf(file, name) {
224
223
  const found = /* @__PURE__ */ new Map();
225
224
  for (const chunk of chunksOf(file)) {
226
225
  if (!TEXT_CHUNKS.has(chunk.type)) continue;
227
- const text = textOf$1(chunk);
226
+ const text = textOf(chunk);
228
227
  if (text !== void 0 && CARD_KEYWORDS.includes(text.keyword) && !found.has(text.keyword)) found.set(text.keyword, text.text);
229
228
  }
230
229
  const keyword = CARD_KEYWORDS.find((candidate) => found.has(candidate));
@@ -257,11 +256,11 @@ function urlsOf(value) {
257
256
  visit(value, 0);
258
257
  return [...found];
259
258
  }
260
- const object$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
259
+ const object = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
261
260
  const text$2 = (value) => typeof value === "string" ? value : typeof value === "number" ? String(value) : "";
262
261
  const texts = (value) => Array.isArray(value) ? value.flatMap((entry) => typeof entry === "string" ? [entry] : typeof entry === "number" ? [String(entry)] : []) : [];
263
262
  function entryOf(value, index) {
264
- const entry = object$1(value);
263
+ const entry = object(value);
265
264
  if (entry === void 0) return void 0;
266
265
  const position = entry["position"];
267
266
  return {
@@ -282,17 +281,17 @@ function entryOf(value, index) {
282
281
  * @throws {ImportCardError} when the file is not such a card.
283
282
  */
284
283
  function readCard(file, name) {
285
- const root = object$1(jsonOf(file, name));
284
+ const root = object(jsonOf(file, name));
286
285
  const spec = root === void 0 ? void 0 : root["spec"];
287
286
  if (spec !== "chara_card_v2" && spec !== "chara_card_v3") throw new ImportCardError(spec === void 0 ? `${name} is not a V2 or V3 character card (it has no "spec")` : `${name} is a "${text$2(spec)}" card: only V2 and V3 cards are read`);
288
- const data = object$1(root?.["data"]);
287
+ const data = object(root?.["data"]);
289
288
  if (data === void 0) throw new ImportCardError(`${name} has no card data`);
290
289
  const cardName = text$2(data["name"]).trim();
291
290
  if (cardName === "") throw new ImportCardError(`${name} has a card with no name`);
292
- const book = object$1(data["character_book"]);
291
+ const book = object(data["character_book"]);
293
292
  const entries = Array.isArray(book?.["entries"]) ? book["entries"].flatMap((entry, index) => entryOf(entry, index) ?? []) : [];
294
- const extensions = object$1(data["extensions"]) ?? {};
295
- const scripts = [extensions["regex_scripts"], object$1(extensions["tavern_helper"])?.["scripts"]].reduce((count, list) => count + (Array.isArray(list) ? list.length : 0), 0);
293
+ const extensions = object(data["extensions"]) ?? {};
294
+ const scripts = [extensions["regex_scripts"], object(extensions["tavern_helper"])?.["scripts"]].reduce((count, list) => count + (Array.isArray(list) ? list.length : 0), 0);
296
295
  return {
297
296
  sourceSpec: spec,
298
297
  name: cardName,
@@ -905,7 +904,8 @@ const TEXT_FIELDS = [
905
904
  "authorUrl",
906
905
  "timeZone",
907
906
  "startingTime",
908
- "version"
907
+ "version",
908
+ "preset"
909
909
  ];
910
910
  const LIST_FIELDS = ["tags", "rules"];
911
911
  /** Reads a body that came from the browser; every field is checked and each problem is reported. */
@@ -1084,6 +1084,8 @@ function parseWorldFile(text) {
1084
1084
  const tools = readTools(reader);
1085
1085
  const alternateOpenings = readAlternateOpenings(reader);
1086
1086
  const narrationVoice = reader.string("narration_voice")?.trim() || void 0;
1087
+ const preset = reader.string("preset")?.trim() || void 0;
1088
+ if (preset !== void 0 && !isPresetName(preset)) reader.fail("preset", "must be the name of a preset: letters, digits, \"-\" and \"_\"");
1087
1089
  if (name === void 0 || issues.length > 0) return {
1088
1090
  ok: false,
1089
1091
  issues
@@ -1104,7 +1106,8 @@ function parseWorldFile(text) {
1104
1106
  ...rules === void 0 ? {} : { rules },
1105
1107
  ...tools === void 0 ? {} : { tools },
1106
1108
  ...alternateOpenings === void 0 ? {} : { alternateOpenings },
1107
- ...narrationVoice === void 0 ? {} : { narrationVoice }
1109
+ ...narrationVoice === void 0 ? {} : { narrationVoice },
1110
+ ...preset === void 0 ? {} : { preset }
1108
1111
  }
1109
1112
  };
1110
1113
  }
@@ -2154,72 +2157,6 @@ function withPlayer(text, name) {
2154
2157
  return text.replace(/\[PLAYER\]|\{\{\s*user\s*\}\}/g, playerWord(text, name));
2155
2158
  }
2156
2159
  //#endregion
2157
- //#region src/host/prompts/world-prompts.ts
2158
- /** The prompts that decide how the story is written and who the models are (prose and persona); every other prompt holds rules of the game. */
2159
- const PROSE_PROMPTS = [
2160
- "roleplay/persona",
2161
- "roleplay/style",
2162
- "roleplay/character-style"
2163
- ];
2164
- function shippedFile(shipped, language, id) {
2165
- return [language, "en"].map((name) => join(shipped, name, `${id}.md`)).find((path) => existsSync(path));
2166
- }
2167
- function fileOf(directory, language, id, shipped) {
2168
- const problem = promptProblem(language, id, "x", shipped);
2169
- if (!id.startsWith("roleplay/")) throw new Error(`"${id}" is not a prompt of the story; the ones that can be carried are listed by list_world_prompts`);
2170
- if (problem !== void 0 && problem.startsWith("there is no prompt")) throw new Error(problem);
2171
- return join(directory, PROMPTS_FOLDER, language, `${id}.md`);
2172
- }
2173
- /** Every prompt of the story, in a language, and whether the world carries its own version. */
2174
- function listWorldPrompts(directory, language, shipped = shippedPromptsDirectory()) {
2175
- const tag = languageOf(language);
2176
- return readdirSync(join(shipped, "en"), { withFileTypes: true }).filter((entry) => entry.isDirectory() && entry.name !== "import" && entry.name !== "world").flatMap((entry) => listFiles(join(shipped, "en", entry.name), `${entry.name}/`)).sort().map((id) => ({
2177
- id,
2178
- kind: PROSE_PROMPTS.includes(id) ? "prose" : "rules",
2179
- carried: existsSync(join(directory, PROMPTS_FOLDER, tag, `${id}.md`))
2180
- }));
2181
- }
2182
- /** A prompt as sessions of the world get it: the world's own version, else the shipped text. */
2183
- function readWorldPrompt(directory, language, id, shipped = shippedPromptsDirectory()) {
2184
- const tag = languageOf(language);
2185
- const own = fileOf(directory, tag, id, shipped);
2186
- if (existsSync(own)) return {
2187
- id,
2188
- language: tag,
2189
- carried: true,
2190
- text: readFileSync(own, "utf8")
2191
- };
2192
- const original = shippedFile(shipped, tag, id);
2193
- return {
2194
- id,
2195
- language: tag,
2196
- carried: false,
2197
- text: original === void 0 ? "" : readFileSync(original, "utf8")
2198
- };
2199
- }
2200
- /** @throws {Error} when the text is not acceptable for the prompt: see `promptProblem`. */
2201
- async function writeWorldPrompt(directory, language, id, text, shipped = shippedPromptsDirectory()) {
2202
- const tag = languageOf(language);
2203
- const file = fileOf(directory, tag, id, shipped);
2204
- const problem = promptProblem(tag, id, text, shipped);
2205
- if (problem !== void 0) throw new Error(problem);
2206
- await mkdir(dirname(file), { recursive: true });
2207
- const temporary = `${file}.tmp`;
2208
- await writeFile(temporary, text.endsWith("\n") ? text : `${text}\n`);
2209
- await rename(temporary, file);
2210
- }
2211
- /** Moves the world's own version into its `.trash`, so sessions use the shipped one again. @returns where it went. */
2212
- async function deleteWorldPrompt(directory, language, id, shipped = shippedPromptsDirectory()) {
2213
- const tag = languageOf(language);
2214
- const file = fileOf(directory, tag, id, shipped);
2215
- if (!existsSync(file)) throw new Error(`the world carries no prompt "${id}" in ${tag}`);
2216
- const aside = join(directory, ".trash", PROMPTS_FOLDER, tag, `${id}.${Date.now()}.md`);
2217
- await mkdir(dirname(aside), { recursive: true });
2218
- await rename(file, aside);
2219
- await rm(dirname(file), { recursive: false }).catch(() => void 0);
2220
- return aside;
2221
- }
2222
- //#endregion
2223
2160
  //#region src/host/import/survey.ts
2224
2161
  const ROLES = [
2225
2162
  "character",
@@ -5554,559 +5491,6 @@ async function finish(ctx, world) {
5554
5491
  return result;
5555
5492
  }
5556
5493
  //#endregion
5557
- //#region src/host/translate/terms.ts
5558
- const STOP = /* @__PURE__ */ new Set([
5559
- "the",
5560
- "and",
5561
- "for",
5562
- "with",
5563
- "from",
5564
- "that",
5565
- "this",
5566
- "his",
5567
- "her",
5568
- "their",
5569
- "she",
5570
- "he",
5571
- "they",
5572
- "you",
5573
- "your",
5574
- "but",
5575
- "not",
5576
- "when",
5577
- "where",
5578
- "what",
5579
- "who",
5580
- "one",
5581
- "two",
5582
- "its",
5583
- "has",
5584
- "had",
5585
- "was",
5586
- "were",
5587
- "are",
5588
- "there",
5589
- "then",
5590
- "now",
5591
- "at",
5592
- "in",
5593
- "on",
5594
- "of",
5595
- "to",
5596
- "a",
5597
- "an"
5598
- ]);
5599
- const MAX_TERMS = 40;
5600
- const MIN_USES = 3;
5601
- const capitalised = (word) => /^\p{Lu}[\p{L}'’-]{2,}$/u.test(word) && !STOP.has(word.toLowerCase());
5602
- /** The parts of a name written "Place - Room": each part is a name of its own, and so is the whole. */
5603
- function partsOfName(name) {
5604
- return name.split(/\s+[-–—]\s+/).map((part) => part.trim()).filter((part) => part !== "");
5605
- }
5606
- /**
5607
- * Words of the world that recur inside other names and texts and so have to be rendered once: the parts of names ("Iron Stag Inn" in "Iron Stag Inn - Bar") and capitalised
5608
- * phrases of two or three words that the texts use again and again ("Iron Stag"). The most used come first; names are not repeated here.
5609
- */
5610
- function recurringTerms(names, texts) {
5611
- const known = new Set(names);
5612
- const found = /* @__PURE__ */ new Map();
5613
- const add = (term, uses) => {
5614
- if (!known.has(term)) found.set(term, (found.get(term) ?? 0) + uses);
5615
- };
5616
- for (const name of names) for (const part of partsOfName(name)) if (part !== name) add(part, MIN_USES);
5617
- const counts = /* @__PURE__ */ new Map();
5618
- for (const text of [...names, ...texts]) {
5619
- const words = text.split(/[^\p{L}'’-]+/u);
5620
- for (let at = 0; at < words.length; at += 1) for (const size of [2, 3]) {
5621
- const phrase = words.slice(at, at + size);
5622
- if (phrase.length !== size || !phrase.every((word) => capitalised(word.replace(/['’]s$/, "")))) continue;
5623
- const key = phrase.join(" ").replace(/['’]s$/, "");
5624
- counts.set(key, (counts.get(key) ?? 0) + 1);
5625
- }
5626
- }
5627
- for (const [phrase, uses] of counts) if (uses >= MIN_USES) add(phrase, uses);
5628
- return [...found].sort((a, b) => b[1] - a[1]).slice(0, MAX_TERMS).map(([term]) => term);
5629
- }
5630
- /** Whether `text` uses `term` as a word of its own (case as written). */
5631
- function usesTerm(text, term) {
5632
- const escaped = term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5633
- return new RegExp(`(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`, "u").test(text);
5634
- }
5635
- //#endregion
5636
- //#region src/host/translate/prose.ts
5637
- const rooted = (roots, paths) => roots.flatMap((root) => paths.map((path) => `${root}${path}`));
5638
- const INTENT = [
5639
- ".name",
5640
- ".description",
5641
- ".plan[]",
5642
- ".open_threads[]",
5643
- ".constraints[]"
5644
- ];
5645
- const FIELDS$1 = {
5646
- world: {
5647
- names: ["name"],
5648
- text: [
5649
- "description",
5650
- "rules[]",
5651
- "metadata.tags[]",
5652
- "opening_message",
5653
- "opening_message[].text",
5654
- "alternate_openings[].title",
5655
- "alternate_openings[].text"
5656
- ]
5657
- },
5658
- calendar: {
5659
- names: ["holidays[].name"],
5660
- text: []
5661
- },
5662
- variables: {
5663
- names: [],
5664
- text: rooted(["[]", "variables[]"], [
5665
- ".name",
5666
- ".description",
5667
- ".bands[].label"
5668
- ])
5669
- },
5670
- triggers: {
5671
- names: [],
5672
- text: rooted(["[]", "triggers[]"], [
5673
- ".name",
5674
- ".announce.text",
5675
- ".effects[].text",
5676
- ".effects[].edit.events[].text"
5677
- ])
5678
- },
5679
- plots: {
5680
- names: [],
5681
- text: [
5682
- "plots[].name",
5683
- "plots[].premise",
5684
- "plots[].themes[]",
5685
- "plots[].stakes[]",
5686
- "plots[].resolutions[]",
5687
- ...["hooks", "developments"].flatMap((list) => [
5688
- `plots[].${list}[].text`,
5689
- `plots[].${list}[].prerequisites[]`,
5690
- `plots[].${list}[].guidance`,
5691
- `plots[].${list}[].avoid[]`
5692
- ])
5693
- ]
5694
- },
5695
- character: {
5696
- names: ["name", "aliases[]"],
5697
- text: [
5698
- "age",
5699
- "gender",
5700
- "summary",
5701
- "personality",
5702
- "background",
5703
- "appearance",
5704
- "speech.style",
5705
- "speech.examples[]",
5706
- "start.public_state",
5707
- "start.inner_state",
5708
- "start.activity",
5709
- ...INTENT.map((path) => `start.intents[]${path}`),
5710
- "relationships[].label",
5711
- "relationships[].summary",
5712
- "routine[].activity",
5713
- "visual_identity.description"
5714
- ]
5715
- },
5716
- location: {
5717
- names: ["name", "features[].name"],
5718
- text: [
5719
- "description",
5720
- "features[].description",
5721
- "exits[].description",
5722
- "exits[].note",
5723
- "exits[].back_description",
5724
- "visual_identity.description"
5725
- ]
5726
- },
5727
- item: {
5728
- names: ["name"],
5729
- text: [
5730
- "description",
5731
- "quality",
5732
- "visual_identity.description"
5733
- ]
5734
- },
5735
- faction: {
5736
- names: ["name", "aliases[]"],
5737
- text: [
5738
- "summary",
5739
- "description",
5740
- "values[]",
5741
- "structure",
5742
- "start.public_state",
5743
- "start.inner_state",
5744
- ...INTENT.map((path) => `start.goals[]${path}`),
5745
- "members[].role",
5746
- "members[].rank",
5747
- "relationships[].label",
5748
- "relationships[].summary"
5749
- ]
5750
- },
5751
- lore: {
5752
- names: [],
5753
- text: [
5754
- "title",
5755
- "summary",
5756
- "body"
5757
- ]
5758
- }
5759
- };
5760
- /** The strings of a document that are words for a reader, in document order; strings with no letters need no translation and are left out. */
5761
- function leavesOf(kind, document) {
5762
- const fields = FIELDS$1[kind];
5763
- const names = new Set(fields.names);
5764
- const text = new Set(fields.text);
5765
- const leaves = [];
5766
- const visit = (value, pattern, path) => {
5767
- if (typeof value === "string") {
5768
- const name = names.has(pattern);
5769
- if ((name || text.has(pattern)) && /\p{L}/u.test(value)) leaves.push({
5770
- path,
5771
- text: value,
5772
- name
5773
- });
5774
- } else if (Array.isArray(value)) value.forEach((entry, index) => {
5775
- visit(entry, `${pattern}[]`, [...path, index]);
5776
- });
5777
- else if (typeof value === "object" && value !== null) for (const [key, entry] of Object.entries(value)) visit(entry, pattern === "" ? key : `${pattern}.${key}`, [...path, key]);
5778
- };
5779
- visit(document, "", []);
5780
- return leaves;
5781
- }
5782
- /** Puts `text` where `path` points in the document. */
5783
- function setLeaf(document, path, text) {
5784
- let at = document;
5785
- for (const step of path.slice(0, -1)) at = at[step];
5786
- at[path[path.length - 1]] = text;
5787
- }
5788
- const ROOT_FILES = [
5789
- ["world.json", "world"],
5790
- ["calendar.json", "calendar"],
5791
- ["variables.json", "variables"],
5792
- ["triggers.json", "triggers"],
5793
- ["plots.json", "plots"]
5794
- ];
5795
- const ENTITIES = [
5796
- [
5797
- "characters",
5798
- "character.json",
5799
- "character"
5800
- ],
5801
- [
5802
- "locations",
5803
- "location.json",
5804
- "location"
5805
- ],
5806
- [
5807
- "items",
5808
- "item.json",
5809
- "item"
5810
- ],
5811
- [
5812
- "factions",
5813
- "faction.json",
5814
- "faction"
5815
- ],
5816
- [
5817
- "lore",
5818
- "lore.json",
5819
- "lore"
5820
- ]
5821
- ];
5822
- async function readIfThere(file) {
5823
- try {
5824
- return JSON.parse(await readFile(file, "utf8"));
5825
- } catch (error) {
5826
- if (error.code === "ENOENT") return void 0;
5827
- throw new Error(`${file} cannot be read: ${error instanceof Error ? error.message : String(error)}`);
5828
- }
5829
- }
5830
- /** Every file of a world that holds words for a reader. A file that does not parse stops the read: a world with a broken file is not translated. */
5831
- async function readWorldDocuments(directory) {
5832
- const found = [];
5833
- for (const [file, kind] of ROOT_FILES) {
5834
- const document = await readIfThere(join(directory, file));
5835
- if (document !== void 0) found.push({
5836
- file,
5837
- kind,
5838
- document
5839
- });
5840
- }
5841
- for (const [folder, name, kind] of ENTITIES) {
5842
- let entries;
5843
- try {
5844
- entries = (await readdir(join(directory, folder), { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
5845
- } catch (error) {
5846
- if (error.code === "ENOENT") continue;
5847
- throw error;
5848
- }
5849
- for (const entry of entries) {
5850
- const file = join(folder, entry, name);
5851
- const document = await readIfThere(join(directory, file));
5852
- if (document !== void 0) found.push({
5853
- file,
5854
- kind,
5855
- document
5856
- });
5857
- }
5858
- }
5859
- return found;
5860
- }
5861
- //#endregion
5862
- //#region src/host/translate/translate-world.ts
5863
- /** What is not carried over to a translation: the removed things of the editor and the card import's working files. */
5864
- const NOT_COPIED = /* @__PURE__ */ new Set([".trash", ".import"]);
5865
- const TERMS_PER_JOB = 40;
5866
- const TEXTS_PER_JOB = 30;
5867
- const CHARS_PER_JOB = 5e3;
5868
- const GLOSSARY_SHOWN = 60;
5869
- /** A text with fewer letters than this is too short to check which language it came out in. */
5870
- const CHECKED_LETTERS = 40;
5871
- /** A name shorter than this is too likely to be an ordinary word to be held to the glossary. */
5872
- const MIN_TERM = 4;
5873
- var TranslationRefusedError = class extends Error {};
5874
- const STRINGS = {
5875
- type: "array",
5876
- items: { type: "string" }
5877
- };
5878
- const GLOSSARY_SCHEMA = {
5879
- type: "object",
5880
- properties: { terms: {
5881
- type: "array",
5882
- items: {
5883
- type: "object",
5884
- properties: {
5885
- source: { type: "string" },
5886
- target: { type: "string" }
5887
- },
5888
- required: ["source", "target"],
5889
- additionalProperties: false
5890
- },
5891
- description: "One entry for each name given, in the same order, with the source exactly as given."
5892
- } },
5893
- required: ["terms"],
5894
- additionalProperties: false
5895
- };
5896
- const TEXTS_SCHEMA = {
5897
- type: "object",
5898
- properties: { translations: {
5899
- ...STRINGS,
5900
- description: "The translation of each text, in the order given."
5901
- } },
5902
- required: ["translations"],
5903
- additionalProperties: false
5904
- };
5905
- const BRACED = /\$?\{[^{}]*\}/g;
5906
- const braces = (text) => (text.match(BRACED) ?? []).sort().join("\0");
5907
- const letters = (text) => text.match(/\p{L}/gu)?.length ?? 0;
5908
- /** The language the world is written in, from the words of all its files; nothing when there are too few to tell. */
5909
- function languageOfDocuments(documents) {
5910
- return textLanguage(documents.flatMap((entry) => leavesOf(entry.kind, entry.document).map((leaf) => leaf.text)).join("\n"));
5911
- }
5912
- function batches(items, size, maxItems, maxSize) {
5913
- const out = [];
5914
- let current = [];
5915
- let used = 0;
5916
- for (const item of items) {
5917
- if (current.length > 0 && (current.length >= maxItems || used + size(item) > maxSize)) {
5918
- out.push(current);
5919
- current = [];
5920
- used = 0;
5921
- }
5922
- current.push(item);
5923
- used += size(item);
5924
- }
5925
- if (current.length > 0) out.push(current);
5926
- return out;
5927
- }
5928
- /** Why a set of translations cannot be used, or nothing. A text left in the language it was written in is not a translation. */
5929
- function problemWith(sources, from, translations, glossary) {
5930
- if (translations.length !== sources.length) return `${sources.length} texts were given and ${translations.length} translations came back: give exactly one for each, in order`;
5931
- for (const [index, source] of sources.entries()) {
5932
- const text = translations[index];
5933
- if (text.trim() === "") return `translation ${index + 1} is empty`;
5934
- if (braces(source) !== braces(text)) return `translation ${index + 1} must keep the text in curly braces exactly as it is: ${(source.match(BRACED) ?? []).join(" ")}`;
5935
- if (letters(source) >= CHECKED_LETTERS && textLanguage(source) === from && textLanguage(text) === from) return `translation ${index + 1} is still in the original language`;
5936
- for (const [term, rendering] of glossary) if (term.length >= MIN_TERM && rendering !== term && !rendering.includes(term) && usesTerm(source, term) && usesTerm(text, term)) return `translation ${index + 1} still has "${term}": the glossary renders it "${rendering}"`;
5937
- }
5938
- }
5939
- async function glossaryOf(ctx, names, vars, known = /* @__PURE__ */ new Map()) {
5940
- const jobs = batches(names, () => 1, TERMS_PER_JOB, TERMS_PER_JOB);
5941
- const parts = await mapLimit(jobs, ctx.concurrency, async (terms) => {
5942
- const job = {
5943
- persona: ctx.text("translate/glossary", vars),
5944
- prompt: JSON.stringify({
5945
- known: Object.fromEntries([...known].filter(([source]) => terms.some((term) => term.toLowerCase().includes(source.toLowerCase())))),
5946
- names: terms
5947
- }),
5948
- result: GLOSSARY_SCHEMA,
5949
- check: (value) => {
5950
- if (value.terms.length !== terms.length) return `${terms.length} names were given and ${value.terms.length} came back: one for each, in order`;
5951
- const wrong = terms.findIndex((term, index) => value.terms[index].source !== term || value.terms[index].target.trim() === "");
5952
- return wrong === -1 ? void 0 : `entry ${wrong + 1} must repeat "${terms[wrong]}" exactly and have a translation`;
5953
- }
5954
- };
5955
- return (await ctx.run(job)).terms;
5956
- });
5957
- return new Map(parts.flat().map((term) => [term.source, term.target.trim()]));
5958
- }
5959
- async function translated(ctx, texts, glossary, from, vars) {
5960
- return (await mapLimit(batches(texts, (text) => text.length, TEXTS_PER_JOB, CHARS_PER_JOB), ctx.concurrency, async (group) => {
5961
- const haystack = group.join("\n").toLowerCase();
5962
- const shown = [...glossary].filter(([source]) => haystack.includes(source.toLowerCase())).slice(0, GLOSSARY_SHOWN);
5963
- const relevant = new Map(shown);
5964
- const job = {
5965
- persona: ctx.text("translate/document", vars),
5966
- prompt: JSON.stringify({
5967
- glossary: Object.fromEntries(shown),
5968
- texts: group.map((text, index) => ({
5969
- n: index + 1,
5970
- text
5971
- }))
5972
- }),
5973
- result: TEXTS_SCHEMA,
5974
- check: (value) => problemWith(group, from, value.translations, relevant)
5975
- };
5976
- return (await ctx.run(job)).translations;
5977
- })).flat();
5978
- }
5979
- async function freeFolder(directory, suffix) {
5980
- for (let n = 1;; n += 1) {
5981
- const candidate = join(dirname(directory), `${basename(directory)} ${suffix}${n === 1 ? "" : ` ${n}`}`);
5982
- try {
5983
- await stat(candidate);
5984
- } catch (error) {
5985
- if (error.code === "ENOENT") return candidate;
5986
- throw error;
5987
- }
5988
- }
5989
- }
5990
- /** The ids of the Markdown prompt files under a world's prompt folder for one language (`roleplay/style`), or none when it has none. */
5991
- async function promptIds(folder, prefix = "") {
5992
- let entries;
5993
- try {
5994
- entries = await readdir(join(folder, prefix), { withFileTypes: true });
5995
- } catch (error) {
5996
- if (error.code === "ENOENT") return [];
5997
- throw error;
5998
- }
5999
- const ids = [];
6000
- for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
6001
- const id = prefix === "" ? entry.name : `${prefix}/${entry.name}`;
6002
- if (entry.isDirectory()) ids.push(...await promptIds(folder, id));
6003
- else if (entry.isFile() && entry.name.endsWith(".md")) ids.push(id.slice(0, -3));
6004
- }
6005
- return ids;
6006
- }
6007
- async function listedIn(directory, names) {
6008
- const present = new Set(await readdir(directory));
6009
- return names.filter((name) => present.has(name));
6010
- }
6011
- /**
6012
- * Makes a copy of a world in another language, next to it: the names first, so that every file calls each person, place and thing the same, then the words of each file.
6013
- * The original is never changed. The copy gets an id of its own and is checked as a story start would check it.
6014
- */
6015
- async function translateWorld(ctx, worlds, source, to, told) {
6016
- const documents = await readWorldDocuments(source.directory);
6017
- const from = languageOfDocuments(documents);
6018
- if (from === void 0) throw new TranslationRefusedError("there is too little text in this world to tell which language it is written in");
6019
- if (from === to) throw new TranslationRefusedError(`this world is already written in ${LANGUAGE_NAMES[to].en}`);
6020
- const vars = {
6021
- from: LANGUAGE_NAMES[from][told],
6022
- to: LANGUAGE_NAMES[to][told]
6023
- };
6024
- const leaves = documents.map((entry) => ({
6025
- entry,
6026
- leaves: leavesOf(entry.kind, entry.document)
6027
- }));
6028
- const names = [...new Set(leaves.flatMap((item) => item.leaves.filter((leaf) => leaf.name).map((leaf) => leaf.text)))];
6029
- ctx.say(`translating ${names.length} names`);
6030
- const prose = leaves.flatMap((item) => item.leaves.filter((leaf) => !leaf.name).map((leaf) => leaf.text));
6031
- const recurring = from === "en" ? recurringTerms(names, prose) : [];
6032
- const parts = await glossaryOf(ctx, recurring, vars);
6033
- const glossary = await glossaryOf(ctx, names, vars, parts);
6034
- for (const [term, rendering] of parts) glossary.set(term, rendering);
6035
- let texts = 0;
6036
- for (const { entry, leaves: own } of leaves) {
6037
- const words = own.filter((leaf) => !leaf.name);
6038
- for (const leaf of own.filter((item) => item.name)) setLeaf(entry.document, leaf.path, glossary.get(leaf.text) ?? leaf.text);
6039
- if (words.length === 0) continue;
6040
- ctx.say(`translating ${entry.file}`);
6041
- const result = await translated(ctx, words.map((leaf) => leaf.text), glossary, from, vars);
6042
- for (const [index, leaf] of words.entries()) setLeaf(entry.document, leaf.path, result[index]);
6043
- texts += words.length;
6044
- }
6045
- for (const { entry, leaves: own } of leaves) {
6046
- const document = entry.document;
6047
- if (entry.kind !== "character" && entry.kind !== "faction") continue;
6048
- const original = own.find((leaf) => leaf.name && leaf.path.length === 1 && leaf.path[0] === "name")?.text;
6049
- const aliases = Array.isArray(document["aliases"]) ? document["aliases"] : [];
6050
- if (original !== void 0 && original !== document["name"] && !aliases.includes(original)) document["aliases"] = [...aliases, original];
6051
- }
6052
- const own = await promptIds(join(source.directory, "prompts", from));
6053
- const present = new Set(await promptIds(join(source.directory, "prompts", to)));
6054
- const owed = own.filter((prompt) => !present.has(prompt));
6055
- const written = [];
6056
- if (owed.length > 0) {
6057
- ctx.say(`translating ${owed.length} prompt files`);
6058
- const result = await translated(ctx, await Promise.all(owed.map((prompt) => readFile(join(source.directory, "prompts", from, `${prompt}.md`), "utf8"))), glossary, from, vars);
6059
- for (const [index, prompt] of owed.entries()) written.push({
6060
- id: prompt,
6061
- text: result[index]
6062
- });
6063
- }
6064
- const id = randomUUID();
6065
- const destination = await freeFolder(source.directory, to);
6066
- await cp(source.directory, destination, {
6067
- recursive: true,
6068
- filter: (path) => !NOT_COPIED.has(relative(source.directory, path).split(sep)[0])
6069
- });
6070
- for (const entry of documents) {
6071
- const document = entry.kind === "world" ? (({ id: _old, ...rest }) => ({
6072
- id,
6073
- ...rest
6074
- }))(entry.document) : entry.document;
6075
- await writeFile(join(destination, entry.file), `${JSON.stringify(document, null, 2)}\n`);
6076
- }
6077
- for (const prompt of written) {
6078
- const file = join(destination, "prompts", to, `${prompt.id}.md`);
6079
- await mkdir(dirname(file), { recursive: true });
6080
- await writeFile(file, prompt.text.endsWith("\n") ? prompt.text : `${prompt.text}\n`);
6081
- }
6082
- const payload = await worlds.list({ refresh: true });
6083
- const made = payload.worlds.find((world) => world.id === id);
6084
- if (made === void 0) throw new Error(`the translated world was written to ${destination} but the catalogue does not list it: ${payload.problems.map((problem) => problem.message).join("; ")}`);
6085
- const record = await worlds.find(id);
6086
- const problems = [];
6087
- if (record !== void 0) try {
6088
- await loadValidatedWorld(record);
6089
- } catch (error) {
6090
- if (!(error instanceof InvalidWorldError)) throw error;
6091
- problems.push(...error.problems.map((problem) => `${relative(destination, problem.path) || "."}: ${problem.message}`));
6092
- }
6093
- return {
6094
- worldId: id,
6095
- name: made.name,
6096
- folder: basename(destination),
6097
- documents: documents.length,
6098
- texts,
6099
- names: names.length + recurring.length,
6100
- problems,
6101
- prompts: written.map((prompt) => prompt.id),
6102
- copiedAsIs: await listedIn(source.directory, [
6103
- "ui",
6104
- "images",
6105
- "media"
6106
- ])
6107
- };
6108
- }
6109
- //#endregion
6110
5494
  //#region src/shared/authoring-chat.ts
6111
5495
  const PREFIX = "world-author-";
6112
5496
  /** Stable DSH chat identity for the authoring conversation of one world. */
@@ -6328,46 +5712,6 @@ function importHooks(ctx, worlds, prompting) {
6328
5712
  });
6329
5713
  }
6330
5714
  //#endregion
6331
- //#region src/host/translate/tools.ts
6332
- const TRANSLATE_TOOL = "translate_world";
6333
- /** The message that has the authoring chat translate its world, in the language of the person who asked. */
6334
- function translateMessage(text, to, language) {
6335
- return text("translate/notice", {
6336
- tool: TRANSLATE_TOOL,
6337
- code: to,
6338
- to: to === "zh" ? language === "zh" ? "中文" : "Chinese" : language === "zh" ? "英文" : "English"
6339
- });
6340
- }
6341
- /** The tool of the authoring chat that translates the chat's world into a copy in another language. */
6342
- function translateTools(worlds, settings, prompting) {
6343
- return [defineTool({
6344
- name: TRANSLATE_TOOL,
6345
- description: "Makes a translated copy of this world, next to it, in another language: its names first, so every file calls each person, place and thing the same, then the words of every file. The world itself is not changed. Takes several minutes. Use it only when the person asked for a translation.",
6346
- parameters: { language: {
6347
- type: "string",
6348
- required: true,
6349
- enum: [...STORY_LANGUAGES],
6350
- description: "The language to translate into: en or zh."
6351
- } },
6352
- output: {
6353
- schema: { type: "json" },
6354
- render: (_args, value) => [{
6355
- type: "text",
6356
- text: JSON.stringify(value, null, 1)
6357
- }]
6358
- },
6359
- isConcurrencySafe: () => false,
6360
- async execute(args, exec) {
6361
- if (!isStoryLanguage(args.language)) throw new Error(`language must be one of: ${STORY_LANGUAGES.join(", ")}`);
6362
- const world = await worldOf(worlds, exec);
6363
- const told = prompting.languages().get(world.id);
6364
- const text = (id, variables) => prompting.prompts().text(id, told, variables);
6365
- const report = await translateWorld(contextOf(exec, settings(), text), worlds, world, args.language, told.startsWith("zh") ? "zh" : "en");
6366
- return JSON.parse(JSON.stringify(report));
6367
- }
6368
- })];
6369
- }
6370
- //#endregion
6371
5715
  //#region src/host/import/preset.ts
6372
5716
  /** The older preset layout keeps its texts under fixed keys. */
6373
5717
  const LEGACY_KEYS = [
@@ -6423,1376 +5767,6 @@ function readPreset(file, name) {
6423
5767
  };
6424
5768
  }
6425
5769
  //#endregion
6426
- //#region src/host/import/preset-tools.ts
6427
- const PRESET_TOOL = "import_preset";
6428
- const PRESET_FILE = "preset.json";
6429
- const PRESET_PATH = `${IMPORT_FOLDER}/${PRESET_FILE}`;
6430
- /** The command that has the authoring chat apply a preset that was uploaded to the world. */
6431
- const presetMessage = () => `Apply the narration preset I uploaded to this world: call ${PRESET_TOOL} with file ${PRESET_PATH}.`;
6432
- /** The tool that turns an uploaded narration preset into the world's prose prompts; every call asks the person first. */
6433
- function presetTools(worlds, settings, prompting) {
6434
- return [defineTool({
6435
- name: PRESET_TOOL,
6436
- description: `Turn the narration preset the person uploaded to this world (${PRESET_PATH}) into the world's prose prompts: how the narration is written and how the characters speak and behave. Rules of the game, formats and scripts in the preset are not carried. It replaces the world's own versions of those prompts, so the person is asked first.`,
6437
- parameters: { file: {
6438
- type: "string",
6439
- required: true,
6440
- description: `The preset: ${PRESET_PATH}.`
6441
- } },
6442
- output: {
6443
- schema: { type: "json" },
6444
- render: (_args, value) => [{
6445
- type: "text",
6446
- text: JSON.stringify(value, null, 1)
6447
- }]
6448
- },
6449
- isConcurrencySafe: () => false,
6450
- async execute(args, exec) {
6451
- if (args.file.trim() !== PRESET_PATH) throw new Error(`the preset is ${PRESET_PATH}`);
6452
- const world = await worldOf(worlds, exec);
6453
- const file = join(world.directory, IMPORT_FOLDER, PRESET_FILE);
6454
- const preset = readPreset(await readFile(file).catch(() => {
6455
- throw new Error("no preset was uploaded to this world");
6456
- }), "preset");
6457
- const language = prompting.languages().get(world.id);
6458
- const text = (id, variables) => prompting.prompts().text(id, language, variables);
6459
- const made = await extractStyleFrom(contextOf(exec, settings(), text), preset.name, preset.pieces);
6460
- for (const { id, text: body } of made.prompts) for (const tag of shippedLanguages()) await writeWorldPrompt(world.directory, tag, id, withPlayer(body));
6461
- await rm(file, { force: true });
6462
- const written = made.prompts.map((entry) => entry.id);
6463
- return JSON.parse(JSON.stringify({
6464
- preset: preset.name,
6465
- written,
6466
- folder: `${PROMPTS_FOLDER}/<language>/`,
6467
- notes: made.notes,
6468
- next: written.length === 0 ? "Nothing in the preset was about how to write the story, so no prompt was changed: tell the person." : "Tell the person which prompts were written (they can read and edit them in the world's Prompts section) and what was not carried over."
6469
- }));
6470
- }
6471
- })];
6472
- }
6473
- //#endregion
6474
- //#region src/host/triggers/parts.ts
6475
- /** What the files of a world say it has, for checking what a trigger names. @throws {InvalidEditProblems} when those files have problems of their own: they are fixed first. */
6476
- async function loadWorldParts(directory) {
6477
- const { characters, problems: characterProblems } = await loadCharacters(directory);
6478
- const { locations, problems: locationProblems } = await loadLocations(directory);
6479
- const { items, slots, problems: itemProblems } = await loadItems(directory, {
6480
- characters: characters.map((character) => character.id),
6481
- locations
6482
- });
6483
- const { defs, problems: variableProblems } = await loadVariables(directory);
6484
- const { calendar, problems: calendarProblems } = await loadCalendar(directory);
6485
- const problems = [
6486
- ...characterProblems,
6487
- ...locationProblems,
6488
- ...itemProblems,
6489
- ...variableProblems,
6490
- ...calendarProblems
6491
- ];
6492
- if (problems.length > 0) throw new InvalidEditProblems([`the world's other files have problems that come first: ${problems.map((problem) => `${problem.path}: ${problem.message}`).join("; ")}`]);
6493
- return {
6494
- characters,
6495
- locations,
6496
- items,
6497
- slots,
6498
- variables: defs,
6499
- calendar
6500
- };
6501
- }
6502
- //#endregion
6503
- //#region src/host/triggers/check.ts
6504
- /**
6505
- * What each trigger names that the world does not have (a character, place, item or variable in its condition, its cues or the words of a
6506
- * cue), found as a session start finds it: against a scratch story made from the world's files. Triggers that wait for each other count
6507
- * as there. @returns the problems by trigger key; a trigger with none is not in it.
6508
- */
6509
- function triggerProblemsOf(parts, definitions) {
6510
- const found = /* @__PURE__ */ new Map();
6511
- if (definitions.length === 0) return found;
6512
- const scratch = createSessionStore(":memory:", {
6513
- id: "scratch",
6514
- name: "scratch",
6515
- world: {
6516
- id: "scratch",
6517
- name: "scratch"
6518
- }
6519
- }, { vectors: false });
6520
- try {
6521
- const session = scratch;
6522
- if (parts.calendar !== void 0) writeCalendar(scratch.metadata, parts.calendar);
6523
- populateLocations(session, parts.locations);
6524
- populateCharacters(session, parts.characters, parts.characters.find((character) => character.role === "playable")?.id ?? "");
6525
- populateItems(session, parts.items, parts.slots, parts.locations);
6526
- populateVariables(session, parts.variables, {
6527
- characters: parts.characters,
6528
- items: parts.items,
6529
- locations: parts.locations,
6530
- values: void 0
6531
- });
6532
- const keys = definitions.map((definition) => definition.key);
6533
- for (const definition of definitions) {
6534
- const problems = triggerReferenceProblems(scratch, definition, keys).map((problem) => problem.slice(definition.key.length + 2));
6535
- if (problems.length > 0) found.set(definition.key, problems);
6536
- }
6537
- } finally {
6538
- scratch.close();
6539
- }
6540
- return found;
6541
- }
6542
- //#endregion
6543
- //#region src/host/triggers/files.ts
6544
- /** The fields of a trigger in the file; any other is a mistake that would otherwise be dropped without a word. */
6545
- const FIELDS = /* @__PURE__ */ new Set([
6546
- "key",
6547
- "name",
6548
- "when",
6549
- "effects",
6550
- "repeat",
6551
- "cooldown_seconds",
6552
- "chance",
6553
- "priority",
6554
- "expires",
6555
- "announce"
6556
- ]);
6557
- const isDocument = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6558
- /** The documents of `<world>/triggers.json` as written; none when the file is not there. @throws {InvalidEditProblems} when it is not a list of objects. */
6559
- async function readTriggerDocuments(directory) {
6560
- let text;
6561
- try {
6562
- text = await readFile(join(directory, TRIGGERS_FILE_NAME), "utf8");
6563
- } catch (error) {
6564
- if (error.code === "ENOENT") return [];
6565
- throw error;
6566
- }
6567
- let data;
6568
- try {
6569
- data = JSON.parse(text.replace(/^/, ""));
6570
- } catch (error) {
6571
- throw new InvalidEditProblems([`triggers.json is not valid JSON: ${error instanceof Error ? error.message : String(error)}`]);
6572
- }
6573
- if (!Array.isArray(data) || !data.every(isDocument)) throw new InvalidEditProblems(["triggers.json is not a list of triggers"]);
6574
- return data;
6575
- }
6576
- async function writeDocuments(directory, documents) {
6577
- const file = join(directory, TRIGGERS_FILE_NAME);
6578
- const temporary = join(dirname(file), `.${basename(file)}.${process.pid}.${randomUUID()}.tmp`);
6579
- try {
6580
- const mode = await stat(file).then((value) => value.mode, () => void 0);
6581
- await writeFile(temporary, `${JSON.stringify(documents, null, 2)}\n`, mode === void 0 ? {} : { mode });
6582
- await rename(temporary, file);
6583
- } catch (error) {
6584
- await rm(temporary, { force: true });
6585
- throw error;
6586
- }
6587
- }
6588
- /** The keys of the triggers a condition waits for. */
6589
- function waitsFor(condition) {
6590
- switch (condition.type) {
6591
- case "fired": return [condition.trigger];
6592
- case "all":
6593
- case "any": return condition.conditions.flatMap(waitsFor);
6594
- case "not": return waitsFor(condition.condition);
6595
- default: return [];
6596
- }
6597
- }
6598
- /**
6599
- * Makes or replaces one trigger of the world, by key, from a complete document in the file format. It is read as a session start reads it, and
6600
- * what it names that the world does not have is refused, with every problem; nothing is written then.
6601
- * @throws {InvalidEditProblems}
6602
- */
6603
- async function writeTriggerDocument(directory, parts, key, document) {
6604
- if (!isDocument(document)) throw new InvalidEditProblems(["document must be a JSON object"]);
6605
- const unknown = Object.keys(document).filter((field) => !FIELDS.has(field));
6606
- if (unknown.length > 0) throw new InvalidEditProblems(unknown.map((field) => `"${field}" is not a field of a trigger (${[...FIELDS].join(", ")})`));
6607
- const written = {
6608
- ...document,
6609
- key
6610
- };
6611
- const parsed = readTriggerDefinition(written, "trigger");
6612
- if ("problems" in parsed) throw new InvalidEditProblems(parsed.problems);
6613
- const documents = await readTriggerDocuments(directory);
6614
- const at = documents.findIndex((entry) => entry["key"] === key);
6615
- const problems = triggerProblemsOf(parts, [...documents.filter((_, index) => index !== at).flatMap((entry) => {
6616
- const read = readTriggerDefinition(entry, "trigger");
6617
- return "definition" in read ? [read.definition] : [];
6618
- }), parsed.definition]).get(key) ?? [];
6619
- if (problems.length > 0) throw new InvalidEditProblems(problems);
6620
- await writeDocuments(directory, at < 0 ? [...documents, written] : documents.map((entry, index) => index === at ? written : entry));
6621
- return at < 0 ? "created" : "replaced";
6622
- }
6623
- /**
6624
- * Removes one trigger from the world's file, keeping its document in `.trash/triggers` so that it can be put back. A trigger that others wait for
6625
- * cannot be removed.
6626
- * @returns where the document was kept.
6627
- * @throws {InvalidEditProblems}
6628
- */
6629
- async function deleteTriggerDocument(directory, key) {
6630
- const documents = await readTriggerDocuments(directory);
6631
- const found = documents.find((entry) => entry["key"] === key);
6632
- if (found === void 0) throw new InvalidEditProblems([`there is no trigger "${key}"`]);
6633
- const waiting = documents.flatMap((entry) => {
6634
- const read = readTriggerDefinition(entry, "trigger");
6635
- return "definition" in read && read.definition.key !== key && waitsFor(read.definition.condition).includes(key) ? [read.definition.key] : [];
6636
- });
6637
- if (waiting.length > 0) throw new InvalidEditProblems([`${waiting.join(", ")} wait${waiting.length === 1 ? "s" : ""} for "${key}" to fire; change ${waiting.length === 1 ? "it" : "them"} first`]);
6638
- const trash = join(directory, ".trash", "triggers");
6639
- await mkdir(trash, { recursive: true });
6640
- const kept = join(trash, `${key}-${Date.now()}-${randomUUID()}.json`);
6641
- await writeFile(kept, `${JSON.stringify(found, null, 2)}\n`, { flag: "wx" });
6642
- await writeDocuments(directory, documents.filter((entry) => entry !== found));
6643
- return kept;
6644
- }
6645
- //#endregion
6646
- //#region src/host/worlds/world-editor.ts
6647
- function stateOf(world, definition, names) {
6648
- const { start } = definition;
6649
- const portrait = referenceImagePath(world.directory, {
6650
- kind: "character",
6651
- localId: definition.id,
6652
- ...definition.visualIdentity?.globalId === void 0 ? {} : { globalId: definition.visualIdentity.globalId }
6653
- });
6654
- return {
6655
- key: definition.id,
6656
- name: definition.name,
6657
- aliases: definition.aliases,
6658
- role: definition.role,
6659
- tier: definition.tier,
6660
- kind: definition.kind,
6661
- control: definition.role === "playable" ? "player" : "agent",
6662
- ...definition.age === void 0 ? {} : { age: definition.age },
6663
- ...definition.gender === void 0 ? {} : { gender: definition.gender },
6664
- ...definition.pronouns === void 0 ? {} : { pronouns: definition.pronouns },
6665
- summary: definition.summary,
6666
- personality: definition.personality,
6667
- background: definition.background,
6668
- appearance: definition.appearance,
6669
- speech: definition.speech,
6670
- ...definition.voice === void 0 ? {} : { voice: definition.voice },
6671
- ...definition.visualIdentity === void 0 ? {} : { visualIdentity: definition.visualIdentity },
6672
- ...existsSync(portrait) ? { portrait: `/${API_PREFIX}/worlds/state/character/portrait/file?id=${encodeURIComponent(world.id)}&key=${encodeURIComponent(definition.id)}&v=${statSync(portrait).mtimeMs}` } : {},
6673
- state: {
6674
- publicState: start.publicState,
6675
- innerState: start.innerState,
6676
- activity: start.activity
6677
- },
6678
- ...start.place === void 0 ? {} : { place: {
6679
- key: start.place.location,
6680
- name: names.get(start.place.location) ?? start.place.location,
6681
- ...start.place.position === void 0 ? {} : { position: start.place.position }
6682
- } },
6683
- goals: start.intents.map((intent, index) => ({
6684
- ref: String(index),
6685
- name: intent.name,
6686
- description: intent.description,
6687
- status: intent.status,
6688
- priority: intent.priority
6689
- }))
6690
- };
6691
- }
6692
- /** The triggers of the world's file as the editor shows them, with what each names that the world does not have; or why the file cannot be shown. */
6693
- function triggersOf(parts, scripted) {
6694
- if (scripted.problems.length > 0) return {
6695
- triggers: [],
6696
- triggersProblem: scripted.problems.map((problem) => problem.message).join("; ")
6697
- };
6698
- const view = (problems) => scripted.triggers.map((definition) => ({
6699
- key: definition.key,
6700
- name: definition.name,
6701
- when: definition.condition,
6702
- effects: definition.effects,
6703
- repeat: definition.repeat,
6704
- priority: definition.priority,
6705
- ...definition.cooldownSeconds === void 0 ? {} : { cooldownSeconds: definition.cooldownSeconds },
6706
- ...definition.chance === void 0 ? {} : { chance: definition.chance },
6707
- ...definition.expires === void 0 ? {} : { expires: definition.expires },
6708
- announced: definition.announce !== void 0,
6709
- problems: problems.get(definition.key) ?? []
6710
- }));
6711
- try {
6712
- return { triggers: view(triggerProblemsOf(parts, scripted.triggers)) };
6713
- } catch (error) {
6714
- return {
6715
- triggers: view(/* @__PURE__ */ new Map()),
6716
- triggersProblem: `what the triggers name could not be checked, because the rest of the world has a problem: ${error instanceof Error ? error.message : String(error)}`
6717
- };
6718
- }
6719
- }
6720
- /** The characters of a world as they start, and the places they can start in. */
6721
- async function readWorldEditor(world) {
6722
- const [{ characters }, { locations }, { factions }, { lore }, { plots }] = await Promise.all([
6723
- loadCharacters(world.directory),
6724
- loadLocations(world.directory),
6725
- loadFactions(world.directory),
6726
- loadLore(world.directory),
6727
- loadPlots(world.directory)
6728
- ]);
6729
- const { items, slots } = await loadItems(world.directory, {
6730
- characters: characters.map((character) => character.id),
6731
- locations
6732
- });
6733
- const scripted = await loadTriggers(world.directory);
6734
- const declared = await loadVariables(world.directory);
6735
- const { calendar } = await loadCalendar(world.directory);
6736
- const { triggers, triggersProblem } = triggersOf({
6737
- characters,
6738
- locations,
6739
- items,
6740
- slots,
6741
- variables: declared.defs,
6742
- calendar
6743
- }, scripted);
6744
- const names = new Map(locations.map((location) => [location.id, location.name]));
6745
- const characterNames = new Map(characters.map((character) => [character.id, character.name]));
6746
- const itemNames = new Map(items.map((item) => [item.id, item.name]));
6747
- const holder = (item) => item.start.kind === "location" ? names.get(item.start.location) ?? item.start.location : item.start.kind === "inside" ? itemNames.get(item.start.item) ?? item.start.item : characterNames.get(item.start.character) ?? item.start.character;
6748
- const entity = (kind, key, name) => ({
6749
- kind,
6750
- key,
6751
- name
6752
- });
6753
- const characterEntity = (key) => entity("character", key, characterNames.get(key) ?? key);
6754
- const factionNames = new Map(factions.map((faction) => [faction.id, faction.name]));
6755
- const relations = [];
6756
- for (const character of characters) {
6757
- for (const relation of character.relationships ?? []) relations.push({
6758
- key: relationKey("character", character.id, relation.to),
6759
- kind: "character",
6760
- from: characterEntity(character.id),
6761
- to: characterEntity(relation.to),
6762
- label: relation.label,
6763
- summary: relation.summary,
6764
- familiarity: relation.familiarity,
6765
- trust: relation.trust,
6766
- affinity: relation.affinity,
6767
- tension: relation.tension
6768
- });
6769
- for (const location of character.knowledge?.locations ?? []) relations.push({
6770
- key: relationKey("knowledge", character.id, "location", location),
6771
- kind: "knowledge",
6772
- from: characterEntity(character.id),
6773
- to: entity("location", location, names.get(location) ?? location),
6774
- observed: false
6775
- });
6776
- for (const item of character.knowledge?.items ?? []) relations.push({
6777
- key: relationKey("knowledge", character.id, "item", item),
6778
- kind: "knowledge",
6779
- from: characterEntity(character.id),
6780
- to: entity("item", item, itemNames.get(item) ?? item),
6781
- observed: false
6782
- });
6783
- for (const exit of character.knowledge?.exits ?? []) relations.push({
6784
- key: relationKey("knowledge", character.id, "exit", exit.from, exit.to),
6785
- kind: "knowledge",
6786
- from: characterEntity(character.id),
6787
- to: entity("exit", `${exit.from}>${exit.to}`, `${names.get(exit.from) ?? exit.from} → ${names.get(exit.to) ?? exit.to}`),
6788
- observed: false
6789
- });
6790
- }
6791
- for (const location of locations) for (const exit of location.exits) relations.push({
6792
- key: relationKey("exit", location.id, exit.to),
6793
- kind: "exit",
6794
- from: entity("location", location.id, location.name),
6795
- to: entity("location", exit.to, names.get(exit.to) ?? exit.to),
6796
- description: exit.description,
6797
- ...exit.travelSeconds === void 0 ? {} : { travelSeconds: exit.travelSeconds },
6798
- state: exit.state,
6799
- note: exit.note,
6800
- oneWay: exit.oneWay
6801
- });
6802
- for (const faction of factions) {
6803
- for (const member of faction.members) relations.push({
6804
- key: relationKey("membership", faction.id, member.character),
6805
- kind: "membership",
6806
- from: characterEntity(member.character),
6807
- to: entity("faction", faction.id, faction.name),
6808
- role: member.role,
6809
- rank: member.rank,
6810
- status: member.status,
6811
- public: member.public,
6812
- commitment: member.commitment
6813
- });
6814
- for (const relation of faction.relationships) {
6815
- const targetName = relation.to.kind === "faction" ? factionNames.get(relation.to.id) ?? relation.to.id : characterNames.get(relation.to.id) ?? relation.to.id;
6816
- relations.push({
6817
- key: relationKey("social", "faction", faction.id, relation.to.kind, relation.to.id),
6818
- kind: "social",
6819
- from: entity("faction", faction.id, faction.name),
6820
- to: entity(relation.to.kind, relation.to.id, targetName),
6821
- label: relation.label,
6822
- summary: relation.summary ?? "",
6823
- familiarity: relation.familiarity ?? 0,
6824
- trust: relation.trust ?? 0,
6825
- affinity: relation.affinity ?? 0,
6826
- tension: relation.tension ?? 0
6827
- });
6828
- }
6829
- }
6830
- const worldDocument = JSON.parse(await readFile(join(world.directory, "world.json"), "utf8"));
6831
- const narrationVoice = typeof worldDocument["narration_voice"] === "string" ? worldDocument["narration_voice"] : void 0;
6832
- return {
6833
- ...narrationVoice === void 0 ? {} : { narrationVoice },
6834
- characters: characters.map((character) => stateOf(world, character, names)),
6835
- places: locations.map((location) => ({
6836
- key: location.id,
6837
- name: location.name,
6838
- description: location.description,
6839
- ...imageOf(world, "place", location.id, location.visualIdentity?.globalId),
6840
- ...location.parent === void 0 ? {} : { parent: {
6841
- key: location.parent,
6842
- name: names.get(location.parent) ?? location.parent
6843
- } },
6844
- features: location.features,
6845
- ...location.visualIdentity === void 0 ? {} : { visualIdentity: location.visualIdentity }
6846
- })),
6847
- things: items.map((item) => ({
6848
- key: item.id,
6849
- name: item.name,
6850
- description: item.description,
6851
- ...imageOf(world, "thing", item.id, item.visualIdentity?.globalId),
6852
- quantity: item.quantity,
6853
- unique: item.unique,
6854
- quality: item.quality,
6855
- notable: item.notable,
6856
- hidden: item.hidden,
6857
- ...item.wearable === void 0 ? {} : { wearable: item.wearable },
6858
- ...item.container === void 0 ? {} : { containerState: item.container.state },
6859
- ...item.owner === void 0 ? {} : { owner: {
6860
- key: item.owner,
6861
- name: characterNames.get(item.owner) ?? item.owner
6862
- } },
6863
- holder: holder(item),
6864
- ...item.visualIdentity === void 0 ? {} : { visualIdentity: item.visualIdentity }
6865
- })),
6866
- factions: factions.map((faction) => ({
6867
- key: faction.id,
6868
- name: faction.name,
6869
- aliases: faction.aliases,
6870
- summary: faction.summary,
6871
- description: faction.description,
6872
- values: faction.values,
6873
- structure: faction.structure,
6874
- state: {
6875
- publicState: faction.start.publicState,
6876
- innerState: faction.start.innerState
6877
- },
6878
- goals: faction.start.goals.map((goal, index) => ({
6879
- ref: String(index),
6880
- name: goal.name,
6881
- description: goal.description,
6882
- status: goal.status,
6883
- priority: goal.priority
6884
- })),
6885
- members: faction.members.map((member) => ({
6886
- ...member,
6887
- name: characterNames.get(member.character) ?? member.character
6888
- })),
6889
- relationships: faction.relationships.map((relationship) => ({
6890
- target: `${relationship.to.kind}:${relationship.to.id}`,
6891
- label: relationship.label,
6892
- summary: relationship.summary ?? ""
6893
- }))
6894
- })),
6895
- lore: lore.map((entry) => ({
6896
- key: entry.id,
6897
- title: entry.title,
6898
- kind: entry.kind,
6899
- summary: entry.summary,
6900
- body: entry.body,
6901
- ...entry.startsAt === void 0 ? {} : { startsAt: entry.startsAt },
6902
- ...entry.endsAt === void 0 ? {} : { endsAt: entry.endsAt },
6903
- subjects: entry.subjects.map((subject) => ({
6904
- kind: subject.kind,
6905
- key: subject.id,
6906
- name: subject.kind === "character" ? characterNames.get(subject.id) ?? subject.id : subject.kind === "faction" ? factionNames.get(subject.id) ?? subject.id : subject.kind === "location" ? names.get(subject.id) ?? subject.id : subject.kind === "item" ? itemNames.get(subject.id) ?? subject.id : lore.find((candidate) => candidate.id === subject.id)?.title ?? subject.id
6907
- })),
6908
- related: entry.related.map((key) => ({
6909
- key,
6910
- title: lore.find((candidate) => candidate.id === key)?.title ?? key
6911
- })),
6912
- sources: entry.sources
6913
- })),
6914
- triggers,
6915
- ...triggersProblem === void 0 ? {} : { triggersProblem },
6916
- plots: plots.map((definition) => ({ definition })),
6917
- relations
6918
- };
6919
- }
6920
- async function editWorldPlots(world, edit) {
6921
- const parsed = parsePlotsFile(JSON.stringify(edit.plots));
6922
- if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
6923
- const state = await readWorldEditor(world);
6924
- const references = plotReferenceProblems(parsed.value, [
6925
- ...state.characters.map((entry) => entry.key),
6926
- ...state.factions.map((entry) => entry.key),
6927
- ...state.places.map((entry) => entry.key),
6928
- ...state.things.map((entry) => entry.key),
6929
- ...(state.lore ?? []).map((entry) => entry.key)
6930
- ]);
6931
- if (references.length > 0) throw new InvalidEditProblems(references);
6932
- const document = parsed.value.map((plot) => ({
6933
- ...plot,
6934
- pacing: {
6935
- quiet_turns: plot.pacing.quietTurns,
6936
- cooldown_turns: plot.pacing.cooldownTurns,
6937
- cooldown_days: plot.pacing.cooldownDays
6938
- }
6939
- }));
6940
- await replaceFile$1(join(world.directory, PLOTS_FILE_NAME), JSON.stringify(document, null, 2) + "\n");
6941
- return await readWorldEditor(world);
6942
- }
6943
- async function editWorldLore(world, key, edit) {
6944
- return await editEntityFile(world, LORE_DIR, LORE_FILE_NAME, key, parseLoreFile, (document) => {
6945
- if (edit.title !== void 0) document["title"] = edit.title;
6946
- if (edit.kind !== void 0) document["kind"] = edit.kind;
6947
- if (edit.summary !== void 0) setOptional(document, "summary", edit.summary);
6948
- if (edit.body !== void 0) setOptional(document, "body", edit.body);
6949
- if (edit.sources !== void 0) document["sources"] = edit.sources;
6950
- if (edit.startsAt !== void 0) {
6951
- if (edit.startsAt === null) delete document["starts_at"];
6952
- else document["starts_at"] = new Date(edit.startsAt).toISOString();
6953
- }
6954
- if (edit.endsAt !== void 0) {
6955
- if (edit.endsAt === null) delete document["ends_at"];
6956
- else document["ends_at"] = new Date(edit.endsAt).toISOString();
6957
- }
6958
- });
6959
- }
6960
- async function editWorldNarrationVoice(world, voice) {
6961
- const file = join(world.directory, "world.json");
6962
- const text = await readFile(file, "utf8");
6963
- const document = JSON.parse(text);
6964
- if (voice.trim() === "") delete document["narration_voice"];
6965
- else document["narration_voice"] = voice.trim();
6966
- await replaceFile$1(file, JSON.stringify(document, null, /^([ \t]+)"/m.exec(text)?.[1] ?? " ") + (text.endsWith("\n") ? "\n" : ""));
6967
- return await readWorldEditor(world);
6968
- }
6969
- const relationKey = (...parts) => parts.map((part) => encodeURIComponent(part)).join(":");
6970
- const relationParts = (key) => key.split(":").map((part) => decodeURIComponent(part));
6971
- /** The folder of a character by its id: the id is the folder's name unless the file says another. */
6972
- async function folderOf$1(worldDirectory, key) {
6973
- const root = join(worldDirectory, CHARACTERS_DIR);
6974
- for (const folder of await subfolders(root)) try {
6975
- const parsed = parseCharacterFile(await readFile(join(root, folder, CHARACTER_FILE_NAME), "utf8"), folder);
6976
- if (parsed.ok && parsed.value.id === key) return folder;
6977
- } catch (error) {
6978
- if (error.code !== "ENOENT") throw error;
6979
- }
6980
- }
6981
- const object = (parent, key) => {
6982
- const found = parent[key];
6983
- if (typeof found === "object" && found !== null && !Array.isArray(found)) return found;
6984
- const made = {};
6985
- parent[key] = made;
6986
- return made;
6987
- };
6988
- /** A blank optional text is taken out of the file instead of being written empty. */
6989
- function setOptional(target, key, value) {
6990
- if (value === void 0) return;
6991
- if (value.trim() === "") delete target[key];
6992
- else target[key] = value.trim();
6993
- }
6994
- /** Puts the edit into the document of a character file; the fields it does not name, and every field the editor does not know, stay as they are. */
6995
- function apply(document, edit, problems) {
6996
- if (edit.name !== void 0) document["name"] = edit.name;
6997
- if (edit.aliases !== void 0) document["aliases"] = edit.aliases.map((alias) => alias.trim()).filter((alias) => alias !== "");
6998
- for (const key of [
6999
- "age",
7000
- "gender",
7001
- "pronouns"
7002
- ]) setOptional(document, key, edit[key]);
7003
- for (const key of [
7004
- "role",
7005
- "tier",
7006
- "kind",
7007
- "summary",
7008
- "personality",
7009
- "background",
7010
- "appearance"
7011
- ]) if (edit[key] !== void 0) document[key] = edit[key];
7012
- if (edit.visualIdentity === null) delete document["visual_identity"];
7013
- else if (edit.visualIdentity !== void 0) document["visual_identity"] = {
7014
- description: edit.visualIdentity.description,
7015
- tags: edit.visualIdentity.tags,
7016
- negative_tags: edit.visualIdentity.negativeTags,
7017
- ...edit.visualIdentity.globalId === void 0 ? {} : { global_id: edit.visualIdentity.globalId }
7018
- };
7019
- if (edit.speech !== void 0) {
7020
- const speech = object(document, "speech");
7021
- if (edit.speech.style !== void 0) speech["style"] = edit.speech.style;
7022
- if (edit.speech.examples !== void 0) speech["examples"] = edit.speech.examples.map((example) => example.trim()).filter((example) => example !== "");
7023
- }
7024
- setOptional(document, "voice", edit.voice);
7025
- const start = object(document, "start");
7026
- if (edit.state !== void 0) {
7027
- if (edit.state.publicState !== void 0) start["public_state"] = edit.state.publicState;
7028
- if (edit.state.innerState !== void 0) start["inner_state"] = edit.state.innerState;
7029
- if (edit.state.activity !== void 0) start["activity"] = edit.state.activity;
7030
- }
7031
- if (edit.place !== void 0) {
7032
- if (start["location"] !== edit.place.location) delete start["feature"];
7033
- start["location"] = edit.place.location;
7034
- setOptional(start, "position", edit.place.position ?? "");
7035
- }
7036
- if (edit.goals !== void 0) {
7037
- const intents = Array.isArray(start["intents"]) ? start["intents"] : [];
7038
- for (const goal of edit.goals) {
7039
- const intent = intents[Number(goal.ref)];
7040
- if (intent === void 0 || typeof intent !== "object" || intent === null) {
7041
- problems.push(`there is no goal "${goal.ref}"`);
7042
- continue;
7043
- }
7044
- if (goal.name !== void 0) intent["name"] = goal.name;
7045
- if (goal.description !== void 0) intent["description"] = goal.description;
7046
- if (goal.status !== void 0) intent["status"] = goal.status;
7047
- if (goal.priority !== void 0) intent["priority"] = goal.priority;
7048
- }
7049
- }
7050
- }
7051
- /** Written in one step, so an interruption cannot leave a character file half written. */
7052
- async function replaceFile$1(file, text) {
7053
- const temporary = join(dirname(file), `.${basename(file)}.${process.pid}.${randomUUID()}.tmp`);
7054
- try {
7055
- const mode = await stat(file).then((value) => value.mode, (error) => {
7056
- if (error.code === "ENOENT") return 420;
7057
- throw error;
7058
- });
7059
- await writeFile(temporary, text, { mode });
7060
- await chmod(temporary, mode);
7061
- await rename(temporary, file);
7062
- } catch (error) {
7063
- await rm(temporary, { force: true });
7064
- throw error;
7065
- }
7066
- }
7067
- /**
7068
- * Change a character in a world's files: the file is read, changed and checked as a whole (it has to read as a valid character, and the place has to be a place of
7069
- * the world) before it is written, so a refused edit changes nothing. Whatever the file holds that the editor does not know stays.
7070
- * @throws {InvalidEditProblems} when the character is not there, or the result would not be a valid character.
7071
- */
7072
- async function editWorldCharacter(world, key, edit) {
7073
- const folder = await folderOf$1(world.directory, key);
7074
- if (folder === void 0) throw new InvalidEditProblems([`there is no character "${key}"`]);
7075
- const file = join(world.directory, CHARACTERS_DIR, folder, CHARACTER_FILE_NAME);
7076
- const text = (await readFile(file, "utf8")).replace(/^/, "");
7077
- const document = JSON.parse(text);
7078
- const problems = [];
7079
- if (edit.place !== void 0) {
7080
- const { locations } = await loadLocations(world.directory);
7081
- if (!locations.some((location) => location.id === edit.place?.location)) problems.push(`there is no place "${edit.place.location}"`);
7082
- }
7083
- apply(document, edit, problems);
7084
- const next = JSON.stringify(document, null, /^([ \t]+)"/m.exec(text)?.[1] ?? " ") + (text.endsWith("\n") ? "\n" : "");
7085
- const parsed = parseCharacterFile(next, folder);
7086
- if (!parsed.ok) problems.push(...parsed.issues.map(formatIssue));
7087
- if (problems.length > 0) throw new InvalidEditProblems(problems);
7088
- await replaceFile$1(file, next);
7089
- return await readWorldEditor(world);
7090
- }
7091
- async function entityFolder(worldDirectory, directory, fileName, key, parse) {
7092
- for (const folder of await subfolders(join(worldDirectory, directory))) try {
7093
- const parsed = parse(await readFile(join(worldDirectory, directory, folder, fileName), "utf8"), folder);
7094
- if (parsed.ok && parsed.value?.id === key) return folder;
7095
- } catch (error) {
7096
- if (error.code !== "ENOENT") throw error;
7097
- }
7098
- }
7099
- function setVisualIdentity(document, identity) {
7100
- if (identity === null) delete document["visual_identity"];
7101
- else if (identity !== void 0) document["visual_identity"] = {
7102
- description: identity.description,
7103
- tags: identity.tags,
7104
- negative_tags: identity.negativeTags,
7105
- ...identity.globalId === void 0 ? {} : { global_id: identity.globalId }
7106
- };
7107
- }
7108
- async function editEntityFile(world, directory, fileName, key, parse, mutate) {
7109
- const folder = await entityFolder(world.directory, directory, fileName, key, parse);
7110
- if (folder === void 0) throw new InvalidEditProblems([`there is no entity "${key}"`]);
7111
- const file = join(world.directory, directory, folder, fileName);
7112
- const text = (await readFile(file, "utf8")).replace(/^/, "");
7113
- const document = JSON.parse(text);
7114
- mutate(document);
7115
- const next = JSON.stringify(document, null, /^([ \t]+)"/m.exec(text)?.[1] ?? " ") + (text.endsWith("\n") ? "\n" : "");
7116
- const parsed = parse(next, folder);
7117
- if (!parsed.ok) throw new InvalidEditProblems((parsed.issues ?? []).map(formatIssue));
7118
- await replaceFile$1(file, next);
7119
- return await readWorldEditor(world);
7120
- }
7121
- async function editWorldPlace(world, key, edit) {
7122
- if (edit.parent !== void 0 && edit.parent !== null) {
7123
- const places = (await readWorldEditor(world)).places;
7124
- if (!places.some((place) => place.key === edit.parent)) throw new InvalidEditProblems([`there is no place "${edit.parent}" to put it in`]);
7125
- const parents = new Map(places.map((place) => [place.key, place.parent?.key]));
7126
- for (let at = edit.parent; at !== void 0; at = parents.get(at)) if (at === key) throw new InvalidEditProblems(["a place cannot be inside itself or a place within it"]);
7127
- }
7128
- return await editEntityFile(world, LOCATIONS_DIR, LOCATION_FILE_NAME, key, parseLocationFile, (document) => {
7129
- if (edit.name !== void 0) document["name"] = edit.name;
7130
- if (edit.description !== void 0) document["description"] = edit.description;
7131
- if (edit.features !== void 0) document["features"] = edit.features.map((feature) => ({
7132
- id: feature.key,
7133
- name: feature.name,
7134
- description: feature.description
7135
- }));
7136
- if (edit.parent === null) delete document["parent"];
7137
- else if (edit.parent !== void 0) document["parent"] = edit.parent;
7138
- setVisualIdentity(document, edit.visualIdentity);
7139
- });
7140
- }
7141
- async function editWorldThing(world, key, edit) {
7142
- if (edit.owner !== void 0 && edit.owner !== null && !(await readWorldEditor(world)).characters.some((character) => character.key === edit.owner)) throw new InvalidEditProblems([`there is no character "${edit.owner}" to own it`]);
7143
- return await editEntityFile(world, ITEMS_DIR, ITEM_FILE_NAME, key, parseItemFile, (document) => {
7144
- for (const field of [
7145
- "name",
7146
- "description",
7147
- "quantity",
7148
- "quality",
7149
- "notable",
7150
- "hidden"
7151
- ]) if (edit[field] !== void 0) document[field] = edit[field];
7152
- if (edit.containerState !== void 0) object(document, "container")["state"] = edit.containerState;
7153
- if (edit.owner === null) delete document["owner"];
7154
- else if (edit.owner !== void 0) document["owner"] = edit.owner;
7155
- setVisualIdentity(document, edit.visualIdentity);
7156
- });
7157
- }
7158
- async function editWorldFaction(world, key, edit) {
7159
- return await editEntityFile(world, FACTIONS_DIR, FACTION_FILE_NAME, key, parseFactionFile, (document) => {
7160
- for (const field of [
7161
- "name",
7162
- "aliases",
7163
- "summary",
7164
- "description",
7165
- "values",
7166
- "structure"
7167
- ]) if (edit[field] !== void 0) document[field] = edit[field];
7168
- const start = object(document, "start");
7169
- if (edit.state?.publicState !== void 0) start["public_state"] = edit.state.publicState;
7170
- if (edit.state?.innerState !== void 0) start["inner_state"] = edit.state.innerState;
7171
- if (edit.goals !== void 0) {
7172
- const goals = Array.isArray(start["goals"]) ? start["goals"] : [];
7173
- for (const goal of edit.goals) {
7174
- const target = goals[Number(goal.ref)];
7175
- if (target === void 0) continue;
7176
- for (const field of [
7177
- "name",
7178
- "description",
7179
- "status",
7180
- "priority"
7181
- ]) if (goal[field] !== void 0) target[field] = goal[field];
7182
- }
7183
- }
7184
- });
7185
- }
7186
- async function createWorldRelation(world, edit) {
7187
- if (edit.kind === "character" || edit.kind === "knowledge") return await editEntityFile(world, CHARACTERS_DIR, CHARACTER_FILE_NAME, edit.from, parseCharacterFile, (document) => {
7188
- if (edit.kind === "character") {
7189
- const relationships = Array.isArray(document["relationships"]) ? document["relationships"] : [];
7190
- if (relationships.some((entry) => entry?.["to"] === edit.to)) throw new InvalidEditProblems(["that relationship already exists"]);
7191
- relationships.push({
7192
- to: edit.to,
7193
- label: edit.label,
7194
- summary: edit.summary ?? "",
7195
- familiarity: edit.familiarity ?? 0,
7196
- trust: edit.trust ?? 0,
7197
- affinity: edit.affinity ?? 0,
7198
- tension: edit.tension ?? 0
7199
- });
7200
- document["relationships"] = relationships;
7201
- } else {
7202
- const knowledge = object(document, "knowledge");
7203
- const field = edit.toKind === "location" ? "locations" : edit.toKind === "item" ? "items" : "exits";
7204
- const entries = Array.isArray(knowledge[field]) ? knowledge[field] : [];
7205
- if (edit.toKind === "exit") {
7206
- const [from, to] = edit.to.split(">");
7207
- if (from === void 0 || to === void 0) throw new InvalidEditProblems(["the route key is invalid"]);
7208
- if (entries.some((entry) => typeof entry === "object" && entry !== null && entry["from"] === from && entry["to"] === to)) throw new InvalidEditProblems(["that knowledge relation already exists"]);
7209
- entries.push({
7210
- from,
7211
- to
7212
- });
7213
- } else {
7214
- if (entries.includes(edit.to)) throw new InvalidEditProblems(["that knowledge relation already exists"]);
7215
- entries.push(edit.to);
7216
- }
7217
- knowledge[field] = entries;
7218
- }
7219
- });
7220
- if (edit.kind === "exit") return await editEntityFile(world, LOCATIONS_DIR, LOCATION_FILE_NAME, edit.from, parseLocationFile, (document) => {
7221
- const exits = Array.isArray(document["exits"]) ? document["exits"] : [];
7222
- if (exits.some((entry) => entry?.["to"] === edit.to)) throw new InvalidEditProblems(["that route already exists"]);
7223
- exits.push({
7224
- to: edit.to,
7225
- description: edit.description,
7226
- ...edit.travelSeconds === void 0 ? {} : { travel_time_seconds: edit.travelSeconds },
7227
- state: edit.state ?? "open",
7228
- note: edit.note ?? ""
7229
- });
7230
- document["exits"] = exits;
7231
- });
7232
- const faction = edit.kind === "membership" ? edit.to : edit.from;
7233
- if (edit.kind === "social" && edit.fromKind !== "faction") throw new InvalidEditProblems(["authored social relationships must start from a faction"]);
7234
- return await editEntityFile(world, FACTIONS_DIR, FACTION_FILE_NAME, faction, parseFactionFile, (document) => {
7235
- if (edit.kind === "membership") {
7236
- const members = Array.isArray(document["members"]) ? document["members"] : [];
7237
- if (members.some((entry) => entry?.["character"] === edit.from)) throw new InvalidEditProblems(["that membership already exists"]);
7238
- members.push({
7239
- character: edit.from,
7240
- role: edit.role,
7241
- rank: edit.rank ?? "",
7242
- status: edit.status ?? "active",
7243
- public: edit.public ?? true,
7244
- commitment: edit.commitment ?? .5
7245
- });
7246
- document["members"] = members;
7247
- } else {
7248
- const relationships = Array.isArray(document["relationships"]) ? document["relationships"] : [];
7249
- if (relationships.some((entry) => typeof entry?.["to"] === "object" && entry["to"] !== null && entry["to"]["kind"] === edit.toKind && entry["to"]["id"] === edit.to)) throw new InvalidEditProblems(["that relationship already exists"]);
7250
- relationships.push({
7251
- to: {
7252
- kind: edit.toKind,
7253
- id: edit.to
7254
- },
7255
- label: edit.label,
7256
- summary: edit.summary ?? "",
7257
- familiarity: edit.familiarity ?? 0,
7258
- trust: edit.trust ?? 0,
7259
- affinity: edit.affinity ?? 0,
7260
- tension: edit.tension ?? 0
7261
- });
7262
- document["relationships"] = relationships;
7263
- }
7264
- });
7265
- }
7266
- const isNewRelation = (edit) => "create" in edit && edit.create === true;
7267
- async function editWorldRelation(world, edit) {
7268
- if (isNewRelation(edit)) return await createWorldRelation(world, edit);
7269
- const parts = relationParts(edit.key);
7270
- if (parts[0] !== edit.kind) throw new InvalidEditProblems([`the relation key "${edit.key}" is not a ${edit.kind} key: copy it exactly from list_relationships ("${edit.kind}:..."), or to make a new one send create: true with from and to and no key`]);
7271
- if (edit.kind === "character" || edit.kind === "knowledge") {
7272
- const character = parts[1];
7273
- if (character === void 0) throw new InvalidEditProblems(["the relation key is invalid"]);
7274
- if (await folderOf$1(world.directory, character) === void 0) throw new InvalidEditProblems([`there is no character "${character}"`]);
7275
- return await editEntityFile(world, CHARACTERS_DIR, CHARACTER_FILE_NAME, character, parseCharacterFile, (document) => {
7276
- if (edit.kind === "character") {
7277
- const target = parts[2];
7278
- const relationships = Array.isArray(document["relationships"]) ? document["relationships"] : [];
7279
- const index = relationships.findIndex((entry) => entry?.["to"] === target);
7280
- if (index < 0) throw new InvalidEditProblems(["the relationship no longer exists"]);
7281
- if (edit.remove === true) relationships.splice(index, 1);
7282
- else for (const field of [
7283
- "label",
7284
- "summary",
7285
- "familiarity",
7286
- "trust",
7287
- "affinity",
7288
- "tension"
7289
- ]) if (edit[field] !== void 0) relationships[index][field] = edit[field];
7290
- document["relationships"] = relationships;
7291
- } else {
7292
- const subjectKind = parts[2];
7293
- const one = parts[3];
7294
- const two = parts[4];
7295
- const knowledge = object(document, "knowledge");
7296
- const field = subjectKind === "location" ? "locations" : subjectKind === "item" ? "items" : "exits";
7297
- const entries = Array.isArray(knowledge[field]) ? knowledge[field] : [];
7298
- const index = subjectKind === "exit" ? entries.findIndex((entry) => typeof entry === "object" && entry !== null && entry["from"] === one && entry["to"] === two) : entries.indexOf(one);
7299
- if (index < 0) throw new InvalidEditProblems(["the knowledge relation no longer exists"]);
7300
- entries.splice(index, 1);
7301
- knowledge[field] = entries;
7302
- }
7303
- });
7304
- }
7305
- if (edit.kind === "exit") {
7306
- const from = parts[1];
7307
- const to = parts[2];
7308
- if (from === void 0 || to === void 0) throw new InvalidEditProblems(["the exit key is invalid"]);
7309
- return await editEntityFile(world, LOCATIONS_DIR, LOCATION_FILE_NAME, from, parseLocationFile, (document) => {
7310
- const exits = Array.isArray(document["exits"]) ? document["exits"] : [];
7311
- const index = exits.findIndex((entry) => entry?.["to"] === to);
7312
- if (index < 0) throw new InvalidEditProblems(["the exit no longer exists"]);
7313
- if (edit.remove === true) exits.splice(index, 1);
7314
- else {
7315
- for (const field of [
7316
- "description",
7317
- "state",
7318
- "note"
7319
- ]) if (edit[field] !== void 0) exits[index][field] = edit[field];
7320
- if (edit.travelSeconds === null) delete exits[index]["travel_time_seconds"];
7321
- else if (edit.travelSeconds !== void 0) exits[index]["travel_time_seconds"] = edit.travelSeconds;
7322
- }
7323
- document["exits"] = exits;
7324
- });
7325
- }
7326
- const faction = edit.kind === "membership" ? parts[1] : parts[2];
7327
- if (faction === void 0) throw new InvalidEditProblems(["the relation key is invalid"]);
7328
- return await editEntityFile(world, FACTIONS_DIR, FACTION_FILE_NAME, faction, parseFactionFile, (document) => {
7329
- if (edit.kind === "membership") {
7330
- const character = parts[2];
7331
- const members = Array.isArray(document["members"]) ? document["members"] : [];
7332
- const index = members.findIndex((entry) => entry?.["character"] === character);
7333
- if (index < 0) throw new InvalidEditProblems(["the membership no longer exists"]);
7334
- if (edit.remove === true) members.splice(index, 1);
7335
- else for (const field of [
7336
- "role",
7337
- "rank",
7338
- "status",
7339
- "public",
7340
- "commitment"
7341
- ]) if (edit[field] !== void 0) members[index][field] = edit[field];
7342
- document["members"] = members;
7343
- } else {
7344
- const targetKind = parts[3];
7345
- const target = parts[4];
7346
- const relationships = Array.isArray(document["relationships"]) ? document["relationships"] : [];
7347
- const index = relationships.findIndex((entry) => typeof entry?.["to"] === "object" && entry["to"] !== null && entry["to"]["kind"] === targetKind && entry["to"]["id"] === target);
7348
- if (index < 0) throw new InvalidEditProblems(["the relationship no longer exists"]);
7349
- if (edit.remove === true) relationships.splice(index, 1);
7350
- else for (const field of [
7351
- "label",
7352
- "summary",
7353
- "familiarity",
7354
- "trust",
7355
- "affinity",
7356
- "tension"
7357
- ]) if (edit[field] !== void 0) relationships[index][field] = edit[field];
7358
- document["relationships"] = relationships;
7359
- }
7360
- });
7361
- }
7362
- async function characterOf(world, key) {
7363
- const { characters } = await loadCharacters(world.directory);
7364
- const character = characters.find((candidate) => candidate.id === key);
7365
- if (character === void 0) throw new InvalidEditProblems([`there is no character "${key}"`]);
7366
- return character;
7367
- }
7368
- /** What kinds of things besides characters have a reference picture, and what the images call them. */
7369
- const IMAGE_SUBJECT = {
7370
- place: "location",
7371
- thing: "item"
7372
- };
7373
- function imageOf(world, kind, id, globalId) {
7374
- const file = referenceImagePath(world.directory, {
7375
- kind: IMAGE_SUBJECT[kind],
7376
- localId: id,
7377
- ...globalId === void 0 ? {} : { globalId }
7378
- });
7379
- return existsSync(file) ? { image: `/${API_PREFIX}/worlds/state/${kind}/image/file?id=${encodeURIComponent(world.id)}&key=${encodeURIComponent(id)}&v=${statSync(file).mtimeMs}` } : {};
7380
- }
7381
- async function imageSubjectOf(world, kind, key) {
7382
- if (kind === "place") {
7383
- const { locations } = await loadLocations(world.directory);
7384
- const found = locations.find((candidate) => candidate.id === key);
7385
- if (found === void 0) throw new InvalidEditProblems([`there is no place "${key}"`]);
7386
- return {
7387
- id: found.id,
7388
- name: found.name,
7389
- ...found.visualIdentity === void 0 ? {} : { identity: found.visualIdentity }
7390
- };
7391
- }
7392
- const { characters } = await loadCharacters(world.directory);
7393
- const { locations } = await loadLocations(world.directory);
7394
- const { items } = await loadItems(world.directory, {
7395
- characters: characters.map((character) => character.id),
7396
- locations
7397
- });
7398
- const found = items.find((candidate) => candidate.id === key);
7399
- if (found === void 0) throw new InvalidEditProblems([`there is no thing "${key}"`]);
7400
- return {
7401
- id: found.id,
7402
- name: found.name,
7403
- ...found.visualIdentity === void 0 ? {} : { identity: found.visualIdentity }
7404
- };
7405
- }
7406
- /** Generate or replace the reference picture of an authored place or thing from its visual identity. */
7407
- async function generateWorldEntityImage(world, kind, key, service) {
7408
- const subject = await imageSubjectOf(world, kind, key);
7409
- if (subject.identity === void 0) throw new InvalidEditProblems([`${subject.name} needs a visual identity before a picture can be generated`]);
7410
- await generateReferenceImage(service, {
7411
- root: world.directory,
7412
- subject: {
7413
- kind: IMAGE_SUBJECT[kind],
7414
- localId: subject.id,
7415
- name: subject.name,
7416
- ...subject.identity.globalId === void 0 ? {} : { globalId: subject.identity.globalId }
7417
- },
7418
- identity: {
7419
- ...subject.identity,
7420
- subjectKind: IMAGE_SUBJECT[kind],
7421
- subjectId: 0,
7422
- version: 1,
7423
- updatedAt: ""
7424
- }
7425
- });
7426
- return await readWorldEditor(world);
7427
- }
7428
- /** The picture the author brought becomes the place's or thing's reference picture. */
7429
- async function uploadWorldEntityImage(world, kind, key, png, originalName) {
7430
- const subject = await imageSubjectOf(world, kind, key);
7431
- try {
7432
- await uploadReferenceImage({
7433
- root: world.directory,
7434
- subject: {
7435
- kind: IMAGE_SUBJECT[kind],
7436
- localId: subject.id,
7437
- name: subject.name,
7438
- ...subject.identity?.globalId === void 0 ? {} : { globalId: subject.identity.globalId }
7439
- },
7440
- png,
7441
- ...originalName === void 0 ? {} : { originalName }
7442
- });
7443
- } catch (error) {
7444
- throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
7445
- }
7446
- return await readWorldEditor(world);
7447
- }
7448
- /** Resolve the picture through authored data so request parameters cannot select arbitrary files. */
7449
- async function worldEntityImageFile(world, kind, key) {
7450
- const subject = await imageSubjectOf(world, kind, key);
7451
- const file = referenceImagePath(world.directory, {
7452
- kind: IMAGE_SUBJECT[kind],
7453
- localId: subject.id,
7454
- ...subject.identity?.globalId === void 0 ? {} : { globalId: subject.identity.globalId }
7455
- });
7456
- return {
7457
- file,
7458
- size: (await stat(file)).size
7459
- };
7460
- }
7461
- /** Generate or replace the authored character's stable reference portrait. */
7462
- async function generateWorldCharacterPortrait(world, key, service) {
7463
- const character = await characterOf(world, key);
7464
- const identity = character.visualIdentity;
7465
- if (identity === void 0) throw new InvalidEditProblems([`${character.name} needs a visual identity before a portrait can be generated`]);
7466
- await generateReferenceImage(service, {
7467
- root: world.directory,
7468
- subject: {
7469
- kind: "character",
7470
- localId: character.id,
7471
- name: character.name,
7472
- ...identity.globalId === void 0 ? {} : { globalId: identity.globalId }
7473
- },
7474
- identity: {
7475
- ...identity,
7476
- subjectKind: "character",
7477
- subjectId: 0,
7478
- version: 1,
7479
- updatedAt: ""
7480
- }
7481
- });
7482
- return await readWorldEditor(world);
7483
- }
7484
- /** The picture the author brought becomes the character's portrait. */
7485
- async function uploadWorldCharacterPortrait(world, key, png, originalName) {
7486
- const character = await characterOf(world, key);
7487
- try {
7488
- await uploadReferenceImage({
7489
- root: world.directory,
7490
- subject: {
7491
- kind: "character",
7492
- localId: character.id,
7493
- name: character.name,
7494
- ...character.visualIdentity?.globalId === void 0 ? {} : { globalId: character.visualIdentity.globalId }
7495
- },
7496
- png,
7497
- ...originalName === void 0 ? {} : { originalName }
7498
- });
7499
- } catch (error) {
7500
- throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
7501
- }
7502
- return await readWorldEditor(world);
7503
- }
7504
- /** Resolve a portrait through authored data so request parameters cannot select arbitrary files. */
7505
- async function worldCharacterPortraitFile(world, key) {
7506
- const character = await characterOf(world, key);
7507
- const file = referenceImagePath(world.directory, {
7508
- kind: "character",
7509
- localId: character.id,
7510
- ...character.visualIdentity?.globalId === void 0 ? {} : { globalId: character.visualIdentity.globalId }
7511
- });
7512
- return {
7513
- file,
7514
- size: (await stat(file)).size
7515
- };
7516
- }
7517
- /** The document of one trigger as the world's file has it, for editing. */
7518
- async function readWorldTrigger(world, key) {
7519
- const found = (await readTriggerDocuments(world.directory)).find((entry) => entry["key"] === key);
7520
- if (found === void 0) throw new InvalidEditProblems([`there is no trigger "${key}"`]);
7521
- return found;
7522
- }
7523
- /** Makes or replaces one trigger from a complete document, checked as a story start checks it, and answers the world as it stands. */
7524
- async function writeWorldTrigger(world, key, document) {
7525
- await writeTriggerDocument(world.directory, await loadWorldParts(world.directory), key, document);
7526
- return await readWorldEditor(world);
7527
- }
7528
- /** Removes one trigger, keeping its document in the world's trash, and answers the world as it stands. */
7529
- async function removeWorldTrigger(world, key) {
7530
- await deleteTriggerDocument(world.directory, key);
7531
- return await readWorldEditor(world);
7532
- }
7533
- //#endregion
7534
- //#region src/host/authoring/documents.ts
7535
- const AUTHORED_ENTITY_KINDS = [
7536
- "character",
7537
- "location",
7538
- "item",
7539
- "faction",
7540
- "lore"
7541
- ];
7542
- const formats = {
7543
- character: {
7544
- directory: CHARACTERS_DIR,
7545
- file: CHARACTER_FILE_NAME,
7546
- parse: parseCharacterFile
7547
- },
7548
- location: {
7549
- directory: LOCATIONS_DIR,
7550
- file: LOCATION_FILE_NAME,
7551
- parse: parseLocationFile
7552
- },
7553
- item: {
7554
- directory: ITEMS_DIR,
7555
- file: ITEM_FILE_NAME,
7556
- parse: parseItemFile
7557
- },
7558
- faction: {
7559
- directory: FACTIONS_DIR,
7560
- file: FACTION_FILE_NAME,
7561
- parse: parseFactionFile
7562
- },
7563
- lore: {
7564
- directory: LORE_DIR,
7565
- file: LORE_FILE_NAME,
7566
- parse: parseLoreFile
7567
- }
7568
- };
7569
- /** Keys become folder names and image paths: letters (any script), digits, marks, `.`, `_` and `-`, starting with a letter or digit. */
7570
- const NEW_KEY = /^[\p{L}\p{N}][\p{L}\p{N}\p{M}._-]{0,99}$/u;
7571
- function validNewKey(key) {
7572
- return NEW_KEY.test(key);
7573
- }
7574
- async function find(world, kind, key) {
7575
- const format = formats[kind];
7576
- const root = join(world.directory, format.directory);
7577
- for (const folder of await subfolders(root)) {
7578
- const file = join(root, folder, format.file);
7579
- try {
7580
- const parsed = format.parse(await readFile(file, "utf8"), folder);
7581
- if (parsed.ok && parsed.value.id === key) return {
7582
- folder,
7583
- file
7584
- };
7585
- } catch (error) {
7586
- if (error.code !== "ENOENT") throw error;
7587
- }
7588
- }
7589
- }
7590
- function serializeDocument(kind, key, value) {
7591
- if (typeof value !== "object" || value === null || Array.isArray(value)) throw new InvalidEditProblems(["document must be a JSON object"]);
7592
- const document = {
7593
- ...value,
7594
- id: key
7595
- };
7596
- const text = `${JSON.stringify(document, null, 2)}\n`;
7597
- const parsed = formats[kind].parse(text, key);
7598
- if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
7599
- return text;
7600
- }
7601
- async function replaceFile(file, text) {
7602
- const temporary = join(dirname(file), `.${basename(file)}.${process.pid}.${randomUUID()}.tmp`);
7603
- try {
7604
- const mode = await stat(file).then((value) => value.mode);
7605
- await writeFile(temporary, text, { mode });
7606
- await rename(temporary, file);
7607
- } catch (error) {
7608
- await rm(temporary, { force: true });
7609
- throw error;
7610
- }
7611
- }
7612
- async function readAuthoredEntityDocument(world, kind, key) {
7613
- const found = await find(world, kind, key);
7614
- if (found === void 0) throw new InvalidEditProblems([`there is no ${kind} "${key}"`]);
7615
- return JSON.parse((await readFile(found.file, "utf8")).replace(/^/, ""));
7616
- }
7617
- async function createAuthoredEntity(world, kind, key, document) {
7618
- if (!validNewKey(key)) throw new InvalidEditProblems(["key must be letters (any script), digits, \".\", \"_\" or \"-\", starting with a letter or digit, at most 100 characters (no brackets, spaces or slashes)"]);
7619
- if (await find(world, kind, key) !== void 0) throw new InvalidEditProblems([`the ${kind} "${key}" already exists`]);
7620
- const format = formats[kind];
7621
- const root = join(world.directory, format.directory);
7622
- const folder = join(root, key);
7623
- const text = serializeDocument(kind, key, document);
7624
- await mkdir(root, { recursive: true });
7625
- await mkdir(folder, { recursive: false });
7626
- try {
7627
- await writeFile(join(folder, format.file), text, { flag: "wx" });
7628
- } catch (error) {
7629
- await rm(folder, {
7630
- recursive: true,
7631
- force: true
7632
- });
7633
- throw error;
7634
- }
7635
- }
7636
- async function replaceAuthoredEntity(world, kind, key, document) {
7637
- const found = await find(world, kind, key);
7638
- if (found === void 0) throw new InvalidEditProblems([`there is no ${kind} "${key}"`]);
7639
- await replaceFile(found.file, serializeDocument(kind, key, document));
7640
- }
7641
- /** Deletions remain recoverable without making the trash visible to the world loaders. */
7642
- async function deleteAuthoredEntity(world, kind, key) {
7643
- const found = await find(world, kind, key);
7644
- if (found === void 0) throw new InvalidEditProblems([`there is no ${kind} "${key}"`]);
7645
- const trash = join(world.directory, ".trash", formats[kind].directory);
7646
- await mkdir(trash, { recursive: true });
7647
- const destination = join(trash, `${found.folder}-${Date.now()}-${randomUUID()}`);
7648
- await rename(dirname(found.file), destination);
7649
- return destination;
7650
- }
7651
- //#endregion
7652
- //#region src/host/interface/world-packs.ts
7653
- /** The kinds of file an assistant may write, as text. */
7654
- const TEXT_EXTENSIONS = [
7655
- "html",
7656
- "css",
7657
- "js",
7658
- "json",
7659
- "txt",
7660
- "svg"
7661
- ];
7662
- const folderOf = (directory, pack) => join(directory, "ui", pack);
7663
- function checked(directory, pack) {
7664
- if (!isPackId(pack)) throw new Error(`"${pack}" is not a usable pack name (letters, digits, "-" and "_")`);
7665
- return folderOf(directory, pack);
7666
- }
7667
- /** What every pack the world carries holds and what is wrong with it. */
7668
- function listWorldPacks(directory) {
7669
- return packIds(directory).map((id) => {
7670
- const { pack, problems } = readPack(folderOf(directory, id), id, (file) => file);
7671
- const files = pack === void 0 ? [] : [...pack.files.keys()];
7672
- return {
7673
- id,
7674
- name: pack?.manifest.name ?? id,
7675
- problems,
7676
- files
7677
- };
7678
- });
7679
- }
7680
- /** What is wrong with a pack (nothing when it can be used). */
7681
- function checkWorldPack(directory, pack) {
7682
- const folder = checked(directory, pack);
7683
- if (!existsSync(folder)) throw new Error(`the world carries no pack "${pack}"`);
7684
- return readPack(folder, pack, (file) => file).problems;
7685
- }
7686
- /** Moves a file of a pack into the world's `.trash`. @returns where it went, and what is wrong with the pack now. */
7687
- async function deleteWorldPackFile(directory, pack, path) {
7688
- const relative = packPath(path);
7689
- if (relative === void 0 || !(extname(relative).slice(1).toLowerCase() in PACK_MEDIA_TYPES)) throw new Error(`"${path}" is not a file of a pack`);
7690
- const folder = checked(directory, pack);
7691
- const file = join(folder, ...relative.split("/"));
7692
- if (!existsSync(file)) throw new Error(`the pack "${pack}" has no file "${path}"`);
7693
- const aside = join(directory, ".trash", "ui", pack, `${relative.replaceAll("/", "__")}.${Date.now()}`);
7694
- await mkdir(dirname(aside), { recursive: true });
7695
- await rename(file, aside);
7696
- return {
7697
- trashPath: aside,
7698
- problems: existsSync(join(folder, "pack.json")) ? readPack(folder, pack, (address) => address).problems : [{
7699
- file: "pack.json",
7700
- message: "the pack has no pack.json"
7701
- }]
7702
- };
7703
- }
7704
- //#endregion
7705
- //#region src/host/authoring/pack-jail.ts
7706
- /** DSH's own file tools, which the world authoring chat uses on the interface packs and nothing else. */
7707
- const PACK_FILE_TOOLS = [
7708
- "read",
7709
- "write",
7710
- "edit"
7711
- ];
7712
- const WRITING = ["write", "edit"];
7713
- /** The most text a call may carry. */
7714
- const MAX_PACK_TEXT = 204800;
7715
- function unsafePath(ui, path) {
7716
- const parts = relative(ui, path).split(sep);
7717
- let current = ui;
7718
- for (const part of ["", ...parts]) {
7719
- if (part !== "") current = join(current, part);
7720
- try {
7721
- if (lstatSync(current).isSymbolicLink()) return `the path passes through the symbolic link ${current}`;
7722
- } catch (error) {
7723
- if (error.code === "ENOENT") break;
7724
- if (error.code === "ENOTDIR") return `${current} cannot be traversed as a folder`;
7725
- throw error;
7726
- }
7727
- }
7728
- }
7729
- /**
7730
- * Why a call of a file tool is not one on an interface pack of the world, or nothing when it is: the file must be a text
7731
- * file of a pack folder `<world>/ui/<pack>/`, and a write must not carry more text than a pack file may hold.
7732
- * @param path - the absolute path asked for.
7733
- * @param world - the world's folder.
7734
- */
7735
- function packFileProblem(tool, path, world, texts = []) {
7736
- const ui = join(world, "ui");
7737
- const inside = relative(ui, path);
7738
- const segments = inside.split(sep);
7739
- const hint = `in this chat the file tools reach only the text files of the world's interface packs, ${join(ui, "<pack>", "<file>")}. Nothing, not another path and not sandbox_permissions, lifts that: do not try again for this file, tell the person that it cannot be changed from here`;
7740
- if (inside === "" || inside.startsWith("..") || isAbsolute(inside) || segments.length < 2) return `${path} is not a file of an interface pack: ${hint}`;
7741
- if (!isPackId(segments[0])) return `"${segments[0]}" is not a usable pack name (letters, digits, "-" and "_"): ${hint}`;
7742
- if (segments.some((segment) => segment.startsWith("."))) return `${path}: names may not start with a dot`;
7743
- if (!TEXT_EXTENSIONS.includes(extname(path).slice(1).toLowerCase())) return `${path} is not a text file of a pack (${TEXT_EXTENSIONS.join(", ")}); pictures and other files are added by hand`;
7744
- const unsafe = unsafePath(ui, path);
7745
- if (unsafe !== void 0) return `${path}: ${unsafe}; file tools do not follow symbolic links in interface packs`;
7746
- if (WRITING.includes(tool) && texts.some((text) => Buffer.byteLength(text) > 204800)) return `a call may carry at most ${MAX_PACK_TEXT / 1024} KB of text`;
7747
- }
7748
- const textOf = (value) => typeof value === "string" ? [value] : [];
7749
- /**
7750
- * Keeps DSH's `read`, `write` and `edit` on the interface packs of the world in an authoring chat, and asks the person before
7751
- * any change. It stands first in the chain, so that what it refuses cannot be let through by a listener after it; and what a
7752
- * later listener decides still stands: a plugin that denies or asks keeps doing so, and only a plain allow becomes an ask.
7753
- */
7754
- async function packJail(exec, next, deps) {
7755
- const chat = exec.agent?.session.id;
7756
- if (!PACK_FILE_TOOLS.includes(exec.name) || chat === void 0 || authoredWorldOf(chat) === void 0) return await next();
7757
- const world = await deps.worldDirectory(chat);
7758
- if (world === void 0) return {
7759
- kind: "deny",
7760
- reason: "the world of this chat no longer exists"
7761
- };
7762
- const args = exec.arguments;
7763
- const requested = args["file_path"];
7764
- if (typeof requested !== "string" || requested === "" || requested.startsWith("~")) return {
7765
- kind: "deny",
7766
- reason: "file_path must be a path of an interface pack of this world"
7767
- };
7768
- const path = resolve(exec.agent?.session.header.cwd ?? world, requested);
7769
- const problem = packFileProblem(exec.name, path, world, [...textOf(args["content"]), ...textOf(args["new_string"])]);
7770
- if (problem !== void 0) return {
7771
- kind: "deny",
7772
- reason: problem
7773
- };
7774
- const writing = WRITING.includes(exec.name);
7775
- if (writing && await deps.reviewing(chat)) return {
7776
- kind: "deny",
7777
- reason: "an import does not write interface packs; they are left to the person"
7778
- };
7779
- const decision = await next();
7780
- if (!writing || decision.kind !== "allow") return decision;
7781
- const target = `“${relative(join(world, "ui"), path)}”`;
7782
- return {
7783
- kind: "ask",
7784
- reason: `${exec.name} interface pack file ${target}`,
7785
- displayReason: {
7786
- en: `${exec.name === "write" ? "Write" : "Edit"} ${target} of an interface pack in the world files?`,
7787
- zh: `${exec.name === "write" ? "写入" : "编辑"}世界文件中界面包的文件${target}?`
7788
- }
7789
- };
7790
- }
7791
- /** Puts the jail first in the chain of `tools/pre-execute`: what it refuses cannot be let through by a listener after it. */
7792
- function registerPackJail(ctx, deps) {
7793
- ctx.on("tools/pre-execute", (exec, next) => packJail(exec, next, deps), { prepend: true });
7794
- }
7795
- //#endregion
7796
- export { populateCalendar as $, readCard as $t, worldEntityImageFile as A, loadVariables as At, translateMessage as B, parseWorldFile as Bt, readWorldEditor as C, subfolders as Ct, uploadWorldCharacterPortrait as D, readWorldPrompt as Dt, replaceFile$1 as E, listWorldPrompts as Et, loadWorldParts as F, IMPORT_FOLDER as Ft, authoringChatSessionId as G, parseLoreEdit as Gt, importHooks as H, InvalidEditProblems as Ht, PRESET_FILE as I, ImportNotFoundError as It, isReviewing as J, parseThingEdit as Jt, languageOfDocuments as K, parsePlaceEdit as Kt, presetMessage as L, ImportStore as Lt, deleteTriggerDocument as M, variableProblems as Mt, readTriggerDocuments as N, CHARACTER_FILE_NAME as Nt, uploadWorldEntityImage as O, writeWorldPrompt as Ot, writeTriggerDocument as P, parseCharacterFile as Pt, loadValidatedWorld as Q, pictureOf as Qt, presetTools as R, parseChoices as Rt, generateWorldEntityImage as S, loadCharacters as St, removeWorldTrigger as T, deleteWorldPrompt as Tt, importTools as U, parseCharacterEdit as Ut, translateTools as V, parseWorldInfoEdit as Vt, authoredWorldOf as W, parseFactionEdit as Wt, guardedLookup as X, ImportCardError as Xt, markReady as Y, IMPORT_COMMAND as Yt, vetUrl as Z, isPng as Zt, editWorldPlots as _, loadCalendar as _t, deleteWorldPackFile as a, populateKnowledge as at, entityFolder as b, loadItems as bt, createAuthoredEntity as c, populateRoutines as ct, replaceAuthoredEntity as d, routineProblems as dt, DICE_COMPARISONS as en, populateCharacters as et, editWorldCharacter as f, TRIGGERS_FILE_NAME as ft, editWorldPlace as g, CALENDAR_FILE_NAME as gt, editWorldNarrationVoice as h, parseDiceFile as ht, checkWorldPack as i, populateItems as it, writeWorldTrigger as j, parseVariablesFile as jt, worldCharacterPortraitFile as k, VARIABLES_FILE_NAME as kt, deleteAuthoredEntity as l, populateTriggers as lt, editWorldLore as m, loadDice as mt, packFileProblem as n, DICE_RESULTS as nn, populateDice as nt, listWorldPacks as o, populateLocations as ot, editWorldFaction as p, DICE_FILE_NAME as pt, readWorldDocuments as q, parseRelationEdit as qt, registerPackJail as r, populateFactions as rt, AUTHORED_ENTITY_KINDS as s, populateLore as st, MAX_PACK_TEXT as t, DICE_READINGS as tn, populateClock as tt, readAuthoredEntityDocument as u, populateVariables as ut, editWorldRelation as v, parseCalendarFile as vt, readWorldTrigger as w, PROSE_PROMPTS as wt, generateWorldCharacterPortrait as x, CHARACTERS_DIR as xt, editWorldThing as y, loadLocations as yt, readPreset as z, WORLD_FILE_NAME as zt };
5770
+ export { LOCATION_FILE_NAME as $, parseDiceFile as A, FACTIONS_DIR as B, populateTriggers as C, isPng as Ct, loadTriggers as D, DICE_READINGS as Dt, TRIGGERS_FILE_NAME as E, DICE_COMPARISONS as Et, loadLore as F, extractStyleFrom as G, CHARACTERS_DIR as H, LOCATIONS_DIR as I, loadVariables as J, withPlayer as K, loadLocations as L, loadCalendar as M, parseCalendarFile as N, DICE_FILE_NAME as O, DICE_RESULTS as Ot, LORE_DIR as P, parseLoreFile as Q, ITEMS_DIR as R, populateRoutines as S, ImportCardError as St, routineProblems as T, readCard as Tt, loadCharacters as U, loadFactions as V, subfolders as W, variableProblems as X, parseVariablesFile as Y, LORE_FILE_NAME as Z, populateFactions as _, parseLoreEdit as _t, worldOf as a, CHARACTER_FILE_NAME as at, populateLocations as b, parseThingEdit as bt, isReviewing as c, ImportNotFoundError as ct, vetUrl as d, WORLD_FILE_NAME as dt, parseLocationFile as et, loadValidatedWorld as f, parseWorldFile as ft, populateDice as g, parseFactionEdit as gt, populateClock as h, parseCharacterEdit as ht, importTools as i, parseFactionFile as it, CALENDAR_FILE_NAME as j, loadDice as k, markReady as l, ImportStore as lt, populateCharacters as m, InvalidEditProblems as mt, contextOf as n, parseItemFile as nt, authoredWorldOf as o, parseCharacterFile as ot, populateCalendar as p, parseWorldInfoEdit as pt, VARIABLES_FILE_NAME as q, importHooks as r, FACTION_FILE_NAME as rt, authoringChatSessionId as s, IMPORT_FOLDER as st, readPreset as t, ITEM_FILE_NAME as tt, guardedLookup as u, parseChoices as ut, populateItems as v, parsePlaceEdit as vt, populateVariables as w, pictureOf as wt, populateLore as x, IMPORT_COMMAND as xt, populateKnowledge as y, parseRelationEdit as yt, loadItems as z };
7797
5771
 
7798
- //# sourceMappingURL=pack-jail-CybSNzxr.js.map
5772
+ //# sourceMappingURL=preset-ClQm7KPQ.js.map