@dsh-agentic-roleplay/core 0.3.3 → 0.3.4

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,10 +1,10 @@
1
- import { _ as API_PREFIX, b as INTENT_TYPES, v as INTENT_HORIZONS, y as INTENT_STATUSES } from "./packs-BYjrAen6.js";
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";
2
2
  import { c as VARIABLE_SUBJECTS, i as parseSwitchboard, l as VARIABLE_VISIBILITIES, s as VARIABLE_KINDS } from "./settings-CA6icLL_.js";
3
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";
4
+ import { a as runChild } from "./child-CFjnaTZt.js";
5
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";
6
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
7
+ import { existsSync, lstatSync, readFileSync, readdirSync, statSync } from "node:fs";
8
8
  import { createHash, randomUUID } from "node:crypto";
9
9
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
10
10
  import { inflateSync } from "node:zlib";
@@ -192,7 +192,7 @@ function chunksOf(file) {
192
192
  return chunks;
193
193
  }
194
194
  /** The keyword and text of a PNG text chunk. */
195
- function textOf(chunk) {
195
+ function textOf$1(chunk) {
196
196
  const end = chunk.data.indexOf(0);
197
197
  if (end < 0) return void 0;
198
198
  const keyword = chunk.data.toString("latin1", 0, end);
@@ -224,7 +224,7 @@ function jsonOf(file, name) {
224
224
  const found = /* @__PURE__ */ new Map();
225
225
  for (const chunk of chunksOf(file)) {
226
226
  if (!TEXT_CHUNKS.has(chunk.type)) continue;
227
- const text = textOf(chunk);
227
+ const text = textOf$1(chunk);
228
228
  if (text !== void 0 && CARD_KEYWORDS.includes(text.keyword) && !found.has(text.keyword)) found.set(text.keyword, text.text);
229
229
  }
230
230
  const keyword = CARD_KEYWORDS.find((candidate) => found.has(candidate));
@@ -2699,7 +2699,20 @@ const CHARACTER_SCHEMA = {
2699
2699
  type: "object",
2700
2700
  properties: {
2701
2701
  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.")
2702
+ things: strs("Names from the list of things that they know of."),
2703
+ ways: {
2704
+ type: "array",
2705
+ items: {
2706
+ type: "object",
2707
+ properties: {
2708
+ from: str("A name from the list of places."),
2709
+ to: str("A name from the list of places.")
2710
+ },
2711
+ required: ["from", "to"],
2712
+ additionalProperties: false
2713
+ },
2714
+ description: "Ways between two places of the list that they know how to take (the way from one to the other)."
2715
+ }
2703
2716
  },
2704
2717
  additionalProperties: false
2705
2718
  }
@@ -2791,6 +2804,23 @@ function characterDocument(entity, answer, roster) {
2791
2804
  const knowledge = {};
2792
2805
  put(knowledge, "locations", known(list(knows["places"]), "place"));
2793
2806
  put(knowledge, "items", known(list(knows["things"]), "thing"));
2807
+ const ways = /* @__PURE__ */ new Set();
2808
+ const exits = [];
2809
+ for (const way of objects(knows["ways"])) {
2810
+ const from = findEntity(roster, text$1(way["from"]), "place");
2811
+ const to = findEntity(roster, text$1(way["to"]), "place");
2812
+ if (from === void 0 || to === void 0 || from.key === to.key) {
2813
+ 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`);
2814
+ continue;
2815
+ }
2816
+ if (ways.has(`${from.key}>${to.key}`)) continue;
2817
+ ways.add(`${from.key}>${to.key}`);
2818
+ exits.push({
2819
+ from: from.key,
2820
+ to: to.key
2821
+ });
2822
+ }
2823
+ put(knowledge, "exits", exits);
2794
2824
  put(document, "knowledge", Object.keys(knowledge).length === 0 ? void 0 : knowledge);
2795
2825
  return {
2796
2826
  document,
@@ -3131,9 +3161,17 @@ function pruneKnowledge(result) {
3131
3161
  locations: new Set(result.locations.map((entry) => String(entry["id"]))),
3132
3162
  items: new Set(result.items.map((entry) => String(entry["id"])))
3133
3163
  };
3164
+ const ways = new Set(result.locations.flatMap((place) => objects(place["exits"]).map((exit) => `${String(place["id"])}>${String(exit["to"])}`)));
3134
3165
  for (const character of result.characters) {
3135
3166
  const knowledge = character["knowledge"];
3136
3167
  if (knowledge === void 0) continue;
3168
+ const routes = objects(knowledge["exits"]);
3169
+ const open = routes.filter((route) => ways.has(`${String(route["from"])}>${String(route["to"])}`));
3170
+ if (open.length !== routes.length) {
3171
+ result.notes.push(`${String(character["name"])}: ${routes.length - open.length} known way(s) left out because the world has no such way`);
3172
+ if (open.length === 0) delete knowledge["exits"];
3173
+ else knowledge["exits"] = open;
3174
+ }
3137
3175
  for (const field of ["locations", "items"]) {
3138
3176
  const keys = knowledge[field] ?? [];
3139
3177
  const kept = keys.filter((key) => written[field].has(key));
@@ -3429,11 +3467,11 @@ const VARIABLES_SCHEMA = {
3429
3467
  description: "Names from the lists of characters, places or things it is limited to; empty for all."
3430
3468
  },
3431
3469
  min: {
3432
- type: ["number", "null"],
3470
+ oneOf: [{ type: "number" }, { type: "null" }],
3433
3471
  description: "The lowest value the card allows, or null."
3434
3472
  },
3435
3473
  max: {
3436
- type: ["number", "null"],
3474
+ oneOf: [{ type: "number" }, { type: "null" }],
3437
3475
  description: "The highest value the card allows, or null."
3438
3476
  },
3439
3477
  integer: {
@@ -3441,11 +3479,11 @@ const VARIABLES_SCHEMA = {
3441
3479
  description: "True when it counts whole units."
3442
3480
  },
3443
3481
  default: {
3444
- type: [
3445
- "number",
3446
- "boolean",
3447
- "string",
3448
- "null"
3482
+ oneOf: [
3483
+ { type: "number" },
3484
+ { type: "boolean" },
3485
+ { type: "string" },
3486
+ { type: "null" }
3449
3487
  ],
3450
3488
  description: "Where it starts: a number, true or false, or one of the options; null when the card does not say."
3451
3489
  },
@@ -5604,7 +5642,7 @@ const INTENT = [
5604
5642
  ".open_threads[]",
5605
5643
  ".constraints[]"
5606
5644
  ];
5607
- const FIELDS = {
5645
+ const FIELDS$1 = {
5608
5646
  world: {
5609
5647
  names: ["name"],
5610
5648
  text: [
@@ -5671,7 +5709,8 @@ const FIELDS = {
5671
5709
  ...INTENT.map((path) => `start.intents[]${path}`),
5672
5710
  "relationships[].label",
5673
5711
  "relationships[].summary",
5674
- "routine[].activity"
5712
+ "routine[].activity",
5713
+ "visual_identity.description"
5675
5714
  ]
5676
5715
  },
5677
5716
  location: {
@@ -5681,12 +5720,17 @@ const FIELDS = {
5681
5720
  "features[].description",
5682
5721
  "exits[].description",
5683
5722
  "exits[].note",
5684
- "exits[].back_description"
5723
+ "exits[].back_description",
5724
+ "visual_identity.description"
5685
5725
  ]
5686
5726
  },
5687
5727
  item: {
5688
5728
  names: ["name"],
5689
- text: ["description", "quality"]
5729
+ text: [
5730
+ "description",
5731
+ "quality",
5732
+ "visual_identity.description"
5733
+ ]
5690
5734
  },
5691
5735
  faction: {
5692
5736
  names: ["name", "aliases[]"],
@@ -5715,7 +5759,7 @@ const FIELDS = {
5715
5759
  };
5716
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. */
5717
5761
  function leavesOf(kind, document) {
5718
- const fields = FIELDS[kind];
5762
+ const fields = FIELDS$1[kind];
5719
5763
  const names = new Set(fields.names);
5720
5764
  const text = new Set(fields.text);
5721
5765
  const leaves = [];
@@ -5858,7 +5902,8 @@ const TEXTS_SCHEMA = {
5858
5902
  required: ["translations"],
5859
5903
  additionalProperties: false
5860
5904
  };
5861
- const braces = (text) => (text.match(/\{[^{}]*\}/g) ?? []).sort().join("\0");
5905
+ const BRACED = /\$?\{[^{}]*\}/g;
5906
+ const braces = (text) => (text.match(BRACED) ?? []).sort().join("\0");
5862
5907
  const letters = (text) => text.match(/\p{L}/gu)?.length ?? 0;
5863
5908
  /** The language the world is written in, from the words of all its files; nothing when there are too few to tell. */
5864
5909
  function languageOfDocuments(documents) {
@@ -5886,7 +5931,7 @@ function problemWith(sources, from, translations, glossary) {
5886
5931
  for (const [index, source] of sources.entries()) {
5887
5932
  const text = translations[index];
5888
5933
  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(" ")}`;
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(" ")}`;
5890
5935
  if (letters(source) >= CHECKED_LETTERS && textLanguage(source) === from && textLanguage(text) === from) return `translation ${index + 1} is still in the original language`;
5891
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}"`;
5892
5937
  }
@@ -5942,6 +5987,23 @@ async function freeFolder(directory, suffix) {
5942
5987
  }
5943
5988
  }
5944
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
+ }
5945
6007
  async function listedIn(directory, names) {
5946
6008
  const present = new Set(await readdir(directory));
5947
6009
  return names.filter((name) => present.has(name));
@@ -5987,6 +6049,18 @@ async function translateWorld(ctx, worlds, source, to, told) {
5987
6049
  const aliases = Array.isArray(document["aliases"]) ? document["aliases"] : [];
5988
6050
  if (original !== void 0 && original !== document["name"] && !aliases.includes(original)) document["aliases"] = [...aliases, original];
5989
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
+ }
5990
6064
  const id = randomUUID();
5991
6065
  const destination = await freeFolder(source.directory, to);
5992
6066
  await cp(source.directory, destination, {
@@ -6000,6 +6074,11 @@ async function translateWorld(ctx, worlds, source, to, told) {
6000
6074
  }))(entry.document) : entry.document;
6001
6075
  await writeFile(join(destination, entry.file), `${JSON.stringify(document, null, 2)}\n`);
6002
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
+ }
6003
6082
  const payload = await worlds.list({ refresh: true });
6004
6083
  const made = payload.worlds.find((world) => world.id === id);
6005
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("; ")}`);
@@ -6019,8 +6098,8 @@ async function translateWorld(ctx, worlds, source, to, told) {
6019
6098
  texts,
6020
6099
  names: names.length + recurring.length,
6021
6100
  problems,
6101
+ prompts: written.map((prompt) => prompt.id),
6022
6102
  copiedAsIs: await listedIn(source.directory, [
6023
- "prompts",
6024
6103
  "ui",
6025
6104
  "images",
6026
6105
  "media"
@@ -6461,6 +6540,109 @@ function triggerProblemsOf(parts, definitions) {
6461
6540
  return found;
6462
6541
  }
6463
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
6464
6646
  //#region src/host/worlds/world-editor.ts
6465
6647
  function stateOf(world, definition, names) {
6466
6648
  const { start } = definition;
@@ -6654,6 +6836,7 @@ async function readWorldEditor(world) {
6654
6836
  key: location.id,
6655
6837
  name: location.name,
6656
6838
  description: location.description,
6839
+ ...imageOf(world, "place", location.id, location.visualIdentity?.globalId),
6657
6840
  ...location.parent === void 0 ? {} : { parent: {
6658
6841
  key: location.parent,
6659
6842
  name: names.get(location.parent) ?? location.parent
@@ -6665,6 +6848,7 @@ async function readWorldEditor(world) {
6665
6848
  key: item.id,
6666
6849
  name: item.name,
6667
6850
  description: item.description,
6851
+ ...imageOf(world, "thing", item.id, item.visualIdentity?.globalId),
6668
6852
  quantity: item.quantity,
6669
6853
  unique: item.unique,
6670
6854
  quality: item.quality,
@@ -6785,7 +6969,7 @@ async function editWorldNarrationVoice(world, voice) {
6785
6969
  const relationKey = (...parts) => parts.map((part) => encodeURIComponent(part)).join(":");
6786
6970
  const relationParts = (key) => key.split(":").map((part) => decodeURIComponent(part));
6787
6971
  /** 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) {
6972
+ async function folderOf$1(worldDirectory, key) {
6789
6973
  const root = join(worldDirectory, CHARACTERS_DIR);
6790
6974
  for (const folder of await subfolders(root)) try {
6791
6975
  const parsed = parseCharacterFile(await readFile(join(root, folder, CHARACTER_FILE_NAME), "utf8"), folder);
@@ -6886,7 +7070,7 @@ async function replaceFile$1(file, text) {
6886
7070
  * @throws {InvalidEditProblems} when the character is not there, or the result would not be a valid character.
6887
7071
  */
6888
7072
  async function editWorldCharacter(world, key, edit) {
6889
- const folder = await folderOf(world.directory, key);
7073
+ const folder = await folderOf$1(world.directory, key);
6890
7074
  if (folder === void 0) throw new InvalidEditProblems([`there is no character "${key}"`]);
6891
7075
  const file = join(world.directory, CHARACTERS_DIR, folder, CHARACTER_FILE_NAME);
6892
7076
  const text = (await readFile(file, "utf8")).replace(/^/, "");
@@ -7087,7 +7271,7 @@ async function editWorldRelation(world, edit) {
7087
7271
  if (edit.kind === "character" || edit.kind === "knowledge") {
7088
7272
  const character = parts[1];
7089
7273
  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}"`]);
