@dsh-agentic-roleplay/core 0.3.2 → 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.
Files changed (33) hide show
  1. package/lib/authoring.js +15 -255
  2. package/lib/child-CFjnaTZt.js +435 -0
  3. package/lib/client.js +2852 -586
  4. package/lib/client.js.map +1 -1
  5. package/lib/{deliver-BSsDtF6X.js → deliver-CpZOxBX5.js} +145 -1622
  6. package/lib/doctor-chat-ByDfCMeo.js +17 -0
  7. package/lib/doctor.js +171 -0
  8. package/lib/{gallery-DS5-qH9F.js → gallery-CtFDL22W.js} +2 -2
  9. package/lib/{generator-BzeepLd2.js → generator-B6FxlKOV.js} +2 -378
  10. package/lib/hooks-KTCR3fNJ.js +1060 -0
  11. package/lib/images.js +3 -3
  12. package/lib/index.js +1365 -201
  13. package/lib/language-DWVwi1R7.js +520 -0
  14. package/lib/orchestration.js +142 -1146
  15. package/lib/{documents-B5XAdfo2.js → pack-jail-CybSNzxr.js} +869 -80
  16. package/lib/{packs-BCGK9KZV.js → packs-BYjrAen6.js} +4 -518
  17. package/lib/{presenter-agent-Cp-J0onD.js → presenter-agent-CiEVKcjJ.js} +4 -3
  18. package/lib/reflection-waxFg1x-.js +1843 -0
  19. package/package.json +3 -2
  20. package/prompts/en/doctor/persona.md +1 -0
  21. package/prompts/en/doctor/procedure.md +5 -0
  22. package/prompts/en/doctor/welcome.md +1 -0
  23. package/prompts/en/import/character.md +1 -0
  24. package/prompts/en/roleplay/record-keeper.md +2 -2
  25. package/prompts/en/roleplay/reflection-check.md +5 -0
  26. package/prompts/en/roleplay/reflection.md +2 -0
  27. package/prompts/zh/doctor/persona.md +1 -0
  28. package/prompts/zh/doctor/procedure.md +5 -0
  29. package/prompts/zh/doctor/welcome.md +1 -0
  30. package/prompts/zh/import/character.md +1 -0
  31. package/prompts/zh/roleplay/record-keeper.md +2 -2
  32. package/prompts/zh/roleplay/reflection-check.md +5 -0
  33. package/prompts/zh/roleplay/reflection.md +2 -0
