@dsh-agentic-roleplay/core 0.3.3 → 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.
Files changed (36) hide show
  1. package/lib/authoring.js +7 -256
  2. package/lib/{child-lPncV1ps.js → child-CFjnaTZt.js} +62 -7
  3. package/lib/client.js +10950 -7439
  4. package/lib/client.js.map +1 -1
  5. package/lib/{deliver-De62a8i9.js → deliver-Cl6bjp7g.js} +49 -11
  6. package/lib/doctor.js +83 -7
  7. package/lib/{gallery-CtFDL22W.js → gallery-DIEgETzU.js} +2 -2
  8. package/lib/generator-DJ48HxPI.js +145 -0
  9. package/lib/{hooks-Ka22sFNy.js → hooks-DdO_tNhu.js} +58 -17
  10. package/lib/images.js +4 -3
  11. package/lib/index.js +1761 -71
  12. package/lib/language-BgyxtB2h.js +38 -0
  13. package/lib/{generator-B6FxlKOV.js → library-9JB9zw5a.js} +2 -143
  14. package/lib/{language-DWVwi1R7.js → load-Clkl0T7C.js} +6 -40
  15. package/lib/orchestration.js +23 -26
  16. package/lib/pack-jail-ClMpVc__.js +1979 -0
  17. package/lib/{packs-BYjrAen6.js → packs-BC2A3geF.js} +3 -29
  18. package/lib/{presenter-agent-Dt21K96b.js → presenter-agent-DnNEG_Mn.js} +5 -4
  19. package/lib/{documents-Do4lz4SB.js → preset-ClQm7KPQ.js} +67 -1656
  20. package/lib/preset-author-tools-Dibp-LY9.js +270 -0
  21. package/lib/preset-authoring.js +53 -0
  22. package/lib/presets-DNjNxQL5.js +335 -0
  23. package/lib/{reflection-md7BCYCl.js → reflection-Bju_LPFn.js} +131 -9
  24. package/package.json +3 -2
  25. package/prompts/en/doctor/procedure.md +1 -1
  26. package/prompts/en/import/character.md +1 -1
  27. package/prompts/en/preset/persona.md +1 -0
  28. package/prompts/en/preset/procedure.md +1 -0
  29. package/prompts/en/preset/welcome.md +1 -0
  30. package/prompts/en/roleplay/record-keeper.md +2 -2
  31. package/prompts/zh/doctor/procedure.md +1 -1
  32. package/prompts/zh/import/character.md +1 -1
  33. package/prompts/zh/preset/persona.md +1 -0
  34. package/prompts/zh/preset/procedure.md +1 -0
  35. package/prompts/zh/preset/welcome.md +1 -0
  36. package/prompts/zh/roleplay/record-keeper.md +2 -2
