@dsh-agentic-roleplay/core 0.3.4 → 0.3.6

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 (40) hide show
  1. package/lib/authoring.js +5 -3
  2. package/lib/client.js +3260 -493
  3. package/lib/client.js.map +1 -1
  4. package/lib/{deliver-CpZOxBX5.js → deliver-BBgciEEK.js} +3 -2
  5. package/lib/doctor.js +3 -3
  6. package/lib/{gallery-CtFDL22W.js → gallery-DIEgETzU.js} +2 -2
  7. package/lib/generator-DJ48HxPI.js +145 -0
  8. package/lib/{hooks-KTCR3fNJ.js → hooks-DkwFGtNH.js} +3 -3
  9. package/lib/images.js +4 -3
  10. package/lib/index.js +889 -52
  11. package/lib/language-BgyxtB2h.js +38 -0
  12. package/lib/{generator-B6FxlKOV.js → library-9JB9zw5a.js} +2 -143
  13. package/lib/{language-DWVwi1R7.js → load-CVwJjIJ5.js} +11 -45
  14. package/lib/lorebook-author-tools-Bj31z1cu.js +619 -0
  15. package/lib/lorebook-authoring.js +67 -0
  16. package/lib/orchestration.js +22 -14
  17. package/lib/pack-jail-2XztyYAX.js +1980 -0
  18. package/lib/{packs-BYjrAen6.js → packs-xHRCcGdb.js} +3 -29
  19. package/lib/{presenter-agent-CiEVKcjJ.js → presenter-agent-DnNEG_Mn.js} +4 -3
  20. package/lib/preset-D0FMSeZ9.js +59 -0
  21. package/lib/preset-author-tools-BxycmoAr.js +276 -0
  22. package/lib/preset-authoring.js +53 -0
  23. package/lib/presets-gkBWAiVb.js +374 -0
  24. package/lib/{reflection-waxFg1x-.js → reflection-q0UpwXlx.js} +130 -8
  25. package/lib/{pack-jail-CybSNzxr.js → tools-Dy1fgP6B.js} +454 -2303
  26. package/package.json +4 -2
  27. package/prompts/en/import/lorebook.md +7 -0
  28. package/prompts/en/lorebook/persona.md +1 -0
  29. package/prompts/en/lorebook/procedure.md +1 -0
  30. package/prompts/en/lorebook/welcome.md +1 -0
  31. package/prompts/en/preset/persona.md +1 -0
  32. package/prompts/en/preset/procedure.md +1 -0
  33. package/prompts/en/preset/welcome.md +1 -0
  34. package/prompts/zh/import/lorebook.md +7 -0
  35. package/prompts/zh/lorebook/persona.md +1 -0
  36. package/prompts/zh/lorebook/procedure.md +1 -0
  37. package/prompts/zh/lorebook/welcome.md +1 -0
  38. package/prompts/zh/preset/persona.md +1 -0
  39. package/prompts/zh/preset/procedure.md +1 -0
  40. package/prompts/zh/preset/welcome.md +1 -0
package/lib/index.js CHANGED
@@ -1,15 +1,21 @@
1
1
  import { n as chatSessionId, r as roleplaySessionOf } from "./access-EbNdZFbk.js";
2
- import { $ as populateCalendar, $t as readCard, A as worldEntityImageFile, At as loadVariables, B as translateMessage, Bt as parseWorldFile, C as readWorldEditor, Ct as subfolders, D as uploadWorldCharacterPortrait, Dt as readWorldPrompt, E as replaceFile$1, Et as listWorldPrompts, F as loadWorldParts, Ft as IMPORT_FOLDER, G as authoringChatSessionId, Gt as parseLoreEdit, Ht as InvalidEditProblems, I as PRESET_FILE, It as ImportNotFoundError, Jt as parseThingEdit, K as languageOfDocuments, Kt as parsePlaceEdit, L as presetMessage, Lt as ImportStore, Mt as variableProblems, Nt as CHARACTER_FILE_NAME, O as uploadWorldEntityImage, Ot as writeWorldPrompt, Pt as parseCharacterFile, Q as loadValidatedWorld, Qt as pictureOf, Rt as parseChoices, S as generateWorldEntityImage, St as loadCharacters, T as removeWorldTrigger, Tt as deleteWorldPrompt, Ut as parseCharacterEdit, Vt as parseWorldInfoEdit, Wt as parseFactionEdit, X as guardedLookup, Xt as ImportCardError, Y as markReady, Yt as IMPORT_COMMAND, Z as vetUrl, Zt as isPng, _ as editWorldPlots$1, _t as loadCalendar, a as deleteWorldPackFile, at as populateKnowledge, b as entityFolder, bt as loadItems, c as createAuthoredEntity, ct as populateRoutines, dt as routineProblems, en as DICE_COMPARISONS, et as populateCharacters, f as editWorldCharacter$1, ft as TRIGGERS_FILE_NAME, g as editWorldPlace$1, gt as CALENDAR_FILE_NAME, h as editWorldNarrationVoice, ht as parseDiceFile, it as populateItems, j as writeWorldTrigger, jt as parseVariablesFile, k as worldCharacterPortraitFile, kt as VARIABLES_FILE_NAME, l as deleteAuthoredEntity, lt as populateTriggers, m as editWorldLore$1, mt as loadDice, n as packFileProblem, nn as DICE_RESULTS, nt as populateDice, ot as populateLocations, p as editWorldFaction$1, pt as DICE_FILE_NAME, q as readWorldDocuments, qt as parseRelationEdit, rt as populateFactions, st as populateLore, t as MAX_PACK_TEXT, tn as DICE_READINGS, tt as populateClock, u as readAuthoredEntityDocument, ut as populateVariables, v as editWorldRelation$1, vt as parseCalendarFile, w as readWorldTrigger, x as generateWorldCharacterPortrait, xt as CHARACTERS_DIR, y as editWorldThing$1, yt as loadLocations, z as readPreset, zt as WORLD_FILE_NAME } from "./pack-jail-CybSNzxr.js";
3
- 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-BYjrAen6.js";
4
- import { c as readTimeline, i as reflectionStatus, l as pathTo, o as TimelineError, u as defaultBoundaries } from "./reflection-waxFg1x-.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
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 { A as WorldNotFoundError, D as ReflectionRefusedError, E as InvalidWorldError, O as SessionArchivedError, T as InvalidStartError, c as parsePlotsFile, d as errorMessage, g as copyWorldPrompts, h as PromptLibrary, k as SessionNotFoundError, l as plotReferenceProblems, p as formatIssue, u as readDocument$1, v as languageOf, w as AgentUnavailableError } from "./language-DWVwi1R7.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-CpZOxBX5.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
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
9
  import { r as childSamplingOf } from "./child-CFjnaTZt.js";
10
- import { T as uniqueKey, a as uploadReferenceImage, m as sceneImagePath, o as addToLibrary, p as referenceImagePath, t as generateReferenceImage, u as inheritImages, w as slug } from "./generator-B6FxlKOV.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";
11
15
  import { t as doctorChatSessionId } from "./doctor-chat-ByDfCMeo.js";
12
- import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-CtFDL22W.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";
13
19
  import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
