@dsh-agentic-roleplay/core 0.3.6 → 0.4.0

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 (47) hide show
  1. package/lib/{tools-Dy1fgP6B.js → authoring-tools-C_8ClUkP.js} +129 -25
  2. package/lib/authoring.js +7 -5
  3. package/lib/{child-CFjnaTZt.js → child-DsixtqTw.js} +94 -2
  4. package/lib/client.js +3714 -2264
  5. package/lib/client.js.map +1 -1
  6. package/lib/compaction.js +1 -1
  7. package/lib/doctor.js +2 -4
  8. package/lib/{gallery-DIEgETzU.js → gallery-CDYKJf_O.js} +2 -2
  9. package/lib/{generator-DJ48HxPI.js → generator-BR1ugzln.js} +2 -2
  10. package/lib/{deliver-BBgciEEK.js → hooks-B2EhBS_-.js} +1884 -236
  11. package/lib/images.js +4 -4
  12. package/lib/index.js +846 -254
  13. package/lib/{library-9JB9zw5a.js → library-COIktKBa.js} +4 -3
  14. package/lib/{lorebook-author-tools-Bj31z1cu.js → lorebook-author-tools-C-o0t4dL.js} +118 -43
  15. package/lib/lorebook-authoring.js +5 -3
  16. package/lib/{settings-CA6icLL_.js → narration-BT9uvQry.js} +145 -2
  17. package/lib/orchestration.js +34 -21
  18. package/lib/{pack-jail-2XztyYAX.js → pack-jail-soI-In96.js} +170 -13
  19. package/lib/{packs-xHRCcGdb.js → packs-CJPSe5LI.js} +7 -4
  20. package/lib/{presenter-agent-DnNEG_Mn.js → presenter-agent-Gu34bZwd.js} +6 -6
  21. package/lib/preset-3zn8xme7.js +242 -0
  22. package/lib/{preset-author-tools-BxycmoAr.js → preset-author-tools-C-X8G40s.js} +7 -7
  23. package/lib/preset-authoring.js +6 -3
  24. package/lib/{presets-gkBWAiVb.js → presets-C3mhqqfz.js} +9 -26
  25. package/lib/{reflection-q0UpwXlx.js → reflection-Btsj0ZLh.js} +51 -17
  26. package/package.json +2 -2
  27. package/packs/scene/map.html +1 -0
  28. package/packs/scene/strip.html +1 -0
  29. package/prompts/en/import/lorebook.md +2 -1
  30. package/prompts/en/import/style.md +1 -0
  31. package/prompts/en/lorebook/procedure.md +1 -1
  32. package/prompts/en/preset/procedure.md +1 -1
  33. package/prompts/en/roleplay/character-lookup.md +1 -0
  34. package/prompts/en/roleplay/game-master.md +1 -1
  35. package/prompts/en/world/procedure.md +1 -1
  36. package/prompts/zh/import/lorebook.md +2 -1
  37. package/prompts/zh/import/style.md +1 -0
  38. package/prompts/zh/lorebook/procedure.md +1 -1
  39. package/prompts/zh/preset/procedure.md +1 -1
  40. package/prompts/zh/roleplay/character-lookup.md +1 -0
  41. package/prompts/zh/roleplay/game-master.md +1 -1
  42. package/prompts/zh/world/procedure.md +1 -1
  43. package/lib/hooks-DkwFGtNH.js +0 -1060
  44. package/lib/language-BgyxtB2h.js +0 -38
  45. package/lib/load-CVwJjIJ5.js +0 -486
  46. package/lib/narration-DK2kiIjE.js +0 -141
  47. package/lib/preset-D0FMSeZ9.js +0 -59
package/lib/index.js CHANGED
@@ -1,21 +1,19 @@
1
1
  import { n as chatSessionId, r as roleplaySessionOf } from "./access-EbNdZFbk.js";
2
- import { A as parseDiceFile, At as parseFactionEdit, B as CHARACTERS_DIR, Bt as LORE_KINDS, C as populateTriggers, Dt as subfolders, E as TRIGGERS_FILE_NAME, F as loadLocations, Ft as IMPORT_COMMAND, Ht as DICE_COMPARISONS, It as ImportCardError, J as parseVariablesFile, K as VARIABLES_FILE_NAME, L as loadItems, Lt as isPng, M as loadCalendar, Mt as parsePlaceEdit, N as parseCalendarFile, Nt as parseRelationEdit, O as DICE_FILE_NAME, Ot as InvalidEditProblems, Pt as parseThingEdit, Rt as pictureOf, S as populateRoutines, St as writeLorebookEntry, T as routineProblems, Ut as DICE_READINGS, V as loadCharacters, Vt as LORE_SCOPES, Wt as DICE_RESULTS, Y as variableProblems, _ as populateFactions, _t as loadLorebook, at as ImportNotFoundError, b as populateLocations, bt as reserveLorebook, c as markReady, ct as WORLD_FILE_NAME, d as loadValidatedWorld, dt as createLorebook, f as knowsCharacter, ft as deleteLorebook, g as populateDice, gt as listLorebooks, h as populateClock, ht as isLorebookName, it as IMPORT_FOLDER, j as CALENDAR_FILE_NAME, jt as parseLoreEdit, k as loadDice, kt as parseCharacterEdit, l as guardedLookup, lt as parseWorldFile, m as populateCharacters, mt as entriesOf, nt as CHARACTER_FILE_NAME, o as authoringChatSessionId, ot as ImportStore, p as populateCalendar, pt as deleteLorebookEntry, q as loadVariables, rt as parseCharacterFile, st as parseChoices, u as vetUrl, ut as parseWorldInfoEdit, v as populateItems, vt as lorebookDirectory, w as populateVariables, x as populateLore, xt as updateLorebookInfo, y as populateKnowledge, zt as readCard } from "./tools-Dy1fgP6B.js";
3
- import { _ as readWorldPrompt, a as isPresetName, c as presetDirectory, d as savePresetFromWorld, g as listWorldPrompts, h as deleteWorldPrompt, i as deletePreset, o as listPresets, p as updatePresetInfo, r as createPresetFromShipped, s as loadPreset, t as PRESET_FILE, u as reservePreset, v as writeWorldPrompt } from "./presets-gkBWAiVb.js";
4
- import { c as copyPreset, d as switchPreset, f as readTimeline, i as reflectionStatus, l as presetStatus, m as defaultBoundaries, o as TimelineError, p as pathTo, u as recordPreset } from "./reflection-q0UpwXlx.js";
5
- import { a as WORLD_RULES_KEY, c as VARIABLE_SUBJECTS, i as parseSwitchboard, l as VARIABLE_VISIBILITIES, n as SETTINGS_SPEC, r as parseSettings, s as VARIABLE_KINDS, t as DEFAULT_SETTINGS } from "./settings-CA6icLL_.js";
6
- import { C as ReflectionRefusedError, E as WorldNotFoundError, S as InvalidWorldError, T as SessionNotFoundError, a as readDocument$1, b as AgentUnavailableError, c as errorMessage, d as PromptLibrary, f as copyWorldPrompts, i as plotReferenceProblems, m as languageOf, r as parsePlotsFile, s as formatIssue, w as SessionArchivedError, x as InvalidStartError } from "./load-CVwJjIJ5.js";
7
- import { A as observeAsPlayer, D as notesOfSession, T as addToNote, b as populatePlots, c as readRunDetail, d as externalTools, h as PLOTS_METADATA_KEY, i as readUsage, k as readNotes, n as readWithdrawn, s as readActivity, y as plotProgressOf, z as zoneOf } from "./deliver-BBgciEEK.js";
8
- import { a as liveSettings, c as writeSettings, i as InvalidSettingsError, n as encodeOutput, o as readSettings, s as useChildReasoning } from "./narration-DK2kiIjE.js";
9
- import { r as childSamplingOf } from "./child-CFjnaTZt.js";
10
- import { a as inheritImages, b as slug, c as referenceImagePath, l as sceneImagePath, t as addToLibrary, x as uniqueKey } from "./library-9JB9zw5a.js";
11
- import { A as worldEntityImageFile, C as readWorldEditor, D as uploadWorldCharacterPortrait, E as replaceFile$1, F as loadWorldParts, H as readWorldDocuments, I as PRESET_FILE$1, L as presetMessage, O as uploadWorldEntityImage, S as generateWorldEntityImage, T as removeWorldTrigger, V as languageOfDocuments, _ as editWorldPlots$1, a as deleteWorldPackFile, b as entityFolder, c as createAuthoredEntity, f as editWorldCharacter$1, g as editWorldPlace$1, h as editWorldNarrationVoice, j as writeWorldTrigger, k as worldCharacterPortraitFile, l as deleteAuthoredEntity, m as editWorldLore$1, n as packFileProblem, p as editWorldFaction$1, t as MAX_PACK_TEXT, u as readAuthoredEntityDocument, v as editWorldRelation$1, w as readWorldTrigger, x as generateWorldCharacterPortrait, y as editWorldThing$1, z as translateMessage } from "./pack-jail-2XztyYAX.js";
12
- import { t as readPreset } from "./preset-D0FMSeZ9.js";
13
- import { a as presetChatSessionId, n as narrationImportMessage } from "./preset-author-tools-BxycmoAr.js";
14
- import { a as lorebookImportMessage, c as lorebookChatSessionId, s as readLorebook, t as LOREBOOK_UPLOAD } from "./lorebook-author-tools-Bj31z1cu.js";
2
+ import { B as loadItems, Bt as ImportCardError, C as populateLocations, D as populateVariables, E as populateTriggers, Et as writeLorebookEntry, F as loadCalendar, Ft as parseLoreEdit, Gt as LORE_SCOPES, Ht as pictureOf, I as parseCalendarFile, It as parsePlaceEdit, J as withPlayer, Jt as DICE_RESULTS, Kt as DICE_COMPARISONS, Lt as parseRelationEdit, M as loadDice, Mt as InvalidEditProblems, N as parseDiceFile, Nt as parseCharacterEdit, O as routineProblems, P as CALENDAR_FILE_NAME, Pt as parseFactionEdit, Q as variableProblems, R as loadLocations, Rt as parseThingEdit, S as populateKnowledge, St as lorebookDirectory, T as populateRoutines, Tt as updateLorebookInfo, U as CHARACTERS_DIR, Ut as readCard, Vt as isPng, W as loadCharacters, Wt as LORE_KINDS, X as loadVariables, Y as VARIABLES_FILE_NAME, Z as parseVariablesFile, _ as populateCharacters, _t as deleteLorebookEntry, at as CHARACTER_FILE_NAME, b as populateFactions, bt as listLorebooks, ct as ImportNotFoundError, d as markReady, dt as WORLD_FILE_NAME, f as guardedLookup, ft as parseWorldFile, g as populateCalendar, gt as deleteLorebook, h as knowsCharacter, ht as createLorebook, j as DICE_FILE_NAME, jt as subfolders, k as TRIGGERS_FILE_NAME, l as authoringChatSessionId, lt as ImportStore, m as loadValidatedWorld, mt as addLorebookEntries, ot as parseCharacterFile, p as vetUrl, pt as parseWorldInfoEdit, q as partsOf, qt as DICE_READINGS, st as IMPORT_FOLDER, t as AuthoringTools, ut as parseChoices, v as populateClock, vt as entriesOf, w as populateLore, wt as reserveLorebook, x as populateItems, xt as loadLorebook, y as populateDice, yt as isLorebookName, zt as IMPORT_COMMAND } from "./authoring-tools-C_8ClUkP.js";
3
+ import { _ as readWorldPrompt, a as isPresetName, c as presetDirectory, d as savePresetFromWorld, g as listWorldPrompts, h as deleteWorldPrompt, i as deletePreset, o as listPresets, p as updatePresetInfo, r as createPresetFromShipped, s as loadPreset, t as PRESET_FILE, u as reservePreset, v as writeWorldPrompt } from "./presets-C3mhqqfz.js";
4
+ import { c as copyPreset, d as switchPreset, f as readTimeline, i as reflectionStatus, l as presetStatus, m as defaultBoundaries, o as TimelineError, p as pathTo, u as recordPreset } from "./reflection-Btsj0ZLh.js";
5
+ import { _ as VARIABLE_VISIBILITIES, a as liveSettings, c as writeSettings, d as parseSettings, g as VARIABLE_SUBJECTS, h as VARIABLE_KINDS, i as InvalidSettingsError, l as DEFAULT_SETTINGS, n as encodeOutput, o as readSettings, p as WORLD_RULES_KEY, s as useChildReasoning, u as SETTINGS_SPEC } from "./narration-BT9uvQry.js";
6
+ import { A as populatePlots, B as readDocument, H as formatIssue, K as PromptLibrary, O as PLOTS_METADATA_KEY, Q as shippedLanguages, R as parsePlotsFile, T as zoneOf, U as errorMessage, Y as languageOf, _ as readWithdrawn, at as SessionNotFoundError, b as readNotes, et as AgentUnavailableError, f as readUsage, i as externalTools, it as SessionArchivedError, k as plotProgressOf, m as readRunDetail, nt as InvalidWorldError, ot as WorldNotFoundError, p as readActivity, q as copyWorldPrompts, rt as ReflectionRefusedError, tt as InvalidStartError, v as addToNote, x as observeAsPlayer, y as notesOfSession, z as plotReferenceProblems } from "./hooks-B2EhBS_-.js";
7
+ import { c as sharedSamplingOf, h as trimCharacters, r as childSamplingOf, s as parseSampling } from "./child-DsixtqTw.js";
8
+ import { a as inheritImages, b as slug, c as referenceImagePath, l as sceneImagePath, t as addToLibrary, x as uniqueKey } from "./library-COIktKBa.js";
9
+ import { A as worldEntityImageFile, B as readWorldInfo, C as readWorldEditor, D as uploadWorldCharacterPortrait, E as replaceFile, F as loadWorldParts, I as PRESET_FILE$1, L as presetMessage, O as uploadWorldEntityImage, S as generateWorldEntityImage, T as removeWorldTrigger, U as languageOfDocuments, V as translateMessage, W as readWorldDocuments, _ as editWorldPlots$1, a as deleteWorldPackFile, b as entityFolder, c as createAuthoredEntity, f as editWorldCharacter$1, g as editWorldPlace$1, h as editWorldNarrationVoice, j as writeWorldTrigger, k as worldCharacterPortraitFile, l as deleteAuthoredEntity, m as editWorldLore$1, n as packFileProblem, p as editWorldFaction$1, t as MAX_PACK_TEXT, u as readAuthoredEntityDocument, v as editWorldRelation$1, w as readWorldTrigger, x as generateWorldCharacterPortrait, y as editWorldThing$1, z as editWorldInfo } from "./pack-jail-soI-In96.js";
10
+ import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-3zn8xme7.js";
11
+ import { a as lorebookImportMessage, d as selectEntries, l as previewLorebook, s as lorebookChatSessionId, t as LOREBOOK_UPLOAD, u as readLorebook } from "./lorebook-author-tools-C-o0t4dL.js";
12
+ import { a as presetChatSessionId, n as narrationImportMessage } from "./preset-author-tools-C-X8G40s.js";
15
13
  import { t as doctorChatSessionId } from "./doctor-chat-ByDfCMeo.js";