@@ -1,10 +1,13 @@
1
- import { A as formatIssue, C as PLOTS_FILE_NAME, D as readDocument, E as plotReferenceProblems, F as languageOf, I as listFiles, J as INTENT_HORIZONS, L as promptProblem, O as errorMessage, R as shippedLanguages, T as parsePlotsFile, U as InvalidWorldError, X as INTENT_TYPES, Y as INTENT_STATUSES, _ as API_PREFIX, b as isStoryLanguage, j as PROMPTS_FOLDER, k as Reader, v as LANGUAGE_NAMES, w as loadPlots, x as textLanguage, y as STORY_LANGUAGES, z as shippedPromptsDirectory } from "./packs-BCGK9KZV.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
- import { A as runChild, 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-BzeepLd2.js";
4
- import { basename, dirname, join, relative, sep } from "node:path";
5
- import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
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-CFjnaTZt.js";
5
+ import { C as norm, S as mapLimit, T as uniqueKey, a as uploadReferenceImage, h as MEDIA_TYPES, o as addToLibrary, p as referenceImagePath, s as imageExtensionOf, t as generateReferenceImage, w as slug, y as writeImageFileMetadata } from "./generator-B6FxlKOV.js";
6
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
7
+ import { existsSync, lstatSync, readFileSync, readdirSync, statSync } from "node:fs";
6
8
  import { createHash, randomUUID } from "node:crypto";
7
9
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
10
+ import { inflateSync } from "node:zlib";
8
11
  import { defineTool } from "@deepseek-ai/dsh-tools";
9
12
  import { chmod, cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
10
13
  import { MAX_ROUTINE_WINDOWS, MINUTE, MONTH_NAMES, SEASONS, checkProblems, createSessionStore, dayTokenProblems, isTimeZone, parseInstant, parseTimeOfDay, readTriggerDefinition, triggerReferenceProblems, valueIssue, writeCalendar } from "@dsh-agentic-roleplay/state";
@@ -152,6 +155,179 @@ const LORE_SUBJECT_KINDS = [
152
155
  "lore"
153
156
  ];
154
157
  //#endregion
158
+ //#region src/host/import/card.ts
159
+ /** The file is not a character card this importer reads. The message says why, for the person who uploaded it. */
160
+ var ImportCardError = class extends Error {};
161
+ const PNG_SIGNATURE = Buffer.from([
162
+ 137,
163
+ 80,
164
+ 78,
165
+ 71,
166
+ 13,
167
+ 10,
168
+ 26,
169
+ 10
170
+ ]);
171
+ const TEXT_CHUNKS = /* @__PURE__ */ new Set([
172
+ "tEXt",
173
+ "iTXt",
174
+ "zTXt"
175
+ ]);
176
+ /** The keywords a card's data is stored under, the newer one first. */
177
+ const CARD_KEYWORDS = ["ccv3", "chara"];
178
+ function chunksOf(file) {
179
+ const chunks = [];
180
+ let at = PNG_SIGNATURE.length;
181
+ while (at + 12 <= file.length) {
182
+ const length = file.readUInt32BE(at);
183
+ const end = at + 12 + length;
184
+ if (end > file.length) throw new ImportCardError("the PNG file is damaged: a part of it is cut off");
185
+ chunks.push({
186
+ type: file.toString("latin1", at + 4, at + 8),
187
+ data: file.subarray(at + 8, at + 8 + length),
188
+ raw: file.subarray(at, end)
189
+ });
190
+ at = end;
191
+ }
192
+ return chunks;
193
+ }
194
+ /** The keyword and text of a PNG text chunk. */
195
+ function textOf$1(chunk) {
196
+ const end = chunk.data.indexOf(0);
197
+ if (end < 0) return void 0;
198
+ const keyword = chunk.data.toString("latin1", 0, end);
199
+ const rest = chunk.data.subarray(end + 1);
200
+ if (chunk.type === "tEXt") return {
201
+ keyword,
202
+ text: rest.toString("latin1")
203
+ };
204
+ if (chunk.type === "zTXt") return {
205
+ keyword,
206
+ text: inflateSync(rest.subarray(1)).toString("latin1")
207
+ };
208
+ const compressed = rest[0] === 1;
209
+ let from = 2;
210
+ for (let skipped = 0; skipped < 2; skipped += 1) from = rest.indexOf(0, from) + 1;
211
+ if (from <= 0) return void 0;
212
+ const body = rest.subarray(from);
213
+ return {
214
+ keyword,
215
+ text: (compressed ? inflateSync(body) : body).toString("utf8")
216
+ };
217
+ }
218
+ /** The PNG without its text chunks: the picture, with none of the card's data in it. */
219
+ function pictureOf(file) {
220
+ return Buffer.concat([PNG_SIGNATURE, ...chunksOf(file).filter((chunk) => !TEXT_CHUNKS.has(chunk.type)).map((chunk) => chunk.raw)]);
221
+ }
222
+ function jsonOf(file, name) {
223
+ if (file.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)) {
224
+ const found = /* @__PURE__ */ new Map();
225
+ for (const chunk of chunksOf(file)) {
226
+ if (!TEXT_CHUNKS.has(chunk.type)) continue;
227
+ const text = textOf$1(chunk);
228
+ if (text !== void 0 && CARD_KEYWORDS.includes(text.keyword) && !found.has(text.keyword)) found.set(text.keyword, text.text);
229
+ }
230
+ const keyword = CARD_KEYWORDS.find((candidate) => found.has(candidate));
231
+ if (keyword === void 0) throw new ImportCardError(`${name} is a PNG picture with no character card in it`);
232
+ try {
233
+ return JSON.parse(Buffer.from(found.get(keyword).trim(), "base64").toString("utf8"));
234
+ } catch {
235
+ throw new ImportCardError(`the card data in ${name} is not readable`);
236
+ }
237
+ }
238
+ try {
239
+ return JSON.parse(file.toString("utf8").replace(/^/, ""));
240
+ } catch {
241
+ throw new ImportCardError(`${name} is neither a PNG picture with a card in it nor a JSON card`);
242
+ }
243
+ }
244
+ const URL_PATTERN = /https?:\/\/[^\s"'`<>()[\]{}\\|^]+/gi;
245
+ /** Every web address in the strings of a document, at any depth; template placeholders and trailing punctuation are not part of one. */
246
+ function urlsOf(value) {
247
+ const found = /* @__PURE__ */ new Set();
248
+ const visit = (node, depth) => {
249
+ if (depth > 32) return;
250
+ if (typeof node === "string") for (const match of node.matchAll(URL_PATTERN)) {
251
+ const url = match[0].replace(/[.,;:!?*_~]+$/, "");
252
+ if (!url.includes("$") && url.length <= 2e3) found.add(url);
253
+ }
254
+ else if (Array.isArray(node)) for (const entry of node) visit(entry, depth + 1);
255
+ else if (typeof node === "object" && node !== null) for (const entry of Object.values(node)) visit(entry, depth + 1);
256
+ };
257
+ visit(value, 0);
258
+ return [...found];
259
+ }
260
+ const object$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
261
+ const text$2 = (value) => typeof value === "string" ? value : typeof value === "number" ? String(value) : "";
262
+ const texts = (value) => Array.isArray(value) ? value.flatMap((entry) => typeof entry === "string" ? [entry] : typeof entry === "number" ? [String(entry)] : []) : [];
263
+ function entryOf(value, index) {
264
+ const entry = object$1(value);
265
+ if (entry === void 0) return void 0;
266
+ const position = entry["position"];
267
+ return {
268
+ id: `entry:${index}`,
269
+ title: text$2(entry["comment"]).trim() || text$2(entry["name"]).trim(),
270
+ keys: texts(entry["keys"]),
271
+ secondaryKeys: texts(entry["secondary_keys"]),
272
+ content: text$2(entry["content"]),
273
+ enabled: entry["enabled"] !== false,
274
+ constant: entry["constant"] === true,
275
+ selective: entry["selective"] === true,
276
+ position: typeof position === "string" ? position : typeof position === "number" ? String(position) : ""
277
+ };
278
+ }
279
+ /**
280
+ * Reads a character card: a PNG with the card in its text chunk (the newer `ccv3` chunk when there is one), or the JSON of a card.
281
+ * Only V2 and V3 cards are read; a V2 card is carried over into the V3 shape, whose fields are a superset.
282
+ * @throws {ImportCardError} when the file is not such a card.
283
+ */
284
+ function readCard(file, name) {
285
+ const root = object$1(jsonOf(file, name));
286
+ const spec = root === void 0 ? void 0 : root["spec"];
287
+ 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"]);
289
+ if (data === void 0) throw new ImportCardError(`${name} has no card data`);
290
+ const cardName = text$2(data["name"]).trim();
291
+ if (cardName === "") throw new ImportCardError(`${name} has a card with no name`);
292
+ const book = object$1(data["character_book"]);
293
+ 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);
296
+ return {
297
+ sourceSpec: spec,
298
+ name: cardName,
299
+ description: text$2(data["description"]),
300
+ personality: text$2(data["personality"]),
301
+ scenario: text$2(data["scenario"]),
302
+ firstMessage: text$2(data["first_mes"]),
303
+ alternateGreetings: texts(data["alternate_greetings"]),
304
+ messageExample: text$2(data["mes_example"]),
305
+ creatorNotes: text$2(data["creator_notes"]),
306
+ systemPrompt: text$2(data["system_prompt"]),
307
+ postHistoryInstructions: text$2(data["post_history_instructions"]),
308
+ tags: texts(data["tags"]),
309
+ creator: text$2(data["creator"]),
310
+ characterVersion: text$2(data["character_version"]),
311
+ ...book === void 0 ? {} : { book: {
312
+ name: text$2(book["name"]),
313
+ description: text$2(book["description"]),
314
+ entries
315
+ } },
316
+ ignored: {
317
+ scripts,
318
+ extensions: Object.keys(extensions).filter((key) => ![
319
+ "talkativeness",
320
+ "fav",
321
+ "world",
322
+ "depth_prompt"
323
+ ].includes(key))
324
+ },
325
+ urls: urlsOf(data)
326
+ };
327
+ }
328
+ /** Whether a file looks like a PNG, so that its picture can be kept. */
329
+ const isPng = (file) => file.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE);
330
+ //#endregion
155
331
  //#region src/shared/import-card.ts
156
332
  /** The message the plugin sends on the player's behalf to start the import in the new world's authoring chat. */
157
333
  const IMPORT_COMMAND = "/import-st";