7274
+ if (await folderOf$1(world.directory, character) === void 0) throw new InvalidEditProblems([`there is no character "${character}"`]);
7091
7275
  return await editEntityFile(world, CHARACTERS_DIR, CHARACTER_FILE_NAME, character, parseCharacterFile, (document) => {
7092
7276
  if (edit.kind === "character") {
7093
7277
  const target = parts[2];
@@ -7181,6 +7365,99 @@ async function characterOf(world, key) {
7181
7365
  if (character === void 0) throw new InvalidEditProblems([`there is no character "${key}"`]);
7182
7366
  return character;
7183
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
+ }
7184
7461
  /** Generate or replace the authored character's stable reference portrait. */
7185
7462
  async function generateWorldCharacterPortrait(world, key, service) {
7186
7463
  const character = await characterOf(world, key);
@@ -7237,6 +7514,22 @@ async function worldCharacterPortraitFile(world, key) {
7237
7514
  size: (await stat(file)).size
7238
7515
  };
7239
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
+ }
7240
7533
  //#endregion
7241
7534
  //#region src/host/authoring/documents.ts
7242
7535
  const AUTHORED_ENTITY_KINDS = [
@@ -7356,6 +7649,150 @@ async function deleteAuthoredEntity(world, kind, key) {
7356
7649
  return destination;
7357
7650
  }
7358
7651
  //#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 };
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 };
7360
7797
 
7361
- //# sourceMappingURL=documents-Do4lz4SB.js.map
7798
+ //# sourceMappingURL=pack-jail-CybSNzxr.js.map