16
- import { _ as API_PREFIX, a as packIds, c as describePack, d as packPath, f as readPack, l as isPackId, m as PACK_LIMITS, n as anyTab, o as syncWorldPacks, r as copyWorldPacks, s as worldPackStates, t as activePack, u as packFile } from "./packs-xHRCcGdb.js";
17
- import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-DJ48HxPI.js";
18
- import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-DIEgETzU.js";
14
+ import { _ as API_PREFIX, a as packIds, c as describePack, d as packPath, f as readPack, l as isPackId, m as PACK_LIMITS, n as anyTab, o as syncWorldPacks, r as copyWorldPacks, s as worldPackStates, t as activePack, u as packFile } from "./packs-CJPSe5LI.js";
15
+ import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-BR1ugzln.js";
16
+ import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-CDYKJf_O.js";
19
17
  import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
20
18
  import { cpSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
21
19
  import { createHash, randomBytes, randomUUID } from "node:crypto";
@@ -420,7 +418,10 @@ async function createWorld(catalog, input) {
420
418
  const FOLDER_CHARS = /[^\p{L}\p{N}._ -]+/gu;
421
419
  /** A name that can be the folder of a world: letters, digits and a few marks, trimmed, not ending in a dot or space. */
422
420
  function folderNameOf(name) {
423
- const folder = name.normalize("NFKC").replace(FOLDER_CHARS, " ").replace(/\s+/g, " ").trim().replace(/^[^\p{L}\p{N}]+/u, "").replace(/[. ]+$/, "").slice(0, 90).trim();
421
+ const characters = [...name.normalize("NFKC").replace(FOLDER_CHARS, " ").replace(/\s+/g, " ").trim()];
422
+ const first = characters.findIndex((character) => /[\p{L}\p{N}]/u.test(character));
423
+ const cleaned = first < 0 ? "" : characters.slice(first).join("");
424
+ const folder = trimCharacters(cleaned, ". ", "end").slice(0, 90).trim();
424
425
  return folder === "" ? "imported world" : folder;
425
426
  }
426
427
  /** The command that starts the import, for a card kept in the world's import folder. */
@@ -496,6 +497,23 @@ async function startTranslation(deps, id, to, title, language) {
496
497
  }
497
498
  }
498
499
  //#endregion
500
+ //#region src/host/presets/verbatim.ts
501
+ /**
502
+ * The chosen prompts of a SillyTavern preset as they are, with no model between: their texts, in the order the preset sends them, become one writing guidance (the narration style).
503
+ * The preset's own macros are played and its names for the characters are replaced as for any import; only what a prompt file cannot hold is changed, so that `${` and `{{` in the text
504
+ * are not read as variables.
505
+ * @throws {ImportCardError} when the file is not a preset or holds nothing to read.
506
+ */
507
+ function verbatimStyle(file, fileName) {
508
+ const preset = readPreset(file, fileName);
509
+ const text = preset.pieces.join("\n\n").replace(/\$\{/g, "$ {").replace(/\{\{/g, "{ {");
510
+ return {
511
+ name: preset.name,
512
+ sampling: preset.sampling,
513
+ text
514
+ };
515
+ }
516
+ //#endregion
499
517
  //#region src/host/import/upload-preset.ts
500
518
  /**
501
519
  * Keeps an uploaded narration preset in the world's import folder and has the world's authoring chat apply it, which asks the person before it changes a prompt.
@@ -521,6 +539,99 @@ async function uploadPreset(deps, worldId, file, name, language) {
521
539
  ...failure === void 0 ? {} : { failure }
522
540
  };
523
541
  }
542
+ const STYLE = "roleplay/style";
543
+ /**
544
+ * Puts the chosen prompts of a preset into a world as its narration style, word for word, with no assistant and no question asked: the person chose it in the dialog.
545
+ * A style the world already carries is moved to the world's trash first, in each language, so nothing is lost; the preset's sampling is written to the world when the file has any.
546
+ * @throws {ImportCardError} when the file is not a preset. @throws {WorldNotFoundError} when the world does not exist.
547
+ */
548
+ async function applyPresetVerbatim(deps, worldId, file, name) {
549
+ const world = await deps.worlds.find(worldId);
550
+ if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
551
+ const made = verbatimStyle(file, name);
552
+ let replaced = false;
553
+ for (const language of shippedLanguages()) {
554
+ if (readWorldPrompt(world.directory, language, STYLE).carried) {
555
+ await deleteWorldPrompt(world.directory, language, STYLE);
556
+ replaced = true;
557
+ }
558
+ await writeWorldPrompt(world.directory, language, STYLE, made.text);
559
+ }
560
+ if (Object.keys(made.sampling).length > 0) {
561
+ await editWorldInfo(world.directory, { sampling: made.sampling });
562
+ await deps.worlds.list({ refresh: true });
563
+ }
564
+ return {
565
+ preset: made.name,
566
+ replaced
567
+ };
568
+ }
569
+ //#endregion
570
+ //#region src/host/import/staging.ts
571
+ const KEEP_MS = 36e5;
572
+ const MAX_STAGED = 12;
573
+ /**
574
+ * Files waiting for the person to choose what of them is imported: a preset's prompts, a lorebook's entries. They are kept in memory for an hour, not on disk:
575
+ * nothing is made of a file until the choice is made, and a restart only asks the person to upload it again.
576
+ */
577
+ var ImportStaging = class {
578
+ staged = /* @__PURE__ */ new Map();
579
+ /** @throws {ImportCardError} when the file is not of the kind. */
580
+ stage(kind, file, name) {
581
+ const preview = kind === "preset" ? previewPreset(file, name) : {
582
+ ...previewLorebook(file, name),
583
+ sampling: void 0
584
+ };
585
+ this.forget();
586
+ const id = randomUUID();
587
+ this.staged.set(id, {
588
+ kind,
589
+ file,
590
+ name,
591
+ at: Date.now()
592
+ });
593
+ while (this.staged.size > MAX_STAGED) this.staged.delete(this.staged.keys().next().value);
594
+ const ignored = "ignored" in preview ? preview.ignored : {};
595
+ return {
596
+ id,
597
+ kind,
598
+ name: preview.name,
599
+ items: preview.items,
600
+ ...Object.keys(ignored).length === 0 ? {} : { ignored },
601
+ ...preview.sampling === void 0 || Object.keys(preview.sampling).length === 0 ? {} : { sampling: preview.sampling }
602
+ };
603
+ }
604
+ /** The staged file with only what the choice names, and the name it was staged under; the staged file stays until it is discarded. @throws {ImportNotFoundError} when there is none. @throws {ImportCardError} when the choice cannot be used. */
605
+ choose(kind, choice) {
606
+ this.forget();
607
+ const found = this.staged.get(choice.id);
608
+ if (found === void 0 || found.kind !== kind) throw new ImportNotFoundError("the file is no longer waiting: upload it again");
609
+ return {
610
+ file: kind === "preset" ? selectPrompts(found.file, choice.enabled, choice.sampling) : selectEntries(found.file, choice.enabled, found.name),
611
+ name: found.name
612
+ };
613
+ }
614
+ discard(id) {
615
+ this.staged.delete(id);
616
+ }
617
+ forget() {
618
+ const limit = Date.now() - KEEP_MS;
619
+ for (const [id, entry] of this.staged) if (entry.at < limit) this.staged.delete(id);
620
+ }
621
+ };
622
+ /** Reads the choice of a request body. @throws {ImportCardError} through the caller's validation when it is not one. */
623
+ function parseSelectionChoice(body) {
624
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return "the choice must be an object";
625
+ const { id, enabled, sampling } = body;
626
+ if (typeof id !== "string" || id === "") return "\"id\" must name the staged file";
627
+ if (!Array.isArray(enabled) || !enabled.every((entry) => typeof entry === "string")) return "\"enabled\" must be a list of text";
628
+ if (sampling !== void 0 && typeof sampling !== "boolean") return "\"sampling\" must be true or false";
629
+ return {
630
+ id,
631
+ enabled,
632
+ sampling: sampling !== false
633
+ };
634
+ }
524
635
  //#endregion
525
636
  //#region src/host/agent/authoring-sessions.ts
526
637
  const AUTHORING_PROJECT_TITLE = "World Authoring";
@@ -680,7 +791,146 @@ var LorebookAuthoringSessions = class {
680
791
  }
681
792
  };
682
793
  //#endregion
794
+ //#region src/host/lorebooks/apply.ts
795
+ /** Which lorebooks a story was started with: kept in the story's own metadata, because the library may change afterwards. */
796
+ const LOREBOOKS_KEY = "roleplay.lorebooks";
797
+ /** The id an entry has in a story, so that books and the world's own lore never clash. */
798
+ const bookEntryId = (book, id) => `${book}:${id}`;
799
+ /**
800
+ * The entries of the named books as a story takes them. A book that cannot be used is refused when the person chose it and told about when only the world suggested it,
801
+ * because the world may come from someone whose library differs. Characters an entry names that this story does not have are left out, and it is told.
802
+ * @throws {Error} when a chosen book cannot be used.
803
+ */
804
+ async function lorebookLore(root, names, chosen, knows, taken) {
805
+ const result = {
806
+ definitions: [],
807
+ applied: [],
808
+ notes: []
809
+ };
810
+ const used = new Set(taken);
811
+ for (const name of [...new Set(names)]) {
812
+ let book;
813
+ try {
814
+ book = await loadLorebook(root, name);
815
+ if (book.summary.problems.length > 0) throw new Error(`it has problems: ${book.summary.problems.join("; ")}`);
816
+ } catch (error) {
817
+ const reason = error instanceof Error ? error.message : String(error);
818
+ if (chosen) throw new Error(`the lorebook "${name}" cannot be used: ${reason}`);
819
+ result.notes.push(`The world suggests the lorebook "${name}", which cannot be used here (${reason}), so the story starts without it.`);
820
+ continue;
821
+ }
822
+ for (const entry of book.entries) {
823
+ const id = bookEntryId(name, entry.id);
824
+ if (used.has(id)) throw new Error(`the lorebook "${name}" has the entry "${entry.id}", whose id the story already has`);
825
+ used.add(id);
826
+ const knownBy = entry.scope === "listed" ? entry.knownBy.filter(knows) : [];
827
+ for (const reference of entry.scope === "listed" ? entry.knownBy : []) if (!knownBy.includes(reference)) result.notes.push(`The lorebook "${name}" says "${entry.title}" is known to "${reference}", who is not in this story.`);
828
+ result.definitions.push({
829
+ ...entry,
830
+ id,
831
+ knownBy,
832
+ related: entry.related.map((other) => bookEntryId(name, other))
833
+ });
834
+ }
835
+ result.applied.push({
836
+ name,
837
+ entries: book.entries.length
838
+ });
839
+ }
840
+ return result;
841
+ }
842
+ //#endregion
843
+ //#region src/host/lorebooks/story.ts
844
+ /** The lorebooks a story holds now. */
845
+ function lorebooksOf(session) {
846
+ return session.metadata.getValue("roleplay.lorebooks") ?? [];
847
+ }
848
+ const keyOf$3 = (entry) => entry.sourceId ?? String(entry.id);
849
+ /**
850
+ * Copies a library lorebook into a story that is already being played. The characters that know an entry learn it at the story's current turn.
851
+ * @throws {Error} when the story already has the book or the book cannot be used.
852
+ */
853
+ async function addLorebook(root, session, name) {
854
+ const held = lorebooksOf(session);
855
+ if (held.some((book) => book.name === name)) throw new Error(`the story already has the lorebook "${name}"`);
856
+ const taken = new Set(session.lore.list().flatMap((entry) => entry.sourceId === void 0 ? [] : [entry.sourceId]));
857
+ const knows = (reference) => session.characters.getBySourceId(reference) !== void 0 || session.characters.findByName(reference).length > 0;
858
+ const book = await lorebookLore(root, [name], true, knows, taken);
859
+ const applied = book.applied[0];
860
+ session.transaction(() => {
861
+ populateLore(session, book.definitions, session.metadata.get().turns);
862
+ session.metadata.setValue(LOREBOOKS_KEY, [...held, applied]);
863
+ });
864
+ return {
865
+ applied,
866
+ notes: book.notes
867
+ };
868
+ }
869
+ /**
870
+ * Takes a lorebook's entries out of a story, together with what the characters learned from them. Entries the book gave are found by their id prefix.
871
+ * @throws {Error} when the story does not have the book, or other lore or a plot still refers to one of its entries.
872
+ */
873
+ function removeLorebook(session, name) {
874
+ const held = lorebooksOf(session);
875
+ if (!held.some((book) => book.name === name)) throw new Error(`the story does not have the lorebook "${name}"`);
876
+ const all = session.lore.list();
877
+ const leaving = all.filter((entry) => entry.sourceId?.startsWith(bookEntryId(name, "")) === true);
878
+ const ids = new Set(leaving.map((entry) => entry.id));
879
+ const citing = all.filter((entry) => !ids.has(entry.id) && (entry.related.some((id) => ids.has(id)) || entry.subjects.some((subject) => subject.kind === "lore" && ids.has(subject.id)))).map((entry) => entry.title);
880
+ if (citing.length > 0) throw new Error(`other lore refers to entries of this lorebook: ${citing.join(", ")}`);
881
+ const remaining = all.filter((entry) => !ids.has(entry.id)).map(keyOf$3);
882
+ const plots = plotReferenceProblems(plotProgressOf(session.metadata).map((progress) => progress.plot), [
883
+ ...session.characters.list().map(keyOf$3),
884
+ ...session.factions.list().map(keyOf$3),
885
+ ...session.locations.list().map(keyOf$3),
886
+ ...session.items.list().map(keyOf$3),
887
+ ...remaining
888
+ ]);
889
+ if (plots.length > 0) throw new Error(`a plot refers to entries of this lorebook: ${plots.join("; ")}`);
890
+ session.transaction(() => {
891
+ for (const entry of leaving) {
892
+ for (const character of session.characters.list()) session.knowledge.forget(character.id, "lore", entry.id);
893
+ session.lore.remove(entry.id);
894
+ }
895
+ session.metadata.setValue(LOREBOOKS_KEY, held.filter((book) => book.name !== name));
896
+ });
897
+ return leaving.length;
898
+ }
899
+ //#endregion
900
+ //#region src/host/lorebooks/verbatim.ts
901
+ const MAX_TITLE$1 = 100;
902
+ /**
903
+ * The entries of a SillyTavern lorebook as they are, with no model between: each keeps its text word for word (an entry longer than a lore entry may be is cut at a paragraph, in order),
904
+ * its keywords go into the summary, because here an entry is found by search, and none is given a kind or a place to be known beyond who may know it.
905
+ * @throws {ImportCardError} when the file is not a lorebook or holds no entries that are switched on.
906
+ */
907
+ function verbatimEntries(file, fileName, knownBy) {
908
+ const book = readLorebook(file, fileName);
909
+ const taken = /* @__PURE__ */ new Set();
910
+ const entries = [];
911
+ for (const source of book.entries) {
912
+ const title = (source.title || source.text.split("\n")[0].trim() || `Entry ${source.ref + 1}`).slice(0, MAX_TITLE$1);
913
+ const parts = partsOf(withPlayer(source.text));
914
+ for (const [index, body] of parts.entries()) entries.push({
915
+ id: uniqueKey(slug(title, "entry"), taken),
916
+ title: parts.length === 1 ? title : `${title.slice(0, 94)} (${index + 1})`,
917
+ kind: "other",
918
+ scope: knownBy === "everyone" ? "everyone" : "listed",
919
+ knownBy: [],
920
+ summary: index === 0 && source.keys.length > 0 ? `Also: ${source.keys.join(", ")}.` : "",
921
+ body,
922
+ related: []
923
+ });
924
+ }
925
+ return {
926
+ name: book.name,
927
+ entries
928
+ };
929
+ }
930
+ //#endregion
683
931
  //#region src/host/lorebooks/service.ts
932
+ /** The story's lore cannot change right now. */
933
+ var LorebookBusyError = class extends Error {};
684
934
  /** The lorebook library. Refusals are plain `Error`s with the reason. */
685
935
  var Lorebooks = class {
686
936
  deps;
@@ -715,6 +965,32 @@ var Lorebooks = class {
715
965
  async remove(name) {
716
966
  await deleteLorebook(this.deps.root(), name);
717
967
  }
968
+ /** The lorebooks a story holds, and the library to choose from. */
969
+ async status(id) {
970
+ return {
971
+ applied: lorebooksOf(this.deps.session(id)),
972
+ available: await this.list()
973
+ };
974
+ }
975
+ /** Copies a library lorebook into a story that is being played; the notes tell what could not be carried over. */
976
+ async addToStory(id, name) {
977
+ const session = this.deps.session(id);
978
+ this.assertIdle(id);
979
+ const { applied, notes } = await addLorebook(this.deps.root(), session, name);
980
+ return {
981
+ entries: applied.entries,
982
+ notes
983
+ };
984
+ }
985
+ /** Takes a lorebook out of a story that is being played. */
986
+ removeFromStory(id, name) {
987
+ const session = this.deps.session(id);
988
+ this.assertIdle(id);
989
+ return { removed: removeLorebook(session, name) };
990
+ }
991
+ assertIdle(id) {
992
+ if (this.deps.playing(id)) throw new LorebookBusyError("a turn is being played; change the lorebooks when it is over");
993
+ }
718
994
  /** Opens the authoring chat of a lorebook. */
719
995
  async author(name, language) {
720
996
  const loaded = await loadLorebook(this.deps.root(), name);
@@ -722,11 +998,15 @@ var Lorebooks = class {
722
998
  }
723
999
  /** Like `importFile`, under a name made from the title that is not yet taken. */
724
1000
  async importTitled(title, file, language) {
725
- const base = title.normalize("NFKD").replace(/[^A-Za-z0-9_-]+/g, "-").replace(/^[-_]+|[-_]+$/g, "").slice(0, 56) || "lorebook";
1001
+ return await this.importFile(await this.freeName(title), file, language, title.trim() === "" ? void 0 : title.trim().slice(0, 300));
1002
+ }
1003
+ /** A library name made from a title that no lorebook has yet. */
1004
+ async freeName(title) {
1005
+ const base = trimCharacters(title.normalize("NFKD").replace(/[^A-Za-z0-9_-]+/g, "-"), "-_").slice(0, 56) || "lorebook";
726
1006
  const taken = new Set((await listLorebooks(this.deps.root())).map((book) => book.summary.name));
727
1007
  let name = base;
728
1008
  for (let index = 2; taken.has(name); index += 1) name = `${base}-${index}`;
729
- return await this.importFile(name, file, language, title.trim() === "" ? void 0 : title.trim().slice(0, 300));
1009
+ return name;
730
1010
  }
731
1011
  /** Keeps an uploaded SillyTavern lorebook in a new library lorebook and has its authoring chat turn it into entries. @throws {ImportCardError} when the file is not a lorebook. */
732
1012
  async importFile(name, file, language, title) {
@@ -758,6 +1038,40 @@ var Lorebooks = class {
758
1038
  ...failure === void 0 ? {} : { failure }
759
1039
  };
760
1040
  }
1041
+ /** Imports a staged lorebook with only the entries the person chose; a name is the library name they gave it, else one is made from the title. @throws {ImportNotFoundError} when the file is no longer staged. */
1042
+ async importStaged(request) {
1043
+ const { file, name: fileName } = this.deps.staging.choose("lorebook", request);
1044
+ const opened = request.name === void 0 ? await this.importTitled(request.title ?? readLorebook(file, fileName).name, file, request.language) : await this.importFile(request.name, file, request.language, request.title);
1045
+ this.deps.staging.discard(request.id);
1046
+ return opened;
1047
+ }
1048
+ /**
1049
+ * Imports the chosen entries of a staged lorebook as they are, with no assistant: a new library lorebook is made and filled at once, and nothing else happens.
1050
+ * @throws {ImportNotFoundError} when the file is no longer staged. @throws {ImportCardError} when the choice cannot be used.
1051
+ */
1052
+ async importVerbatim(request) {
1053
+ const { file, name: fileName } = this.deps.staging.choose("lorebook", request);
1054
+ const made = verbatimEntries(file, fileName, request.knownBy);
1055
+ const title = request.title ?? made.name;
1056
+ const name = request.name ?? await this.freeName(title);
1057
+ if (!isLorebookName(name)) throw new Error(`"${name}" is not a usable lorebook name (letters, digits, "-" and "_", up to 64)`);
1058
+ const root = this.deps.root();
1059
+ await reserveLorebook(root, name, title);
1060
+ try {
1061
+ await addLorebookEntries(root, name, made.entries);
1062
+ } catch (error) {
1063
+ await rm(lorebookDirectory(root, name), {
1064
+ recursive: true,
1065
+ force: true
1066
+ });
1067
+ throw error;
1068
+ }
1069
+ this.deps.staging.discard(request.id);
1070
+ return {
1071
+ name,
1072
+ entries: made.entries.length
1073
+ };
1074
+ }
761
1075
  };
762
1076
  //#endregion
763
1077
  //#region src/host/agent/doctor-sessions.ts
@@ -1299,20 +1613,56 @@ var Presets = class {
1299
1613
  }
1300
1614
  /** Writes the person's own text of a prompt; `undefined` takes the preset's version out. */
1301
1615
  async writePrompt(name, language, id, text) {
1302
- const directory = presetDirectory(this.deps.root(), name);
1303
- if (!existsSync(directory)) throw new Error(`there is no preset "${name}"`);
1616
+ const directory = this.existing(name);
1304
1617
  if (!id.startsWith("roleplay/")) throw new Error(`"${id}" is not a prompt of the story`);
1305
1618
  if (text === void 0) await deleteWorldPrompt(directory, language, id);
1306
1619
  else await writeWorldPrompt(directory, language, id, text);
1307
1620
  return loadPreset(this.deps.root(), name).summary;
1308
1621
  }
1622
+ /** The prompts holding the rules of the game that the preset does not carry yet, which it may take over from the shipped ones. */
1623
+ rulesPrompts(name, language) {
1624
+ return listWorldPrompts(this.existing(name), language).filter((entry) => entry.kind === "rules" && !entry.carried).map((entry) => entry.id);
1625
+ }
1626
+ /** The text of a prompt as a story with this preset gets it: the preset's own, else the shipped one. */
1627
+ promptText(name, language, id) {
1628
+ return readWorldPrompt(this.existing(name), language, id).text;
1629
+ }
1630
+ existing(name) {
1631
+ const directory = presetDirectory(this.deps.root(), name);
1632
+ if (!existsSync(directory)) throw new Error(`there is no preset "${name}"`);
1633
+ return directory;
1634
+ }
1309
1635
  /** Like `importFile`, under a name made from the title that is not yet taken. */
1310
1636
  async importTitled(title, file, language) {
1311
- const base = title.normalize("NFKD").replace(/[^A-Za-z0-9_-]+/g, "-").replace(/^[-_]+|[-_]+$/g, "").slice(0, 56) || "preset";
1637
+ return await this.importFile(this.freeName(title), file, language, title.trim() === "" ? void 0 : title.trim().slice(0, 300));
1638
+ }
1639
+ freeName(title) {
1640
+ const base = trimCharacters(title.normalize("NFKD").replace(/[^A-Za-z0-9_-]+/g, "-"), "-_").slice(0, 56) || "preset";
1312
1641
  const taken = new Set(listPresets(this.deps.root()).map((entry) => entry.summary.name));
1313
1642
  let name = base;
1314
1643
  for (let index = 2; taken.has(name); index += 1) name = `${base}-${index}`;
1315
- return await this.importFile(name, file, language, title.trim() === "" ? void 0 : title.trim().slice(0, 300));
1644
+ return name;
1645
+ }
1646
+ /**
1647
+ * Imports the chosen prompts of a staged preset as they are, with no assistant: a new library preset is made and holds them as its narration style in every language the program ships, and nothing else happens.
1648
+ * @throws {ImportNotFoundError} when the file is no longer staged. @throws {ImportCardError} when the choice cannot be used.
1649
+ */
1650
+ async importVerbatim(request) {
1651
+ const { file, name: fileName } = this.deps.staging.choose("preset", request);
1652
+ const made = verbatimStyle(file, fileName);
1653
+ const title = request.title ?? made.name;
1654
+ const name = request.name ?? this.freeName(title);
1655
+ if (!isPresetName(name)) throw new Error(`"${name}" is not a usable preset name (letters, digits, "-" and "_", up to 64)`);
1656
+ const root = this.deps.root();
1657
+ const directory = await reservePreset(root, name, title, made.sampling);
1658
+ try {
1659
+ for (const language of shippedLanguages()) await writeWorldPrompt(directory, language, "roleplay/style", made.text);
1660
+ } catch (error) {
1661
+ await deletePreset(root, name);
1662
+ throw error;
1663
+ }
1664
+ this.deps.staging.discard(request.id);
1665
+ return { name };
1316
1666
  }
1317
1667
  /** Opens the authoring chat of a preset. */
1318
1668
  async author(name, language) {
@@ -1323,7 +1673,7 @@ var Presets = class {
1323
1673
  async importFile(name, file, language, title) {
1324
1674
  const uploaded = readPreset(file, name);
1325
1675
  const root = this.deps.root();
1326
- const directory = await reservePreset(root, name, title ?? uploaded.name);
1676
+ const directory = await reservePreset(root, name, title ?? uploaded.name, uploaded.sampling);
1327
1677
  try {
1328
1678
  await mkdir(join(directory, IMPORT_FOLDER), { recursive: true });
1329
1679
  await writeFile(join(directory, IMPORT_FOLDER, PRESET_FILE), file);
@@ -1345,6 +1695,13 @@ var Presets = class {
1345
1695
  ...failure === void 0 ? {} : { failure }
1346
1696
  };
1347
1697
  }
1698
+ /** Imports a staged preset with only the prompts the person chose; a name is the library name they gave it, else one is made from the title. @throws {ImportNotFoundError} when the file is no longer staged. */
1699
+ async importStaged(request) {
1700
+ const { file, name: fileName } = this.deps.staging.choose("preset", request);
1701
+ const opened = request.name === void 0 ? await this.importTitled(request.title ?? readPreset(file, fileName).name, file, request.language) : await this.importFile(request.name, file, request.language, request.title);
1702
+ this.deps.staging.discard(request.id);
1703
+ return opened;
1704
+ }
1348
1705
  async remove(name) {
1349
1706
  await deletePreset(this.deps.root(), name);
1350
1707
  }
@@ -1367,20 +1724,16 @@ var Presets = class {
1367
1724
  //#region src/host/presets/routes.ts
1368
1725
  /** Not found is 404 and a request the library refuses is 422 with its reason; anything else is a fault. */
1369
1726
  function failure$1(res, error) {
1727
+ if (error instanceof ImportNotFoundError) return sendError(res, 404, error.message);
1370
1728
  if (error instanceof SessionNotFoundError || error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
1371
1729
  if (error instanceof PresetBusyError) return sendError(res, 409, error.message);
1372
1730
  if (error instanceof Error) return sendError(res, 422, error.message);
1373
1731
  throw error;
1374
1732
  }
1375
1733
  function samplingOf(value) {
1376
- if (value === void 0) return {};
1377
- if (typeof value !== "object" || value === null || Array.isArray(value)) return "\"sampling\" must be an object";
1378
- const { master, characters } = value;
1379
- for (const number of [master, characters]) if (number !== void 0 && typeof number !== "number") return "sampling values must be numbers";
1380
- return {
1381
- ...master === void 0 ? {} : { master },
1382
- ...characters === void 0 ? {} : { characters }
1383
- };
1734
+ const problems = [];
1735
+ const sampling = parseSampling(value, "sampling", problems);
1736
+ return problems.length === 0 ? sampling : problems.join("; ");
1384
1737
  }
1385
1738
  function presetRoutes(api) {
1386
1739
  return {
@@ -1445,7 +1798,21 @@ function presetRoutes(api) {
1445
1798
  }
1446
1799
  }
1447
1800
  },
1801
+ "/presets/prompts": { GET: async (_req, res, url) => {
1802
+ try {
1803
+ sendJson(res, 200, api.rulesPrompts(url.searchParams.get("name") ?? "", languageOf(url.searchParams.get("language") ?? "")));
1804
+ } catch (error) {
1805
+ failure$1(res, error);
1806
+ }
1807
+ } },
1448
1808
  "/presets/prompt": {
1809
+ GET: async (_req, res, url) => {
1810
+ try {
1811
+ sendJson(res, 200, { text: api.promptText(url.searchParams.get("name") ?? "", languageOf(url.searchParams.get("language") ?? ""), url.searchParams.get("id") ?? "") });
1812
+ } catch (error) {
1813
+ failure$1(res, error);
1814
+ }
1815
+ },
1449
1816
  PUT: async (req, res, url) => {
1450
1817
  const { text } = await readJsonBody(req);
1451
1818
  if (typeof text !== "string" || text.trim() === "") return sendError(res, 400, "\"text\" is required");
@@ -1472,6 +1839,43 @@ function presetRoutes(api) {
1472
1839
  failure$1(res, error);
1473
1840
  }
1474
1841
  } },
1842
+ "/presets/import/verbatim": { POST: async (req, res) => {
1843
+ const body = await readJsonBody(req);
1844
+ const choice = parseSelectionChoice(body);
1845
+ if (typeof choice === "string") return sendError(res, 400, choice);
1846
+ const { name, title } = body;
1847
+ for (const [field, value] of [["name", name], ["title", title]]) if (value !== void 0 && typeof value !== "string") return sendError(res, 400, `"${field}" must be text`);
1848
+ try {
1849
+ sendJson(res, 200, await api.importVerbatim({
1850
+ ...choice,
1851
+ ...name === void 0 ? {} : { name },
1852
+ ...title === void 0 ? {} : { title }
1853
+ }));
1854
+ } catch (error) {
1855
+ failure$1(res, error);
1856
+ }
1857
+ } },
1858
+ "/presets/import/staged": { POST: async (req, res) => {
1859
+ const body = await readJsonBody(req);
1860
+ const choice = parseSelectionChoice(body);
1861
+ if (typeof choice === "string") return sendError(res, 400, choice);
1862
+ const { name, title, language } = body;
1863
+ for (const [field, value] of [
1864
+ ["name", name],
1865
+ ["title", title],
1866
+ ["language", language]
1867
+ ]) if (value !== void 0 && typeof value !== "string") return sendError(res, 400, `"${field}" must be text`);
1868
+ try {
1869
+ sendJson(res, 200, await api.importStaged({
1870
+ ...choice,
1871
+ ...name === void 0 ? {} : { name },
1872
+ ...title === void 0 ? {} : { title },
1873
+ ...language === void 0 ? {} : { language: languageOf(language) }
1874
+ }));
1875
+ } catch (error) {
1876
+ failure$1(res, error);
1877
+ }
1878
+ } },
1475
1879
  "/presets/import": { POST: async (req, res, url) => {
1476
1880
  const language = url.searchParams.get("language");
1477
1881
  try {
@@ -1502,8 +1906,11 @@ function presetRoutes(api) {
1502
1906
  }
1503
1907
  //#endregion
1504
1908
  //#region src/host/lorebooks/routes.ts
1505
- /** A request the library refuses is 422 with its reason; anything else is a fault. */
1909
+ /** Not found is 404, a story in the middle of a turn 409, and a request the library refuses 422 with its reason; anything else is a fault. */
1506
1910
  function failure(res, error) {
1911
+ if (error instanceof ImportNotFoundError) return sendError(res, 404, error.message);
1912
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
1913
+ if (error instanceof LorebookBusyError) return sendError(res, 409, error.message);
1507
1914
  if (error instanceof Error) return sendError(res, 422, error.message);
1508
1915
  throw error;
1509
1916
  }
@@ -1530,6 +1937,31 @@ function entryOf(id, body) {
1530
1937
  }
1531
1938
  function lorebookRoutes(api) {
1532
1939
  return {
1940
+ "/sessions/lorebooks": {
1941
+ GET: async (_req, res, url) => {
1942
+ try {
1943
+ sendJson(res, 200, await api.status(url.searchParams.get("id") ?? ""));
1944
+ } catch (error) {
1945
+ failure(res, error);
1946
+ }
1947
+ },
1948
+ POST: async (req, res, url) => {
1949
+ const { name } = await readJsonBody(req);
1950
+ if (typeof name !== "string" || name === "") return sendError(res, 400, "\"name\" is required");
1951
+ try {
1952
+ sendJson(res, 200, await api.addToStory(url.searchParams.get("id") ?? "", name));
1953
+ } catch (error) {
1954
+ failure(res, error);
1955
+ }
1956
+ },
1957
+ DELETE: async (_req, res, url) => {
1958
+ try {
1959
+ sendJson(res, 200, api.removeFromStory(url.searchParams.get("id") ?? "", url.searchParams.get("name") ?? ""));
1960
+ } catch (error) {
1961
+ failure(res, error);
1962
+ }
1963
+ }
1964
+ },
1533
1965
  "/lorebooks": {
1534
1966
  GET: async (_req, res) => {
1535
1967
  try {
@@ -1610,6 +2042,45 @@ function lorebookRoutes(api) {
1610
2042
  failure(res, error);
1611
2043
  }
1612
2044
  } },
2045
+ "/lorebooks/import/verbatim": { POST: async (req, res) => {
2046
+ const body = await readJsonBody(req);
2047
+ const choice = parseSelectionChoice(body);
2048
+ if (typeof choice === "string") return sendError(res, 400, choice);
2049
+ const { name, title, knownBy } = body;
2050
+ for (const [field, value] of [["name", name], ["title", title]]) if (value !== void 0 && typeof value !== "string") return sendError(res, 400, `"${field}" must be text`);
2051
+ if (knownBy !== "everyone" && knownBy !== "master") return sendError(res, 400, "\"knownBy\" must be everyone or master");
2052
+ try {
2053
+ sendJson(res, 200, await api.importVerbatim({
2054
+ ...choice,
2055
+ knownBy,
2056
+ ...name === void 0 ? {} : { name },
2057
+ ...title === void 0 ? {} : { title }
2058
+ }));
2059
+ } catch (error) {
2060
+ failure(res, error);
2061
+ }
2062
+ } },
2063
+ "/lorebooks/import/staged": { POST: async (req, res) => {
2064
+ const body = await readJsonBody(req);
2065
+ const choice = parseSelectionChoice(body);
2066
+ if (typeof choice === "string") return sendError(res, 400, choice);
2067
+ const { name, title, language } = body;
2068
+ for (const [field, value] of [
2069
+ ["name", name],
2070
+ ["title", title],
2071
+ ["language", language]
2072
+ ]) if (value !== void 0 && typeof value !== "string") return sendError(res, 400, `"${field}" must be text`);
2073
+ try {
2074
+ sendJson(res, 200, await api.importStaged({
2075
+ ...choice,
2076
+ ...name === void 0 ? {} : { name },
2077
+ ...title === void 0 ? {} : { title },
2078
+ ...language === void 0 ? {} : { language: languageOf(language) }
2079
+ }));
2080
+ } catch (error) {
2081
+ failure(res, error);
2082
+ }
2083
+ } },
1613
2084
  "/lorebooks/import": { POST: async (req, res, url) => {
1614
2085
  const language = url.searchParams.get("language");
1615
2086
  try {
@@ -2385,7 +2856,8 @@ const CATALOGUE_STATUS = {
2385
2856
  unknown: 404,
2386
2857
  upstream: 502,
2387
2858
  invalid: 422,
2388
- conflict: 409
2859
+ conflict: 409,
2860
+ unavailable: 503
2389
2861
  };
2390
2862
  /** A catalogue failure with the status that says whose fault it is; anything else is not ours to describe. */
2391
2863
  function catalogueFailure(res, error) {
@@ -2461,8 +2933,30 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
2461
2933
  }
2462
2934
  },
2463
2935
  "/catalogue/sources": { GET: async (_req, res) => {
2464
- sendJson(res, 200, catalogue.sources());
2936
+ try {
2937
+ sendJson(res, 200, await catalogue.sources());
2938
+ } catch (error) {
2939
+ return catalogueFailure(res, error);
2940
+ }
2465
2941
  } },
2942
+ "/catalogue/key": {
2943
+ GET: async (_req, res, url) => {
2944
+ try {
2945
+ sendJson(res, 200, await catalogue.describeKey(url.searchParams.get("ref") ?? ""));
2946
+ } catch (error) {
2947
+ return catalogueFailure(res, error);
2948
+ }
2949
+ },
2950
+ PUT: async (req, res) => {
2951
+ const { ref, value } = await readJsonBody(req);
2952
+ if (typeof ref !== "string" || typeof value !== "string") return sendError(res, 400, "\"ref\" and \"value\" must be text");
2953
+ try {
2954
+ sendJson(res, 200, await catalogue.keepKey(ref, value));
2955
+ } catch (error) {
2956
+ return catalogueFailure(res, error);
2957
+ }
2958
+ }
2959
+ },
2466
2960
  "/catalogue/worlds": { GET: async (_req, res, url) => {
2467
2961
  const offset = Number(url.searchParams.get("offset") ?? 0);
2468
2962
  const sort = url.searchParams.get("sort") === "popular" ? "popular" : "recent";
@@ -2539,6 +3033,34 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
2539
3033
  return error instanceof CatalogueError ? catalogueFailure(res, error) : importFailure(res, error);
2540
3034
  }
2541
3035
  } },
3036
+ "/catalogue/stage/card": { POST: async (req, res) => {
3037
+ const body = await readJsonBody(req);
3038
+ if (typeof body.source !== "string" || typeof body.versionId !== "string") return sendError(res, 400, "source and versionId must be text");
3039
+ try {
3040
+ sendJson(res, 200, await catalogue.stageCard({
3041
+ source: body.source,
3042
+ versionId: body.versionId
3043
+ }));
3044
+ } catch (error) {
3045
+ return error instanceof CatalogueError ? catalogueFailure(res, error) : importFailure(res, error);
3046
+ }
3047
+ } },
3048
+ "/catalogue/convert/staged": { POST: async (req, res) => {
3049
+ const body = await readJsonBody(req);
3050
+ if (typeof body.source !== "string" || typeof body.versionId !== "string" || typeof body.id !== "string") return sendError(res, 400, "source, versionId and id must be text");
3051
+ try {
3052
+ const language = languageField(body.language);
3053
+ sendJson(res, 201, await catalogue.convertStaged({
3054
+ source: body.source,
3055
+ versionId: body.versionId,
3056
+ id: body.id,
3057
+ choices: parseChoices(body.choices),
3058
+ ...language === void 0 ? {} : { language }
3059
+ }));
3060
+ } catch (error) {
3061
+ return error instanceof CatalogueError ? catalogueFailure(res, error) : importFailure(res, error);
3062
+ }
3063
+ } },
2542
3064
  "/catalogue/convert/preset": { POST: async (req, res) => {
2543
3065
  const body = await readJsonBody(req);
2544
3066
  if (typeof body.source !== "string" || typeof body.versionId !== "string") return sendError(res, 400, "source and versionId must be text");
@@ -2555,6 +3077,20 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
2555
3077
  return error instanceof CatalogueError ? catalogueFailure(res, error) : importFailure(res, error);
2556
3078
  }
2557
3079
  } },
3080
+ "/catalogue/stage": { POST: async (req, res) => {
3081
+ const body = await readJsonBody(req);
3082
+ if (typeof body.source !== "string" || typeof body.versionId !== "string") return sendError(res, 400, "source and versionId must be text");
3083
+ if (body.kind !== "preset" && body.kind !== "lorebook") return sendError(res, 400, "kind must be preset or lorebook");
3084
+ try {
3085
+ sendJson(res, 200, await catalogue.stage({
3086
+ source: body.source,
3087
+ versionId: body.versionId,
3088
+ kind: body.kind
3089
+ }));
3090
+ } catch (error) {
3091
+ return error instanceof CatalogueError ? catalogueFailure(res, error) : importFailure(res, error);
3092
+ }
3093
+ } },
2558
3094
  "/catalogue/convert/lorebook": { POST: async (req, res) => {
2559
3095
  const body = await readJsonBody(req);
2560
3096
  if (typeof body.source !== "string" || typeof body.versionId !== "string") return sendError(res, 400, "source and versionId must be text");
@@ -2604,6 +3140,49 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
2604
3140
  return importFailure(res, error);
2605
3141
  }
2606
3142
  } },
3143
+ "/import/stage": {
3144
+ POST: async (req, res, url) => {
3145
+ const kind = url.searchParams.get("kind");
3146
+ if (kind !== "preset" && kind !== "lorebook") return sendError(res, 400, "\"kind\" must be preset or lorebook");
3147
+ const name = decodeURIComponent(String(req.headers["x-file-name"] ?? url.searchParams.get("name") ?? kind));
3148
+ try {
3149
+ sendJson(res, 200, importer.stage(kind, await readBinaryBody(req, importer.maxUploadBytes), name));
3150
+ } catch (error) {
3151
+ return importFailure(res, error);
3152
+ }
3153
+ },
3154
+ DELETE: async (_req, res, url) => {
3155
+ importer.discardStaged(url.searchParams.get("id") ?? "");
3156
+ res.statusCode = 204;
3157
+ res.end();
3158
+ }
3159
+ },
3160
+ "/worlds/import/preset/verbatim": { POST: async (req, res) => {
3161
+ const body = await readJsonBody(req);
3162
+ const choice = parseSelectionChoice(body);
3163
+ if (typeof choice === "string") return sendError(res, 400, choice);
3164
+ const { worldId } = body;
3165
+ if (typeof worldId !== "string") return sendError(res, 400, "\"worldId\" must be text");
3166
+ try {
3167
+ sendJson(res, 200, await importer.applyStagedVerbatim(worldId, choice));
3168
+ } catch (error) {
3169
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
3170
+ return importFailure(res, error);
3171
+ }
3172
+ } },
3173
+ "/worlds/import/preset/staged": { POST: async (req, res) => {
3174
+ const body = await readJsonBody(req);
3175
+ const choice = parseSelectionChoice(body);
3176
+ if (typeof choice === "string") return sendError(res, 400, choice);
3177
+ const { worldId, language } = body;
3178
+ if (typeof worldId !== "string") return sendError(res, 400, "\"worldId\" must be text");
3179
+ try {
3180
+ sendJson(res, 200, await importer.uploadStaged(worldId, choice, languageField(language)));
3181
+ } catch (error) {
3182
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
3183
+ return importFailure(res, error);
3184
+ }
3185
+ } },
2607
3186
  "/worlds/import": {
2608
3187
  GET: async (_req, res, url) => {
2609
3188
  try {
@@ -3896,7 +4475,7 @@ async function editRoutine(world, key, windows) {
3896
4475
  const { calendar } = await loadCalendar(world.directory);
3897
4476
  const places = routineProblems([parsed.value], locations, calendar);
3898
4477
  if (places.length > 0) throw new InvalidEditProblems(places);
3899
- await replaceFile$1(file, next);
4478
+ await replaceFile(file, next);
3900
4479
  return await readRoutines(world);
3901
4480
  }
3902
4481
  /** The variables the world declares, as the file writes them. */
@@ -3938,7 +4517,7 @@ async function editVariables(world, declarations) {
3938
4517
  }
3939
4518
  async function replaceFileOrCreate(file, text) {
3940
4519
  try {
3941
- await replaceFile$1(file, text);
4520
+ await replaceFile(file, text);
3942
4521
  } catch (error) {
3943
4522
  if (error.code !== "ENOENT") throw error;
3944
4523
  await writeFile(file, text, { flag: "wx" });
@@ -4212,6 +4791,8 @@ function worldOf$1(session, sessionsDir) {
4212
4791
  key: entry.sourceId ?? String(entry.id),
4213
4792
  title: entry.title,
4214
4793
  kind: entry.kind,
4794
+ scope: entry.scope,
4795
+ knownBy: session.characters.list().filter((character) => session.knowledge.knows(character.id, "lore", entry.id)).map((character) => character.name),
4215
4796
  summary: entry.summary,
4216
4797
  body: entry.body,
4217
4798
  ...entry.startsAt === void 0 ? {} : { startsAt: entry.startsAt },
@@ -4349,7 +4930,21 @@ function editWorldLore(deps, id, key, edit) {
4349
4930
  const session = sessionOf(deps, id);
4350
4931
  const entry = session.lore.list().find((candidate) => (candidate.sourceId ?? String(candidate.id)) === key);
4351
4932
  if (entry === void 0) throw new InvalidEditProblems([`there is no lore "${key}"`]);
4352
- session.lore.update(entry.id, edit);
4933
+ const { knownBy, ...patch } = edit;
4934
+ if (knownBy !== void 0 && knownBy.length > 0 && (edit.scope ?? entry.scope) === "everyone") throw new InvalidEditProblems(["an entry everyone knows has no list of who knows it"]);
4935
+ const knowers = knownBy?.map((name) => ({
4936
+ name,
4937
+ character: session.characters.getBySourceId(name) ?? session.characters.findByName(name)[0]
4938
+ }));
4939
+ const strangers = knowers?.filter((found) => found.character === void 0) ?? [];
4940
+ if (strangers.length > 0) throw new InvalidEditProblems(strangers.map((found) => `"${found.name}" is not a character of this story`));
4941
+ session.transaction(() => {
4942
+ session.lore.update(entry.id, patch);
4943
+ if (knowers === void 0) return;
4944
+ const wanted = new Set(knowers.map((found) => found.character.id));
4945
+ for (const character of session.characters.list()) if (wanted.has(character.id)) session.knowledge.learn(character.id, "lore", entry.id, session.metadata.get().turns);
4946
+ else session.knowledge.forget(character.id, "lore", entry.id);
4947
+ });
4353
4948
  return worldOf$1(session, deps.sessionsDir());
4354
4949
  }
4355
4950
  function editWorldPlots(deps, id, edit) {
@@ -4881,175 +5476,6 @@ async function addAvatarsToWorld(avatars, world, keys, locations) {
4881
5476
  }
4882
5477
  return brought.map((entry) => entry.id);
4883
5478
  }
4884
- //#endregion
4885
- //#region src/host/worlds/world-info.ts
4886
- async function replaceFile(file, text) {
4887
- const temporary = join(dirname(file), `.${basename(file)}.${process.pid}.${randomUUID()}.tmp`);
4888
- try {
4889
- const { mode } = await stat(file);
4890
- await writeFile(temporary, text, { mode });
4891
- await chmod(temporary, mode);
4892
- await rename(temporary, file);
4893
- } catch (error) {
4894
- await rm(temporary, { force: true });
4895
- throw error;
4896
- }
4897
- }
4898
- const textOf = (value) => typeof value === "string" ? value : "";
4899
- const toolsOf = (value) => {
4900
- const board = value === void 0 ? {} : parseSwitchboard(value, "tools");
4901
- return typeof board === "string" ? {} : board;
4902
- };
4903
- function infoOf(document) {
4904
- const opening = document["opening_message"];
4905
- const parts = Array.isArray(opening) && opening.some((part) => typeof part === "object" && part !== null && part["type"] === "utterance");
4906
- const plain = typeof opening === "string" ? opening : Array.isArray(opening) ? opening.map((part) => textOf(part?.["text"])).filter((text) => text !== "").join("\n\n") : "";
4907
- const metadata = typeof document["metadata"] === "object" && document["metadata"] !== null ? document["metadata"] : {};
4908
- const author = typeof document["author"] === "object" && document["author"] !== null ? document["author"] : {};
4909
- const rules = document["rules"];
4910
- return {
4911
- name: textOf(document["name"]),
4912
- description: textOf(document["description"]),
4913
- tags: Array.isArray(metadata["tags"]) ? metadata["tags"].filter((tag) => typeof tag === "string") : [],
4914
- rules: typeof rules === "string" ? [rules] : Array.isArray(rules) ? rules.filter((rule) => typeof rule === "string") : [],
4915
- opening: plain,
4916
- openingParts: parts,
4917
- authorName: textOf(author["name"]),
4918
- authorUrl: textOf(author["url"]),
4919
- timeZone: textOf(document["time_zone"]),
4920
- startingTime: textOf(document["starting_time"]),
4921
- preset: textOf(document["preset"]),
4922
- lorebooks: Array.isArray(document["lorebooks"]) ? document["lorebooks"].filter((name) => typeof name === "string") : [],
4923
- version: typeof document["version"] === "number" ? String(document["version"]) : textOf(document["version"]),
4924
- tools: toolsOf(document["tools"]),
4925
- alternateOpenings: Array.isArray(document["alternate_openings"]) ? document["alternate_openings"].flatMap((entry) => typeof entry === "object" && entry !== null && typeof entry["text"] === "string" ? [{
4926
- title: textOf(entry["title"]),
4927
- text: entry["text"],
4928
- ...textOf(entry["character"]) === "" ? {} : { character: textOf(entry["character"]) }
4929
- }] : []) : []
4930
- };
4931
- }
4932
- async function readDocument(directory) {
4933
- const text = await readFile(join(directory, WORLD_FILE_NAME), "utf8");
4934
- return {
4935
- text,
4936
- document: JSON.parse(text.replace(/^/, ""))
4937
- };
4938
- }
4939
- async function readWorldInfo(directory) {
4940
- return infoOf((await readDocument(directory)).document);
4941
- }
4942
- function setOrRemove(document, key, value) {
4943
- if (value === "") delete document[key];
4944
- else document[key] = value;
4945
- }
4946
- /**
4947
- * Changes the fields of `world.json` the edit names and nothing else, keeping the file's other fields and its indentation. The result is read
4948
- * back as the world will be read before it is written.
4949
- * @throws {InvalidEditProblems} when the world would no longer be valid.
4950
- */
4951
- async function editWorldInfo(directory, edit) {
4952
- const { text, document } = await readDocument(directory);
4953
- const before = infoOf(document);
4954
- if (edit.opening !== void 0 && before.openingParts && edit.opening !== before.opening) throw new InvalidEditProblems(["the opening has lines spoken by characters: change it in the file, or ask the authoring assistant"]);
4955
- if (edit.name !== void 0) document["name"] = edit.name;
4956
- if (edit.description !== void 0) document["description"] = edit.description;
4957
- if (edit.tags !== void 0) document["metadata"] = {
4958
- ...typeof document["metadata"] === "object" && document["metadata"] !== null ? document["metadata"] : {},
4959
- tags: edit.tags
4960
- };
4961
- if (edit.rules !== void 0) {
4962
- if (edit.rules.length === 0) delete document["rules"];
4963
- else document["rules"] = edit.rules;
4964
- }
4965
- if (edit.opening !== void 0 && !before.openingParts) setOrRemove(document, "opening_message", edit.opening);
4966
- if (edit.authorName !== void 0 || edit.authorUrl !== void 0) {
4967
- const name = edit.authorName ?? before.authorName;
4968
- const url = edit.authorUrl ?? before.authorUrl;
4969
- if (name === "" && url !== "") throw new InvalidEditProblems(["an author link needs the author's name"]);
4970
- if (name === "") delete document["author"];
4971
- else document["author"] = {
4972
- ...typeof document["author"] === "object" && document["author"] !== null ? document["author"] : {},
4973
- name,
4974
- ...url === "" ? {} : { url }
4975
- };
4976
- if (url === "" && typeof document["author"] === "object") delete document["author"]["url"];
4977
- }
4978
- if (edit.timeZone !== void 0) setOrRemove(document, "time_zone", edit.timeZone);
4979
- if (edit.startingTime !== void 0) setOrRemove(document, "starting_time", edit.startingTime);
4980
- if (edit.version !== void 0) setOrRemove(document, "version", edit.version);
4981
- if (edit.preset !== void 0) setOrRemove(document, "preset", edit.preset);
4982
- if (edit.lorebooks !== void 0) {
4983
- if (edit.lorebooks.length === 0) delete document["lorebooks"];
4984
- else document["lorebooks"] = edit.lorebooks;
4985
- }
4986
- if (edit.alternateOpenings !== void 0) {
4987
- if (edit.alternateOpenings.length === 0) delete document["alternate_openings"];
4988
- else document["alternate_openings"] = edit.alternateOpenings.map((entry) => ({
4989
- title: entry.title === "" ? entry.text.slice(0, 40) : entry.title,
4990
- text: entry.text,
4991
- ...entry.character === void 0 || entry.character === "" ? {} : { character: entry.character }
4992
- }));
4993
- }
4994
- if (edit.tools !== void 0) {
4995
- if (Object.keys(edit.tools).length === 0) delete document["tools"];
4996
- else document["tools"] = edit.tools;
4997
- }
4998
- const next = JSON.stringify(document, null, /^([ \t]+)"/m.exec(text)?.[1] ?? " ") + (text.endsWith("\n") ? "\n" : "");
4999
- const parsed = parseWorldFile(next);
5000
- if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
5001
- await replaceFile(join(directory, WORLD_FILE_NAME), next);
5002
- return infoOf(document);
5003
- }
5004
- //#endregion
5005
- //#region src/host/lorebooks/apply.ts
5006
- /** Which lorebooks a story was started with: kept in the story's own metadata, because the library may change afterwards. */
5007
- const LOREBOOKS_KEY = "roleplay.lorebooks";
5008
- /** The id an entry has in a story, so that books and the world's own lore never clash. */
5009
- const bookEntryId = (book, id) => `${book}:${id}`;
5010
- /**
5011
- * The entries of the named books as a story takes them. A book that cannot be used is refused when the person chose it and told about when only the world suggested it,
5012
- * because the world may come from someone whose library differs. Characters an entry names that this story does not have are left out, and it is told.
5013
- * @throws {Error} when a chosen book cannot be used.
5014
- */
5015
- async function lorebookLore(root, names, chosen, characters, taken) {
5016
- const result = {
5017
- definitions: [],
5018
- applied: [],
5019
- notes: []
5020
- };
5021
- const used = new Set(taken);
5022
- for (const name of [...new Set(names)]) {
5023
- let book;
5024
- try {
5025
- book = await loadLorebook(root, name);
5026
- if (book.summary.problems.length > 0) throw new Error(`it has problems: ${book.summary.problems.join("; ")}`);
5027
- } catch (error) {
5028
- const reason = error instanceof Error ? error.message : String(error);
5029
- if (chosen) throw new Error(`the lorebook "${name}" cannot be used: ${reason}`);
5030
- result.notes.push(`The world suggests the lorebook "${name}", which cannot be used here (${reason}), so the story starts without it.`);
5031
- continue;
5032
- }
5033
- for (const entry of book.entries) {
5034
- const id = bookEntryId(name, entry.id);
5035
- if (used.has(id)) throw new Error(`the lorebook "${name}" has the entry "${entry.id}", whose id the story already has`);
5036
- used.add(id);
5037
- const knownBy = entry.scope === "listed" ? entry.knownBy.filter((reference) => knowsCharacter(characters, reference)) : [];
5038
- for (const reference of entry.scope === "listed" ? entry.knownBy : []) if (!knownBy.includes(reference)) result.notes.push(`The lorebook "${name}" says "${entry.title}" is known to "${reference}", who is not in this story.`);
5039
- result.definitions.push({
5040
- ...entry,
5041
- id,
5042
- knownBy,
5043
- related: entry.related.map((other) => bookEntryId(name, other))
5044
- });
5045
- }
5046
- result.applied.push({
5047
- name,
5048
- entries: book.entries.length
5049
- });
5050
- }
5051
- return result;
5052
- }
5053
5479
  /**
5054
5480
  * Start a new session for a world: create its folder and database and fill it
5055
5481
  * from the world. Either the whole session exists afterwards or nothing does.
@@ -5125,22 +5551,24 @@ async function startSession(deps, request) {
5125
5551
  if (wanted.length > 0) {
5126
5552
  if (deps.root === void 0) throw new InvalidStartError("the lorebook library is not available");
5127
5553
  try {
5128
- books = await lorebookLore(deps.root(), wanted, asked, characters, new Set(authoredLore.lore.map((entry) => entry.id)));
5554
+ books = await lorebookLore(deps.root(), wanted, asked, (reference) => knowsCharacter(characters, reference), new Set(authoredLore.lore.map((entry) => entry.id)));
5129
5555
  } catch (error) {
5130
5556
  throw new InvalidStartError(error instanceof Error ? error.message : String(error));
5131
5557
  }
5132
5558
  unavailable.push(...books.notes);
5133
5559
  }
5134
- if (preset !== void 0) {
5135
- const given = request.settings?.sampling ?? {};
5136
- settings = {
5137
- ...settings,
5138
- sampling: {
5139
- ...settings.sampling,
5140
- ...Object.fromEntries(Object.entries(preset.summary.sampling).filter(([key]) => given[key] === void 0))
5141
- }
5142
- };
5143
- }
5560
+ const given = request.settings?.sampling ?? {};
5561
+ const suggested = {
5562
+ ...world.sampling,
5563
+ ...preset?.summary.sampling
5564
+ };
5565
+ if (Object.keys(suggested).length > 0) settings = {
5566
+ ...settings,
5567
+ sampling: {
5568
+ ...settings.sampling,
5569
+ ...Object.fromEntries(Object.entries(suggested).filter(([key]) => given[key] === void 0))
5570
+ }
5571
+ };
5144
5572
  let startsAt = world.clock?.startingTime;
5145
5573
  if (request.startingTime !== void 0 && request.startingTime.trim() !== "") {
5146
5574
  if (settings.clock.mode === "real") throw new InvalidStartError("the story's time follows the wall clock, so it has no starting time to choose");
@@ -5615,9 +6043,12 @@ var RoleplayRoot = class extends Service {
5615
6043
  super(ctx, "roleplayRoot");
5616
6044
  this.source = source;
5617
6045
  this.current = resolveRootPath(source.get());
5618
- this.prepare(this.current);
5619
6046
  ctx.on("loader/volatile-update", () => this.refresh());
5620
6047
  }
6048
+ /** Prepare the configured root after construction. */
6049
+ start() {
6050
+ this.prepare(this.current);
6051
+ }
5621
6052
  /** Absolute path of the active root. */
5622
6053
  get path() {
5623
6054
  return this.current;
@@ -5740,7 +6171,7 @@ async function scanWorlds(worldsDir) {
5740
6171
  return result;
5741
6172
  }
5742
6173
  async function loadWorld(folder, dir, file, problems) {
5743
- const world = await readDocument$1(file, parseWorldFile, problems);
6174
+ const world = await readDocument(file, parseWorldFile, problems);
5744
6175
  if (world === void 0) return void 0;
5745
6176
  let id = world.id;
5746
6177
  if (id === void 0) try {
@@ -5770,6 +6201,7 @@ async function loadWorld(folder, dir, file, problems) {
5770
6201
  ...world.rules === void 0 ? {} : { rules: world.rules },
5771
6202
  ...world.tools === void 0 ? {} : { tools: world.tools },
5772
6203
  ...world.narrationVoice === void 0 ? {} : { narrationVoice: world.narrationVoice },
6204
+ ...world.sampling === void 0 ? {} : { sampling: world.sampling },
5773
6205
  ...world.preset === void 0 ? {} : { preset: world.preset },
5774
6206
  ...world.lorebooks === void 0 ? {} : { lorebooks: world.lorebooks }
5775
6207
  };
@@ -5900,6 +6332,16 @@ var WorldCatalog = class extends Service {
5900
6332
  };
5901
6333
  //#endregion
5902
6334
  //#region src/shared/catalogue.ts
6335
+ /** What a credential reference is: letters, digits and `_`, not starting with a digit (DSH's grammar). */
6336
+ const CREDENTIAL_REF = /^[A-Za-z_][A-Za-z0-9_]*$/;
6337
+ /** The credential a catalogue's key is stored under when its entry names none. Names with other characters get a short checksum so that two of them never share a key. */
6338
+ function catalogueKeyRef(name) {
6339
+ const trimmed = name.trim();
6340
+ const slug = trimCharacters(trimmed.normalize("NFKD").replace(/[^A-Za-z0-9]+/g, "_"), "_").toUpperCase();
6341
+ let checksum = 2166136261;
6342
+ for (const unit of trimmed) checksum = Math.imul(checksum ^ unit.codePointAt(0), 16777619) >>> 0;
6343
+ return `ROLEPLAY_CATALOGUE_${slug !== "" && /^[A-Za-z0-9 _.-]+$/.test(trimmed) ? slug : `${slug === "" ? "X" : slug}_${checksum.toString(16).toUpperCase()}`}_API_KEY`;
6344
+ }
5903
6345
  const CATALOGUE_CARD_TYPE = "sillytavern/character";
5904
6346
  const CATALOGUE_PRESET_TYPE = "sillytavern/preset";
5905
6347
  const CATALOGUE_LOREBOOK_TYPE = "sillytavern/lorebook";
@@ -6316,7 +6758,7 @@ async function fetchAddress(address, options) {
6316
6758
  const vetted = vetUrl(url.href);
6317
6759
  if (typeof vetted === "string") throw new CatalogueError(`${url.href} ${vetted}`, "input");
6318
6760
  }
6319
- const key = source?.apiKey;
6761
+ const key = source === void 0 ? void 0 : await options.sources.key(source);
6320
6762
  let reply;
6321
6763
  try {
6322
6764
  reply = await transport(url, {
@@ -6415,8 +6857,16 @@ var Catalogue = class {
6415
6857
  constructor(deps) {
6416
6858
  this.deps = deps;
6417
6859
  }
6418
- sources() {
6419
- return this.deps.sources.status();
6860
+ async sources() {
6861
+ return await this.deps.sources.status();
6862
+ }
6863
+ /** What the credential store says about a key's reference, never the key. */
6864
+ async describeKey(ref) {
6865
+ return await this.deps.sources.describe(ref);
6866
+ }
6867
+ /** Keeps a key in the credential store, or removes it when the value is empty. */
6868
+ async keepKey(ref, value) {
6869
+ return await this.deps.sources.keep(ref, value);
6420
6870
  }
6421
6871
  async worlds(name, query) {
6422
6872
  const source = this.deps.sources.get(name);
@@ -6436,7 +6886,7 @@ var Catalogue = class {
6436
6886
  return {
6437
6887
  items: answer["items"].map(worldOf),
6438
6888
  ...typeof next === "number" ? { nextOffset: next } : {},
6439
- withKey: source.apiKey !== void 0
6889
+ withKey: await this.deps.sources.key(source) !== void 0
6440
6890
  };
6441
6891
  }
6442
6892
  async world(name, id) {
@@ -6582,13 +7032,7 @@ var Catalogue = class {
6582
7032
  async convert(request) {
6583
7033
  const source = this.deps.sources.get(request.source);
6584
7034
  const release = await this.download(source, request.versionId, CATALOGUE_CARD_TYPE, "a character card");
6585
- const png = release.body.subarray(0, 4).equals(Buffer.from([
6586
- 137,
6587
- 80,
6588
- 78,
6589
- 71
6590
- ]));
6591
- const converted = await this.deps.importCard(release.body, `${release.versionId}${png ? ".png" : ".json"}`, request.language);
7035
+ const converted = await this.deps.importCard(release.body, `${release.versionId}${isPng(release.body) ? ".png" : ".json"}`, request.language);
6592
7036
  const record = await this.deps.worlds.find(converted.worldId);
6593
7037
  if (record === void 0) throw new CatalogueError("the world was made but cannot be found", "upstream");
6594
7038
  await writeOrigin(record.directory, {
@@ -6600,6 +7044,27 @@ var Catalogue = class {
6600
7044
  });
6601
7045
  return converted;
6602
7046
  }
7047
+ /** Downloads a card of a catalogue and offers what it holds for the person to look through, before any world is made. */
7048
+ async stageCard(request) {
7049
+ const release = await this.download(this.deps.sources.get(request.source), request.versionId, CATALOGUE_CARD_TYPE, "a character card");
7050
+ return await this.deps.previewCard(release.body, `${release.versionId}${isPng(release.body) ? ".png" : ".json"}`);
7051
+ }
7052
+ /** Makes the world of a card that `stageCard` offered, with what the person chose. Like `convert`, it never replaces a world. */
7053
+ async convertStaged(request) {
7054
+ const source = this.deps.sources.get(request.source);
7055
+ const release = await this.describe(source, request.versionId, CATALOGUE_CARD_TYPE, "a character card");
7056
+ const converted = await this.deps.startCard(request.id, request.choices, request.language);
7057
+ const record = await this.deps.worlds.find(converted.worldId);
7058
+ if (record === void 0) throw new CatalogueError("the world was made but cannot be found", "upstream");
7059
+ await writeOrigin(record.directory, {
7060
+ kind: "card",
7061
+ root: source.root,
7062
+ resourceId: release.resourceId,
7063
+ versionId: release.versionId,
7064
+ version: text(release.version["version"])
7065
+ });
7066
+ return converted;
7067
+ }
6603
7068
  /** Turns a SillyTavern lorebook of a catalogue into a new library lorebook, which its authoring chat fills with entries. Like a card it is never an update of an earlier one. */
6604
7069
  async convertLorebook(request) {
6605
7070
  const release = await this.download(this.deps.sources.get(request.source), request.versionId, CATALOGUE_LOREBOOK_TYPE, "a lorebook");
@@ -6612,11 +7077,7 @@ var Catalogue = class {
6612
7077
  }
6613
7078
  /** A release of the given type, downloaded with the catalogue's key and checked against the checksum it published. */
6614
7079
  async download(source, versionIdText, type, what) {
6615
- const versionId = this.identifier(versionIdText);
6616
- const version = object(await this.json(source, `/versions/${versionId}`), "a version");
6617
- if (text(version["resourceType"]) !== type) throw new CatalogueError(`that release is not ${what}`, "invalid");
6618
- const resourceId = text(version["resourceId"]);
6619
- if (!ID.test(resourceId)) throw unexpected("a version without a resource id");
7080
+ const { version, versionId, resourceId } = await this.describe(source, versionIdText, type, what);
6620
7081
  const reply = await fetchAddress(this.address(source, `/versions/${versionId}/download`), {
6621
7082
  sources: this.deps.sources,
6622
7083
  maxBytes: this.deps.maxCardBytes(),
@@ -6632,6 +7093,24 @@ var Catalogue = class {
6632
7093
  version: text(version["version"])
6633
7094
  };
6634
7095
  }
7096
+ /** What the catalogue says about a release, checked to be of the type wanted. */
7097
+ async describe(source, versionIdText, type, what) {
7098
+ const versionId = this.identifier(versionIdText);
7099
+ const version = object(await this.json(source, `/versions/${versionId}`), "a version");
7100
+ if (text(version["resourceType"]) !== type) throw new CatalogueError(`that release is not ${what}`, "invalid");
7101
+ const resourceId = text(version["resourceId"]);
7102
+ if (!ID.test(resourceId)) throw unexpected("a version without a resource id");
7103
+ return {
7104
+ version,
7105
+ versionId,
7106
+ resourceId
7107
+ };
7108
+ }
7109
+ /** Downloads a preset or a lorebook of a catalogue and offers what it holds for the person to choose from, before anything is imported. */
7110
+ async stage(request) {
7111
+ const release = await this.download(this.deps.sources.get(request.source), request.versionId, request.kind === "preset" ? CATALOGUE_PRESET_TYPE : CATALOGUE_LOREBOOK_TYPE, request.kind === "preset" ? "a preset" : "a lorebook");
7112
+ return this.deps.stage(request.kind, release.body, request.kind);
7113
+ }
6635
7114
  /** The catalogue release an address names, when it is a release download on a configured catalogue. */
6636
7115
  async provenance(url) {
6637
7116
  const source = this.deps.sources.match(url);
@@ -6715,8 +7194,11 @@ const prefixLength = (prefix, path) => prefix === "" || path === prefix || path.
6715
7194
  /** The catalogues the person configured, read afresh on every use so an edit applies at once. */
6716
7195
  var Sources = class {
6717
7196
  read;
6718
- constructor(read) {
7197
+ store;
7198
+ /** `store` is looked up on each use: a key saved or rotated reaches the next request without a restart. */
7199
+ constructor(read, store = () => void 0) {
6719
7200
  this.read = read;
7201
+ this.store = store;
6720
7202
  }
6721
7203
  resolved() {
6722
7204
  const seen = /* @__PURE__ */ new Set();
@@ -6736,7 +7218,12 @@ var Sources = class {
6736
7218
  source,
6737
7219
  problem: `address ${base}`
6738
7220
  };
6739
- const prefix = base.pathname.replace(/\/+$/, "");
7221
+ const prefix = trimCharacters(base.pathname, "/", "end");
7222
+ const keyRef = source.apiKeyRef.trim() === "" ? catalogueKeyRef(name) : source.apiKeyRef.trim();
7223
+ if (!CREDENTIAL_REF.test(keyRef)) return {
7224
+ source,
7225
+ problem: `has a key name "${keyRef}" that is not a credential name (letters, digits and "_", not starting with a digit)`
7226
+ };
6740
7227
  return {
6741
7228
  source,
6742
7229
  resolved: {
@@ -6744,19 +7231,74 @@ var Sources = class {
6744
7231
  root: `${base.origin}${prefix}`,
6745
7232
  origin: base.origin,
6746
7233
  prefix,
6747
- apiKey: source.apiKey.trim() === "" ? void 0 : source.apiKey.trim()
7234
+ keyRef,
7235
+ legacyKey: source.apiKey.trim() === "" ? void 0 : source.apiKey.trim()
6748
7236
  }
6749
7237
  };
6750
7238
  });
6751
7239
  }
6752
- status() {
6753
- return this.resolved().map(({ source, resolved, problem }) => ({
6754
- name: source.name.trim(),
6755
- baseUrl: source.baseUrl.trim(),
6756
- hasKey: source.apiKey.trim() !== "",
6757
- ...resolved === void 0 ? { problem: problem ?? "cannot be used" } : {}
7240
+ /** The catalogue's key: the credential store's value for its reference, else the one an earlier version wrote in the configuration. */
7241
+ async key(source) {
7242
+ const store = this.store();
7243
+ if (store !== void 0) {
7244
+ let found;
7245
+ try {
7246
+ found = await store.resolve(source.keyRef);
7247
+ } catch (error) {
7248
+ throw new CatalogueError(`could not read the key "${source.keyRef}" of the catalogue "${source.name}": ${error instanceof Error ? error.message : String(error)}`, "invalid");
7249
+ }
7250
+ if (found !== void 0) return found.value;
7251
+ }
7252
+ return source.legacyKey;
7253
+ }
7254
+ async status() {
7255
+ const store = this.store();
7256
+ return await Promise.all(this.resolved().map(async ({ source, resolved, problem }) => {
7257
+ const keyRef = resolved?.keyRef ?? (source.apiKeyRef.trim() === "" ? catalogueKeyRef(source.name) : source.apiKeyRef.trim());
7258
+ const stored = resolved === void 0 || store === void 0 ? void 0 : await store.describe(keyRef);
7259
+ const legacy = source.apiKey.trim() !== "";
7260
+ return {
7261
+ name: source.name.trim(),
7262
+ baseUrl: source.baseUrl.trim(),
7263
+ keyRef,
7264
+ hasKey: stored?.configured === true || legacy,
7265
+ ...stored?.configured === true && stored.source !== void 0 ? { keySource: stored.source } : legacy ? { keySource: "configuration" } : {},
7266
+ ...legacy ? { legacyKey: true } : {},
7267
+ ...resolved === void 0 ? { problem: problem ?? "cannot be used" } : {}
7268
+ };
6758
7269
  }));
6759
7270
  }
7271
+ /** The credential store's account of a reference, for the settings page; never the value. @throws {CatalogueError} when the profile has no credential store. */
7272
+ async describe(ref) {
7273
+ const info = await this.needStore().describe(this.reference(ref));
7274
+ return {
7275
+ ref,
7276
+ configured: info.configured,
7277
+ writable: info.writable,
7278
+ ...info.source === void 0 ? {} : { source: info.source }
7279
+ };
7280
+ }
7281
+ /** Stores a key from the settings page, or removes the stored one when the value is empty. @throws {CatalogueError} when the store refuses. */
7282
+ async keep(ref, value) {
7283
+ const store = this.needStore();
7284
+ try {
7285
+ if (value === "") await store.unset(this.reference(ref));
7286
+ else await store.set(this.reference(ref), value);
7287
+ } catch (error) {
7288
+ if (error instanceof CatalogueError) throw error;
7289
+ throw new CatalogueError(error instanceof Error ? error.message : "the key could not be stored", "conflict");
7290
+ }
7291
+ return await this.describe(ref);
7292
+ }
7293
+ reference(ref) {
7294
+ if (!CREDENTIAL_REF.test(ref)) throw new CatalogueError(`"${ref}" is not a credential name (letters, digits and "_", not starting with a digit)`, "input");
7295
+ return ref;
7296
+ }
7297
+ needStore() {
7298
+ const store = this.store();
7299
+ if (store === void 0) throw new CatalogueError("this profile has no credential store, so keys cannot be kept from here", "unavailable");
7300
+ return store;
7301
+ }
6760
7302
  /** @throws {CatalogueError} when no usable catalogue has the name. */
6761
7303
  get(name) {
6762
7304
  const entry = this.resolved().find((candidate) => candidate.source.name.trim() === name);
@@ -6853,8 +7395,10 @@ const Config = z.object({
6853
7395
  catalogues: z.array(z.object({
6854
7396
  name: z.string().required(),
6855
7397
  baseUrl: z.string().required(),
7398
+ apiKeyRef: z.string().default(""),
6856
7399
  apiKey: z.string().default("")
6857
7400
  })).default([]).volatile(),
7401
+ authoringTools: z.dict(z.dict(z.boolean())).default({}).volatile(),
6858
7402
  catalogueMaxBytes: z.number().min(1024).default(268435456),
6859
7403
  catalogueTrashDays: z.number().min(0).default(30),
6860
7404
  importMaxUploadBytes: z.number().min(1024).default(104857600),
@@ -6878,27 +7422,34 @@ function apply(ctx, config) {
6878
7422
  const helper = childSamplingOf(id);
6879
7423
  if (helper !== void 0) return helper;
6880
7424
  const session = roleplaySessionOf(id);
6881
- return session === void 0 ? void 0 : {
6882
- temperature: liveSettings(sessionFolder(join(root.path, "sessions"), session)).sampling.master,
7425
+ if (session === void 0) return void 0;
7426
+ const { sampling } = liveSettings(sessionFolder(join(root.path, "sessions"), session));
7427
+ return {
7428
+ temperature: sampling.master,
7429
+ ...sharedSamplingOf(sampling),
6883
7430
  priority: "foreground"
6884
7431
  };
6885
7432
  }), "roleplay: request controls");
6886
7433
  });
6887
7434
  ctx.effect(() => useChildReasoning(config.childReasoning), "roleplay: helper thinking level");
6888
7435
  const root = new RoleplayRoot(ctx, config.rootPath);
6889
- new RoleplayOrchestration(ctx);
7436
+ root.start();
7437
+ const orchestration = new RoleplayOrchestration(ctx);
6890
7438
  const worlds = new WorldCatalog(ctx, root);
6891
7439
  const prompts = new PromptLibrary(ctx, root);
6892
7440
  prompts.bootstrap();
7441
+ const edited = prompts.problems();
7442
+ if (edited.length > 0) ctx.logger.error(`these prompt files in ${prompts.directory} cannot be used (fix them, or delete a file to restore the original):\n${edited.map((problem) => `${problem.path}: ${problem.message}`).join("\n")}`);
6893
7443
  installFirstPartyPacks(root.path);
6894
7444
  const languages = new AuthoringLanguages(ctx, () => join(root.path, "worlds"));
7445
+ const authoringTools = new AuthoringTools(ctx, () => config.authoringTools.get());
6895
7446
  const agent = new AgentSessions(agentServicesOf(ctx), () => root.path);
6896
7447
  const authoring = new AuthoringSessions(agentServicesOf(ctx), () => root.path, prompts, languages);
6897
7448
  const presetAuthoring = new PresetAuthoringSessions(agentServicesOf(ctx), () => root.path, prompts, languages);
6898
7449
  const lorebookAuthoring = new LorebookAuthoringSessions(agentServicesOf(ctx), () => root.path, prompts, languages);
6899
7450
  const doctors = new DoctorSessions(agentServicesOf(ctx), () => root.path, prompts);
6900
7451
  const imports = new ImportStore(() => root.path);
6901
- new RoleplayImport(ctx, {
7452
+ const roleplayImport = new RoleplayImport(ctx, {
6902
7453
  maxUploadBytes: config.importMaxUploadBytes,
6903
7454
  concurrency: config.importConcurrency,
6904
7455
  reasoning: config.importReasoning,
@@ -6911,11 +7462,12 @@ function apply(ctx, config) {
6911
7462
  clockMode: (id) => ctx.roleplayState.openSession(join(root.path, "sessions"), id).clock.get()?.mode,
6912
7463
  pendingConsolidation: (id) => ctx.roleplayState.openSession(join(root.path, "sessions"), id).consolidation.pending().length,
6913
7464
  vectors: (id) => vectorStatus(ctx.roleplayState.openSession(join(root.path, "sessions"), id)),
6914
- reflection: (id) => reflectionStatus(ctx.roleplayState.openSession(join(root.path, "sessions"), id), ctx.roleplayOrchestration.reflecting(chatSessionId(id))),
7465
+ reflection: (id) => reflectionStatus(ctx.roleplayState.openSession(join(root.path, "sessions"), id), orchestration.reflecting(chatSessionId(id))),
6915
7466
  activity: (id) => readActivity(ctx.roleplayState.openSession(join(root.path, "sessions"), id)),
6916
7467
  usage: (id) => readUsage(ctx.roleplayState.openSession(join(root.path, "sessions"), id)),
6917
7468
  interventions: (id) => readInterventions(ctx.roleplayState.openSession(join(root.path, "sessions"), id))
6918
7469
  };
7470
+ const staging = new ImportStaging();
6919
7471
  const purgeChat = purgeOf(ctx, config.sessionStorePath);
6920
7472
  const deps = {
6921
7473
  worlds,
@@ -6931,16 +7483,24 @@ function apply(ctx, config) {
6931
7483
  authoring: presetAuthoring,
6932
7484
  importMessage: narrationImportMessage,
6933
7485
  maxUploadBytes: config.importMaxUploadBytes,
6934
- playing: (id) => ctx.roleplayOrchestration.playing(chatSessionId(id))
7486
+ staging,
7487
+ playing: (id) => orchestration.playing(chatSessionId(id))
6935
7488
  });
6936
7489
  const lorebookLibrary = new Lorebooks({
6937
7490
  root: () => root.path,
6938
7491
  authoring: lorebookAuthoring,
6939
7492
  importMessage: lorebookImportMessage,
6940
- maxUploadBytes: config.importMaxUploadBytes
7493
+ maxUploadBytes: config.importMaxUploadBytes,
7494
+ staging,
7495
+ session: (id) => {
7496
+ const sessions = join(root.path, "sessions");
7497
+ if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);
7498
+ return ctx.roleplayState.openSession(sessions, id);
7499
+ },
7500
+ playing: (id) => orchestration.playing(chatSessionId(id))
6941
7501
  });
6942
7502
  const catalogue = new Catalogue({
6943
- sources: new Sources(() => config.catalogues.get()),
7503
+ sources: new Sources(() => config.catalogues.get(), () => ctx.get("credentials")),
6944
7504
  worlds,
6945
7505
  maxBytes: () => config.catalogueMaxBytes,
6946
7506
  maxCardBytes: () => config.importMaxUploadBytes,
@@ -6948,8 +7508,16 @@ function apply(ctx, config) {
6948
7508
  problem: (message) => {
6949
7509
  ctx.logger.warn(message);
6950
7510
  },
7511
+ stage: (kind, file, name) => staging.stage(kind, file, name),
6951
7512
  importPreset: async (file, title, language) => await presetLibrary.importTitled(title, file, language),
6952
7513
  importLorebook: async (file, title, language) => await lorebookLibrary.importTitled(title, file, language),
7514
+ previewCard: async (file, name) => await imports.create(readCard(file, name), isPng(file) ? pictureOf(file) : void 0),
7515
+ startCard: async (id, choices, language) => await startImport({
7516
+ store: imports,
7517
+ worlds,
7518
+ authoring,
7519
+ chatTitle: (title) => `Authoring ${title}`
7520
+ }, id, choices, language),
6953
7521
  importCard: async (file, name, language) => {
6954
7522
  const preview = await imports.create(readCard(file, name), isPng(file) ? pictureOf(file) : void 0);
6955
7523
  return await startImport({
@@ -7014,7 +7582,26 @@ function apply(ctx, config) {
7014
7582
  uploadPreset: (worldId, file, name, language) => uploadPreset({
7015
7583
  worlds,
7016
7584
  authoring
7017
- }, worldId, file, name, language)
7585
+ }, worldId, file, name, language),
7586
+ stage: (kind, file, name) => staging.stage(kind, file, name),
7587
+ discardStaged: (id) => {
7588
+ staging.discard(id);
7589
+ },
7590
+ applyStagedVerbatim: async (worldId, choice) => {
7591
+ const { file, name } = staging.choose("preset", choice);
7592
+ const applied = await applyPresetVerbatim({ worlds }, worldId, file, name);
7593
+ staging.discard(choice.id);
7594
+ return applied;
7595
+ },
7596
+ uploadStaged: async (worldId, choice, language) => {
7597
+ const { file, name } = staging.choose("preset", choice);
7598
+ const uploaded = await uploadPreset({
7599
+ worlds,
7600
+ authoring
7601
+ }, worldId, file, name, language);
7602
+ staging.discard(choice.id);
7603
+ return uploaded;
7604
+ }
7018
7605
  },
7019
7606
  worldCharacters: (worldId) => worldCharacters(worlds, worldId),
7020
7607
  avatars: {
@@ -7220,6 +7807,11 @@ function apply(ctx, config) {
7220
7807
  }
7221
7808
  }
7222
7809
  });
7810
+ return {
7811
+ orchestration,
7812
+ authoringTools,
7813
+ roleplayImport
7814
+ };
7223
7815
  }
7224
7816
  /** The folder of a session whose images are listed. @throws {SessionNotFoundError} when there is no such session. */
7225
7817
  function galleryFolder(sessionsDir, id) {