@@ -752,11 +928,12 @@ function parseWorldInfoEdit(value) {
752
928
  if (input["alternateOpenings"] !== void 0) {
753
929
  const list = input["alternateOpenings"];
754
930
  const entries = Array.isArray(list) ? list.map((entry) => typeof entry === "object" && entry !== null ? entry : void 0) : void 0;
755
- if (entries === void 0 || entries.some((entry) => entry === void 0 || typeof entry["text"] !== "string" || entry["title"] !== void 0 && typeof entry["title"] !== "string")) problems.push("alternateOpenings must be a list of { title, text }");
931
+ if (entries === void 0 || entries.some((entry) => entry === void 0 || typeof entry["text"] !== "string" || entry["title"] !== void 0 && typeof entry["title"] !== "string" || entry["character"] !== void 0 && typeof entry["character"] !== "string")) problems.push("alternateOpenings must be a list of { title, text, character? }");
756
932
  else {
757
933
  const kept = entries.map((entry) => ({
758
934
  title: String(entry["title"] ?? "").trim(),
759
- text: String(entry["text"]).trim()
935
+ text: String(entry["text"]).trim(),
936
+ ...String(entry["character"] ?? "").trim() === "" ? {} : { character: String(entry["character"]).trim() }
760
937
  })).filter((entry) => entry.text !== "");
761
938
  if (kept.length > 30) problems.push(`there are more than 30 alternate openings`);
762
939
  if (kept.some((entry) => entry.text.length > 2e4)) problems.push(`an alternate opening is longer than ${MAX_OPENING_CHARS} characters`);
@@ -777,7 +954,7 @@ function parseWorldInfoEdit(value) {
777
954
  //#endregion
778
955
  //#region src/host/worlds/world-file.ts
779
956
  const WORLD_FILE_NAME = "world.json";
780
- /** `alternate_openings` is a list of `{ title, text }`: other first messages the player may start with. */
957
+ /** `alternate_openings` is a list of `{ title, text, character? }`: other first messages the player may start with, each for any character or for one playable character. */
781
958
  function readAlternateOpenings(reader) {
782
959
  const value = reader.raw("alternate_openings");
783
960
  if (value === void 0 || value === null) return void 0;
@@ -791,9 +968,11 @@ function readAlternateOpenings(reader) {
791
968
  const text = entry.string("text", { required: true })?.trim();
792
969
  if (text === void 0 || text === "") continue;
793
970
  if (text.length > 2e4) entry.fail("text", `is longer than ${MAX_OPENING_CHARS} characters`);
971
+ const character = entry.string("character")?.trim();
794
972
  openings.push({
795
973
  title: entry.string("title")?.trim() || text.slice(0, 40),
796
- text
974
+ text,
975
+ ...character === void 0 || character === "" ? {} : { character }
797
976
  });
798
977
  }
799
978
  return openings.length === 0 ? void 0 : openings;
@@ -2400,7 +2579,7 @@ const SOURCE_BUDGET_CHARS = 14e3;
2400
2579
  const MAX_TAGGED = 8;
2401
2580
  const MAX_MENTIONS = 6;
2402
2581
  const MIN_MENTION_CHARS = 2;
2403
- const text = (value) => typeof value === "string" ? value.trim() : "";
2582
+ const text$1 = (value) => typeof value === "string" ? value.trim() : "";
2404
2583
  const list = (value) => Array.isArray(value) ? value.flatMap((entry) => typeof entry === "string" && entry.trim() !== "" ? [entry.trim()] : []) : [];
2405
2584
  const objects = (value) => Array.isArray(value) ? value.filter((entry) => typeof entry === "object" && entry !== null && !Array.isArray(entry)) : [];
2406
2585
  const put = (document, key, value) => {
@@ -2515,6 +2694,27 @@ const CHARACTER_SCHEMA = {
2515
2694
  required: ["with", "label"],
2516
2695
  additionalProperties: false
2517
2696
  }
2697
+ },
2698
+ knows: {
2699
+ type: "object",
2700
+ properties: {
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."),
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
+ }
2716
+ },
2717
+ additionalProperties: false
2518
2718
  }
2519
2719
  },
2520
2720
  required: [
@@ -2540,7 +2740,7 @@ function characterDocument(entity, answer, roster) {
2540
2740
  "age",
2541
2741
  "gender",
2542
2742
  "pronouns"
2543
- ]) put(document, field, text(answer[field]));
2743
+ ]) put(document, field, text$1(answer[field]));
2544
2744
  const playable = entity.player;
2545
2745
  const group = answer["kind"] === "group" && !playable;
2546
2746
  document["role"] = playable ? "playable" : "npc";
@@ -2551,10 +2751,10 @@ function characterDocument(entity, answer, roster) {
2551
2751
  "personality",
2552
2752
  "background",
2553
2753
  "appearance"
2554
- ]) document[field] = text(answer[field]);
2754
+ ]) document[field] = text$1(answer[field]);
2555
2755
  const speech = typeof answer["speech"] === "object" && answer["speech"] !== null ? answer["speech"] : {};
2556
2756
  document["speech"] = {
2557
- style: text(speech["style"]),
2757
+ style: text$1(speech["style"]),
2558
2758
  examples: list(speech["examples"]).slice(0, 8)
2559
2759
  };
2560
2760
  const start = {};
@@ -2563,17 +2763,17 @@ function characterDocument(entity, answer, roster) {
2563
2763
  ["public_state", "public_state"],
2564
2764
  ["inner_state", "inner_state"],
2565
2765
  ["activity", "activity"]
2566
- ]) put(start, to, text(given[from]));
2567
- const place = text(given["location"]) === "" ? void 0 : findEntity(roster, text(given["location"]), "place");
2568
- if (text(given["location"]) !== "" && place === void 0) notes.push(`${entity.name}: the place "${text(given["location"])}" is not one of the world's places, so the character starts nowhere`);
2766
+ ]) put(start, to, text$1(given[from]));
2767
+ const place = text$1(given["location"]) === "" ? void 0 : findEntity(roster, text$1(given["location"]), "place");
2768
+ if (text$1(given["location"]) !== "" && place === void 0) notes.push(`${entity.name}: the place "${text$1(given["location"])}" is not one of the world's places, so the character starts nowhere`);
2569
2769
  if (place !== void 0) {
2570
2770
  start["location"] = place.key;
2571
- put(start, "position", text(given["position"]));
2771
+ put(start, "position", text$1(given["position"]));
2572
2772
  }