@@ -1,15 +1,14 @@
1
- import { _ as API_PREFIX, b as INTENT_TYPES, 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";
4
- import { a as runChild } from "./child-lPncV1ps.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, join, relative, sep } from "node:path";
7
- import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
3
+ import { S as InvalidWorldError, _ as shippedLanguages, a as readDocument, c as formatIssue, g as promptProblem, i as plotReferenceProblems, n as loadPlots, o as errorMessage, s as Reader, u as PROMPTS_FOLDER } from "./load-Clkl0T7C.js";
4
+ import { a as runChild } from "./child-CFjnaTZt.js";
5
+ import { b as slug, c as referenceImagePath, d as MEDIA_TYPES, h as writeImageFileMetadata, n as imageExtensionOf, t as addToLibrary, v as mapLimit, x as uniqueKey, y as norm } from "./library-9JB9zw5a.js";
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";
@@ -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",
@@ -2699,7 +2636,20 @@ const CHARACTER_SCHEMA = {
2699
2636
  type: "object",
2700
2637
  properties: {
2701
2638
  places: strs("Names from the list of places that they know of."),
2702
- things: strs("Names from the list of things that they know of.")
2639
+ things: strs("Names from the list of things that they know of."),
2640
+ ways: {
2641
+ type: "array",
2642
+ items: {
2643
+ type: "object",
2644
+ properties: {
2645
+ from: str("A name from the list of places."),
2646
+ to: str("A name from the list of places.")
2647
+ },
2648
+ required: ["from", "to"],
2649
+ additionalProperties: false
2650
+ },
2651
+ description: "Ways between two places of the list that they know how to take (the way from one to the other)."
2652
+ }
2703
2653
  },
2704
2654
  additionalProperties: false
2705
2655
  }
@@ -2791,6 +2741,23 @@ function characterDocument(entity, answer, roster) {
2791
2741
  const knowledge = {};
2792
2742
  put(knowledge, "locations", known(list(knows["places"]), "place"));
2793
2743
  put(knowledge, "items", known(list(knows["things"]), "thing"));
2744
+ const ways = /* @__PURE__ */ new Set();
2745
+ const exits = [];
2746
+ for (const way of objects(knows["ways"])) {
2747
+ const from = findEntity(roster, text$1(way["from"]), "place");
2748
+ const to = findEntity(roster, text$1(way["to"]), "place");
2749
+ if (from === void 0 || to === void 0 || from.key === to.key) {
2750
+ notes.push(`${entity.name}: the way from "${text$1(way["from"])}" to "${text$1(way["to"])}" is not between two places of the world, so they do not know of it`);
2751
+ continue;
2752
+ }
2753
+ if (ways.has(`${from.key}>${to.key}`)) continue;
2754
+ ways.add(`${from.key}>${to.key}`);
2755
+ exits.push({
2756
+ from: from.key,
2757
+ to: to.key
2758
+ });
2759
+ }
2760
+ put(knowledge, "exits", exits);
2794
2761
  put(document, "knowledge", Object.keys(knowledge).length === 0 ? void 0 : knowledge);
2795
2762
  return {
2796
2763
  document,
@@ -3131,9 +3098,17 @@ function pruneKnowledge(result) {
3131
3098
  locations: new Set(result.locations.map((entry) => String(entry["id"]))),
3132
3099
  items: new Set(result.items.map((entry) => String(entry["id"])))
3133
3100
  };
3101
+ const ways = new Set(result.locations.flatMap((place) => objects(place["exits"]).map((exit) => `${String(place["id"])}>${String(exit["to"])}`)));
3134
3102
  for (const character of result.characters) {
3135
3103
  const knowledge = character["knowledge"];
3136
3104
  if (knowledge === void 0) continue;
3105
+ const routes = objects(knowledge["exits"]);
3106
+ const open = routes.filter((route) => ways.has(`${String(route["from"])}>${String(route["to"])}`));
3107
+ if (open.length !== routes.length) {
3108
+ result.notes.push(`${String(character["name"])}: ${routes.length - open.length} known way(s) left out because the world has no such way`);
3109
+ if (open.length === 0) delete knowledge["exits"];
3110
+ else knowledge["exits"] = open;
3111
+ }
3137
3112
  for (const field of ["locations", "items"]) {
3138
3113
  const keys = knowledge[field] ?? [];
3139
3114
  const kept = keys.filter((key) => written[field].has(key));
@@ -3429,11 +3404,11 @@ const VARIABLES_SCHEMA = {
3429
3404
  description: "Names from the lists of characters, places or things it is limited to; empty for all."
3430
3405
  },
3431
3406
  min: {
3432
- type: ["number", "null"],
3407
+ oneOf: [{ type: "number" }, { type: "null" }],
3433
3408
  description: "The lowest value the card allows, or null."
3434
3409
  },
3435
3410
  max: {
3436
- type: ["number", "null"],
3411
+ oneOf: [{ type: "number" }, { type: "null" }],
3437
3412
  description: "The highest value the card allows, or null."
3438
3413
  },
3439
3414
  integer: {
@@ -3441,11 +3416,11 @@ const VARIABLES_SCHEMA = {
3441
3416
  description: "True when it counts whole units."
3442
3417
  },
3443
3418
  default: {
3444
- type: [
3445
- "number",
3446
- "boolean",
3447
- "string",
3448
- "null"
3419
+ oneOf: [
3420
+ { type: "number" },
3421
+ { type: "boolean" },
3422
+ { type: "string" },
3423
+ { type: "null" }
3449
3424
  ],
3450
3425
  description: "Where it starts: a number, true or false, or one of the options; null when the card does not say."
3451
3426
  },
@@ -5516,518 +5491,6 @@ async function finish(ctx, world) {
5516
5491
  return result;
5517
5492
  }
5518
5493
  //#endregion
5519
- //#region src/host/translate/terms.ts
5520
- const STOP = /* @__PURE__ */ new Set([
5521
- "the",
5522
- "and",
5523
- "for",
5524
- "with",
5525
- "from",
5526
- "that",
5527
- "this",
5528
- "his",
5529
- "her",
5530
- "their",
5531
- "she",
5532
- "he",
5533
- "they",
5534
- "you",
5535
- "your",
5536
- "but",
5537
- "not",
5538
- "when",
5539
- "where",
5540
- "what",
5541
- "who",
5542
- "one",
5543
- "two",
5544
- "its",
5545
- "has",
5546
- "had",
5547
- "was",
5548
- "were",
5549
- "are",
5550
- "there",
5551
- "then",
5552
- "now",
5553
- "at",
5554
- "in",
5555
- "on",
5556
- "of",
5557
- "to",
5558
- "a",
5559
- "an"
5560
- ]);
5561
- const MAX_TERMS = 40;
5562
- const MIN_USES = 3;
5563
- const capitalised = (word) => /^\p{Lu}[\p{L}'’-]{2,}$/u.test(word) && !STOP.has(word.toLowerCase());
5564
- /** The parts of a name written "Place - Room": each part is a name of its own, and so is the whole. */
5565
- function partsOfName(name) {
5566
- return name.split(/\s+[-–—]\s+/).map((part) => part.trim()).filter((part) => part !== "");
5567
- }
5568
- /**
5569
- * 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
5570
- * 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.
5571
- */
5572
- function recurringTerms(names, texts) {
5573
- const known = new Set(names);
5574
- const found = /* @__PURE__ */ new Map();
5575
- const add = (term, uses) => {
5576
- if (!known.has(term)) found.set(term, (found.get(term) ?? 0) + uses);
5577
- };
5578
- for (const name of names) for (const part of partsOfName(name)) if (part !== name) add(part, MIN_USES);
5579
- const counts = /* @__PURE__ */ new Map();
5580
- for (const text of [...names, ...texts]) {
5581
- const words = text.split(/[^\p{L}'’-]+/u);
5582
- for (let at = 0; at < words.length; at += 1) for (const size of [2, 3]) {
5583
- const phrase = words.slice(at, at + size);
5584
- if (phrase.length !== size || !phrase.every((word) => capitalised(word.replace(/['’]s$/, "")))) continue;
5585
- const key = phrase.join(" ").replace(/['’]s$/, "");
5586
- counts.set(key, (counts.get(key) ?? 0) + 1);
5587
- }
5588
- }
5589
- for (const [phrase, uses] of counts) if (uses >= MIN_USES) add(phrase, uses);
5590
- return [...found].sort((a, b) => b[1] - a[1]).slice(0, MAX_TERMS).map(([term]) => term);
5591
- }
5592
- /** Whether `text` uses `term` as a word of its own (case as written). */
5593
- function usesTerm(text, term) {
5594
- const escaped = term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5595
- return new RegExp(`(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`, "u").test(text);
5596
- }
5597
- //#endregion
5598
- //#region src/host/translate/prose.ts
5599
- const rooted = (roots, paths) => roots.flatMap((root) => paths.map((path) => `${root}${path}`));
5600
- const INTENT = [
5601
- ".name",
5602
- ".description",
5603
- ".plan[]",
5604
- ".open_threads[]",
5605
- ".constraints[]"
5606
- ];
5607
- const FIELDS = {
5608
- world: {
5609
- names: ["name"],
5610
- text: [
5611
- "description",
5612
- "rules[]",
5613
- "metadata.tags[]",
5614
- "opening_message",
5615
- "opening_message[].text",
5616
- "alternate_openings[].title",
5617
- "alternate_openings[].text"
5618
- ]
5619
- },
5620
- calendar: {
5621
- names: ["holidays[].name"],
5622
- text: []
5623
- },
5624
- variables: {
5625
- names: [],
5626
- text: rooted(["[]", "variables[]"], [
5627
- ".name",
5628
- ".description",
5629
- ".bands[].label"
5630
- ])
5631
- },
5632
- triggers: {
5633
- names: [],
5634
- text: rooted(["[]", "triggers[]"], [
5635
- ".name",
5636
- ".announce.text",
5637
- ".effects[].text",
5638
- ".effects[].edit.events[].text"
5639
- ])
5640
- },
5641
- plots: {
5642
- names: [],
5643
- text: [
5644
- "plots[].name",
5645
- "plots[].premise",
5646
- "plots[].themes[]",
5647
- "plots[].stakes[]",
5648
- "plots[].resolutions[]",
5649
- ...["hooks", "developments"].flatMap((list) => [
5650
- `plots[].${list}[].text`,
5651
- `plots[].${list}[].prerequisites[]`,
5652
- `plots[].${list}[].guidance`,
5653
- `plots[].${list}[].avoid[]`
5654
- ])
5655
- ]
5656
- },
5657
- character: {
5658
- names: ["name", "aliases[]"],
5659
- text: [
5660
- "age",
5661
- "gender",
5662
- "summary",
5663
- "personality",
5664
- "background",
5665
- "appearance",
5666
- "speech.style",
5667
- "speech.examples[]",
5668
- "start.public_state",
5669
- "start.inner_state",
5670
- "start.activity",
5671
- ...INTENT.map((path) => `start.intents[]${path}`),
5672
- "relationships[].label",
5673
- "relationships[].summary",
5674
- "routine[].activity"
5675
- ]
5676
- },
5677
- location: {
5678
- names: ["name", "features[].name"],
5679
- text: [
5680
- "description",
5681
- "features[].description",
5682
- "exits[].description",
5683
- "exits[].note",
5684
- "exits[].back_description"
5685
- ]
5686
- },
5687
- item: {
5688
- names: ["name"],
5689
- text: ["description", "quality"]
5690
- },
5691
- faction: {
5692
- names: ["name", "aliases[]"],
5693
- text: [
5694
- "summary",
5695
- "description",
5696
- "values[]",
5697
- "structure",
5698
- "start.public_state",
5699
- "start.inner_state",
5700
- ...INTENT.map((path) => `start.goals[]${path}`),
5701
- "members[].role",
5702
- "members[].rank",
5703
- "relationships[].label",
5704
- "relationships[].summary"
5705
- ]
5706
- },
5707
- lore: {
5708
- names: [],
5709
- text: [
5710
- "title",
5711
- "summary",
5712
- "body"
5713
- ]
5714
- }
5715
- };
5716
- /** 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. */
5717
- function leavesOf(kind, document) {
5718
- const fields = FIELDS[kind];
5719
- const names = new Set(fields.names);
5720
- const text = new Set(fields.text);
5721
- const leaves = [];
5722
- const visit = (value, pattern, path) => {
5723
- if (typeof value === "string") {
5724
- const name = names.has(pattern);
5725
- if ((name || text.has(pattern)) && /\p{L}/u.test(value)) leaves.push({
5726
- path,
5727
- text: value,
5728
- name
5729
- });
5730
- } else if (Array.isArray(value)) value.forEach((entry, index) => {
5731
- visit(entry, `${pattern}[]`, [...path, index]);
5732
- });
5733
- else if (typeof value === "object" && value !== null) for (const [key, entry] of Object.entries(value)) visit(entry, pattern === "" ? key : `${pattern}.${key}`, [...path, key]);
5734
- };
5735
- visit(document, "", []);
5736
- return leaves;
5737
- }
5738
- /** Puts `text` where `path` points in the document. */
5739
- function setLeaf(document, path, text) {
5740
- let at = document;
5741
- for (const step of path.slice(0, -1)) at = at[step];
5742
- at[path[path.length - 1]] = text;
5743
- }
5744
- const ROOT_FILES = [
5745
- ["world.json", "world"],
5746
- ["calendar.json", "calendar"],
5747
- ["variables.json", "variables"],
5748
- ["triggers.json", "triggers"],
5749
- ["plots.json", "plots"]
5750
- ];
5751
- const ENTITIES = [
5752
- [
5753
- "characters",
5754
- "character.json",
5755
- "character"
5756
- ],
5757
- [
5758
- "locations",
5759
- "location.json",
5760
- "location"
5761
- ],
5762
- [
5763
- "items",
5764
- "item.json",
5765
- "item"
5766
- ],
5767
- [
5768
- "factions",
5769
- "faction.json",
5770
- "faction"
5771
- ],
5772
- [
5773
- "lore",
5774
- "lore.json",
5775
- "lore"
5776
- ]
5777
- ];
5778
- async function readIfThere(file) {
5779
- try {
5780
- return JSON.parse(await readFile(file, "utf8"));
5781
- } catch (error) {
5782
- if (error.code === "ENOENT") return void 0;
5783
- throw new Error(`${file} cannot be read: ${error instanceof Error ? error.message : String(error)}`);
5784
- }
5785
- }
5786
- /** 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. */
5787
- async function readWorldDocuments(directory) {
5788
- const found = [];
5789
- for (const [file, kind] of ROOT_FILES) {
5790
- const document = await readIfThere(join(directory, file));
5791
- if (document !== void 0) found.push({
5792
- file,
5793
- kind,
5794
- document
5795
- });
5796
- }
5797
- for (const [folder, name, kind] of ENTITIES) {
5798
- let entries;
5799
- try {
5800
- entries = (await readdir(join(directory, folder), { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
5801
- } catch (error) {
5802
- if (error.code === "ENOENT") continue;
5803
- throw error;
5804
- }
5805
- for (const entry of entries) {
5806
- const file = join(folder, entry, name);
5807
- const document = await readIfThere(join(directory, file));
5808
- if (document !== void 0) found.push({
5809
- file,
5810
- kind,
5811
- document
5812
- });
5813
- }
5814
- }
5815
- return found;
5816
- }
5817
- //#endregion
5818
- //#region src/host/translate/translate-world.ts
5819
- /** What is not carried over to a translation: the removed things of the editor and the card import's working files. */
5820
- const NOT_COPIED = /* @__PURE__ */ new Set([".trash", ".import"]);
5821
- const TERMS_PER_JOB = 40;
5822
- const TEXTS_PER_JOB = 30;
5823
- const CHARS_PER_JOB = 5e3;
5824
- const GLOSSARY_SHOWN = 60;
5825
- /** A text with fewer letters than this is too short to check which language it came out in. */
5826
- const CHECKED_LETTERS = 40;
5827
- /** A name shorter than this is too likely to be an ordinary word to be held to the glossary. */
5828
- const MIN_TERM = 4;
5829
- var TranslationRefusedError = class extends Error {};
5830
- const STRINGS = {
5831
- type: "array",
5832
- items: { type: "string" }
5833
- };
5834
- const GLOSSARY_SCHEMA = {
5835
- type: "object",
5836
- properties: { terms: {
5837
- type: "array",
5838
- items: {
5839
- type: "object",
5840
- properties: {
5841
- source: { type: "string" },
5842
- target: { type: "string" }
5843
- },
5844
- required: ["source", "target"],
5845
- additionalProperties: false
5846
- },
5847
- description: "One entry for each name given, in the same order, with the source exactly as given."
5848
- } },
5849
- required: ["terms"],
5850
- additionalProperties: false
5851
- };
5852
- const TEXTS_SCHEMA = {
5853
- type: "object",
5854
- properties: { translations: {
5855
- ...STRINGS,
5856
- description: "The translation of each text, in the order given."
5857
- } },
5858
- required: ["translations"],
5859
- additionalProperties: false
5860
- };
5861
- const braces = (text) => (text.match(/\{[^{}]*\}/g) ?? []).sort().join("\0");
5862
- const letters = (text) => text.match(/\p{L}/gu)?.length ?? 0;
5863
- /** The language the world is written in, from the words of all its files; nothing when there are too few to tell. */
5864
- function languageOfDocuments(documents) {
5865
- return textLanguage(documents.flatMap((entry) => leavesOf(entry.kind, entry.document).map((leaf) => leaf.text)).join("\n"));
5866
- }
5867
- function batches(items, size, maxItems, maxSize) {
5868
- const out = [];
5869
- let current = [];
5870
- let used = 0;
5871
- for (const item of items) {
5872
- if (current.length > 0 && (current.length >= maxItems || used + size(item) > maxSize)) {
5873
- out.push(current);
5874
- current = [];
5875
- used = 0;
5876
- }
5877
- current.push(item);
5878
- used += size(item);
5879
- }
5880
- if (current.length > 0) out.push(current);
5881
- return out;
5882
- }
5883
- /** Why a set of translations cannot be used, or nothing. A text left in the language it was written in is not a translation. */
5884
- function problemWith(sources, from, translations, glossary) {
5885
- if (translations.length !== sources.length) return `${sources.length} texts were given and ${translations.length} translations came back: give exactly one for each, in order`;
5886
- for (const [index, source] of sources.entries()) {
5887
- const text = translations[index];
5888
- if (text.trim() === "") return `translation ${index + 1} is empty`;
5889
- if (braces(source) !== braces(text)) return `translation ${index + 1} must keep the text in curly braces exactly as it is: ${(source.match(/\{[^{}]*\}/g) ?? []).join(" ")}`;
5890
- if (letters(source) >= CHECKED_LETTERS && textLanguage(source) === from && textLanguage(text) === from) return `translation ${index + 1} is still in the original language`;
5891
- 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}"`;
5892
- }
5893
- }
5894
- async function glossaryOf(ctx, names, vars, known = /* @__PURE__ */ new Map()) {
5895
- const jobs = batches(names, () => 1, TERMS_PER_JOB, TERMS_PER_JOB);
5896
- const parts = await mapLimit(jobs, ctx.concurrency, async (terms) => {
5897
- const job = {
5898
- persona: ctx.text("translate/glossary", vars),
5899
- prompt: JSON.stringify({
5900
- known: Object.fromEntries([...known].filter(([source]) => terms.some((term) => term.toLowerCase().includes(source.toLowerCase())))),
5901
- names: terms
5902
- }),
5903
- result: GLOSSARY_SCHEMA,
5904
- check: (value) => {
5905
- if (value.terms.length !== terms.length) return `${terms.length} names were given and ${value.terms.length} came back: one for each, in order`;
5906
- const wrong = terms.findIndex((term, index) => value.terms[index].source !== term || value.terms[index].target.trim() === "");
5907
- return wrong === -1 ? void 0 : `entry ${wrong + 1} must repeat "${terms[wrong]}" exactly and have a translation`;
5908
- }
5909
- };
5910
- return (await ctx.run(job)).terms;
5911
- });
5912
- return new Map(parts.flat().map((term) => [term.source, term.target.trim()]));
5913
- }
5914
- async function translated(ctx, texts, glossary, from, vars) {
5915
- return (await mapLimit(batches(texts, (text) => text.length, TEXTS_PER_JOB, CHARS_PER_JOB), ctx.concurrency, async (group) => {
5916
- const haystack = group.join("\n").toLowerCase();
5917
- const shown = [...glossary].filter(([source]) => haystack.includes(source.toLowerCase())).slice(0, GLOSSARY_SHOWN);
5918
- const relevant = new Map(shown);
5919
- const job = {
5920
- persona: ctx.text("translate/document", vars),
5921
- prompt: JSON.stringify({
5922
- glossary: Object.fromEntries(shown),
5923
- texts: group.map((text, index) => ({
5924
- n: index + 1,
5925
- text
5926
- }))
5927
- }),
5928
- result: TEXTS_SCHEMA,
5929
- check: (value) => problemWith(group, from, value.translations, relevant)
5930
- };
5931
- return (await ctx.run(job)).translations;
5932
- })).flat();
5933
- }
5934
- async function freeFolder(directory, suffix) {
5935
- for (let n = 1;; n += 1) {
5936
- const candidate = join(dirname(directory), `${basename(directory)} ${suffix}${n === 1 ? "" : ` ${n}`}`);
5937
- try {
5938
- await stat(candidate);
5939
- } catch (error) {
5940
- if (error.code === "ENOENT") return candidate;
5941
- throw error;
5942
- }
5943
- }
5944
- }
5945
- async function listedIn(directory, names) {
5946
- const present = new Set(await readdir(directory));
5947
- return names.filter((name) => present.has(name));
5948
- }
5949
- /**
5950
- * 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.
5951
- * The original is never changed. The copy gets an id of its own and is checked as a story start would check it.
5952
- */
5953
- async function translateWorld(ctx, worlds, source, to, told) {
5954
- const documents = await readWorldDocuments(source.directory);
5955
- const from = languageOfDocuments(documents);
5956
- if (from === void 0) throw new TranslationRefusedError("there is too little text in this world to tell which language it is written in");
5957
- if (from === to) throw new TranslationRefusedError(`this world is already written in ${LANGUAGE_NAMES[to].en}`);
5958
- const vars = {
5959
- from: LANGUAGE_NAMES[from][told],
5960
- to: LANGUAGE_NAMES[to][told]
5961
- };
5962
- const leaves = documents.map((entry) => ({
5963
- entry,
5964
- leaves: leavesOf(entry.kind, entry.document)
5965
- }));
5966
- const names = [...new Set(leaves.flatMap((item) => item.leaves.filter((leaf) => leaf.name).map((leaf) => leaf.text)))];
5967
- ctx.say(`translating ${names.length} names`);
5968
- const prose = leaves.flatMap((item) => item.leaves.filter((leaf) => !leaf.name).map((leaf) => leaf.text));
5969
- const recurring = from === "en" ? recurringTerms(names, prose) : [];
5970
- const parts = await glossaryOf(ctx, recurring, vars);
5971
- const glossary = await glossaryOf(ctx, names, vars, parts);
5972
- for (const [term, rendering] of parts) glossary.set(term, rendering);
5973
- let texts = 0;
5974
- for (const { entry, leaves: own } of leaves) {
5975
- const words = own.filter((leaf) => !leaf.name);
5976
- for (const leaf of own.filter((item) => item.name)) setLeaf(entry.document, leaf.path, glossary.get(leaf.text) ?? leaf.text);
5977
- if (words.length === 0) continue;
5978
- ctx.say(`translating ${entry.file}`);
5979
- const result = await translated(ctx, words.map((leaf) => leaf.text), glossary, from, vars);
5980
- for (const [index, leaf] of words.entries()) setLeaf(entry.document, leaf.path, result[index]);
5981
- texts += words.length;
5982
- }
5983
- for (const { entry, leaves: own } of leaves) {
5984
- const document = entry.document;
5985
- if (entry.kind !== "character" && entry.kind !== "faction") continue;
5986
- const original = own.find((leaf) => leaf.name && leaf.path.length === 1 && leaf.path[0] === "name")?.text;
5987
- const aliases = Array.isArray(document["aliases"]) ? document["aliases"] : [];
5988
- if (original !== void 0 && original !== document["name"] && !aliases.includes(original)) document["aliases"] = [...aliases, original];
5989
- }
5990
- const id = randomUUID();
5991
- const destination = await freeFolder(source.directory, to);
5992
- await cp(source.directory, destination, {
5993
- recursive: true,
5994
- filter: (path) => !NOT_COPIED.has(relative(source.directory, path).split(sep)[0])
5995
- });
5996
- for (const entry of documents) {
5997
- const document = entry.kind === "world" ? (({ id: _old, ...rest }) => ({
5998
- id,
5999
- ...rest
6000
- }))(entry.document) : entry.document;
6001
- await writeFile(join(destination, entry.file), `${JSON.stringify(document, null, 2)}\n`);
6002
- }
6003
- const payload = await worlds.list({ refresh: true });
6004
- const made = payload.worlds.find((world) => world.id === id);
6005
- 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("; ")}`);
6006
- const record = await worlds.find(id);
6007
- const problems = [];
6008
- if (record !== void 0) try {
6009
- await loadValidatedWorld(record);
6010
- } catch (error) {
6011
- if (!(error instanceof InvalidWorldError)) throw error;
6012
- problems.push(...error.problems.map((problem) => `${relative(destination, problem.path) || "."}: ${problem.message}`));
6013
- }
6014
- return {
6015
- worldId: id,
6016
- name: made.name,
6017
- folder: basename(destination),
6018
- documents: documents.length,
6019
- texts,
6020
- names: names.length + recurring.length,
6021
- problems,
6022
- copiedAsIs: await listedIn(source.directory, [
6023
- "prompts",
6024
- "ui",
6025
- "images",
6026
- "media"
6027
- ])
6028
- };
6029
- }
6030
- //#endregion
6031
5494
  //#region src/shared/authoring-chat.ts
6032
5495
  const PREFIX = "world-author-";
6033
5496
  /** Stable DSH chat identity for the authoring conversation of one world. */
@@ -6249,46 +5712,6 @@ function importHooks(ctx, worlds, prompting) {
6249
5712
  });
6250
5713
  }
6251
5714
  //#endregion
6252
- //#region src/host/translate/tools.ts
6253
- const TRANSLATE_TOOL = "translate_world";
6254
- /** The message that has the authoring chat translate its world, in the language of the person who asked. */
6255
- function translateMessage(text, to, language) {
6256
- return text("translate/notice", {
6257
- tool: TRANSLATE_TOOL,
6258
- code: to,
6259
- to: to === "zh" ? language === "zh" ? "中文" : "Chinese" : language === "zh" ? "英文" : "English"
6260
- });
6261
- }
6262
- /** The tool of the authoring chat that translates the chat's world into a copy in another language. */
6263
- function translateTools(worlds, settings, prompting) {
6264
- return [defineTool({
6265
- name: TRANSLATE_TOOL,
6266
- 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.",
6267
- parameters: { language: {
6268
- type: "string",
6269
- required: true,
6270
- enum: [...STORY_LANGUAGES],
6271
- description: "The language to translate into: en or zh."
6272
- } },
6273
- output: {
6274
- schema: { type: "json" },
6275
- render: (_args, value) => [{
6276
- type: "text",
6277
- text: JSON.stringify(value, null, 1)
6278
- }]
6279
- },
6280
- isConcurrencySafe: () => false,
6281
- async execute(args, exec) {
6282
- if (!isStoryLanguage(args.language)) throw new Error(`language must be one of: ${STORY_LANGUAGES.join(", ")}`);
6283
- const world = await worldOf(worlds, exec);
6284
- const told = prompting.languages().get(world.id);
6285
- const text = (id, variables) => prompting.prompts().text(id, told, variables);
6286
- const report = await translateWorld(contextOf(exec, settings(), text), worlds, world, args.language, told.startsWith("zh") ? "zh" : "en");
6287
- return JSON.parse(JSON.stringify(report));
6288
- }
6289
- })];
6290
- }
6291
- //#endregion
6292
5715
  //#region src/host/import/preset.ts
6293
5716
  /** The older preset layout keeps its texts under fixed keys. */
6294
5717
  const LEGACY_KEYS = [
@@ -6344,1018 +5767,6 @@ function readPreset(file, name) {
6344
5767
  };
6345
5768
  }
6346
5769
  //#endregion
6347
- //#region src/host/import/preset-tools.ts
6348
- const PRESET_TOOL = "import_preset";
6349
- const PRESET_FILE = "preset.json";
6350
- const PRESET_PATH = `${IMPORT_FOLDER}/${PRESET_FILE}`;
6351
- /** The command that has the authoring chat apply a preset that was uploaded to the world. */
6352
- const presetMessage = () => `Apply the narration preset I uploaded to this world: call ${PRESET_TOOL} with file ${PRESET_PATH}.`;
6353
- /** The tool that turns an uploaded narration preset into the world's prose prompts; every call asks the person first. */
6354
- function presetTools(worlds, settings, prompting) {
6355
- return [defineTool({
6356
- name: PRESET_TOOL,
6357
- 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.`,
6358
- parameters: { file: {
6359
- type: "string",
6360
- required: true,
6361
- description: `The preset: ${PRESET_PATH}.`
6362
- } },
6363
- output: {
6364
- schema: { type: "json" },
6365
- render: (_args, value) => [{
6366
- type: "text",
6367
- text: JSON.stringify(value, null, 1)
6368
- }]
6369
- },
6370
- isConcurrencySafe: () => false,
6371
- async execute(args, exec) {
6372
- if (args.file.trim() !== PRESET_PATH) throw new Error(`the preset is ${PRESET_PATH}`);
6373
- const world = await worldOf(worlds, exec);
6374
- const file = join(world.directory, IMPORT_FOLDER, PRESET_FILE);
6375
- const preset = readPreset(await readFile(file).catch(() => {
6376
- throw new Error("no preset was uploaded to this world");
6377
- }), "preset");
6378
- const language = prompting.languages().get(world.id);
6379
- const text = (id, variables) => prompting.prompts().text(id, language, variables);
6380
- const made = await extractStyleFrom(contextOf(exec, settings(), text), preset.name, preset.pieces);
6381
- for (const { id, text: body } of made.prompts) for (const tag of shippedLanguages()) await writeWorldPrompt(world.directory, tag, id, withPlayer(body));
6382
- await rm(file, { force: true });
6383
- const written = made.prompts.map((entry) => entry.id);
6384
- return JSON.parse(JSON.stringify({
6385
- preset: preset.name,
6386
- written,
6387
- folder: `${PROMPTS_FOLDER}/<language>/`,
6388
- notes: made.notes,
6389
- 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."
6390
- }));
6391
- }
6392
- })];
6393
- }
6394
- //#endregion
6395
- //#region src/host/triggers/parts.ts
6396
- /** 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. */
6397
- async function loadWorldParts(directory) {
6398
- const { characters, problems: characterProblems } = await loadCharacters(directory);
6399
- const { locations, problems: locationProblems } = await loadLocations(directory);
6400
- const { items, slots, problems: itemProblems } = await loadItems(directory, {
6401
- characters: characters.map((character) => character.id),
6402
- locations
6403
- });
6404
- const { defs, problems: variableProblems } = await loadVariables(directory);
6405
- const { calendar, problems: calendarProblems } = await loadCalendar(directory);
6406
- const problems = [
6407
- ...characterProblems,
6408
- ...locationProblems,
6409
- ...itemProblems,
6410
- ...variableProblems,
6411
- ...calendarProblems
6412
- ];
6413
- 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("; ")}`]);
6414
- return {
6415
- characters,
6416
- locations,
6417
- items,
6418
- slots,
6419
- variables: defs,
6420
- calendar
6421
- };
6422
- }
6423
- //#endregion
6424
- //#region src/host/triggers/check.ts
6425
- /**
6426
- * 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
6427
- * 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
6428
- * as there. @returns the problems by trigger key; a trigger with none is not in it.
6429
- */
6430
- function triggerProblemsOf(parts, definitions) {
6431
- const found = /* @__PURE__ */ new Map();
6432
- if (definitions.length === 0) return found;
6433
- const scratch = createSessionStore(":memory:", {
6434
- id: "scratch",
6435
- name: "scratch",
6436
- world: {
6437
- id: "scratch",
6438
- name: "scratch"
6439
- }
6440
- }, { vectors: false });
6441
- try {
6442
- const session = scratch;
6443
- if (parts.calendar !== void 0) writeCalendar(scratch.metadata, parts.calendar);
6444
- populateLocations(session, parts.locations);
6445
- populateCharacters(session, parts.characters, parts.characters.find((character) => character.role === "playable")?.id ?? "");
6446
- populateItems(session, parts.items, parts.slots, parts.locations);
6447
- populateVariables(session, parts.variables, {
6448
- characters: parts.characters,
6449
- items: parts.items,
6450
- locations: parts.locations,
6451
- values: void 0
6452
- });
6453
- const keys = definitions.map((definition) => definition.key);
6454
- for (const definition of definitions) {
6455
- const problems = triggerReferenceProblems(scratch, definition, keys).map((problem) => problem.slice(definition.key.length + 2));
6456
- if (problems.length > 0) found.set(definition.key, problems);
6457
- }
6458
- } finally {
6459
- scratch.close();
6460
- }
6461
- return found;
6462
- }
6463
- //#endregion
6464
- //#region src/host/worlds/world-editor.ts
6465
- function stateOf(world, definition, names) {
6466
- const { start } = definition;
6467
- const portrait = referenceImagePath(world.directory, {
6468
- kind: "character",
6469
- localId: definition.id,
6470
- ...definition.visualIdentity?.globalId === void 0 ? {} : { globalId: definition.visualIdentity.globalId }
6471
- });
6472
- return {
6473
- key: definition.id,
6474
- name: definition.name,
6475
- aliases: definition.aliases,
6476
- role: definition.role,
6477
- tier: definition.tier,
6478
- kind: definition.kind,
6479
- control: definition.role === "playable" ? "player" : "agent",
6480
- ...definition.age === void 0 ? {} : { age: definition.age },
6481
- ...definition.gender === void 0 ? {} : { gender: definition.gender },
6482
- ...definition.pronouns === void 0 ? {} : { pronouns: definition.pronouns },
6483
- summary: definition.summary,
6484
- personality: definition.personality,
6485
- background: definition.background,
6486
- appearance: definition.appearance,
6487
- speech: definition.speech,
6488
- ...definition.voice === void 0 ? {} : { voice: definition.voice },
6489
- ...definition.visualIdentity === void 0 ? {} : { visualIdentity: definition.visualIdentity },
6490
- ...existsSync(portrait) ? { portrait: `/${API_PREFIX}/worlds/state/character/portrait/file?id=${encodeURIComponent(world.id)}&key=${encodeURIComponent(definition.id)}&v=${statSync(portrait).mtimeMs}` } : {},
6491
- state: {
6492
- publicState: start.publicState,
6493
- innerState: start.innerState,
6494
- activity: start.activity
6495
- },
6496
- ...start.place === void 0 ? {} : { place: {
6497
- key: start.place.location,
6498
- name: names.get(start.place.location) ?? start.place.location,
6499
- ...start.place.position === void 0 ? {} : { position: start.place.position }
6500
- } },
6501
- goals: start.intents.map((intent, index) => ({
6502
- ref: String(index),
6503
- name: intent.name,
6504
- description: intent.description,
6505
- status: intent.status,
6506
- priority: intent.priority
6507
- }))
6508
- };
6509
- }
6510
- /** 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. */
6511
- function triggersOf(parts, scripted) {
6512
- if (scripted.problems.length > 0) return {
6513
- triggers: [],
6514
- triggersProblem: scripted.problems.map((problem) => problem.message).join("; ")
6515
- };
6516
- const view = (problems) => scripted.triggers.map((definition) => ({
6517
- key: definition.key,
6518
- name: definition.name,
6519
- when: definition.condition,
6520
- effects: definition.effects,
6521
- repeat: definition.repeat,
6522
- priority: definition.priority,
6523
- ...definition.cooldownSeconds === void 0 ? {} : { cooldownSeconds: definition.cooldownSeconds },
6524
- ...definition.chance === void 0 ? {} : { chance: definition.chance },
6525
- ...definition.expires === void 0 ? {} : { expires: definition.expires },
6526
- announced: definition.announce !== void 0,
6527
- problems: problems.get(definition.key) ?? []
6528
- }));
6529
- try {
6530
- return { triggers: view(triggerProblemsOf(parts, scripted.triggers)) };
6531
- } catch (error) {
6532
- return {
6533
- triggers: view(/* @__PURE__ */ new Map()),
6534
- 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)}`
6535
- };
6536
- }
6537
- }
6538
- /** The characters of a world as they start, and the places they can start in. */
6539
- async function readWorldEditor(world) {
6540
- const [{ characters }, { locations }, { factions }, { lore }, { plots }] = await Promise.all([
6541
- loadCharacters(world.directory),
6542
- loadLocations(world.directory),
6543
- loadFactions(world.directory),
6544
- loadLore(world.directory),
6545
- loadPlots(world.directory)
6546
- ]);
6547
- const { items, slots } = await loadItems(world.directory, {
6548
- characters: characters.map((character) => character.id),
6549
- locations
6550
- });
6551
- const scripted = await loadTriggers(world.directory);
6552
- const declared = await loadVariables(world.directory);
6553
- const { calendar } = await loadCalendar(world.directory);
6554
- const { triggers, triggersProblem } = triggersOf({
6555
- characters,
6556
- locations,
6557
- items,
6558
- slots,
6559
- variables: declared.defs,
6560
- calendar
6561
- }, scripted);
6562
- const names = new Map(locations.map((location) => [location.id, location.name]));
6563
- const characterNames = new Map(characters.map((character) => [character.id, character.name]));
6564
- const itemNames = new Map(items.map((item) => [item.id, item.name]));
6565
- 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;
6566
- const entity = (kind, key, name) => ({
6567
- kind,
6568
- key,
6569
- name
6570
- });
6571
- const characterEntity = (key) => entity("character", key, characterNames.get(key) ?? key);
6572
- const factionNames = new Map(factions.map((faction) => [faction.id, faction.name]));
6573
- const relations = [];
6574
- for (const character of characters) {
6575
- for (const relation of character.relationships ?? []) relations.push({
6576
- key: relationKey("character", character.id, relation.to),
6577
- kind: "character",
6578
- from: characterEntity(character.id),
6579
- to: characterEntity(relation.to),
6580
- label: relation.label,
6581
- summary: relation.summary,
6582
- familiarity: relation.familiarity,
6583
- trust: relation.trust,
6584
- affinity: relation.affinity,
6585
- tension: relation.tension
6586
- });
6587
- for (const location of character.knowledge?.locations ?? []) relations.push({
6588
- key: relationKey("knowledge", character.id, "location", location),
6589
- kind: "knowledge",
6590
- from: characterEntity(character.id),
6591
- to: entity("location", location, names.get(location) ?? location),
6592
- observed: false
6593
- });
6594
- for (const item of character.knowledge?.items ?? []) relations.push({
6595
- key: relationKey("knowledge", character.id, "item", item),
6596
- kind: "knowledge",
6597
- from: characterEntity(character.id),
6598
- to: entity("item", item, itemNames.get(item) ?? item),
6599
- observed: false
6600
- });
6601
- for (const exit of character.knowledge?.exits ?? []) relations.push({
6602
- key: relationKey("knowledge", character.id, "exit", exit.from, exit.to),
6603
- kind: "knowledge",
6604
- from: characterEntity(character.id),
6605
- to: entity("exit", `${exit.from}>${exit.to}`, `${names.get(exit.from) ?? exit.from} → ${names.get(exit.to) ?? exit.to}`),
6606
- observed: false
6607
- });
6608
- }
6609
- for (const location of locations) for (const exit of location.exits) relations.push({
6610
- key: relationKey("exit", location.id, exit.to),
6611
- kind: "exit",
6612
- from: entity("location", location.id, location.name),
6613
- to: entity("location", exit.to, names.get(exit.to) ?? exit.to),
6614
- description: exit.description,
6615
- ...exit.travelSeconds === void 0 ? {} : { travelSeconds: exit.travelSeconds },
6616
- state: exit.state,
6617
- note: exit.note,
6618
- oneWay: exit.oneWay
6619
- });
6620
- for (const faction of factions) {
6621
- for (const member of faction.members) relations.push({
6622
- key: relationKey("membership", faction.id, member.character),
6623
- kind: "membership",
6624
- from: characterEntity(member.character),
6625
- to: entity("faction", faction.id, faction.name),
6626
- role: member.role,
6627
- rank: member.rank,
6628
- status: member.status,
6629
- public: member.public,
6630
- commitment: member.commitment
6631
- });
6632
- for (const relation of faction.relationships) {
6633
- const targetName = relation.to.kind === "faction" ? factionNames.get(relation.to.id) ?? relation.to.id : characterNames.get(relation.to.id) ?? relation.to.id;
6634
- relations.push({
6635
- key: relationKey("social", "faction", faction.id, relation.to.kind, relation.to.id),
6636
- kind: "social",
6637
- from: entity("faction", faction.id, faction.name),
6638
- to: entity(relation.to.kind, relation.to.id, targetName),
6639
- label: relation.label,
6640
- summary: relation.summary ?? "",
6641
- familiarity: relation.familiarity ?? 0,
6642
- trust: relation.trust ?? 0,
6643
- affinity: relation.affinity ?? 0,
6644
- tension: relation.tension ?? 0
6645
- });
6646
- }
6647
- }
6648
- const worldDocument = JSON.parse(await readFile(join(world.directory, "world.json"), "utf8"));
6649
- const narrationVoice = typeof worldDocument["narration_voice"] === "string" ? worldDocument["narration_voice"] : void 0;
6650
- return {
6651
- ...narrationVoice === void 0 ? {} : { narrationVoice },
6652
- characters: characters.map((character) => stateOf(world, character, names)),
6653
- places: locations.map((location) => ({
6654
- key: location.id,
6655
- name: location.name,
6656
- description: location.description,
6657
- ...location.parent === void 0 ? {} : { parent: {
6658
- key: location.parent,
6659
- name: names.get(location.parent) ?? location.parent
6660
- } },
6661
- features: location.features,
6662
- ...location.visualIdentity === void 0 ? {} : { visualIdentity: location.visualIdentity }
6663
- })),
6664
- things: items.map((item) => ({
6665
- key: item.id,
6666
- name: item.name,
6667
- description: item.description,
6668
- quantity: item.quantity,
6669
- unique: item.unique,
6670
- quality: item.quality,
6671
- notable: item.notable,
6672
- hidden: item.hidden,
6673
- ...item.wearable === void 0 ? {} : { wearable: item.wearable },
6674
- ...item.container === void 0 ? {} : { containerState: item.container.state },
6675
- ...item.owner === void 0 ? {} : { owner: {
6676
- key: item.owner,
6677
- name: characterNames.get(item.owner) ?? item.owner
6678
- } },
6679
- holder: holder(item),
6680
- ...item.visualIdentity === void 0 ? {} : { visualIdentity: item.visualIdentity }
6681
- })),
6682
- factions: factions.map((faction) => ({
6683
- key: faction.id,
6684
- name: faction.name,
6685
- aliases: faction.aliases,
6686
- summary: faction.summary,
6687
- description: faction.description,
6688
- values: faction.values,
6689
- structure: faction.structure,
6690
- state: {
6691
- publicState: faction.start.publicState,
6692
- innerState: faction.start.innerState
6693
- },
6694
- goals: faction.start.goals.map((goal, index) => ({
6695
- ref: String(index),
6696
- name: goal.name,
6697
- description: goal.description,
6698
- status: goal.status,
6699
- priority: goal.priority
6700
- })),
6701
- members: faction.members.map((member) => ({
6702
- ...member,
6703
- name: characterNames.get(member.character) ?? member.character
6704
- })),
6705
- relationships: faction.relationships.map((relationship) => ({
6706
- target: `${relationship.to.kind}:${relationship.to.id}`,
6707
- label: relationship.label,
6708
- summary: relationship.summary ?? ""
6709
- }))
6710
- })),
6711
- lore: lore.map((entry) => ({
6712
- key: entry.id,
6713
- title: entry.title,
6714
- kind: entry.kind,
6715
- summary: entry.summary,
6716
- body: entry.body,
6717
- ...entry.startsAt === void 0 ? {} : { startsAt: entry.startsAt },
6718
- ...entry.endsAt === void 0 ? {} : { endsAt: entry.endsAt },
6719
- subjects: entry.subjects.map((subject) => ({
6720
- kind: subject.kind,
6721
- key: subject.id,
6722
- 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
6723
- })),
6724
- related: entry.related.map((key) => ({
6725
- key,
6726
- title: lore.find((candidate) => candidate.id === key)?.title ?? key
6727
- })),
6728
- sources: entry.sources
6729
- })),
6730
- triggers,
6731
- ...triggersProblem === void 0 ? {} : { triggersProblem },
6732
- plots: plots.map((definition) => ({ definition })),
6733
- relations
6734
- };
6735
- }
6736
- async function editWorldPlots(world, edit) {
6737
- const parsed = parsePlotsFile(JSON.stringify(edit.plots));
6738
- if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
6739
- const state = await readWorldEditor(world);
6740
- const references = plotReferenceProblems(parsed.value, [
6741
- ...state.characters.map((entry) => entry.key),
6742
- ...state.factions.map((entry) => entry.key),
6743
- ...state.places.map((entry) => entry.key),
6744
- ...state.things.map((entry) => entry.key),
6745
- ...(state.lore ?? []).map((entry) => entry.key)
6746
- ]);
6747
- if (references.length > 0) throw new InvalidEditProblems(references);
6748
- const document = parsed.value.map((plot) => ({
6749
- ...plot,
6750
- pacing: {
6751
- quiet_turns: plot.pacing.quietTurns,
6752
- cooldown_turns: plot.pacing.cooldownTurns,
6753
- cooldown_days: plot.pacing.cooldownDays
6754
- }
6755
- }));
6756
- await replaceFile$1(join(world.directory, PLOTS_FILE_NAME), JSON.stringify(document, null, 2) + "\n");
6757
- return await readWorldEditor(world);
6758
- }
6759
- async function editWorldLore(world, key, edit) {
6760
- return await editEntityFile(world, LORE_DIR, LORE_FILE_NAME, key, parseLoreFile, (document) => {
6761
- if (edit.title !== void 0) document["title"] = edit.title;
6762
- if (edit.kind !== void 0) document["kind"] = edit.kind;
6763
- if (edit.summary !== void 0) setOptional(document, "summary", edit.summary);
6764
- if (edit.body !== void 0) setOptional(document, "body", edit.body);
6765
- if (edit.sources !== void 0) document["sources"] = edit.sources;
6766
- if (edit.startsAt !== void 0) {
6767
- if (edit.startsAt === null) delete document["starts_at"];
6768
- else document["starts_at"] = new Date(edit.startsAt).toISOString();
6769
- }
6770
- if (edit.endsAt !== void 0) {
6771
- if (edit.endsAt === null) delete document["ends_at"];
6772
- else document["ends_at"] = new Date(edit.endsAt).toISOString();
6773
- }
6774
- });
6775
- }
6776
- async function editWorldNarrationVoice(world, voice) {
6777
- const file = join(world.directory, "world.json");
6778
- const text = await readFile(file, "utf8");
6779
- const document = JSON.parse(text);
6780
- if (voice.trim() === "") delete document["narration_voice"];
6781
- else document["narration_voice"] = voice.trim();
6782
- await replaceFile$1(file, JSON.stringify(document, null, /^([ \t]+)"/m.exec(text)?.[1] ?? " ") + (text.endsWith("\n") ? "\n" : ""));
6783
- return await readWorldEditor(world);
6784
- }
6785
- const relationKey = (...parts) => parts.map((part) => encodeURIComponent(part)).join(":");
6786
- const relationParts = (key) => key.split(":").map((part) => decodeURIComponent(part));
6787
- /** The folder of a character by its id: the id is the folder's name unless the file says another. */
6788
- async function folderOf(worldDirectory, key) {
6789
- const root = join(worldDirectory, CHARACTERS_DIR);
6790
- for (const folder of await subfolders(root)) try {
6791
- const parsed = parseCharacterFile(await readFile(join(root, folder, CHARACTER_FILE_NAME), "utf8"), folder);
6792
- if (parsed.ok && parsed.value.id === key) return folder;
6793
- } catch (error) {
6794
- if (error.code !== "ENOENT") throw error;
6795
- }
6796
- }
6797
- const object = (parent, key) => {
6798
- const found = parent[key];
6799
- if (typeof found === "object" && found !== null && !Array.isArray(found)) return found;
6800
- const made = {};
6801
- parent[key] = made;
6802
- return made;
6803
- };
6804
- /** A blank optional text is taken out of the file instead of being written empty. */
6805
- function setOptional(target, key, value) {
6806
- if (value === void 0) return;
6807
- if (value.trim() === "") delete target[key];
6808
- else target[key] = value.trim();
6809
- }
6810
- /** 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. */
6811
- function apply(document, edit, problems) {
6812
- if (edit.name !== void 0) document["name"] = edit.name;
6813
- if (edit.aliases !== void 0) document["aliases"] = edit.aliases.map((alias) => alias.trim()).filter((alias) => alias !== "");
6814
- for (const key of [
6815
- "age",
6816
- "gender",
6817
- "pronouns"
6818
- ]) setOptional(document, key, edit[key]);
6819
- for (const key of [
6820
- "role",
6821
- "tier",
6822
- "kind",
6823
- "summary",
6824
- "personality",
6825
- "background",
6826
- "appearance"
6827
- ]) if (edit[key] !== void 0) document[key] = edit[key];
6828
- if (edit.visualIdentity === null) delete document["visual_identity"];
6829
- else if (edit.visualIdentity !== void 0) document["visual_identity"] = {
6830
- description: edit.visualIdentity.description,
6831
- tags: edit.visualIdentity.tags,
6832
- negative_tags: edit.visualIdentity.negativeTags,
6833
- ...edit.visualIdentity.globalId === void 0 ? {} : { global_id: edit.visualIdentity.globalId }
6834
- };
6835
- if (edit.speech !== void 0) {
6836
- const speech = object(document, "speech");
6837
- if (edit.speech.style !== void 0) speech["style"] = edit.speech.style;
6838
- if (edit.speech.examples !== void 0) speech["examples"] = edit.speech.examples.map((example) => example.trim()).filter((example) => example !== "");
6839
- }
6840
- setOptional(document, "voice", edit.voice);
6841
- const start = object(document, "start");
6842
- if (edit.state !== void 0) {
6843
- if (edit.state.publicState !== void 0) start["public_state"] = edit.state.publicState;
6844
- if (edit.state.innerState !== void 0) start["inner_state"] = edit.state.innerState;
6845
- if (edit.state.activity !== void 0) start["activity"] = edit.state.activity;
6846
- }
6847
- if (edit.place !== void 0) {
6848
- if (start["location"] !== edit.place.location) delete start["feature"];
6849
- start["location"] = edit.place.location;
6850
- setOptional(start, "position", edit.place.position ?? "");
6851
- }
6852
- if (edit.goals !== void 0) {
6853
- const intents = Array.isArray(start["intents"]) ? start["intents"] : [];
6854
- for (const goal of edit.goals) {
6855
- const intent = intents[Number(goal.ref)];
6856
- if (intent === void 0 || typeof intent !== "object" || intent === null) {
6857
- problems.push(`there is no goal "${goal.ref}"`);
6858
- continue;
6859
- }
6860
- if (goal.name !== void 0) intent["name"] = goal.name;
6861
- if (goal.description !== void 0) intent["description"] = goal.description;
6862
- if (goal.status !== void 0) intent["status"] = goal.status;
6863
- if (goal.priority !== void 0) intent["priority"] = goal.priority;
6864
- }
6865
- }
6866
- }
6867
- /** Written in one step, so an interruption cannot leave a character file half written. */
6868
- async function replaceFile$1(file, text) {
6869
- const temporary = join(dirname(file), `.${basename(file)}.${process.pid}.${randomUUID()}.tmp`);
6870
- try {
6871
- const mode = await stat(file).then((value) => value.mode, (error) => {
6872
- if (error.code === "ENOENT") return 420;
6873
- throw error;
6874
- });
6875
- await writeFile(temporary, text, { mode });
6876
- await chmod(temporary, mode);
6877
- await rename(temporary, file);
6878
- } catch (error) {
6879
- await rm(temporary, { force: true });
6880
- throw error;
6881
- }
6882
- }
6883
- /**
6884
- * 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
6885
- * the world) before it is written, so a refused edit changes nothing. Whatever the file holds that the editor does not know stays.
6886
- * @throws {InvalidEditProblems} when the character is not there, or the result would not be a valid character.
6887
- */
6888
- async function editWorldCharacter(world, key, edit) {
6889
- const folder = await folderOf(world.directory, key);
6890
- if (folder === void 0) throw new InvalidEditProblems([`there is no character "${key}"`]);
6891
- const file = join(world.directory, CHARACTERS_DIR, folder, CHARACTER_FILE_NAME);
6892
- const text = (await readFile(file, "utf8")).replace(/^/, "");
6893
- const document = JSON.parse(text);
6894
- const problems = [];
6895
- if (edit.place !== void 0) {
6896
- const { locations } = await loadLocations(world.directory);
6897
- if (!locations.some((location) => location.id === edit.place?.location)) problems.push(`there is no place "${edit.place.location}"`);
6898
- }
6899
- apply(document, edit, problems);
6900
- const next = JSON.stringify(document, null, /^([ \t]+)"/m.exec(text)?.[1] ?? " ") + (text.endsWith("\n") ? "\n" : "");
6901
- const parsed = parseCharacterFile(next, folder);
6902
- if (!parsed.ok) problems.push(...parsed.issues.map(formatIssue));
6903
- if (problems.length > 0) throw new InvalidEditProblems(problems);
6904
- await replaceFile$1(file, next);
6905
- return await readWorldEditor(world);
6906
- }
6907
- async function entityFolder(worldDirectory, directory, fileName, key, parse) {
6908
- for (const folder of await subfolders(join(worldDirectory, directory))) try {
6909
- const parsed = parse(await readFile(join(worldDirectory, directory, folder, fileName), "utf8"), folder);
6910
- if (parsed.ok && parsed.value?.id === key) return folder;
6911
- } catch (error) {
6912
- if (error.code !== "ENOENT") throw error;
6913
- }
6914
- }
6915
- function setVisualIdentity(document, identity) {
6916
- if (identity === null) delete document["visual_identity"];
6917
- else if (identity !== void 0) document["visual_identity"] = {
6918
- description: identity.description,
6919
- tags: identity.tags,
6920
- negative_tags: identity.negativeTags,
6921
- ...identity.globalId === void 0 ? {} : { global_id: identity.globalId }
6922
- };
6923
- }
6924
- async function editEntityFile(world, directory, fileName, key, parse, mutate) {
6925
- const folder = await entityFolder(world.directory, directory, fileName, key, parse);
6926
- if (folder === void 0) throw new InvalidEditProblems([`there is no entity "${key}"`]);
6927
- const file = join(world.directory, directory, folder, fileName);
6928
- const text = (await readFile(file, "utf8")).replace(/^/, "");
6929
- const document = JSON.parse(text);
6930
- mutate(document);
6931
- const next = JSON.stringify(document, null, /^([ \t]+)"/m.exec(text)?.[1] ?? " ") + (text.endsWith("\n") ? "\n" : "");
6932
- const parsed = parse(next, folder);
6933
- if (!parsed.ok) throw new InvalidEditProblems((parsed.issues ?? []).map(formatIssue));
6934
- await replaceFile$1(file, next);
6935
- return await readWorldEditor(world);
6936
- }
6937
- async function editWorldPlace(world, key, edit) {
6938
- if (edit.parent !== void 0 && edit.parent !== null) {
6939
- const places = (await readWorldEditor(world)).places;
6940
- if (!places.some((place) => place.key === edit.parent)) throw new InvalidEditProblems([`there is no place "${edit.parent}" to put it in`]);
6941
- const parents = new Map(places.map((place) => [place.key, place.parent?.key]));
6942
- 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"]);
6943
- }
6944
- return await editEntityFile(world, LOCATIONS_DIR, LOCATION_FILE_NAME, key, parseLocationFile, (document) => {
6945
- if (edit.name !== void 0) document["name"] = edit.name;
6946
- if (edit.description !== void 0) document["description"] = edit.description;
6947
- if (edit.features !== void 0) document["features"] = edit.features.map((feature) => ({
6948
- id: feature.key,
6949
- name: feature.name,
6950
- description: feature.description
6951
- }));
6952
- if (edit.parent === null) delete document["parent"];
6953
- else if (edit.parent !== void 0) document["parent"] = edit.parent;
6954
- setVisualIdentity(document, edit.visualIdentity);
6955
- });
6956
- }
6957
- async function editWorldThing(world, key, edit) {
6958
- 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`]);
6959
- return await editEntityFile(world, ITEMS_DIR, ITEM_FILE_NAME, key, parseItemFile, (document) => {
6960
- for (const field of [
6961
- "name",
6962
- "description",
6963
- "quantity",
6964
- "quality",
6965
- "notable",
6966
- "hidden"
6967
- ]) if (edit[field] !== void 0) document[field] = edit[field];
6968
- if (edit.containerState !== void 0) object(document, "container")["state"] = edit.containerState;
6969
- if (edit.owner === null) delete document["owner"];
6970
- else if (edit.owner !== void 0) document["owner"] = edit.owner;
6971
- setVisualIdentity(document, edit.visualIdentity);
6972
- });
6973
- }
6974
- async function editWorldFaction(world, key, edit) {
6975
- return await editEntityFile(world, FACTIONS_DIR, FACTION_FILE_NAME, key, parseFactionFile, (document) => {
6976
- for (const field of [
6977
- "name",
6978
- "aliases",
6979
- "summary",
6980
- "description",
6981
- "values",
6982
- "structure"
6983
- ]) if (edit[field] !== void 0) document[field] = edit[field];
6984
- const start = object(document, "start");
6985
- if (edit.state?.publicState !== void 0) start["public_state"] = edit.state.publicState;
6986
- if (edit.state?.innerState !== void 0) start["inner_state"] = edit.state.innerState;
6987
- if (edit.goals !== void 0) {
6988
- const goals = Array.isArray(start["goals"]) ? start["goals"] : [];
6989
- for (const goal of edit.goals) {
6990
- const target = goals[Number(goal.ref)];
6991
- if (target === void 0) continue;
6992
- for (const field of [
6993
- "name",
6994
- "description",
6995
- "status",
6996
- "priority"
6997
- ]) if (goal[field] !== void 0) target[field] = goal[field];
6998
- }
6999
- }
7000
- });
7001
- }
7002
- async function createWorldRelation(world, edit) {
7003
- if (edit.kind === "character" || edit.kind === "knowledge") return await editEntityFile(world, CHARACTERS_DIR, CHARACTER_FILE_NAME, edit.from, parseCharacterFile, (document) => {
7004
- if (edit.kind === "character") {
7005
- const relationships = Array.isArray(document["relationships"]) ? document["relationships"] : [];
7006
- if (relationships.some((entry) => entry?.["to"] === edit.to)) throw new InvalidEditProblems(["that relationship already exists"]);
7007
- relationships.push({
7008
- to: edit.to,
7009
- label: edit.label,
7010
- summary: edit.summary ?? "",
7011
- familiarity: edit.familiarity ?? 0,
7012
- trust: edit.trust ?? 0,
7013
- affinity: edit.affinity ?? 0,
7014
- tension: edit.tension ?? 0
7015
- });
7016
- document["relationships"] = relationships;
7017
- } else {
7018
- const knowledge = object(document, "knowledge");
7019
- const field = edit.toKind === "location" ? "locations" : edit.toKind === "item" ? "items" : "exits";
7020
- const entries = Array.isArray(knowledge[field]) ? knowledge[field] : [];
7021
- if (edit.toKind === "exit") {
7022
- const [from, to] = edit.to.split(">");
7023
- if (from === void 0 || to === void 0) throw new InvalidEditProblems(["the route key is invalid"]);
7024
- if (entries.some((entry) => typeof entry === "object" && entry !== null && entry["from"] === from && entry["to"] === to)) throw new InvalidEditProblems(["that knowledge relation already exists"]);
7025
- entries.push({
7026
- from,
7027
- to
7028
- });
7029
- } else {
7030
- if (entries.includes(edit.to)) throw new InvalidEditProblems(["that knowledge relation already exists"]);
7031
- entries.push(edit.to);
7032
- }
7033
- knowledge[field] = entries;
7034
- }
7035
- });
7036
- if (edit.kind === "exit") return await editEntityFile(world, LOCATIONS_DIR, LOCATION_FILE_NAME, edit.from, parseLocationFile, (document) => {
7037
- const exits = Array.isArray(document["exits"]) ? document["exits"] : [];
7038
- if (exits.some((entry) => entry?.["to"] === edit.to)) throw new InvalidEditProblems(["that route already exists"]);
7039
- exits.push({
7040
- to: edit.to,
7041
- description: edit.description,
7042
- ...edit.travelSeconds === void 0 ? {} : { travel_time_seconds: edit.travelSeconds },
7043
- state: edit.state ?? "open",
7044
- note: edit.note ?? ""
7045
- });
7046
- document["exits"] = exits;
7047
- });
7048
- const faction = edit.kind === "membership" ? edit.to : edit.from;
7049
- if (edit.kind === "social" && edit.fromKind !== "faction") throw new InvalidEditProblems(["authored social relationships must start from a faction"]);
7050
- return await editEntityFile(world, FACTIONS_DIR, FACTION_FILE_NAME, faction, parseFactionFile, (document) => {
7051
- if (edit.kind === "membership") {
7052
- const members = Array.isArray(document["members"]) ? document["members"] : [];
7053
- if (members.some((entry) => entry?.["character"] === edit.from)) throw new InvalidEditProblems(["that membership already exists"]);
7054
- members.push({
7055
- character: edit.from,
7056
- role: edit.role,
7057
- rank: edit.rank ?? "",
7058
- status: edit.status ?? "active",
7059
- public: edit.public ?? true,
7060
- commitment: edit.commitment ?? .5
7061
- });
7062
- document["members"] = members;
7063
- } else {
7064
- const relationships = Array.isArray(document["relationships"]) ? document["relationships"] : [];
7065
- 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"]);
7066
- relationships.push({
7067
- to: {
7068
- kind: edit.toKind,
7069
- id: edit.to
7070
- },
7071
- label: edit.label,
7072
- summary: edit.summary ?? "",
7073
- familiarity: edit.familiarity ?? 0,
7074
- trust: edit.trust ?? 0,
7075
- affinity: edit.affinity ?? 0,
7076
- tension: edit.tension ?? 0
7077
- });
7078
- document["relationships"] = relationships;
7079
- }
7080
- });
7081
- }
7082
- const isNewRelation = (edit) => "create" in edit && edit.create === true;
7083
- async function editWorldRelation(world, edit) {
7084
- if (isNewRelation(edit)) return await createWorldRelation(world, edit);
7085
- const parts = relationParts(edit.key);
7086
- 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`]);
7087
- if (edit.kind === "character" || edit.kind === "knowledge") {
7088
- const character = parts[1];
7089
- if (character === void 0) throw new InvalidEditProblems(["the relation key is invalid"]);
7090
- if (await folderOf(world.directory, character) === void 0) throw new InvalidEditProblems([`there is no character "${character}"`]);
7091
- return await editEntityFile(world, CHARACTERS_DIR, CHARACTER_FILE_NAME, character, parseCharacterFile, (document) => {
7092
- if (edit.kind === "character") {
7093
- const target = parts[2];
7094
- const relationships = Array.isArray(document["relationships"]) ? document["relationships"] : [];
7095
- const index = relationships.findIndex((entry) => entry?.["to"] === target);
7096
- if (index < 0) throw new InvalidEditProblems(["the relationship no longer exists"]);
7097
- if (edit.remove === true) relationships.splice(index, 1);
7098
- else for (const field of [
7099
- "label",
7100
- "summary",
7101
- "familiarity",
7102
- "trust",
7103
- "affinity",
7104
- "tension"
7105
- ]) if (edit[field] !== void 0) relationships[index][field] = edit[field];
7106
- document["relationships"] = relationships;
7107
- } else {
7108
- const subjectKind = parts[2];
7109
- const one = parts[3];
7110
- const two = parts[4];
7111
- const knowledge = object(document, "knowledge");
7112
- const field = subjectKind === "location" ? "locations" : subjectKind === "item" ? "items" : "exits";
7113
- const entries = Array.isArray(knowledge[field]) ? knowledge[field] : [];
7114
- const index = subjectKind === "exit" ? entries.findIndex((entry) => typeof entry === "object" && entry !== null && entry["from"] === one && entry["to"] === two) : entries.indexOf(one);
7115
- if (index < 0) throw new InvalidEditProblems(["the knowledge relation no longer exists"]);
7116
- entries.splice(index, 1);
7117
- knowledge[field] = entries;
7118
- }
7119
- });
7120
- }
7121
- if (edit.kind === "exit") {
7122
- const from = parts[1];
7123
- const to = parts[2];
7124
- if (from === void 0 || to === void 0) throw new InvalidEditProblems(["the exit key is invalid"]);
7125
- return await editEntityFile(world, LOCATIONS_DIR, LOCATION_FILE_NAME, from, parseLocationFile, (document) => {
7126
- const exits = Array.isArray(document["exits"]) ? document["exits"] : [];
7127
- const index = exits.findIndex((entry) => entry?.["to"] === to);
7128
- if (index < 0) throw new InvalidEditProblems(["the exit no longer exists"]);
7129
- if (edit.remove === true) exits.splice(index, 1);
7130
- else {
7131
- for (const field of [
7132
- "description",
7133
- "state",
7134
- "note"
7135
- ]) if (edit[field] !== void 0) exits[index][field] = edit[field];
7136
- if (edit.travelSeconds === null) delete exits[index]["travel_time_seconds"];
7137
- else if (edit.travelSeconds !== void 0) exits[index]["travel_time_seconds"] = edit.travelSeconds;
7138
- }
7139
- document["exits"] = exits;
7140
- });
7141
- }
7142
- const faction = edit.kind === "membership" ? parts[1] : parts[2];
7143
- if (faction === void 0) throw new InvalidEditProblems(["the relation key is invalid"]);
7144
- return await editEntityFile(world, FACTIONS_DIR, FACTION_FILE_NAME, faction, parseFactionFile, (document) => {
7145
- if (edit.kind === "membership") {
7146
- const character = parts[2];
7147
- const members = Array.isArray(document["members"]) ? document["members"] : [];
7148
- const index = members.findIndex((entry) => entry?.["character"] === character);
7149
- if (index < 0) throw new InvalidEditProblems(["the membership no longer exists"]);
7150
- if (edit.remove === true) members.splice(index, 1);
7151
- else for (const field of [
7152
- "role",
7153
- "rank",
7154
- "status",
7155
- "public",
7156
- "commitment"
7157
- ]) if (edit[field] !== void 0) members[index][field] = edit[field];
7158
- document["members"] = members;
7159
- } else {
7160
- const targetKind = parts[3];
7161
- const target = parts[4];
7162
- const relationships = Array.isArray(document["relationships"]) ? document["relationships"] : [];
7163
- const index = relationships.findIndex((entry) => typeof entry?.["to"] === "object" && entry["to"] !== null && entry["to"]["kind"] === targetKind && entry["to"]["id"] === target);
7164
- if (index < 0) throw new InvalidEditProblems(["the relationship no longer exists"]);
7165
- if (edit.remove === true) relationships.splice(index, 1);
7166
- else for (const field of [
7167
- "label",
7168
- "summary",
7169
- "familiarity",
7170
- "trust",
7171
- "affinity",
7172
- "tension"
7173
- ]) if (edit[field] !== void 0) relationships[index][field] = edit[field];
7174
- document["relationships"] = relationships;
7175
- }
7176
- });
7177
- }
7178
- async function characterOf(world, key) {
7179
- const { characters } = await loadCharacters(world.directory);
7180
- const character = characters.find((candidate) => candidate.id === key);
7181
- if (character === void 0) throw new InvalidEditProblems([`there is no character "${key}"`]);
7182
- return character;
7183
- }
7184
- /** Generate or replace the authored character's stable reference portrait. */
7185
- async function generateWorldCharacterPortrait(world, key, service) {
7186
- const character = await characterOf(world, key);
7187
- const identity = character.visualIdentity;
7188
- if (identity === void 0) throw new InvalidEditProblems([`${character.name} needs a visual identity before a portrait can be generated`]);
7189
- await generateReferenceImage(service, {
7190
- root: world.directory,
7191
- subject: {
7192
- kind: "character",
7193
- localId: character.id,
7194
- name: character.name,
7195
- ...identity.globalId === void 0 ? {} : { globalId: identity.globalId }
7196
- },
7197
- identity: {
7198
- ...identity,
7199
- subjectKind: "character",
7200
- subjectId: 0,
7201
- version: 1,
7202
- updatedAt: ""
7203
- }
7204
- });
7205
- return await readWorldEditor(world);
7206
- }
7207
- /** The picture the author brought becomes the character's portrait. */
7208
- async function uploadWorldCharacterPortrait(world, key, png, originalName) {
7209
- const character = await characterOf(world, key);
7210
- try {
7211
- await uploadReferenceImage({
7212
- root: world.directory,
7213
- subject: {
7214
- kind: "character",
7215
- localId: character.id,
7216
- name: character.name,
7217
- ...character.visualIdentity?.globalId === void 0 ? {} : { globalId: character.visualIdentity.globalId }
7218
- },
7219
- png,
7220
- ...originalName === void 0 ? {} : { originalName }
7221
- });
7222
- } catch (error) {
7223
- throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
7224
- }
7225
- return await readWorldEditor(world);
7226
- }
7227
- /** Resolve a portrait through authored data so request parameters cannot select arbitrary files. */
7228
- async function worldCharacterPortraitFile(world, key) {
7229
- const character = await characterOf(world, key);
7230
- const file = referenceImagePath(world.directory, {
7231
- kind: "character",
7232
- localId: character.id,
7233
- ...character.visualIdentity?.globalId === void 0 ? {} : { globalId: character.visualIdentity.globalId }
7234
- });
7235
- return {
7236
- file,
7237
- size: (await stat(file)).size
7238
- };
7239
- }
7240
- //#endregion
7241
- //#region src/host/authoring/documents.ts
7242
- const AUTHORED_ENTITY_KINDS = [
7243
- "character",
7244
- "location",
7245
- "item",
7246
- "faction",
7247
- "lore"
7248
- ];
7249
- const formats = {
7250
- character: {
7251
- directory: CHARACTERS_DIR,
7252
- file: CHARACTER_FILE_NAME,
7253
- parse: parseCharacterFile
7254
- },
7255
- location: {
7256
- directory: LOCATIONS_DIR,
7257
- file: LOCATION_FILE_NAME,
7258
- parse: parseLocationFile
7259
- },
7260
- item: {
7261
- directory: ITEMS_DIR,
7262
- file: ITEM_FILE_NAME,
7263
- parse: parseItemFile
7264
- },
7265
- faction: {
7266
- directory: FACTIONS_DIR,
7267
- file: FACTION_FILE_NAME,
7268
- parse: parseFactionFile
7269
- },
7270
- lore: {
7271
- directory: LORE_DIR,
7272
- file: LORE_FILE_NAME,
7273
- parse: parseLoreFile
7274
- }
7275
- };
7276
- /** Keys become folder names and image paths: letters (any script), digits, marks, `.`, `_` and `-`, starting with a letter or digit. */
7277
- const NEW_KEY = /^[\p{L}\p{N}][\p{L}\p{N}\p{M}._-]{0,99}$/u;
7278
- function validNewKey(key) {
7279
- return NEW_KEY.test(key);
7280
- }
7281
- async function find(world, kind, key) {
7282
- const format = formats[kind];
7283
- const root = join(world.directory, format.directory);
7284
- for (const folder of await subfolders(root)) {
7285
- const file = join(root, folder, format.file);
7286
- try {
7287
- const parsed = format.parse(await readFile(file, "utf8"), folder);
7288
- if (parsed.ok && parsed.value.id === key) return {
7289
- folder,
7290
- file
7291
- };
7292
- } catch (error) {
7293
- if (error.code !== "ENOENT") throw error;
7294
- }
7295
- }
7296
- }
7297
- function serializeDocument(kind, key, value) {
7298
- if (typeof value !== "object" || value === null || Array.isArray(value)) throw new InvalidEditProblems(["document must be a JSON object"]);
7299
- const document = {
7300
- ...value,
7301
- id: key
7302
- };
7303
- const text = `${JSON.stringify(document, null, 2)}\n`;
7304
- const parsed = formats[kind].parse(text, key);
7305
- if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
7306
- return text;
7307
- }
7308
- async function replaceFile(file, text) {
7309
- const temporary = join(dirname(file), `.${basename(file)}.${process.pid}.${randomUUID()}.tmp`);
7310
- try {
7311
- const mode = await stat(file).then((value) => value.mode);
7312
- await writeFile(temporary, text, { mode });
7313
- await rename(temporary, file);
7314
- } catch (error) {
7315
- await rm(temporary, { force: true });
7316
- throw error;
7317
- }
7318
- }
7319
- async function readAuthoredEntityDocument(world, kind, key) {
7320
- const found = await find(world, kind, key);
7321
- if (found === void 0) throw new InvalidEditProblems([`there is no ${kind} "${key}"`]);
7322
- return JSON.parse((await readFile(found.file, "utf8")).replace(/^/, ""));
7323
- }
7324
- async function createAuthoredEntity(world, kind, key, document) {
7325
- 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)"]);
7326
- if (await find(world, kind, key) !== void 0) throw new InvalidEditProblems([`the ${kind} "${key}" already exists`]);
7327
- const format = formats[kind];
7328
- const root = join(world.directory, format.directory);
7329
- const folder = join(root, key);
7330
- const text = serializeDocument(kind, key, document);
7331
- await mkdir(root, { recursive: true });
7332
- await mkdir(folder, { recursive: false });
7333
- try {
7334
- await writeFile(join(folder, format.file), text, { flag: "wx" });
7335
- } catch (error) {
7336
- await rm(folder, {
7337
- recursive: true,
7338
- force: true
7339
- });
7340
- throw error;
7341
- }
7342
- }
7343
- async function replaceAuthoredEntity(world, kind, key, document) {
7344
- const found = await find(world, kind, key);
7345
- if (found === void 0) throw new InvalidEditProblems([`there is no ${kind} "${key}"`]);
7346
- await replaceFile(found.file, serializeDocument(kind, key, document));
7347
- }
7348
- /** Deletions remain recoverable without making the trash visible to the world loaders. */
7349
- async function deleteAuthoredEntity(world, kind, key) {
7350
- const found = await find(world, kind, key);
7351
- if (found === void 0) throw new InvalidEditProblems([`there is no ${kind} "${key}"`]);
7352
- const trash = join(world.directory, ".trash", formats[kind].directory);
7353
- await mkdir(trash, { recursive: true });
7354
- const destination = join(trash, `${found.folder}-${Date.now()}-${randomUUID()}`);
7355
- await rename(dirname(found.file), destination);
7356
- return destination;
7357
- }
7358
- //#endregion
7359
- export { parseDiceFile as $, authoredWorldOf as A, parsePlaceEdit as At, populateDice as B, DICE_RESULTS as Bt, presetMessage as C, WORLD_FILE_NAME as Ct, translateTools as D, parseCharacterEdit as Dt, translateMessage as E, InvalidEditProblems as Et, markReady as F, isPng as Ft, populateLore as G, populateItems as H, loadValidatedWorld as I, pictureOf as It, populateVariables as J, populateRoutines as K, populateCalendar as L, readCard as Lt, languageOfDocuments as M, parseThingEdit as Mt, readWorldDocuments as N, IMPORT_COMMAND as Nt, importHooks as O, parseFactionEdit as Ot, isReviewing as P, ImportCardError as Pt, loadDice as Q, populateCharacters as R, DICE_COMPARISONS as Rt, PRESET_FILE as S, parseChoices as St, readPreset as T, parseWorldInfoEdit as Tt, populateKnowledge as U, populateFactions as V, populateLocations as W, TRIGGERS_FILE_NAME as X, routineProblems as Y, DICE_FILE_NAME as Z, replaceFile$1 as _, CHARACTER_FILE_NAME as _t, replaceAuthoredEntity as a, CHARACTERS_DIR as at, triggerProblemsOf as b, ImportNotFoundError as bt, editWorldLore as c, PROSE_PROMPTS as ct, editWorldPlots as d, readWorldPrompt as dt, CALENDAR_FILE_NAME as et, editWorldRelation as f, writeWorldPrompt as ft, readWorldEditor as g, variableProblems as gt, generateWorldCharacterPortrait as h, parseVariablesFile as ht, readAuthoredEntityDocument as i, loadItems as it, authoringChatSessionId as j, parseRelationEdit as jt, importTools as k, parseLoreEdit as kt, editWorldNarrationVoice as l, deleteWorldPrompt as lt, entityFolder as m, loadVariables as mt, createAuthoredEntity as n, parseCalendarFile as nt, editWorldCharacter as o, loadCharacters as ot, editWorldThing as p, VARIABLES_FILE_NAME as pt, populateTriggers as q, deleteAuthoredEntity as r, loadLocations as rt, editWorldFaction as s, subfolders as st, AUTHORED_ENTITY_KINDS as t, loadCalendar as tt, editWorldPlace as u, listWorldPrompts as ut, uploadWorldCharacterPortrait as v, parseCharacterFile as vt, presetTools as w, parseWorldFile as wt, loadWorldParts as x, ImportStore as xt, worldCharacterPortraitFile as y, IMPORT_FOLDER as yt, populateClock as z, DICE_READINGS 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 };
7360
5771
 
7361
- //# sourceMappingURL=documents-Do4lz4SB.js.map
5772
+ //# sourceMappingURL=preset-ClQm7KPQ.js.map