14
20
  import { cpSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
15
21
  import { createHash, randomBytes, randomUUID } from "node:crypto";
@@ -379,6 +385,7 @@ async function createWorld(catalog, input) {
379
385
  if (folder === "" || !FOLDER.test(folder) || folder === "." || folder === ".." || /[. ]$/.test(folder)) problems.push("folder must be 1–100 letters, numbers, spaces, dots, underscores or hyphens; it cannot end in a dot or space");
380
386
  if (name === "") problems.push("world name is required");
381
387
  if (name.length > 200) problems.push("world name must be at most 200 characters");
388
+ if (input.preset !== void 0 && input.preset !== "" && !isPresetName(input.preset)) problems.push("preset must be the name of a preset in the library");
382
389
  if (problems.length > 0) throw new InvalidEditProblems(problems);
383
390
  await mkdir(catalog.directory, { recursive: true });
384
391
  const directory = join(catalog.directory, folder);
@@ -394,7 +401,8 @@ async function createWorld(catalog, input) {
394
401
  id,
395
402
  name,
396
403
  description: "",
397
- metadata: { tags: [] }
404
+ metadata: { tags: [] },
405
+ ...input.preset === void 0 || input.preset === "" ? {} : { preset: input.preset }
398
406
  }, null, 2) + "\n", {
399
407
  flag: "wx",
400
408
  mode: 420
@@ -498,7 +506,7 @@ async function uploadPreset(deps, worldId, file, name, language) {
498
506
  if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
499
507
  const preset = readPreset(file, name);
500
508
  await mkdir(join(world.directory, IMPORT_FOLDER), { recursive: true });
501
- await writeFile(join(world.directory, IMPORT_FOLDER, PRESET_FILE), file);
509
+ await writeFile(join(world.directory, IMPORT_FOLDER, PRESET_FILE$1), file);
502
510
  const chatSessionId = await deps.authoring.ensure(world.summary.id, world.summary.name, `Authoring ${world.summary.name}`, language);
503
511
  let failure;
504
512
  try {
@@ -568,6 +576,190 @@ var AuthoringSessions = class {
568
576
  }
569
577
  };
570
578
  //#endregion
579
+ //#region src/host/agent/preset-authoring-sessions.ts
580
+ const PRESET_AUTHORING_PROJECT_TITLE = "Preset Authoring";
581
+ const PRESET_AUTHORING_PRESET = "preset-authoring";
582
+ /** Creates or reopens the dedicated authoring chat of a library preset, and speaks in it for the person when asked to. */
583
+ var PresetAuthoringSessions = class {
584
+ services;
585
+ roleplayRoot;
586
+ prompts;
587
+ languages;
588
+ constructor(services, roleplayRoot, prompts, languages) {
589
+ this.services = services;
590
+ this.roleplayRoot = roleplayRoot;
591
+ this.prompts = prompts;
592
+ this.languages = languages;
593
+ }
594
+ async ensure(name, title, language) {
595
+ this.languages.set(`preset:${name}`, language);
596
+ const services = this.services();
597
+ const projectPath = join(this.roleplayRoot(), "presets");
598
+ const project = await services.registry.create(projectPath, PRESET_AUTHORING_PROJECT_TITLE);
599
+ const sessionId = presetChatSessionId(name);
600
+ const stored = !project.sessionIds.includes(sessionId) && await isStored(services.persistence, sessionId);
601
+ if (!project.sessionIds.includes(sessionId) && !stored) {
602
+ if (services.persistence === void 0) throw new AgentUnavailableError("this DSH profile cannot store the opening of an authoring chat");
603
+ await storeAuthoringOpening(services.persistence, {
604
+ id: sessionId,
605
+ cwd: project.path,
606
+ agentPreset: PRESET_AUTHORING_PRESET
607
+ }, this.prompts.text("preset/welcome", this.languages.get(`preset:${name}`), { preset: title }));
608
+ }
609
+ return await ensureAgentChat(services, {
610
+ projectPath,
611
+ projectTitle: PRESET_AUTHORING_PROJECT_TITLE,
612
+ sessionId,
613
+ agentPreset: PRESET_AUTHORING_PRESET,
614
+ title: `Preset ${title}`,
615
+ renameExisting: true
616
+ }, project);
617
+ }
618
+ async send(sessionId, text) {
619
+ await this.services().controller.prompt({
620
+ requestId: randomUUID(),
621
+ sessionId,
622
+ mode: "queue",
623
+ content: [{
624
+ type: "text",
625
+ text
626
+ }]
627
+ }, new AbortController().signal);
628
+ }
629
+ };
630
+ //#endregion
631
+ //#region src/host/agent/lorebook-authoring-sessions.ts
632
+ const LOREBOOK_AUTHORING_PROJECT_TITLE = "Lorebook Authoring";
633
+ const LOREBOOK_AUTHORING_PRESET = "lorebook-authoring";
634
+ /** Creates or reopens the dedicated authoring chat of a library lorebook, and speaks in it for the person when asked to. */
635
+ var LorebookAuthoringSessions = class {
636
+ services;
637
+ roleplayRoot;
638
+ prompts;
639
+ languages;
640
+ constructor(services, roleplayRoot, prompts, languages) {
641
+ this.services = services;
642
+ this.roleplayRoot = roleplayRoot;
643
+ this.prompts = prompts;
644
+ this.languages = languages;
645
+ }
646
+ async ensure(name, title, language) {
647
+ this.languages.set(`lorebook:${name}`, language);
648
+ const services = this.services();
649
+ const projectPath = join(this.roleplayRoot(), "lorebooks");
650
+ const project = await services.registry.create(projectPath, LOREBOOK_AUTHORING_PROJECT_TITLE);
651
+ const sessionId = lorebookChatSessionId(name);
652
+ const stored = !project.sessionIds.includes(sessionId) && await isStored(services.persistence, sessionId);
653
+ if (!project.sessionIds.includes(sessionId) && !stored) {
654
+ if (services.persistence === void 0) throw new AgentUnavailableError("this DSH profile cannot store the opening of an authoring chat");
655
+ await storeAuthoringOpening(services.persistence, {
656
+ id: sessionId,
657
+ cwd: project.path,
658
+ agentPreset: LOREBOOK_AUTHORING_PRESET
659
+ }, this.prompts.text("lorebook/welcome", this.languages.get(`lorebook:${name}`), { lorebook: title }));
660
+ }
661
+ return await ensureAgentChat(services, {
662
+ projectPath,
663
+ projectTitle: LOREBOOK_AUTHORING_PROJECT_TITLE,
664
+ sessionId,
665
+ agentPreset: LOREBOOK_AUTHORING_PRESET,
666
+ title: `Lorebook ${title}`,
667
+ renameExisting: true
668
+ }, project);
669
+ }
670
+ async send(sessionId, text) {
671
+ await this.services().controller.prompt({
672
+ requestId: randomUUID(),
673
+ sessionId,
674
+ mode: "queue",
675
+ content: [{
676
+ type: "text",
677
+ text
678
+ }]
679
+ }, new AbortController().signal);
680
+ }
681
+ };
682
+ //#endregion
683
+ //#region src/host/lorebooks/service.ts
684
+ /** The lorebook library. Refusals are plain `Error`s with the reason. */
685
+ var Lorebooks = class {
686
+ deps;
687
+ constructor(deps) {
688
+ this.deps = deps;
689
+ }
690
+ get maxUploadBytes() {
691
+ return this.deps.maxUploadBytes;
692
+ }
693
+ async list() {
694
+ return (await listLorebooks(this.deps.root())).map((book) => book.summary);
695
+ }
696
+ async read(name) {
697
+ const book = await loadLorebook(this.deps.root(), name);
698
+ return {
699
+ summary: book.summary,
700
+ entries: entriesOf(book)
701
+ };
702
+ }
703
+ async create(request) {
704
+ return (await createLorebook(this.deps.root(), request)).summary;
705
+ }
706
+ async updateInfo(name, change) {
707
+ return (await updateLorebookInfo(this.deps.root(), name, change)).summary;
708
+ }
709
+ async writeEntry(name, entry) {
710
+ return (await writeLorebookEntry(this.deps.root(), name, entry)).summary;
711
+ }
712
+ async removeEntry(name, id) {
713
+ return (await deleteLorebookEntry(this.deps.root(), name, id)).summary;
714
+ }
715
+ async remove(name) {
716
+ await deleteLorebook(this.deps.root(), name);
717
+ }
718
+ /** Opens the authoring chat of a lorebook. */
719
+ async author(name, language) {
720
+ const loaded = await loadLorebook(this.deps.root(), name);
721
+ return { chatSessionId: await this.deps.authoring.ensure(name, loaded.summary.title, language) };
722
+ }
723
+ /** Like `importFile`, under a name made from the title that is not yet taken. */
724
+ async importTitled(title, file, language) {
725
+ const base = title.normalize("NFKD").replace(/[^A-Za-z0-9_-]+/g, "-").replace(/^[-_]+|[-_]+$/g, "").slice(0, 56) || "lorebook";
726
+ const taken = new Set((await listLorebooks(this.deps.root())).map((book) => book.summary.name));
727
+ let name = base;
728
+ 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));
730
+ }
731
+ /** 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
+ async importFile(name, file, language, title) {
733
+ if (!isLorebookName(name)) throw new Error(`"${name}" is not a usable lorebook name (letters, digits, "-" and "_", up to 64)`);
734
+ const uploaded = readLorebook(file, name);
735
+ const root = this.deps.root();
736
+ const directory = await reserveLorebook(root, name, title ?? uploaded.name);
737
+ try {
738
+ await mkdir(join(directory, IMPORT_FOLDER), { recursive: true });
739
+ await writeFile(join(directory, LOREBOOK_UPLOAD), file);
740
+ } catch (error) {
741
+ await rm(lorebookDirectory(root, name), {
742
+ recursive: true,
743
+ force: true
744
+ });
745
+ throw error;
746
+ }
747
+ const chatSessionId = await this.deps.authoring.ensure(name, title ?? uploaded.name, language);
748
+ let failure;
749
+ try {
750
+ await this.deps.authoring.send(chatSessionId, this.deps.importMessage());
751
+ } catch (problem) {
752
+ failure = problem instanceof Error ? problem.message : String(problem);
753
+ }
754
+ return {
755
+ name,
756
+ chatSessionId,
757
+ started: failure === void 0,
758
+ ...failure === void 0 ? {} : { failure }
759
+ };
760
+ }
761
+ };
762
+ //#endregion
571
763
  //#region src/host/agent/doctor-sessions.ts
572
764
  const DOCTOR_PROJECT_TITLE = "Session Doctor";
573
765
  const DOCTOR_AGENT_PRESET = "session-doctor";
@@ -617,6 +809,8 @@ var RoleplayOrchestration = class extends Service {
617
809
  halt = () => Promise.resolve();
618
810
  /** Starts a reflection of a chat's characters on what they have taken in, in the background; there while the orchestration is. */
619
811
  reflect = () => Promise.reject(/* @__PURE__ */ new Error("the orchestration is not running"));
812
+ /** Whether a turn of the chat is being played; there while the orchestration is. */
813
+ playing = () => false;
620
814
  /** Whether a reflection of the chat is running; there while the orchestration is. */
621
815
  reflecting = () => false;
622
816
  /** What the story's turns are and taking the story back to one; there while the orchestration is. */
@@ -1063,6 +1257,369 @@ async function readBinaryBody(req, limit) {
1063
1257
  if (size === 0) throw new HttpError(400, "the upload is empty");
1064
1258
  return Buffer.concat(chunks);
1065
1259
  }
1260
+ //#endregion
1261
+ //#region src/host/presets/service.ts
1262
+ /** The story's prompts cannot change right now. */
1263
+ var PresetBusyError = class extends Error {};
1264
+ /** The preset library and the presets of stories. Refusals are plain `Error`s with the reason; unknown stories and worlds are not-found errors. */
1265
+ var Presets = class {
1266
+ deps;
1267
+ constructor(deps) {
1268
+ this.deps = deps;
1269
+ }
1270
+ get maxUploadBytes() {
1271
+ return this.deps.maxUploadBytes;
1272
+ }
1273
+ list() {
1274
+ return listPresets(this.deps.root()).map((entry) => entry.summary);
1275
+ }
1276
+ /** A preset with the text of each prompt it carries, keyed `<language>/<id>`. */
1277
+ read(name) {
1278
+ const loaded = loadPreset(this.deps.root(), name);
1279
+ return {
1280
+ summary: loaded.summary,
1281
+ prompts: Object.fromEntries([...loaded.files].map(([path, text]) => [path.slice(0, -3), text]))
1282
+ };
1283
+ }
1284
+ async saveFromWorld(request) {
1285
+ const directory = await this.deps.worldDirectory(request.fromWorld);
1286
+ if (directory === void 0) throw new WorldNotFoundError(`there is no world with id "${request.fromWorld}"`);
1287
+ return (await savePresetFromWorld(this.deps.root(), directory, request)).summary;
1288
+ }
1289
+ /** Makes a preset from a world's own prose prompts, or from the shipped ones as a starting point when no world is given. */
1290
+ async create(request) {
1291
+ if (request.fromWorld !== void 0) return await this.saveFromWorld({
1292
+ ...request,
1293
+ fromWorld: request.fromWorld
1294
+ });
1295
+ return (await createPresetFromShipped(this.deps.root(), request)).summary;
1296
+ }
1297
+ async updateInfo(name, change) {
1298
+ return (await updatePresetInfo(this.deps.root(), name, change)).summary;
1299
+ }
1300
+ /** Writes the person's own text of a prompt; `undefined` takes the preset's version out. */
1301
+ 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}"`);
1304
+ if (!id.startsWith("roleplay/")) throw new Error(`"${id}" is not a prompt of the story`);
1305
+ if (text === void 0) await deleteWorldPrompt(directory, language, id);
1306
+ else await writeWorldPrompt(directory, language, id, text);
1307
+ return loadPreset(this.deps.root(), name).summary;
1308
+ }
1309
+ /** Like `importFile`, under a name made from the title that is not yet taken. */
1310
+ async importTitled(title, file, language) {
1311
+ const base = title.normalize("NFKD").replace(/[^A-Za-z0-9_-]+/g, "-").replace(/^[-_]+|[-_]+$/g, "").slice(0, 56) || "preset";
1312
+ const taken = new Set(listPresets(this.deps.root()).map((entry) => entry.summary.name));
1313
+ let name = base;
1314
+ 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));
1316
+ }
1317
+ /** Opens the authoring chat of a preset. */
1318
+ async author(name, language) {
1319
+ const loaded = loadPreset(this.deps.root(), name);
1320
+ return { chatSessionId: await this.deps.authoring.ensure(name, loaded.summary.title, language) };
1321
+ }
1322
+ /** Keeps an uploaded SillyTavern preset in a new library preset and has its authoring chat turn it into prompts. @throws {ImportCardError} when the file is not a preset. */
1323
+ async importFile(name, file, language, title) {
1324
+ const uploaded = readPreset(file, name);
1325
+ const root = this.deps.root();
1326
+ const directory = await reservePreset(root, name, title ?? uploaded.name);
1327
+ try {
1328
+ await mkdir(join(directory, IMPORT_FOLDER), { recursive: true });
1329
+ await writeFile(join(directory, IMPORT_FOLDER, PRESET_FILE), file);
1330
+ } catch (error) {
1331
+ await deletePreset(root, name);
1332
+ throw error;
1333
+ }
1334
+ const chatSessionId = await this.deps.authoring.ensure(name, title ?? uploaded.name, language);
1335
+ let failure;
1336
+ try {
1337
+ await this.deps.authoring.send(chatSessionId, this.deps.importMessage());
1338
+ } catch (problem) {
1339
+ failure = problem instanceof Error ? problem.message : String(problem);
1340
+ }
1341
+ return {
1342
+ name,
1343
+ chatSessionId,
1344
+ started: failure === void 0,
1345
+ ...failure === void 0 ? {} : { failure }
1346
+ };
1347
+ }
1348
+ async remove(name) {
1349
+ await deletePreset(this.deps.root(), name);
1350
+ }
1351
+ status(session) {
1352
+ return presetStatus(this.deps.root(), this.folder(session));
1353
+ }
1354
+ /** Puts the named preset into a story, or takes the story's preset out when no name is given. */
1355
+ apply(session, name) {
1356
+ const folder = this.folder(session);
1357
+ if (this.deps.playing(session)) throw new PresetBusyError("a turn is being played; change the preset when it is over");
1358
+ return { files: switchPreset(this.deps.root(), folder, name) };
1359
+ }
1360
+ folder(id) {
1361
+ const sessions = `${this.deps.root()}/sessions`;
1362
+ if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);
1363
+ return sessionFolder(sessions, id);
1364
+ }
1365
+ };
1366
+ //#endregion
1367
+ //#region src/host/presets/routes.ts
1368
+ /** Not found is 404 and a request the library refuses is 422 with its reason; anything else is a fault. */
1369
+ function failure$1(res, error) {
1370
+ if (error instanceof SessionNotFoundError || error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
1371
+ if (error instanceof PresetBusyError) return sendError(res, 409, error.message);
1372
+ if (error instanceof Error) return sendError(res, 422, error.message);
1373
+ throw error;
1374
+ }
1375
+ 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
+ };
1384
+ }
1385
+ function presetRoutes(api) {
1386
+ return {
1387
+ "/presets": {
1388
+ GET: async (_req, res) => {
1389
+ try {
1390
+ sendJson(res, 200, api.list());
1391
+ } catch (error) {
1392
+ failure$1(res, error);
1393
+ }
1394
+ },
1395
+ POST: async (req, res) => {
1396
+ const { name, title, description, sampling, fromWorld } = await readJsonBody(req);
1397
+ if (typeof name !== "string" || name === "") return sendError(res, 400, "\"name\" is required");
1398
+ if (fromWorld !== void 0 && (typeof fromWorld !== "string" || fromWorld === "")) return sendError(res, 400, "\"fromWorld\" must be a world id, or left out to start from the shipped prompts");
1399
+ if (title !== void 0 && typeof title !== "string" || description !== void 0 && typeof description !== "string") return sendError(res, 400, "\"title\" and \"description\" must be text");
1400
+ const given = samplingOf(sampling);
1401
+ if (typeof given === "string") return sendError(res, 400, given);
1402
+ try {
1403
+ sendJson(res, 201, await api.create({
1404
+ name,
1405
+ ...fromWorld === void 0 ? {} : { fromWorld },
1406
+ ...title === void 0 ? {} : { title },
1407
+ ...description === void 0 ? {} : { description },
1408
+ sampling: given
1409
+ }));
1410
+ } catch (error) {
1411
+ failure$1(res, error);
1412
+ }
1413
+ }
1414
+ },
1415
+ "/presets/item": {
1416
+ GET: async (_req, res, url) => {
1417
+ try {
1418
+ sendJson(res, 200, api.read(url.searchParams.get("name") ?? ""));
1419
+ } catch (error) {
1420
+ failure$1(res, error);
1421
+ }
1422
+ },
1423
+ PUT: async (req, res, url) => {
1424
+ const { title, description, sampling } = await readJsonBody(req);
1425
+ if (title !== void 0 && typeof title !== "string" || description !== void 0 && typeof description !== "string") return sendError(res, 400, "\"title\" and \"description\" must be text");
1426
+ const given = sampling === void 0 ? void 0 : samplingOf(sampling);
1427
+ if (typeof given === "string") return sendError(res, 400, given);
1428
+ try {
1429
+ sendJson(res, 200, await api.updateInfo(url.searchParams.get("name") ?? "", {
1430
+ ...title === void 0 ? {} : { title },
1431
+ ...description === void 0 ? {} : { description },
1432
+ ...given === void 0 ? {} : { sampling: given }
1433
+ }));
1434
+ } catch (error) {
1435
+ failure$1(res, error);
1436
+ }
1437
+ },
1438
+ DELETE: async (_req, res, url) => {
1439
+ try {
1440
+ await api.remove(url.searchParams.get("name") ?? "");
1441
+ res.statusCode = 204;
1442
+ res.end();
1443
+ } catch (error) {
1444
+ failure$1(res, error);
1445
+ }
1446
+ }
1447
+ },
1448
+ "/presets/prompt": {
1449
+ PUT: async (req, res, url) => {
1450
+ const { text } = await readJsonBody(req);
1451
+ if (typeof text !== "string" || text.trim() === "") return sendError(res, 400, "\"text\" is required");
1452
+ try {
1453
+ sendJson(res, 200, await api.writePrompt(url.searchParams.get("name") ?? "", languageOf(url.searchParams.get("language") ?? ""), url.searchParams.get("id") ?? "", text));
1454
+ } catch (error) {
1455
+ failure$1(res, error);
1456
+ }
1457
+ },
1458
+ DELETE: async (_req, res, url) => {
1459
+ try {
1460
+ sendJson(res, 200, await api.writePrompt(url.searchParams.get("name") ?? "", languageOf(url.searchParams.get("language") ?? ""), url.searchParams.get("id") ?? "", void 0));
1461
+ } catch (error) {
1462
+ failure$1(res, error);
1463
+ }
1464
+ }
1465
+ },
1466
+ "/presets/authoring": { POST: async (req, res, url) => {
1467
+ const { language } = await readJsonBody(req);
1468
+ if (language !== void 0 && typeof language !== "string") return sendError(res, 400, "\"language\" must be text");
1469
+ try {
1470
+ sendJson(res, 200, await api.author(url.searchParams.get("name") ?? "", language === void 0 ? void 0 : languageOf(language)));
1471
+ } catch (error) {
1472
+ failure$1(res, error);
1473
+ }
1474
+ } },
1475
+ "/presets/import": { POST: async (req, res, url) => {
1476
+ const language = url.searchParams.get("language");
1477
+ try {
1478
+ sendJson(res, 200, await api.importFile(url.searchParams.get("name") ?? "", await readBinaryBody(req, api.maxUploadBytes), language === null ? void 0 : languageOf(language)));
1479
+ } catch (error) {
1480
+ failure$1(res, error);
1481
+ }
1482
+ } },
1483
+ "/sessions/preset": {
1484
+ GET: async (_req, res, url) => {
1485
+ try {
1486
+ sendJson(res, 200, api.status(url.searchParams.get("id") ?? ""));
1487
+ } catch (error) {
1488
+ failure$1(res, error);
1489
+ }
1490
+ },
1491
+ POST: async (req, res, url) => {
1492
+ const { name } = await readJsonBody(req);
1493
+ if (name !== void 0 && name !== null && (typeof name !== "string" || name === "")) return sendError(res, 400, "\"name\" must be a preset name, or left out to take the preset out");
1494
+ try {
1495
+ sendJson(res, 200, api.apply(url.searchParams.get("id") ?? "", typeof name === "string" ? name : void 0));
1496
+ } catch (error) {
1497
+ failure$1(res, error);
1498
+ }
1499
+ }
1500
+ }
1501
+ };
1502
+ }
1503
+ //#endregion
1504
+ //#region src/host/lorebooks/routes.ts
1505
+ /** A request the library refuses is 422 with its reason; anything else is a fault. */
1506
+ function failure(res, error) {
1507
+ if (error instanceof Error) return sendError(res, 422, error.message);
1508
+ throw error;
1509
+ }
1510
+ const texts = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string");
1511
+ /** Reads the body of an entry, or says what is wrong with it. */
1512
+ function entryOf(id, body) {
1513
+ const { title, kind, scope, knownBy, summary, body: text, related } = body;
1514
+ if (typeof title !== "string") return "\"title\" must be text";
1515
+ if (typeof kind !== "string" || !LORE_KINDS.includes(kind)) return `"kind" must be one of ${LORE_KINDS.join(", ")}`;
1516
+ if (typeof scope !== "string" || !LORE_SCOPES.includes(scope)) return `"scope" must be one of ${LORE_SCOPES.join(", ")}`;
1517
+ if (knownBy !== void 0 && !texts(knownBy)) return "\"knownBy\" must be a list of text";
1518
+ if (related !== void 0 && !texts(related)) return "\"related\" must be a list of text";
1519
+ if (summary !== void 0 && typeof summary !== "string" || text !== void 0 && typeof text !== "string") return "\"summary\" and \"body\" must be text";
1520
+ return {
1521
+ id,
1522
+ title,
1523
+ kind,
1524
+ scope,
1525
+ knownBy: knownBy?.map((entry) => entry.trim()).filter((entry) => entry !== "") ?? [],
1526
+ summary: summary ?? "",
1527
+ body: text ?? "",
1528
+ related: related ?? []
1529
+ };
1530
+ }
1531
+ function lorebookRoutes(api) {
1532
+ return {
1533
+ "/lorebooks": {
1534
+ GET: async (_req, res) => {
1535
+ try {
1536
+ sendJson(res, 200, await api.list());
1537
+ } catch (error) {
1538
+ failure(res, error);
1539
+ }
1540
+ },
1541
+ POST: async (req, res) => {
1542
+ const { name, title, description } = await readJsonBody(req);
1543
+ if (typeof name !== "string" || name === "") return sendError(res, 400, "\"name\" is required");
1544
+ if (title !== void 0 && typeof title !== "string" || description !== void 0 && typeof description !== "string") return sendError(res, 400, "\"title\" and \"description\" must be text");
1545
+ try {
1546
+ sendJson(res, 201, await api.create({
1547
+ name,
1548
+ ...title === void 0 ? {} : { title },
1549
+ ...description === void 0 ? {} : { description }
1550
+ }));
1551
+ } catch (error) {
1552
+ failure(res, error);
1553
+ }
1554
+ }
1555
+ },
1556
+ "/lorebooks/item": {
1557
+ GET: async (_req, res, url) => {
1558
+ try {
1559
+ sendJson(res, 200, await api.read(url.searchParams.get("name") ?? ""));
1560
+ } catch (error) {
1561
+ failure(res, error);
1562
+ }
1563
+ },
1564
+ PUT: async (req, res, url) => {
1565
+ const { title, description } = await readJsonBody(req);
1566
+ if (title !== void 0 && typeof title !== "string" || description !== void 0 && typeof description !== "string") return sendError(res, 400, "\"title\" and \"description\" must be text");
1567
+ try {
1568
+ sendJson(res, 200, await api.updateInfo(url.searchParams.get("name") ?? "", {
1569
+ ...title === void 0 ? {} : { title },
1570
+ ...description === void 0 ? {} : { description }
1571
+ }));
1572
+ } catch (error) {
1573
+ failure(res, error);
1574
+ }
1575
+ },
1576
+ DELETE: async (_req, res, url) => {
1577
+ try {
1578
+ await api.remove(url.searchParams.get("name") ?? "");
1579
+ res.statusCode = 204;
1580
+ res.end();
1581
+ } catch (error) {
1582
+ failure(res, error);
1583
+ }
1584
+ }
1585
+ },
1586
+ "/lorebooks/entry": {
1587
+ PUT: async (req, res, url) => {
1588
+ const entry = entryOf(url.searchParams.get("id") ?? "", await readJsonBody(req));
1589
+ if (typeof entry === "string") return sendError(res, 400, entry);
1590
+ try {
1591
+ sendJson(res, 200, await api.writeEntry(url.searchParams.get("name") ?? "", entry));
1592
+ } catch (error) {
1593
+ failure(res, error);
1594
+ }
1595
+ },
1596
+ DELETE: async (_req, res, url) => {
1597
+ try {
1598
+ sendJson(res, 200, await api.removeEntry(url.searchParams.get("name") ?? "", url.searchParams.get("id") ?? ""));
1599
+ } catch (error) {
1600
+ failure(res, error);
1601
+ }
1602
+ }
1603
+ },
1604
+ "/lorebooks/authoring": { POST: async (req, res, url) => {
1605
+ const { language } = await readJsonBody(req);
1606
+ if (language !== void 0 && typeof language !== "string") return sendError(res, 400, "\"language\" must be text");
1607
+ try {
1608
+ sendJson(res, 200, await api.author(url.searchParams.get("name") ?? "", language === void 0 ? void 0 : languageOf(language)));
1609
+ } catch (error) {
1610
+ failure(res, error);
1611
+ }
1612
+ } },
1613
+ "/lorebooks/import": { POST: async (req, res, url) => {
1614
+ const language = url.searchParams.get("language");
1615
+ try {
1616
+ sendJson(res, 200, await api.importFile(url.searchParams.get("name") ?? "", await readBinaryBody(req, api.maxUploadBytes), language === null ? void 0 : languageOf(language)));
1617
+ } catch (error) {
1618
+ failure(res, error);
1619
+ }
1620
+ } }
1621
+ };
1622
+ }
1066
1623
  /** The headers of every file of a pack. */