2573
- const goals = objects(answer["goals"]).filter((goal) => text(goal["name"]) !== "").map((goal) => ({
2773
+ const goals = objects(answer["goals"]).filter((goal) => text$1(goal["name"]) !== "").map((goal) => ({
2574
2774
  type: "agenda",
2575
- name: text(goal["name"]),
2576
- ...text(goal["description"]) === "" ? {} : { description: text(goal["description"]) },
2775
+ name: text$1(goal["name"]),
2776
+ ...text$1(goal["description"]) === "" ? {} : { description: text$1(goal["description"]) },
2577
2777
  status: "active"
2578
2778
  }));
2579
2779
  put(start, "intents", goals);
@@ -2581,20 +2781,47 @@ function characterDocument(entity, answer, roster) {
2581
2781
  const seen = /* @__PURE__ */ new Set([entity.key]);
2582
2782
  const relationships = [];
2583
2783
  for (const relation of objects(answer["relationships"])) {
2584
- const other = findEntity(roster, text(relation["with"]), "character");
2784
+ const other = findEntity(roster, text$1(relation["with"]), "character");
2585
2785
  if (other === void 0) {
2586
- notes.push(`${entity.name}: the relationship with "${text(relation["with"])}" names nobody in the world`);
2786
+ notes.push(`${entity.name}: the relationship with "${text$1(relation["with"])}" names nobody in the world`);
2587
2787
  continue;
2588
2788
  }
2589
- if (seen.has(other.key) || text(relation["label"]) === "") continue;
2789
+ if (seen.has(other.key) || text$1(relation["label"]) === "") continue;
2590
2790
  seen.add(other.key);
2591
2791
  relationships.push({
2592
2792
  to: other.key,
2593
- label: text(relation["label"]),
2594
- ...text(relation["summary"]) === "" ? {} : { summary: text(relation["summary"]) }
2793
+ label: text$1(relation["label"]),
2794
+ ...text$1(relation["summary"]) === "" ? {} : { summary: text$1(relation["summary"]) }
2595
2795
  });
2596
2796
  }
2597
2797
  put(document, "relationships", relationships.slice(0, 60));
2798
+ const knows = typeof answer["knows"] === "object" && answer["knows"] !== null ? answer["knows"] : {};
2799
+ const known = (names, kind) => [...new Set(names.flatMap((name) => {
2800
+ const found = findEntity(roster, name, kind);
2801
+ if (found === void 0) notes.push(`${entity.name}: "${name}" is not one of the world's ${kind === "place" ? "places" : "things"}, so they do not know of it`);
2802
+ return found === void 0 ? [] : [found.key];
2803
+ }))];
2804
+ const knowledge = {};
2805
+ put(knowledge, "locations", known(list(knows["places"]), "place"));
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);
2824
+ put(document, "knowledge", Object.keys(knowledge).length === 0 ? void 0 : knowledge);
2598
2825
  return {
2599
2826
  document,
2600
2827
  notes
@@ -2639,30 +2866,30 @@ function placeDocument(entity, answer, roster) {
2639
2866
  id: entity.key,
2640
2867
  name: entity.name
2641
2868
  };
2642
- put(document, "description", text(answer["description"]));
2643
- const named = text(answer["parent"]) === "" ? entity.parent : text(answer["parent"]);
2869
+ put(document, "description", text$1(answer["description"]));
2870
+ const named = text$1(answer["parent"]) === "" ? entity.parent : text$1(answer["parent"]);
2644
2871
  const parent = named === void 0 ? void 0 : findEntity(roster, named, "place");
2645
2872
  if (named !== void 0 && (parent === void 0 || parent.key === entity.key)) notes.push(`${entity.name}: the place it is in, "${named}", is not one of the world's places`);
2646
2873
  if (parent !== void 0 && parent.key !== entity.key) document["parent"] = parent.key;
2647
- const features = objects(answer["features"]).filter((feature) => text(feature["name"]) !== "").slice(0, 30).map((feature, index) => ({
2874
+ const features = objects(answer["features"]).filter((feature) => text$1(feature["name"]) !== "").slice(0, 30).map((feature, index) => ({
2648
2875
  id: `feature-${index + 1}`,
2649
- name: text(feature["name"]),
2650
- ...text(feature["description"]) === "" ? {} : { description: text(feature["description"]) }
2876
+ name: text$1(feature["name"]),
2877
+ ...text$1(feature["description"]) === "" ? {} : { description: text$1(feature["description"]) }
2651
2878
  }));
2652
2879
  put(document, "features", features);
2653
2880
  const exits = [];
2654
2881
  const to = /* @__PURE__ */ new Set();
2655
2882
  for (const exit of objects(answer["exits"])) {
2656
- const target = findEntity(roster, text(exit["to"]), "place");
2883
+ const target = findEntity(roster, text$1(exit["to"]), "place");
2657
2884
  if (target === void 0 || target.key === entity.key) {
2658
- notes.push(`${entity.name}: the way to "${text(exit["to"])}" leads to no place of the world`);
2885
+ notes.push(`${entity.name}: the way to "${text$1(exit["to"])}" leads to no place of the world`);
2659
2886
  continue;
2660
2887
  }
2661
2888
  if (to.has(target.key)) continue;
2662
2889
  to.add(target.key);
2663
2890
  exits.push({
2664
2891
  to: target.key,
2665
- ...text(exit["description"]) === "" ? {} : { description: text(exit["description"]) }
2892
+ ...text$1(exit["description"]) === "" ? {} : { description: text$1(exit["description"]) }
2666
2893
  });
2667
2894
  }
2668
2895
  put(document, "exits", exits.slice(0, 30));
@@ -2708,25 +2935,25 @@ function factionDocument(entity, answer, roster) {
2708
2935
  "summary",
2709
2936
  "description",
2710
2937
  "structure"
2711
- ]) put(document, field, text(answer[field]));
2938
+ ]) put(document, field, text$1(answer[field]));
2712
2939
  put(document, "values", list(answer["values"]));
2713
2940
  const start = {};
2714
- put(start, "public_state", text(answer["public_state"]));
2715
- put(start, "inner_state", text(answer["inner_state"]));
2941
+ put(start, "public_state", text$1(answer["public_state"]));
2942
+ put(start, "inner_state", text$1(answer["inner_state"]));
2716
2943
  put(document, "start", Object.keys(start).length === 0 ? void 0 : start);
2717
2944
  const members = [];
2718
2945
  const seen = /* @__PURE__ */ new Set();
2719
2946
  for (const member of objects(answer["members"])) {
2720
- const character = findEntity(roster, text(member["character"]), "character");
2947
+ const character = findEntity(roster, text$1(member["character"]), "character");
2721
2948
  if (character === void 0) {
2722
- notes.push(`${entity.name}: the member "${text(member["character"])}" is nobody in the world`);
2949
+ notes.push(`${entity.name}: the member "${text$1(member["character"])}" is nobody in the world`);
2723
2950
  continue;
2724
2951
  }
2725
2952
  if (seen.has(character.key)) continue;
2726
2953
  seen.add(character.key);
2727
2954
  members.push({
2728
2955
  character: character.key,
2729
- ...text(member["role"]) === "" ? {} : { role: text(member["role"]) }
2956
+ ...text$1(member["role"]) === "" ? {} : { role: text$1(member["role"]) }
2730
2957
  });
2731
2958
  }
2732
2959
  put(document, "members", members);
@@ -2754,11 +2981,11 @@ function thingDocument(entity, answer, roster) {
2754
2981
  name: entity.name,
2755
2982
  unique: true
2756
2983
  };
2757
- put(document, "description", text(answer["description"]));
2758
- put(document, "quality", text(answer["quality"]));
2984
+ put(document, "description", text$1(answer["description"]));
2985
+ put(document, "quality", text$1(answer["quality"]));
2759
2986
  if (answer["notable"] === true) document["notable"] = true;
2760
- const holder = text(answer["held_by"]) === "" ? void 0 : findEntity(roster, text(answer["held_by"]), "character");
2761
- const place = text(answer["location"]) === "" ? void 0 : findEntity(roster, text(answer["location"]), "place");
2987
+ const holder = text$1(answer["held_by"]) === "" ? void 0 : findEntity(roster, text$1(answer["held_by"]), "character");
2988
+ const place = text$1(answer["location"]) === "" ? void 0 : findEntity(roster, text$1(answer["location"]), "place");
2762
2989
  if (holder !== void 0) document["held_by"] = holder.key;
2763
2990
  else if (place !== void 0) document["location"] = place.key;
2764
2991
  else notes.push(`${entity.name}: it is nowhere in the world and nobody has it, so it is left out`);
@@ -2822,8 +3049,8 @@ const LORE_SUBJECT = {
2822
3049
  };
2823
3050
  function loreDocuments(answer, roster, taken) {
2824
3051
  return objects(answer["entries"]).flatMap((entry) => {
2825
- const title = text(entry["title"]);
2826
- const body = text(entry["body"]);
3052
+ const title = text$1(entry["title"]);
3053
+ const body = text$1(entry["body"]);
2827
3054
  if (title === "" || body === "") return [];
2828
3055
  const notes = [];
2829
3056
  const subjects = [];
@@ -2834,10 +3061,10 @@ function loreDocuments(answer, roster, taken) {
2834
3061
  "place",
2835
3062
  "faction",
2836
3063
  "thing"
2837
- ].includes(text(subject["kind"])) ? text(subject["kind"]) : void 0;
2838
- const found = kind === void 0 ? void 0 : findEntity(roster, text(subject["name"]), kind);
3064
+ ].includes(text$1(subject["kind"])) ? text$1(subject["kind"]) : void 0;
3065
+ const found = kind === void 0 ? void 0 : findEntity(roster, text$1(subject["name"]), kind);
2839
3066
  if (found === void 0) {
2840
- notes.push(`${title}: the subject "${text(subject["name"])}" is not in the world`);
3067
+ notes.push(`${title}: the subject "${text$1(subject["name"])}" is not in the world`);
2841
3068
  continue;
2842
3069
  }
2843
3070
  if (!seen.has(found.key)) {
@@ -2853,7 +3080,7 @@ function loreDocuments(answer, roster, taken) {
2853
3080
  id: uniqueKey(slug(title, "lore"), taken),
2854
3081
  title,
2855
3082
  kind,
2856
- summary: text(entry["summary"]),
3083
+ summary: text$1(entry["summary"]),
2857
3084
  body
2858
3085
  };
2859
3086
  put(document, "subjects", subjects);
@@ -2928,6 +3155,61 @@ function pruneLoreSubjects(result) {
2928
3155
  else entry["subjects"] = kept;
2929
3156
  }
2930
3157
  }
3158
+ /** Takes out of what characters know the places and things that were not written (a thing that is nowhere and nobody's is not made). */
3159
+ function pruneKnowledge(result) {
3160
+ const written = {
3161
+ locations: new Set(result.locations.map((entry) => String(entry["id"]))),
3162
+ items: new Set(result.items.map((entry) => String(entry["id"])))
3163
+ };
3164
+ const ways = new Set(result.locations.flatMap((place) => objects(place["exits"]).map((exit) => `${String(place["id"])}>${String(exit["to"])}`)));
3165
+ for (const character of result.characters) {
3166
+ const knowledge = character["knowledge"];
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
+ }
3175
+ for (const field of ["locations", "items"]) {
3176
+ const keys = knowledge[field] ?? [];
3177
+ const kept = keys.filter((key) => written[field].has(key));
3178
+ if (kept.length === keys.length) continue;
3179
+ result.notes.push(`${String(character["name"])}: ${keys.length - kept.length} known ${field === "items" ? "thing(s)" : "place(s)"} left out because the world has no such entity`);
3180
+ if (kept.length === 0) delete knowledge[field];
3181
+ else knowledge[field] = kept;
3182
+ }
3183
+ if (Object.keys(knowledge).length === 0) delete character["knowledge"];
3184
+ }
3185
+ }
3186
+ /**
3187
+ * Completes what characters are aware of, because a missing edge means a character does not know the other exists: a character named in someone's relationships
3188
+ * knows of that someone (a neutral acquaintance, added when the character has none), and knows the lore that is about them.
3189
+ */
3190
+ function completeAwareness(result) {
3191
+ const byId = new Map(result.characters.map((character) => [String(character["id"]), character]));
3192
+ let added = 0;
3193
+ for (const character of result.characters) for (const relation of character["relationships"] ?? []) {
3194
+ const other = byId.get(String(relation["to"]));
3195
+ if (other === void 0 || other === character) continue;
3196
+ const theirs = other["relationships"] ?? [];
3197
+ if (theirs.some((entry) => entry["to"] === character["id"])) continue;
3198
+ other["relationships"] = [...theirs, {
3199
+ to: character["id"],
3200
+ label: "acquaintance"
3201
+ }];
3202
+ added += 1;
3203
+ }
3204
+ if (added > 0) result.notes.push(`${added} relationship(s) were added in the other direction as plain acquaintances, so that both characters know of each other`);
3205
+ for (const entry of result.lore) for (const subject of entry["subjects"] ?? []) {
3206
+ const character = subject["kind"] === "character" ? byId.get(String(subject["id"])) : void 0;
3207
+ if (character === void 0) continue;
3208
+ const knowledge = character["knowledge"] ?? (character["knowledge"] = {});
3209
+ const known = knowledge["lore"] ?? [];
3210
+ if (!known.includes(String(entry["id"]))) knowledge["lore"] = [...known, String(entry["id"])];
3211
+ }
3212
+ }
2931
3213
  /** Adds an entry unless the world already has it: the same title, or a body that an earlier entry already contains (a longer one replaces a shorter that it contains). */
2932
3214
  function addLore(lore, entry) {
2933
3215
  const title = norm(String(entry["title"]));
@@ -3064,6 +3346,8 @@ async function extractEntities(ctx, card, items, classified, roster) {
3064
3346
  }
3065
3347
  placeAtScenario(result, items, classified, roster);
3066
3348
  pruneLoreSubjects(result);
3349
+ pruneKnowledge(result);
3350
+ completeAwareness(result);
3067
3351
  return result;
3068
3352
  }
3069
3353
  const STYLE_SCHEMA = {
@@ -3102,21 +3386,24 @@ function styleProblem(id, value) {
3102
3386
  }
3103
3387
  /** Turns the instructions of a card into the prose prompts of the world. Only prose and behaviour are kept: the rules of the game stay the program's. */
3104
3388
  async function extractStyle(ctx, card, items, classified) {
3105
- const pieces = instructionPieces(card, items, classified);
3389
+ return await extractStyleFrom(ctx, card.name, instructionPieces(card, items, classified));
3390
+ }
3391
+ /** The prose prompts that instruction texts become, and what was left out of them. */
3392
+ async function extractStyleFrom(ctx, name, pieces) {
3106
3393
  if (pieces.length === 0) return {
3107
3394
  prompts: [],
3108
3395
  notes: []
3109
3396
  };
3110
3397
  ctx.say("writing the style prompts");
3111
3398
  try {
3112
- const prompt = `Card: ${card.name}\n\nThe instructions of the card:\n\n${pieces.join("\n\n---\n\n").slice(0, SOURCE_BUDGET_CHARS)}`;
3399
+ const prompt = `Card: ${name}\n\nThe instructions of the card:\n\n${pieces.join("\n\n---\n\n").slice(0, SOURCE_BUDGET_CHARS)}`;
3113
3400
  const answer = await ctx.run({
3114
3401
  persona: ctx.text("import/style", { rules: ctx.text("import/common-rules") }),
3115
3402
  prompt,
3116
3403
  result: STYLE_SCHEMA,
3117
- check: (value) => styleProblem("roleplay/style", text(value.narration)) ?? styleProblem("roleplay/character-style", text(value.characters))
3404
+ check: (value) => styleProblem("roleplay/style", text$1(value.narration)) ?? styleProblem("roleplay/character-style", text$1(value.characters))
3118
3405
  });
3119
- const prompts = [["roleplay/style", text(answer.narration)], ["roleplay/character-style", text(answer.characters)]].flatMap(([id, body]) => body === "" ? [] : [{
3406
+ const prompts = [["roleplay/style", text$1(answer.narration)], ["roleplay/character-style", text$1(answer.characters)]].flatMap(([id, body]) => body === "" ? [] : [{
3120
3407
  id,
3121
3408
  text: body
3122
3409
  }]);
@@ -3180,11 +3467,11 @@ const VARIABLES_SCHEMA = {
3180
3467
  description: "Names from the lists of characters, places or things it is limited to; empty for all."
3181
3468
  },
3182
3469
  min: {
3183
- type: ["number", "null"],
3470
+ oneOf: [{ type: "number" }, { type: "null" }],
3184
3471
  description: "The lowest value the card allows, or null."
3185
3472
  },
3186
3473
  max: {
3187
- type: ["number", "null"],
3474
+ oneOf: [{ type: "number" }, { type: "null" }],
3188
3475
  description: "The highest value the card allows, or null."
3189
3476
  },
3190
3477
  integer: {
@@ -3192,11 +3479,11 @@ const VARIABLES_SCHEMA = {
3192
3479
  description: "True when it counts whole units."
3193
3480
  },
3194
3481
  default: {
3195
- type: [
3196
- "number",
3197
- "boolean",
3198
- "string",
3199
- "null"
3482
+ oneOf: [
3483
+ { type: "number" },
3484
+ { type: "boolean" },
3485
+ { type: "string" },
3486
+ { type: "null" }
3200
3487
  ],
3201
3488
  description: "Where it starts: a number, true or false, or one of the options; null when the card does not say."
3202
3489
  },
@@ -3252,15 +3539,15 @@ function variableDocuments(answer, roster) {
3252
3539
  const keyOf = (name) => roster.find((entity) => norm(entity.name) === norm(name) || entity.aliases.some((alias) => norm(alias) === norm(name)))?.key;
3253
3540
  const taken = /* @__PURE__ */ new Set();
3254
3541
  return objects(answer["variables"]).map((entry, index) => {
3255
- const base = slug(text(entry["key"]) || text(entry["name"]), "").replace(/-/g, "_").slice(0, 40);
3542
+ const base = slug(text$1(entry["key"]) || text$1(entry["name"]), "").replace(/-/g, "_").slice(0, 40);
3256
3543
  const document = {
3257
3544
  key: uniqueKey(/^[a-z][a-z0-9_]*$/.test(base) ? base : `variable_${index + 1}`, taken),
3258
- name: text(entry["name"]),
3259
- kind: text(entry["kind"]),
3260
- subject: text(entry["subject"])
3545
+ name: text$1(entry["name"]),
3546
+ kind: text$1(entry["kind"]),
3547
+ subject: text$1(entry["subject"])
3261
3548
  };
3262
- put(document, "description", text(entry["description"]));
3263
- put(document, "visibility", text(entry["visibility"]));
3549
+ put(document, "description", text$1(entry["description"]));
3550
+ put(document, "visibility", text$1(entry["visibility"]));
3264
3551
  put(document, "only", list(entry["only"]).flatMap((name) => keyOf(name) ?? []));
3265
3552
  for (const field of ["min", "max"]) if (typeof entry[field] === "number") document[field] = entry[field];
3266
3553
  if (typeof entry["integer"] === "boolean") document["integer"] = entry["integer"];
@@ -3270,9 +3557,9 @@ function variableDocuments(answer, roster) {
3270
3557
  "string"
3271
3558
  ].includes(typeof entry["default"])) document["default"] = entry["default"];
3272
3559
  put(document, "options", list(entry["options"]));
3273
- put(document, "bands", objects(entry["bands"]).filter((band) => typeof band["up_to"] === "number" && text(band["label"]) !== "").map((band) => ({
3560
+ put(document, "bands", objects(entry["bands"]).filter((band) => typeof band["up_to"] === "number" && text$1(band["label"]) !== "").map((band) => ({
3274
3561
  up_to: band["up_to"],
3275
- label: text(band["label"])
3562
+ label: text$1(band["label"])
3276
3563
  })));
3277
3564
  return document;
3278
3565
  });
@@ -5355,7 +5642,7 @@ const INTENT = [
5355
5642
  ".open_threads[]",
5356
5643
  ".constraints[]"
5357
5644
  ];
5358
- const FIELDS = {
5645
+ const FIELDS$1 = {
5359
5646
  world: {
5360
5647
  names: ["name"],
5361
5648
  text: [
@@ -5422,7 +5709,8 @@ const FIELDS = {
5422
5709
  ...INTENT.map((path) => `start.intents[]${path}`),
5423
5710
  "relationships[].label",
5424
5711
  "relationships[].summary",
5425
- "routine[].activity"
5712
+ "routine[].activity",
5713
+ "visual_identity.description"
5426
5714
  ]
5427
5715
  },
5428
5716
  location: {
@@ -5432,12 +5720,17 @@ const FIELDS = {
5432
5720
  "features[].description",
5433
5721
  "exits[].description",
5434
5722
  "exits[].note",
5435
- "exits[].back_description"
5723
+ "exits[].back_description",
5724
+ "visual_identity.description"
5436
5725
  ]
5437
5726
  },
5438
5727
  item: {
5439
5728
  names: ["name"],
5440
- text: ["description", "quality"]
5729
+ text: [
5730
+ "description",
5731
+ "quality",
5732
+ "visual_identity.description"
5733
+ ]
5441
5734
  },
5442
5735
  faction: {
5443
5736
  names: ["name", "aliases[]"],
@@ -5466,7 +5759,7 @@ const FIELDS = {
5466
5759
  };
5467
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. */
5468
5761
  function leavesOf(kind, document) {
5469
- const fields = FIELDS[kind];
5762
+ const fields = FIELDS$1[kind];
5470
5763
  const names = new Set(fields.names);
5471
5764
  const text = new Set(fields.text);
5472
5765
  const leaves = [];
@@ -5609,7 +5902,8 @@ const TEXTS_SCHEMA = {
5609
5902
  required: ["translations"],
5610
5903
  additionalProperties: false
5611
5904
  };
5612
- const braces = (text) => (text.match(/\{[^{}]*\}/g) ?? []).sort().join("\0");
5905
+ const BRACED = /\$?\{[^{}]*\}/g;
5906
+ const braces = (text) => (text.match(BRACED) ?? []).sort().join("\0");
5613
5907
  const letters = (text) => text.match(/\p{L}/gu)?.length ?? 0;
5614
5908
  /** The language the world is written in, from the words of all its files; nothing when there are too few to tell. */
5615
5909
  function languageOfDocuments(documents) {
@@ -5637,7 +5931,7 @@ function problemWith(sources, from, translations, glossary) {
5637
5931
  for (const [index, source] of sources.entries()) {
5638
5932
  const text = translations[index];
5639
5933
  if (text.trim() === "") return `translation ${index + 1} is empty`;
5640
- 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(" ")}`;
5641
5935
  if (letters(source) >= CHECKED_LETTERS && textLanguage(source) === from && textLanguage(text) === from) return `translation ${index + 1} is still in the original language`;
5642
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}"`;
5643
5937
  }
@@ -5693,6 +5987,23 @@ async function freeFolder(directory, suffix) {
5693
5987
  }
5694
5988
  }
5695
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
+ }
5696
6007
  async function listedIn(directory, names) {
5697
6008
  const present = new Set(await readdir(directory));
5698
6009
  return names.filter((name) => present.has(name));
@@ -5738,6 +6049,18 @@ async function translateWorld(ctx, worlds, source, to, told) {
5738
6049
  const aliases = Array.isArray(document["aliases"]) ? document["aliases"] : [];
5739
6050
  if (original !== void 0 && original !== document["name"] && !aliases.includes(original)) document["aliases"] = [...aliases, original];
5740
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
+ }
5741
6064
  const id = randomUUID();
5742
6065
  const destination = await freeFolder(source.directory, to);
5743
6066
  await cp(source.directory, destination, {
@@ -5751,6 +6074,11 @@ async function translateWorld(ctx, worlds, source, to, told) {
5751
6074
  }))(entry.document) : entry.document;
5752
6075
  await writeFile(join(destination, entry.file), `${JSON.stringify(document, null, 2)}\n`);
5753
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
+ }
5754
6082
  const payload = await worlds.list({ refresh: true });
5755
6083
  const made = payload.worlds.find((world) => world.id === id);
5756
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("; ")}`);
@@ -5770,8 +6098,8 @@ async function translateWorld(ctx, worlds, source, to, told) {
5770
6098
  texts,
5771
6099
  names: names.length + recurring.length,
5772
6100
  problems,
6101
+ prompts: written.map((prompt) => prompt.id),
5773
6102
  copiedAsIs: await listedIn(source.directory, [
5774
- "prompts",
5775
6103
  "ui",
5776
6104
  "images",
5777
6105
  "media"
@@ -6040,6 +6368,109 @@ function translateTools(worlds, settings, prompting) {
6040
6368
  })];
6041
6369
  }
6042
6370
  //#endregion
6371
+ //#region src/host/import/preset.ts
6372
+ /** The older preset layout keeps its texts under fixed keys. */
6373
+ const LEGACY_KEYS = [
6374
+ "main_prompt",
6375
+ "nsfw_prompt",
6376
+ "jailbreak_prompt",
6377
+ "impersonation_prompt",
6378
+ "new_chat_prompt",
6379
+ "new_group_chat_prompt",
6380
+ "new_example_chat_prompt"
6381
+ ];
6382
+ const MAX_PIECES = 60;
6383
+ const MAX_PIECE_CHARS = 8e3;
6384
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6385
+ const text = (value) => typeof value === "string" ? value.trim() : "";
6386
+ /** The order the preset sends its prompts in: the longest list it gives, with what each entry says about being on. */
6387
+ function orderOf(root) {
6388
+ return ((Array.isArray(root["prompt_order"]) ? root["prompt_order"].flatMap((entry) => isObject(entry) && Array.isArray(entry["order"]) ? [entry["order"]] : []) : []).sort((a, b) => b.length - a.length)[0] ?? []).flatMap((entry) => isObject(entry) && typeof entry["identifier"] === "string" ? [{
6389
+ identifier: entry["identifier"],
6390
+ enabled: entry["enabled"] !== false
6391
+ }] : []);
6392
+ }
6393
+ /**
6394
+ * Reads a preset file. Markers (places where chat history or the card's fields are inserted), switched-off prompts and empty ones are left out.
6395
+ * @throws {ImportCardError} when the file is not a preset, with why.
6396
+ */
6397
+ function readPreset(file, name) {
6398
+ let root;
6399
+ try {
6400
+ root = JSON.parse(file.toString("utf8").replace(/^/, ""));
6401
+ } catch {
6402
+ throw new ImportCardError("the file is not JSON: a preset is the .json file SillyTavern exports");
6403
+ }
6404
+ if (!isObject(root)) throw new ImportCardError("the file is not a preset: it must be a JSON object");
6405
+ const pieces = [];
6406
+ const prompts = Array.isArray(root["prompts"]) ? root["prompts"].filter(isObject) : [];
6407
+ if (prompts.length > 0) {
6408
+ const byId = new Map(prompts.flatMap((prompt) => typeof prompt["identifier"] === "string" ? [[prompt["identifier"], prompt]] : []));
6409
+ const ordered = orderOf(root);
6410
+ const chosen = ordered.length > 0 ? ordered.flatMap((entry) => entry.enabled && byId.has(entry.identifier) ? [byId.get(entry.identifier)] : []) : prompts.filter((prompt) => prompt["enabled"] !== false);
6411
+ for (const prompt of chosen) {
6412
+ const content = text(prompt["content"]);
6413
+ if (prompt["marker"] === true || content === "") continue;
6414
+ const title = text(prompt["name"]);
6415
+ pieces.push(`${title === "" ? "" : `[${title}]\n`}${content.slice(0, MAX_PIECE_CHARS)}`);
6416
+ }
6417
+ } else for (const key of LEGACY_KEYS) if (text(root[key]) !== "") pieces.push(`[${key}]\n${text(root[key]).slice(0, MAX_PIECE_CHARS)}`);
6418
+ if (pieces.length === 0) throw new ImportCardError("the file holds no instructions this importer can read: a preset has a \"prompts\" list with texts in it");
6419
+ const title = text(root["name"]) || text(root["preset_name"]);
6420
+ return {
6421
+ name: title === "" ? name.replace(/\.json$/i, "") : title,
6422
+ pieces: pieces.slice(0, MAX_PIECES)
6423
+ };
6424
+ }
6425
+ //#endregion
6426
+ //#region src/host/import/preset-tools.ts
6427
+ const PRESET_TOOL = "import_preset";
6428
+ const PRESET_FILE = "preset.json";
6429
+ const PRESET_PATH = `${IMPORT_FOLDER}/${PRESET_FILE}`;
6430
+ /** The command that has the authoring chat apply a preset that was uploaded to the world. */
6431
+ const presetMessage = () => `Apply the narration preset I uploaded to this world: call ${PRESET_TOOL} with file ${PRESET_PATH}.`;
6432
+ /** The tool that turns an uploaded narration preset into the world's prose prompts; every call asks the person first. */
6433
+ function presetTools(worlds, settings, prompting) {
6434
+ return [defineTool({
6435
+ name: PRESET_TOOL,
6436
+ description: `Turn the narration preset the person uploaded to this world (${PRESET_PATH}) into the world's prose prompts: how the narration is written and how the characters speak and behave. Rules of the game, formats and scripts in the preset are not carried. It replaces the world's own versions of those prompts, so the person is asked first.`,
6437
+ parameters: { file: {
6438
+ type: "string",
6439
+ required: true,
6440
+ description: `The preset: ${PRESET_PATH}.`
6441
+ } },
6442
+ output: {
6443
+ schema: { type: "json" },
6444
+ render: (_args, value) => [{
6445
+ type: "text",
6446
+ text: JSON.stringify(value, null, 1)
6447
+ }]
6448
+ },
6449
+ isConcurrencySafe: () => false,
6450
+ async execute(args, exec) {
6451
+ if (args.file.trim() !== PRESET_PATH) throw new Error(`the preset is ${PRESET_PATH}`);
6452
+ const world = await worldOf(worlds, exec);
6453
+ const file = join(world.directory, IMPORT_FOLDER, PRESET_FILE);
6454
+ const preset = readPreset(await readFile(file).catch(() => {
6455
+ throw new Error("no preset was uploaded to this world");
6456
+ }), "preset");
6457
+ const language = prompting.languages().get(world.id);
6458
+ const text = (id, variables) => prompting.prompts().text(id, language, variables);
6459
+ const made = await extractStyleFrom(contextOf(exec, settings(), text), preset.name, preset.pieces);
6460
+ for (const { id, text: body } of made.prompts) for (const tag of shippedLanguages()) await writeWorldPrompt(world.directory, tag, id, withPlayer(body));
6461
+ await rm(file, { force: true });
6462
+ const written = made.prompts.map((entry) => entry.id);
6463
+ return JSON.parse(JSON.stringify({
6464
+ preset: preset.name,
6465
+ written,
6466
+ folder: `${PROMPTS_FOLDER}/<language>/`,
6467
+ notes: made.notes,
6468
+ next: written.length === 0 ? "Nothing in the preset was about how to write the story, so no prompt was changed: tell the person." : "Tell the person which prompts were written (they can read and edit them in the world's Prompts section) and what was not carried over."
6469
+ }));
6470
+ }
6471
+ })];
6472
+ }
6473
+ //#endregion
6043
6474
  //#region src/host/triggers/parts.ts
6044
6475
  /** What the files of a world say it has, for checking what a trigger names. @throws {InvalidEditProblems} when those files have problems of their own: they are fixed first. */
6045
6476
  async function loadWorldParts(directory) {
@@ -6109,6 +6540,109 @@ function triggerProblemsOf(parts, definitions) {
6109
6540
  return found;
6110
6541
  }
6111
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
6112
6646
  //#region src/host/worlds/world-editor.ts
6113
6647
  function stateOf(world, definition, names) {
6114
6648
  const { start } = definition;
@@ -6302,6 +6836,7 @@ async function readWorldEditor(world) {
6302
6836
  key: location.id,
6303
6837
  name: location.name,
6304
6838
  description: location.description,
6839
+ ...imageOf(world, "place", location.id, location.visualIdentity?.globalId),
6305
6840
  ...location.parent === void 0 ? {} : { parent: {
6306
6841
  key: location.parent,
6307
6842
  name: names.get(location.parent) ?? location.parent
@@ -6313,6 +6848,7 @@ async function readWorldEditor(world) {
6313
6848
  key: item.id,
6314
6849
  name: item.name,
6315
6850
  description: item.description,
6851
+ ...imageOf(world, "thing", item.id, item.visualIdentity?.globalId),
6316
6852
  quantity: item.quantity,
6317
6853
  unique: item.unique,
6318
6854
  quality: item.quality,
@@ -6433,7 +6969,7 @@ async function editWorldNarrationVoice(world, voice) {
6433
6969
  const relationKey = (...parts) => parts.map((part) => encodeURIComponent(part)).join(":");
6434
6970
  const relationParts = (key) => key.split(":").map((part) => decodeURIComponent(part));
6435
6971
  /** The folder of a character by its id: the id is the folder's name unless the file says another. */
6436
- async function folderOf(worldDirectory, key) {
6972
+ async function folderOf$1(worldDirectory, key) {
6437
6973
  const root = join(worldDirectory, CHARACTERS_DIR);
6438
6974
  for (const folder of await subfolders(root)) try {
6439
6975
  const parsed = parseCharacterFile(await readFile(join(root, folder, CHARACTER_FILE_NAME), "utf8"), folder);
@@ -6534,7 +7070,7 @@ async function replaceFile$1(file, text) {
6534
7070
  * @throws {InvalidEditProblems} when the character is not there, or the result would not be a valid character.
6535
7071
  */
6536
7072
  async function editWorldCharacter(world, key, edit) {
6537
- const folder = await folderOf(world.directory, key);
7073
+ const folder = await folderOf$1(world.directory, key);
6538
7074
  if (folder === void 0) throw new InvalidEditProblems([`there is no character "${key}"`]);
6539
7075
  const file = join(world.directory, CHARACTERS_DIR, folder, CHARACTER_FILE_NAME);
6540
7076
  const text = (await readFile(file, "utf8")).replace(/^/, "");
@@ -6735,7 +7271,7 @@ async function editWorldRelation(world, edit) {
6735
7271
  if (edit.kind === "character" || edit.kind === "knowledge") {
6736
7272
  const character = parts[1];
6737
7273
  if (character === void 0) throw new InvalidEditProblems(["the relation key is invalid"]);
6738
- 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}"`]);
6739
7275
  return await editEntityFile(world, CHARACTERS_DIR, CHARACTER_FILE_NAME, character, parseCharacterFile, (document) => {
6740
7276
  if (edit.kind === "character") {
6741
7277
  const target = parts[2];
@@ -6829,6 +7365,99 @@ async function characterOf(world, key) {
6829
7365
  if (character === void 0) throw new InvalidEditProblems([`there is no character "${key}"`]);
6830
7366
  return character;
6831
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
+ }
6832
7461
  /** Generate or replace the authored character's stable reference portrait. */
6833
7462
  async function generateWorldCharacterPortrait(world, key, service) {
6834
7463
  const character = await characterOf(world, key);
@@ -6885,6 +7514,22 @@ async function worldCharacterPortraitFile(world, key) {
6885
7514
  size: (await stat(file)).size
6886
7515
  };
6887
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
+ }
6888
7533
  //#endregion
6889
7534
  //#region src/host/authoring/documents.ts
6890
7535
  const AUTHORED_ENTITY_KINDS = [
@@ -7004,6 +7649,150 @@ async function deleteAuthoredEntity(world, kind, key) {
7004
7649
  return destination;
7005
7650
  }
7006
7651
  //#endregion
7007
- export { loadLocations as $, isReviewing as A, DICE_COMPARISONS as At, populateLocations as B, translateTools as C, parseCharacterEdit as Ct, authoringChatSessionId as D, parseRelationEdit as Dt, authoredWorldOf as E, parsePlaceEdit as Et, populateClock as F, routineProblems as G, populateRoutines as H, populateDice as I, loadDice as J, TRIGGERS_FILE_NAME as K, populateFactions as L, loadValidatedWorld as M, DICE_RESULTS as Mt, populateCalendar as N, languageOfDocuments as O, parseThingEdit as Ot, populateCharacters as P, parseCalendarFile as Q, populateItems as R, translateMessage as S, InvalidEditProblems as St, importTools as T, parseLoreEdit as Tt, populateTriggers as U, populateLore as V, populateVariables as W, CALENDAR_FILE_NAME as X, parseDiceFile as Y, loadCalendar as Z, replaceFile$1 as _, ImportStore as _t, replaceAuthoredEntity as a, deleteWorldPrompt as at, triggerProblemsOf as b, parseWorldFile as bt, editWorldLore as c, writeWorldPrompt as ct, editWorldPlots as d, parseVariablesFile as dt, loadItems as et, editWorldRelation as f, variableProblems as ft, readWorldEditor as g, ImportNotFoundError as gt, generateWorldCharacterPortrait as h, IMPORT_FOLDER as ht, readAuthoredEntityDocument as i, PROSE_PROMPTS as it, markReady as j, DICE_READINGS as jt, readWorldDocuments as k, IMPORT_COMMAND as kt, editWorldNarrationVoice as l, VARIABLES_FILE_NAME as lt, entityFolder as m, parseCharacterFile as mt, createAuthoredEntity as n, loadCharacters as nt, editWorldCharacter as o, listWorldPrompts as ot, editWorldThing as p, CHARACTER_FILE_NAME as pt, DICE_FILE_NAME as q, deleteAuthoredEntity as r, subfolders as rt, editWorldFaction as s, readWorldPrompt as st, AUTHORED_ENTITY_KINDS as t, CHARACTERS_DIR as tt, editWorldPlace as u, loadVariables as ut, uploadWorldCharacterPortrait as v, parseChoices as vt, importHooks as w, parseFactionEdit as wt, loadWorldParts as x, parseWorldInfoEdit as xt, worldCharacterPortraitFile as y, WORLD_FILE_NAME as yt, populateKnowledge as z };
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 };
7008
7797
 
7009
- //# sourceMappingURL=documents-B5XAdfo2.js.map
7798
+ //# sourceMappingURL=pack-jail-CybSNzxr.js.map