1067
1624
  const PACK_HEADERS = {
1068
1625
  "content-security-policy": [
@@ -1860,7 +2417,7 @@ function languageField(value) {
1860
2417
  throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
1861
2418
  }
1862
2419
  }
1863
- function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld, translation, worldCharacters, importer, avatars, worldFiles, worldEditor, sessions, packs, connection, speech, externalTools }) {
2420
+ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld, translation, worldCharacters, importer, avatars, worldFiles, worldEditor, sessions, packs, presets, lorebooks, connection, speech, externalTools }) {
1864
2421
  const routes = {
1865
2422
  "/speech/capabilities": { GET: async (_req, res) => {
1866
2423
  sendJson(res, 200, { streaming: speech.streaming() });
@@ -1887,9 +2444,11 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
1887
2444
  try {
1888
2445
  const body = await readJsonBody(req);
1889
2446
  if (typeof body.folder !== "string" || typeof body.name !== "string") return sendError(res, 400, "folder and name must be text");
2447
+ if (body.preset !== void 0 && typeof body.preset !== "string") return sendError(res, 400, "preset must be text");
1890
2448
  sendJson(res, 201, await createWorld({
1891
2449
  folder: body.folder,
1892
- name: body.name
2450
+ name: body.name,
2451
+ ...body.preset === void 0 ? {} : { preset: body.preset }
1893
2452
  }));
1894
2453
  } catch (error) {
1895
2454
  if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
@@ -1909,7 +2468,11 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
1909
2468
  const sort = url.searchParams.get("sort") === "popular" ? "popular" : "recent";
1910
2469
  try {
1911
2470
  sendJson(res, 200, await catalogue.worlds(url.searchParams.get("source") ?? "", {
1912
- kind: url.searchParams.get("kind") === "card" ? "card" : "world",
2471
+ kind: [
2472
+ "card",
2473
+ "preset",
2474
+ "lorebook"
2475
+ ].find((entry) => entry === url.searchParams.get("kind")) ?? "world",
1913
2476
  search: url.searchParams.get("search") ?? "",
1914
2477
  offset: Number.isFinite(offset) ? offset : 0,
1915
2478
  sort
@@ -1976,6 +2539,38 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
1976
2539
  return error instanceof CatalogueError ? catalogueFailure(res, error) : importFailure(res, error);
1977
2540
  }
1978
2541
  } },
2542
+ "/catalogue/convert/preset": { POST: async (req, res) => {
2543
+ const body = await readJsonBody(req);
2544
+ if (typeof body.source !== "string" || typeof body.versionId !== "string") return sendError(res, 400, "source and versionId must be text");
2545
+ if (body.title !== void 0 && typeof body.title !== "string") return sendError(res, 400, "title must be text");
2546
+ try {
2547
+ const language = languageField(body.language);
2548
+ sendJson(res, 201, await catalogue.convertPreset({
2549
+ source: body.source,
2550
+ versionId: body.versionId,
2551
+ ...body.title === void 0 ? {} : { title: body.title },
2552
+ ...language === void 0 ? {} : { language }
2553
+ }));
2554
+ } catch (error) {
2555
+ return error instanceof CatalogueError ? catalogueFailure(res, error) : importFailure(res, error);
2556
+ }
2557
+ } },
2558
+ "/catalogue/convert/lorebook": { POST: async (req, res) => {
2559
+ const body = await readJsonBody(req);
2560
+ if (typeof body.source !== "string" || typeof body.versionId !== "string") return sendError(res, 400, "source and versionId must be text");
2561
+ if (body.title !== void 0 && typeof body.title !== "string") return sendError(res, 400, "title must be text");
2562
+ try {
2563
+ const language = languageField(body.language);
2564
+ sendJson(res, 201, await catalogue.convertLorebook({
2565
+ source: body.source,
2566
+ versionId: body.versionId,
2567
+ ...body.title === void 0 ? {} : { title: body.title },
2568
+ ...language === void 0 ? {} : { language }
2569
+ }));
2570
+ } catch (error) {
2571
+ return error instanceof CatalogueError ? catalogueFailure(res, error) : importFailure(res, error);
2572
+ }
2573
+ } },
1979
2574
  "/worlds/starter": {
1980
2575
  GET: async (_req, res) => {
1981
2576
  sendJson(res, 200, await starter.list());
@@ -2631,7 +3226,7 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
2631
3226
  sendJson(res, 200, sessions.list());
2632
3227
  },
2633
3228
  POST: async (req, res) => {
2634
- const { worldId, playerCharacterId, playerAvatar, avatars: brought, name, settings, opening, startingTime } = await readJsonBody(req);
3229
+ const { worldId, playerCharacterId, playerAvatar, avatars: brought, name, settings, opening, startingTime, preset, lorebooks } = await readJsonBody(req);
2635
3230
  if (typeof worldId !== "string" || worldId.trim() === "") return sendError(res, 400, "\"worldId\" is required");
2636
3231
  if (playerCharacterId === void 0 && playerAvatar === void 0) return sendError(res, 400, "\"playerCharacterId\" or \"playerAvatar\" is required");
2637
3232
  if (playerCharacterId !== void 0 && (typeof playerCharacterId !== "string" || playerCharacterId.trim() === "")) return sendError(res, 400, "\"playerCharacterId\" must be text");
@@ -2640,8 +3235,12 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
2640
3235
  if (name !== void 0 && typeof name !== "string") return sendError(res, 400, "\"name\" must be a string");
2641
3236
  if (opening !== void 0 && (typeof opening !== "number" || !Number.isInteger(opening))) return sendError(res, 400, "\"opening\" must be a whole number");
2642
3237
  if (startingTime !== void 0 && typeof startingTime !== "string") return sendError(res, 400, "\"startingTime\" must be text");
3238
+ if (preset !== void 0 && typeof preset !== "string") return sendError(res, 400, "\"preset\" must be text");
3239
+ if (lorebooks !== void 0 && (!Array.isArray(lorebooks) || !lorebooks.every((entry) => typeof entry === "string"))) return sendError(res, 400, "\"lorebooks\" must be a list of lorebook names");
2643
3240
  try {
2644
3241
  sendJson(res, 201, await sessions.start({
3242
+ ...preset === void 0 || preset === "" ? {} : { preset },
3243
+ ...lorebooks === void 0 ? {} : { lorebooks },
2645
3244
  ...opening === void 0 ? {} : { opening },
2646
3245
  ...startingTime === void 0 ? {} : { startingTime },
2647
3246
  worldId,
@@ -3028,6 +3627,8 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
3028
3627
  res.end();
3029
3628
  } },
3030
3629
  ...interfaceRoutes(packs),
3630
+ ...presetRoutes(presets),
3631
+ ...lorebookRoutes(lorebooks),
3031
3632
  "/worlds/cover": { GET: async (_req, res, url) => {
3032
3633
  const cover = await worlds.cover(url.searchParams.get("id") ?? "");
3033
3634
  if (cover === void 0) return sendError(res, 404, "no cover");
@@ -4317,6 +4918,8 @@ function infoOf(document) {
4317
4918
  authorUrl: textOf(author["url"]),
4318
4919
  timeZone: textOf(document["time_zone"]),
4319
4920
  startingTime: textOf(document["starting_time"]),
4921
+ preset: textOf(document["preset"]),
4922
+ lorebooks: Array.isArray(document["lorebooks"]) ? document["lorebooks"].filter((name) => typeof name === "string") : [],
4320
4923
  version: typeof document["version"] === "number" ? String(document["version"]) : textOf(document["version"]),
4321
4924
  tools: toolsOf(document["tools"]),
4322
4925
  alternateOpenings: Array.isArray(document["alternate_openings"]) ? document["alternate_openings"].flatMap((entry) => typeof entry === "object" && entry !== null && typeof entry["text"] === "string" ? [{
@@ -4375,6 +4978,11 @@ async function editWorldInfo(directory, edit) {
4375
4978
  if (edit.timeZone !== void 0) setOrRemove(document, "time_zone", edit.timeZone);
4376
4979
  if (edit.startingTime !== void 0) setOrRemove(document, "starting_time", edit.startingTime);
4377
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
+ }
4378
4986
  if (edit.alternateOpenings !== void 0) {
4379
4987
  if (edit.alternateOpenings.length === 0) delete document["alternate_openings"];
4380
4988
  else document["alternate_openings"] = edit.alternateOpenings.map((entry) => ({
@@ -4393,6 +5001,55 @@ async function editWorldInfo(directory, edit) {
4393
5001
  await replaceFile(join(directory, WORLD_FILE_NAME), next);
4394
5002
  return infoOf(document);
4395
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
+ }
4396
5053
  /**
4397
5054
  * Start a new session for a world: create its folder and database and fill it
4398
5055
  * from the world. Either the whole session exists afterwards or nothing does.
@@ -4457,6 +5114,33 @@ async function startSession(deps, request) {
4457
5114
  },
4458
5115
  tools
4459
5116
  };
5117
+ const { preset, unavailable } = presetFor(deps, request.preset, world.preset);
5118
+ const asked = request.lorebooks !== void 0;
5119
+ const wanted = request.lorebooks ?? world.lorebooks ?? [];
5120
+ let books = {
5121
+ definitions: [],
5122
+ applied: [],
5123
+ notes: []
5124
+ };
5125
+ if (wanted.length > 0) {
5126
+ if (deps.root === void 0) throw new InvalidStartError("the lorebook library is not available");
5127
+ try {
5128
+ books = await lorebookLore(deps.root(), wanted, asked, characters, new Set(authoredLore.lore.map((entry) => entry.id)));
5129
+ } catch (error) {
5130
+ throw new InvalidStartError(error instanceof Error ? error.message : String(error));
5131
+ }
5132
+ unavailable.push(...books.notes);
5133
+ }
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
+ }
4460
5144
  let startsAt = world.clock?.startingTime;
4461
5145
  if (request.startingTime !== void 0 && request.startingTime.trim() !== "") {
4462
5146
  if (settings.clock.mode === "real") throw new InvalidStartError("the story's time follows the wall clock, so it has no starting time to choose");
@@ -4487,7 +5171,8 @@ async function startSession(deps, request) {
4487
5171
  populateDice(session, checks);
4488
5172
  populateRoutines(session, characters);
4489
5173
  populateItems(session, items, slots, locations);
4490
- populateLore(session, authoredLore.lore);
5174
+ populateLore(session, [...authoredLore.lore, ...books.definitions]);
5175
+ if (books.applied.length > 0) session.metadata.setValue(LOREBOOKS_KEY, books.applied);
4491
5176
  populateKnowledge(session, characters);
4492
5177
  populateVariables(session, declared.defs, {
4493
5178
  characters,
@@ -4503,12 +5188,18 @@ async function startSession(deps, request) {
4503
5188
  });
4504
5189
  await inheritImages(world.directory, sessionFolder(sessionsDir, id), []);
4505
5190
  if (avatars !== void 0) for (const entry of brought) await copyPortrait(avatars, entry.from, entry.document, sessionFolder(sessionsDir, id), entry.id);
4506
- const promptProblems = copyWorldPrompts(world.directory, sessionFolder(sessionsDir, id));
5191
+ const folder = sessionFolder(sessionsDir, id);
5192
+ if (preset !== void 0 && request.preset === void 0) copyPreset(preset, folder);
5193
+ const promptProblems = copyWorldPrompts(world.directory, folder);
4507
5194
  if (promptProblems.length > 0) throw new InvalidWorldError(`the prompts of "${world.summary.name}" have ${promptProblems.length} problem(s)`, promptProblems);
5195
+ if (preset !== void 0) {
5196
+ if (request.preset !== void 0) copyPreset(preset, folder);
5197
+ recordPreset(folder, preset);
5198
+ }
4508
5199
  const packProblems = copyWorldPacks(world.directory, sessionFolder(sessionsDir, id));
4509
5200
  if (packProblems.length > 0) throw new InvalidWorldError(`the interface packs of "${world.summary.name}" have ${packProblems.length} problem(s)`, packProblems);
4510
5201
  writeSettings(sessionFolder(sessionsDir, id), settings);
4511
- addToNote(session, "world", 1, worldFindings(session));
5202
+ addToNote(session, "world", 1, [...unavailable, ...worldFindings(session)]);
4512
5203
  chatSessionId = await deps.agent.ensure(id, name, opening);
4513
5204
  } catch (error) {
4514
5205
  deps.state.deleteSession(sessionsDir, id);
@@ -4524,6 +5215,30 @@ async function startSession(deps, request) {
4524
5215
  characterCount: characters.length
4525
5216
  };
4526
5217
  }
5218
+ /**
5219
+ * The preset a story uses: the one asked for, else the one the world suggests. Asking for one that cannot be used refuses the start;
5220
+ * a suggestion that cannot be followed is told to the player instead, because the world may come from someone whose library differs.
5221
+ */
5222
+ function presetFor(deps, asked, suggested) {
5223
+ const name = asked ?? suggested;
5224
+ if (name === void 0 || name === "none") return { unavailable: [] };
5225
+ const load = () => {
5226
+ if (deps.root === void 0) throw new Error("the preset library is not available");
5227
+ const loaded = loadPreset(deps.root(), name);
5228
+ if (loaded.summary.problems.length > 0) throw new Error(`it has problems: ${loaded.summary.problems.join("; ")}`);
5229
+ return loaded;
5230
+ };
5231
+ try {
5232
+ return {
5233
+ preset: load(),
5234
+ unavailable: []
5235
+ };
5236
+ } catch (error) {
5237
+ const reason = error instanceof Error ? error.message : String(error);
5238
+ if (asked !== void 0) throw new InvalidStartError(`the preset "${name}" cannot be used: ${reason}`);
5239
+ return { unavailable: [`The world suggests the preset "${name}", which cannot be used here (${reason}), so the story is told in the default style.`] };
5240
+ }
5241
+ }
4527
5242
  /** What a story opens with when its world gives no opening: a chat with nothing in it is DSH's start screen, which has none of the story's tabs. */
4528
5243
  const DEFAULT_OPENING = "The story begins.";
4529
5244
  /** The opening of the world with each speaker's name, or the reason it cannot be used. */
@@ -4880,6 +5595,8 @@ async function worldCharacters(worlds, worldId) {
4880
5595
  })),
4881
5596
  startingTime: world.clock?.startingTime === void 0 ? "" : localInstant(world.clock.startingTime, world.clock.timeZone ?? "UTC"),
4882
5597
  timeZone: world.clock?.timeZone ?? "",
5598
+ ...world.preset === void 0 ? {} : { preset: world.preset },
5599
+ ...world.lorebooks === void 0 ? {} : { lorebooks: world.lorebooks },
4883
5600
  problems
4884
5601
  };
4885
5602
  }
@@ -5052,7 +5769,9 @@ async function loadWorld(folder, dir, file, problems) {
5052
5769
  ...world.alternateOpenings === void 0 ? {} : { alternateOpenings: world.alternateOpenings },
5053
5770
  ...world.rules === void 0 ? {} : { rules: world.rules },
5054
5771
  ...world.tools === void 0 ? {} : { tools: world.tools },
5055
- ...world.narrationVoice === void 0 ? {} : { narrationVoice: world.narrationVoice }
5772
+ ...world.narrationVoice === void 0 ? {} : { narrationVoice: world.narrationVoice },
5773
+ ...world.preset === void 0 ? {} : { preset: world.preset },
5774
+ ...world.lorebooks === void 0 ? {} : { lorebooks: world.lorebooks }
5056
5775
  };
5057
5776
  if (world.coverMediaId !== void 0) try {
5058
5777
  record.cover = await resolveCover(dir, world.coverMediaId);
@@ -5182,6 +5901,8 @@ var WorldCatalog = class extends Service {
5182
5901
  //#endregion
5183
5902
  //#region src/shared/catalogue.ts
5184
5903
  const CATALOGUE_CARD_TYPE = "sillytavern/character";
5904
+ const CATALOGUE_PRESET_TYPE = "sillytavern/preset";
5905
+ const CATALOGUE_LOREBOOK_TYPE = "sillytavern/lorebook";
5185
5906
  const CATALOGUE_WORLD_TYPE = "dsh-agentic-roleplay/world";
5186
5907
  //#endregion
5187
5908
  //#region src/host/catalogue/origin.ts
@@ -5466,6 +6187,56 @@ async function installWorld(catalog, archive, maxBytes, options) {
5466
6187
  }
5467
6188
  }
5468
6189
  //#endregion
6190
+ //#region src/host/catalogue/trash.ts
6191
+ const DAY_MS = 864e5;
6192
+ const STAMP = /-(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z$/;
6193
+ /** Staging folders left by an interrupted install are removed after this long. */
6194
+ const STALE_STAGING_MS = DAY_MS;
6195
+ /** When a world's old files were moved to the trash, read from the folder name the update gave them; entries without such a stamp are not ours. */
6196
+ function movedAt(name) {
6197
+ const match = STAMP.exec(name);
6198
+ if (match === null) return void 0;
6199
+ const time = Date.parse(`${match[1]}T${match[2]}:${match[3]}:${match[4]}.${match[5]}Z`);
6200
+ return Number.isNaN(time) ? void 0 : time;
6201
+ }
6202
+ async function entries(directory) {
6203
+ try {
6204
+ return await readdir(directory);
6205
+ } catch (error) {
6206
+ if (error.code === "ENOENT") return [];
6207
+ throw error;
6208
+ }
6209
+ }
6210
+ /**
6211
+ * Removes what updates and installs leave behind: world files moved to `.trash/worlds/` more than `keepDays` days ago (0 keeps them for
6212
+ * good), and staging folders of an install that never finished. A folder that cannot be removed is reported and the rest still goes.
6213
+ * @returns the folders removed and the failures.
6214
+ */
6215
+ async function pruneTrash(root, keepDays, now = Date.now()) {
6216
+ const removed = [];
6217
+ const failures = [];
6218
+ const drop = async (path, label) => {
6219
+ try {
6220
+ await rm(path, {
6221
+ recursive: true,
6222
+ force: true
6223
+ });
6224
+ removed.push(label);
6225
+ } catch (error) {
6226
+ failures.push(`${label}: ${error instanceof Error ? error.message : String(error)}`);
6227
+ }
6228
+ };
6229
+ if (keepDays > 0) for (const name of await entries(join(root, ".trash", "worlds"))) {
6230
+ const at = movedAt(name);
6231
+ if (at !== void 0 && now - at > keepDays * DAY_MS) await drop(join(root, ".trash", "worlds", name), `.trash/worlds/${name}`);
6232
+ }
6233
+ for (const name of await entries(join(root, ".install"))) if (now - (await stat(join(root, ".install", name))).mtimeMs > STALE_STAGING_MS) await drop(join(root, ".install", name), `.install/${name}`);
6234
+ return {
6235
+ removed,
6236
+ failures
6237
+ };
6238
+ }
6239
+ //#endregion
5469
6240
  //#region src/host/catalogue/transport.ts
5470
6241
  const TIMEOUT_MS = 6e4;
5471
6242
  const MAX_REDIRECTS = 5;
@@ -5594,6 +6365,13 @@ const object = (value, what) => {
5594
6365
  };
5595
6366
  const text = (value) => typeof value === "string" ? value : "";
5596
6367
  const count = (value) => typeof value === "number" && Number.isFinite(value) ? value : 0;
6368
+ const kindOf = (type) => type === "sillytavern/character" ? "card" : type === "sillytavern/preset" ? "preset" : type === "sillytavern/lorebook" ? "lorebook" : "world";
6369
+ const TYPES = {
6370
+ world: CATALOGUE_WORLD_TYPE,
6371
+ card: CATALOGUE_CARD_TYPE,
6372
+ preset: CATALOGUE_PRESET_TYPE,
6373
+ lorebook: CATALOGUE_LOREBOOK_TYPE
6374
+ };
5597
6375
  function worldOf(value) {
5598
6376
  const item = object(value, "a world entry");
5599
6377
  const metadata = object(item["metadata"], "a world entry without metadata");
@@ -5602,7 +6380,7 @@ function worldOf(value) {
5602
6380
  const visibility = text(metadata["visibility"]);
5603
6381
  return {
5604
6382
  id,
5605
- kind: text(item["resourceType"]) === "sillytavern/character" ? "card" : "world",
6383
+ kind: kindOf(text(item["resourceType"])),
5606
6384
  name: text(metadata["name"]),
5607
6385
  description: text(metadata["description"]),
5608
6386
  tags: Array.isArray(metadata["tags"]) ? metadata["tags"].filter((tag) => typeof tag === "string") : [],
@@ -5644,7 +6422,7 @@ var Catalogue = class {
5644
6422
  const source = this.deps.sources.get(name);
5645
6423
  const offset = Math.max(0, Math.floor(query.offset ?? 0));
5646
6424
  const params = {
5647
- resourceType: query.kind === "card" ? CATALOGUE_CARD_TYPE : CATALOGUE_WORLD_TYPE,
6425
+ resourceType: TYPES[query.kind ?? "world"],
5648
6426
  publishedOnly: "true",
5649
6427
  limit: String(24),
5650
6428
  offset: String(offset),
@@ -5779,11 +6557,22 @@ var Catalogue = class {
5779
6557
  if (reply.body.length < 4 || reply.body.readUInt32LE(0) !== 67324752) throw new CatalogueError(`${url.href} did not answer with a ZIP archive${reply.type === "" ? "" : ` (it sent ${reply.type})`}`, "invalid");
5780
6558
  if (request.sha256 !== void 0 && createHash("sha256").update(reply.body).digest("hex") !== request.sha256.toLowerCase()) throw new CatalogueError("the download does not match the checksum the catalogue published for it", "invalid");
5781
6559
  const provenance = await this.provenance(url);
5782
- return await installWorld(this.deps.worlds, reply.body, this.deps.maxBytes(), {
6560
+ const installed = await installWorld(this.deps.worlds, reply.body, this.deps.maxBytes(), {
5783
6561
  mode: request.mode ?? "new",
5784
6562
  overwriteChanges: request.overwriteChanges === true,
5785
6563
  ...provenance === void 0 ? {} : { provenance }
5786
6564
  });
6565
+ if (installed.backup !== void 0) await this.tidy();
6566
+ return installed;
6567
+ }
6568
+ /** Deletes what updates left in the trash past the configured time; a failure is reported and never fails the request that triggered it. */
6569
+ async tidy() {
6570
+ try {
6571
+ const { failures } = await pruneTrash(dirname(this.deps.worlds.directory), this.deps.trashDays());
6572
+ for (const failure of failures) this.deps.problem(`could not remove old catalogue files: ${failure}`);
6573
+ } catch (error) {
6574
+ this.deps.problem(`could not clean the catalogue trash: ${error instanceof Error ? error.message : String(error)}`);
6575
+ }
5787
6576
  }
5788
6577
  /**
5789
6578
  * Turns a character card of a catalogue into a new world: the card is downloaded with the catalogue's key and handed to the importer, whose
@@ -5792,9 +6581,40 @@ var Catalogue = class {
5792
6581
  */
5793
6582
  async convert(request) {
5794
6583
  const source = this.deps.sources.get(request.source);
5795
- const versionId = this.identifier(request.versionId);
6584
+ 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);
6592
+ const record = await this.deps.worlds.find(converted.worldId);
6593
+ if (record === void 0) throw new CatalogueError("the world was made but cannot be found", "upstream");
6594
+ await writeOrigin(record.directory, {
6595
+ kind: "card",
6596
+ root: source.root,
6597
+ resourceId: release.resourceId,
6598
+ versionId: release.versionId,
6599
+ version: release.version
6600
+ });
6601
+ return converted;
6602
+ }
6603
+ /** 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
+ async convertLorebook(request) {
6605
+ const release = await this.download(this.deps.sources.get(request.source), request.versionId, CATALOGUE_LOREBOOK_TYPE, "a lorebook");
6606
+ return await this.deps.importLorebook(release.body, request.title ?? "", request.language);
6607
+ }
6608
+ /** Turns a SillyTavern preset of a catalogue into a new library preset, which its authoring chat fills with prompts. Like a card it is never an update of an earlier one. */
6609
+ async convertPreset(request) {
6610
+ const release = await this.download(this.deps.sources.get(request.source), request.versionId, CATALOGUE_PRESET_TYPE, "a preset");
6611
+ return await this.deps.importPreset(release.body, request.title ?? "", request.language);
6612
+ }
6613
+ /** A release of the given type, downloaded with the catalogue's key and checked against the checksum it published. */
6614
+ async download(source, versionIdText, type, what) {
6615
+ const versionId = this.identifier(versionIdText);
5796
6616
  const version = object(await this.json(source, `/versions/${versionId}`), "a version");
5797
- if (text(version["resourceType"]) !== "sillytavern/character") throw new CatalogueError("that release is not a character card", "invalid");
6617
+ if (text(version["resourceType"]) !== type) throw new CatalogueError(`that release is not ${what}`, "invalid");
5798
6618
  const resourceId = text(version["resourceId"]);
5799
6619
  if (!ID.test(resourceId)) throw unexpected("a version without a resource id");
5800
6620
  const reply = await fetchAddress(this.address(source, `/versions/${versionId}/download`), {
@@ -5805,23 +6625,12 @@ var Catalogue = class {
5805
6625
  });
5806
6626
  const sha256 = text(version["artifactSha256"]);
5807
6627
  if (sha256 !== "" && createHash("sha256").update(reply.body).digest("hex") !== sha256.toLowerCase()) throw new CatalogueError("the download does not match the checksum the catalogue published for it", "invalid");
5808
- const png = reply.body.subarray(0, 4).equals(Buffer.from([
5809
- 137,
5810
- 80,
5811
- 78,
5812
- 71
5813
- ]));
5814
- const converted = await this.deps.importCard(reply.body, `${versionId}${png ? ".png" : ".json"}`, request.language);
5815
- const record = await this.deps.worlds.find(converted.worldId);
5816
- if (record === void 0) throw new CatalogueError("the world was made but cannot be found", "upstream");
5817
- await writeOrigin(record.directory, {
5818
- kind: "card",
5819
- root: source.root,
5820
- resourceId,
6628
+ return {
6629
+ body: reply.body,
5821
6630
  versionId,
6631
+ resourceId,
5822
6632
  version: text(version["version"])
5823
- });
5824
- return converted;
6633
+ };
5825
6634
  }
5826
6635
  /** The catalogue release an address names, when it is a release download on a configured catalogue. */
5827
6636
  async provenance(url) {
@@ -6047,6 +6856,7 @@ const Config = z.object({
6047
6856
  apiKey: z.string().default("")
6048
6857
  })).default([]).volatile(),
6049
6858
  catalogueMaxBytes: z.number().min(1024).default(268435456),
6859
+ catalogueTrashDays: z.number().min(0).default(30),
6050
6860
  importMaxUploadBytes: z.number().min(1024).default(104857600),
6051
6861
  importConcurrency: z.number().min(1).max(16).default(4),
6052
6862
  importReasoning: z.string().default(""),
@@ -6084,6 +6894,8 @@ function apply(ctx, config) {
6084
6894
  const languages = new AuthoringLanguages(ctx, () => join(root.path, "worlds"));
6085
6895
  const agent = new AgentSessions(agentServicesOf(ctx), () => root.path);
6086
6896
  const authoring = new AuthoringSessions(agentServicesOf(ctx), () => root.path, prompts, languages);
6897
+ const presetAuthoring = new PresetAuthoringSessions(agentServicesOf(ctx), () => root.path, prompts, languages);
6898
+ const lorebookAuthoring = new LorebookAuthoringSessions(agentServicesOf(ctx), () => root.path, prompts, languages);
6087
6899
  const doctors = new DoctorSessions(agentServicesOf(ctx), () => root.path, prompts);
6088
6900
  const imports = new ImportStore(() => root.path);
6089
6901
  new RoleplayImport(ctx, {
@@ -6110,24 +6922,49 @@ function apply(ctx, config) {
6110
6922
  state: ctx.roleplayState,
6111
6923
  agent,
6112
6924
  sessionsDir: () => join(root.path, "sessions"),
6925
+ root: () => root.path,
6113
6926
  avatars: () => avatarsWorld(root.path)
6114
6927
  };
6928
+ const presetLibrary = new Presets({
6929
+ root: () => root.path,
6930
+ worldDirectory: async (worldId) => (await worlds.find(worldId))?.directory,
6931
+ authoring: presetAuthoring,
6932
+ importMessage: narrationImportMessage,
6933
+ maxUploadBytes: config.importMaxUploadBytes,
6934
+ playing: (id) => ctx.roleplayOrchestration.playing(chatSessionId(id))
6935
+ });
6936
+ const lorebookLibrary = new Lorebooks({
6937
+ root: () => root.path,
6938
+ authoring: lorebookAuthoring,
6939
+ importMessage: lorebookImportMessage,
6940
+ maxUploadBytes: config.importMaxUploadBytes
6941
+ });
6942
+ const catalogue = new Catalogue({
6943
+ sources: new Sources(() => config.catalogues.get()),
6944
+ worlds,
6945
+ maxBytes: () => config.catalogueMaxBytes,
6946
+ maxCardBytes: () => config.importMaxUploadBytes,
6947
+ trashDays: () => config.catalogueTrashDays,
6948
+ problem: (message) => {
6949
+ ctx.logger.warn(message);
6950
+ },
6951
+ importPreset: async (file, title, language) => await presetLibrary.importTitled(title, file, language),
6952
+ importLorebook: async (file, title, language) => await lorebookLibrary.importTitled(title, file, language),
6953
+ importCard: async (file, name, language) => {
6954
+ const preview = await imports.create(readCard(file, name), isPng(file) ? pictureOf(file) : void 0);
6955
+ return await startImport({
6956
+ store: imports,
6957
+ worlds,
6958
+ authoring,
6959
+ chatTitle: (title) => `Authoring ${title}`
6960
+ }, preview.id, preview.choices, language);
6961
+ }
6962
+ });
6963
+ catalogue.tidy();
6115
6964
  registerApi(ctx, {
6116
- catalogue: new Catalogue({
6117
- sources: new Sources(() => config.catalogues.get()),
6118
- worlds,
6119
- maxBytes: () => config.catalogueMaxBytes,
6120
- maxCardBytes: () => config.importMaxUploadBytes,
6121
- importCard: async (file, name, language) => {
6122
- const preview = await imports.create(readCard(file, name), isPng(file) ? pictureOf(file) : void 0);
6123
- return await startImport({
6124
- store: imports,
6125
- worlds,
6126
- authoring,
6127
- chatTitle: (title) => `Authoring ${title}`
6128
- }, preview.id, preview.choices, language);
6129
- }
6130
- }),
6965
+ catalogue,
6966
+ presets: presetLibrary,
6967
+ lorebooks: lorebookLibrary,
6131
6968
  packs: new InterfaceService({
6132
6969
  open: (id) => ctx.roleplayState.openSession(deps.sessionsDir(), id),
6133
6970
  root: () => root.path,