@dsh-agentic-roleplay/core 0.3.5 → 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 (52) hide show
  1. package/lib/{preset-ClQm7KPQ.js → authoring-tools-C_8ClUkP.js} +542 -261
  2. package/lib/authoring.js +7 -5
  3. package/lib/{child-CFjnaTZt.js → child-DsixtqTw.js} +94 -2
  4. package/lib/client.js +16938 -14212
  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-Cl6bjp7g.js → hooks-B2EhBS_-.js} +1884 -236
  11. package/lib/images.js +4 -4
  12. package/lib/index.js +1200 -242
  13. package/lib/{library-9JB9zw5a.js → library-COIktKBa.js} +4 -3
  14. package/lib/lorebook-author-tools-C-o0t4dL.js +694 -0
  15. package/lib/lorebook-authoring.js +69 -0
  16. package/lib/{settings-CA6icLL_.js → narration-BT9uvQry.js} +145 -2
  17. package/lib/orchestration.js +34 -21
  18. package/lib/{pack-jail-ClMpVc__.js → pack-jail-soI-In96.js} +170 -12
  19. package/lib/{packs-BC2A3geF.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-Dibp-LY9.js → preset-author-tools-C-X8G40s.js} +24 -18
  23. package/lib/preset-authoring.js +6 -3
  24. package/lib/{presets-DNjNxQL5.js → presets-C3mhqqfz.js} +50 -28
  25. package/lib/{reflection-Bju_LPFn.js → reflection-Btsj0ZLh.js} +51 -17
  26. package/package.json +3 -2
  27. package/packs/scene/map.html +1 -0
  28. package/packs/scene/strip.html +1 -0
  29. package/prompts/en/import/lorebook.md +8 -0
  30. package/prompts/en/import/style.md +1 -0
  31. package/prompts/en/lorebook/persona.md +1 -0
  32. package/prompts/en/lorebook/procedure.md +1 -0
  33. package/prompts/en/lorebook/welcome.md +1 -0
  34. package/prompts/en/preset/persona.md +1 -1
  35. package/prompts/en/preset/procedure.md +1 -1
  36. package/prompts/en/roleplay/character-lookup.md +1 -0
  37. package/prompts/en/roleplay/game-master.md +1 -1
  38. package/prompts/en/world/procedure.md +1 -1
  39. package/prompts/zh/import/lorebook.md +8 -0
  40. package/prompts/zh/import/style.md +1 -0
  41. package/prompts/zh/lorebook/persona.md +1 -0
  42. package/prompts/zh/lorebook/procedure.md +1 -0
  43. package/prompts/zh/lorebook/welcome.md +1 -0
  44. package/prompts/zh/preset/persona.md +1 -1
  45. package/prompts/zh/preset/procedure.md +1 -1
  46. package/prompts/zh/roleplay/character-lookup.md +1 -0
  47. package/prompts/zh/roleplay/game-master.md +1 -1
  48. package/prompts/zh/world/procedure.md +1 -1
  49. package/lib/hooks-DdO_tNhu.js +0 -1060
  50. package/lib/language-BgyxtB2h.js +0 -38
  51. package/lib/load-Clkl0T7C.js +0 -486
  52. package/lib/narration-DK2kiIjE.js +0 -141
package/lib/index.js CHANGED
@@ -1,19 +1,19 @@
1
1
  import { n as chatSessionId, r as roleplaySessionOf } from "./access-EbNdZFbk.js";
2
- import { A as parseDiceFile, C as populateTriggers, Ct as isPng, Dt as DICE_READINGS, E as TRIGGERS_FILE_NAME, Et as DICE_COMPARISONS, H as CHARACTERS_DIR, J as loadVariables, L as loadLocations, M as loadCalendar, N as parseCalendarFile, O as DICE_FILE_NAME, Ot as DICE_RESULTS, S as populateRoutines, St as ImportCardError, T as routineProblems, Tt as readCard, U as loadCharacters, W as subfolders, X as variableProblems, Y as parseVariablesFile, _ as populateFactions, _t as parseLoreEdit, at as CHARACTER_FILE_NAME, b as populateLocations, bt as parseThingEdit, ct as ImportNotFoundError, d as vetUrl, dt as WORLD_FILE_NAME, f as loadValidatedWorld, ft as parseWorldFile, g as populateDice, gt as parseFactionEdit, h as populateClock, ht as parseCharacterEdit, j as CALENDAR_FILE_NAME, k as loadDice, l as markReady, lt as ImportStore, m as populateCharacters, mt as InvalidEditProblems, ot as parseCharacterFile, p as populateCalendar, pt as parseWorldInfoEdit, q as VARIABLES_FILE_NAME, s as authoringChatSessionId, st as IMPORT_FOLDER, t as readPreset, u as guardedLookup, ut as parseChoices, v as populateItems, vt as parsePlaceEdit, w as populateVariables, wt as pictureOf, x as populateLore, xt as IMPORT_COMMAND, y as populateKnowledge, yt as parseRelationEdit, z as loadItems } from "./preset-ClQm7KPQ.js";
3
- import { _ as writeWorldPrompt, a as listPresets, f as updatePresetInfo, g as readWorldPrompt, h as listWorldPrompts, i as isPresetName, l as reservePreset, m as deleteWorldPrompt, n as createPresetFromShipped, o as loadPreset, p as PROSE_PROMPTS, r as deletePreset, s as presetDirectory, t as PRESET_FILE, u as savePresetFromWorld } from "./presets-DNjNxQL5.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-Bju_LPFn.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 formatIssue, d as PromptLibrary, f as copyWorldPrompts, i as plotReferenceProblems, m as languageOf, o as errorMessage, r as parsePlotsFile, w as SessionArchivedError, x as InvalidStartError } from "./load-Clkl0T7C.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-Cl6bjp7g.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-ClMpVc__.js";
12
- import { a as presetChatSessionId, n as narrationImportMessage } from "./preset-author-tools-Dibp-LY9.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";
13
13
  import { t as doctorChatSessionId } from "./doctor-chat-ByDfCMeo.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-BC2A3geF.js";
15
- import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-DJ48HxPI.js";
16
- 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";
17
17
  import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
18
18
  import { cpSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
19
19
  import { createHash, randomBytes, randomUUID } from "node:crypto";
@@ -418,7 +418,10 @@ async function createWorld(catalog, input) {
418
418
  const FOLDER_CHARS = /[^\p{L}\p{N}._ -]+/gu;
419
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. */
420
420
  function folderNameOf(name) {
421
- 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();
422
425
  return folder === "" ? "imported world" : folder;
423
426
  }
424
427
  /** The command that starts the import, for a card kept in the world's import folder. */
@@ -494,6 +497,23 @@ async function startTranslation(deps, id, to, title, language) {
494
497
  }
495
498
  }
496
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
497
517
  //#region src/host/import/upload-preset.ts
498
518
  /**
499
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.
@@ -519,6 +539,99 @@ async function uploadPreset(deps, worldId, file, name, language) {
519
539
  ...failure === void 0 ? {} : { failure }
520
540
  };
521
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
+ }
522
635
  //#endregion
523
636
  //#region src/host/agent/authoring-sessions.ts
524
637
  const AUTHORING_PROJECT_TITLE = "World Authoring";
@@ -626,6 +739,341 @@ var PresetAuthoringSessions = class {
626
739
  }
627
740
  };
628
741
  //#endregion
742
+ //#region src/host/agent/lorebook-authoring-sessions.ts
743
+ const LOREBOOK_AUTHORING_PROJECT_TITLE = "Lorebook Authoring";
744
+ const LOREBOOK_AUTHORING_PRESET = "lorebook-authoring";
745
+ /** Creates or reopens the dedicated authoring chat of a library lorebook, and speaks in it for the person when asked to. */
746
+ var LorebookAuthoringSessions = class {
747
+ services;
748
+ roleplayRoot;
749
+ prompts;
750
+ languages;
751
+ constructor(services, roleplayRoot, prompts, languages) {
752
+ this.services = services;
753
+ this.roleplayRoot = roleplayRoot;
754
+ this.prompts = prompts;
755
+ this.languages = languages;
756
+ }
757
+ async ensure(name, title, language) {
758
+ this.languages.set(`lorebook:${name}`, language);
759
+ const services = this.services();
760
+ const projectPath = join(this.roleplayRoot(), "lorebooks");
761
+ const project = await services.registry.create(projectPath, LOREBOOK_AUTHORING_PROJECT_TITLE);
762
+ const sessionId = lorebookChatSessionId(name);
763
+ const stored = !project.sessionIds.includes(sessionId) && await isStored(services.persistence, sessionId);
764
+ if (!project.sessionIds.includes(sessionId) && !stored) {
765
+ if (services.persistence === void 0) throw new AgentUnavailableError("this DSH profile cannot store the opening of an authoring chat");
766
+ await storeAuthoringOpening(services.persistence, {
767
+ id: sessionId,
768
+ cwd: project.path,
769
+ agentPreset: LOREBOOK_AUTHORING_PRESET
770
+ }, this.prompts.text("lorebook/welcome", this.languages.get(`lorebook:${name}`), { lorebook: title }));
771
+ }
772
+ return await ensureAgentChat(services, {
773
+ projectPath,
774
+ projectTitle: LOREBOOK_AUTHORING_PROJECT_TITLE,
775
+ sessionId,
776
+ agentPreset: LOREBOOK_AUTHORING_PRESET,
777
+ title: `Lorebook ${title}`,
778
+ renameExisting: true
779
+ }, project);
780
+ }
781
+ async send(sessionId, text) {
782
+ await this.services().controller.prompt({
783
+ requestId: randomUUID(),
784
+ sessionId,
785
+ mode: "queue",
786
+ content: [{
787
+ type: "text",
788
+ text
789
+ }]
790
+ }, new AbortController().signal);
791
+ }
792
+ };
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
931
+ //#region src/host/lorebooks/service.ts
932
+ /** The story's lore cannot change right now. */
933
+ var LorebookBusyError = class extends Error {};
934
+ /** The lorebook library. Refusals are plain `Error`s with the reason. */
935
+ var Lorebooks = class {
936
+ deps;
937
+ constructor(deps) {
938
+ this.deps = deps;
939
+ }
940
+ get maxUploadBytes() {
941
+ return this.deps.maxUploadBytes;
942
+ }
943
+ async list() {
944
+ return (await listLorebooks(this.deps.root())).map((book) => book.summary);
945
+ }
946
+ async read(name) {
947
+ const book = await loadLorebook(this.deps.root(), name);
948
+ return {
949
+ summary: book.summary,
950
+ entries: entriesOf(book)
951
+ };
952
+ }
953
+ async create(request) {
954
+ return (await createLorebook(this.deps.root(), request)).summary;
955
+ }
956
+ async updateInfo(name, change) {
957
+ return (await updateLorebookInfo(this.deps.root(), name, change)).summary;
958
+ }
959
+ async writeEntry(name, entry) {
960
+ return (await writeLorebookEntry(this.deps.root(), name, entry)).summary;
961
+ }
962
+ async removeEntry(name, id) {
963
+ return (await deleteLorebookEntry(this.deps.root(), name, id)).summary;
964
+ }
965
+ async remove(name) {
966
+ await deleteLorebook(this.deps.root(), name);
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
+ }
994
+ /** Opens the authoring chat of a lorebook. */
995
+ async author(name, language) {
996
+ const loaded = await loadLorebook(this.deps.root(), name);
997
+ return { chatSessionId: await this.deps.authoring.ensure(name, loaded.summary.title, language) };
998
+ }
999
+ /** Like `importFile`, under a name made from the title that is not yet taken. */
1000
+ async importTitled(title, file, language) {
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";
1006
+ const taken = new Set((await listLorebooks(this.deps.root())).map((book) => book.summary.name));
1007
+ let name = base;
1008
+ for (let index = 2; taken.has(name); index += 1) name = `${base}-${index}`;
1009
+ return name;
1010
+ }
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. */
1012
+ async importFile(name, file, language, title) {
1013
+ if (!isLorebookName(name)) throw new Error(`"${name}" is not a usable lorebook name (letters, digits, "-" and "_", up to 64)`);
1014
+ const uploaded = readLorebook(file, name);
1015
+ const root = this.deps.root();
1016
+ const directory = await reserveLorebook(root, name, title ?? uploaded.name);
1017
+ try {
1018
+ await mkdir(join(directory, IMPORT_FOLDER), { recursive: true });
1019
+ await writeFile(join(directory, LOREBOOK_UPLOAD), file);
1020
+ } catch (error) {
1021
+ await rm(lorebookDirectory(root, name), {
1022
+ recursive: true,
1023
+ force: true
1024
+ });
1025
+ throw error;
1026
+ }
1027
+ const chatSessionId = await this.deps.authoring.ensure(name, title ?? uploaded.name, language);
1028
+ let failure;
1029
+ try {
1030
+ await this.deps.authoring.send(chatSessionId, this.deps.importMessage());
1031
+ } catch (problem) {
1032
+ failure = problem instanceof Error ? problem.message : String(problem);
1033
+ }
1034
+ return {
1035
+ name,
1036
+ chatSessionId,
1037
+ started: failure === void 0,
1038
+ ...failure === void 0 ? {} : { failure }
1039
+ };
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
+ }
1075
+ };
1076
+ //#endregion
629
1077
  //#region src/host/agent/doctor-sessions.ts
630
1078
  const DOCTOR_PROJECT_TITLE = "Session Doctor";
631
1079
  const DOCTOR_AGENT_PRESET = "session-doctor";
@@ -1165,20 +1613,56 @@ var Presets = class {
1165
1613
  }
1166
1614
  /** Writes the person's own text of a prompt; `undefined` takes the preset's version out. */
1167
1615
  async writePrompt(name, language, id, text) {
1168
- const directory = presetDirectory(this.deps.root(), name);
1169
- if (!existsSync(directory)) throw new Error(`there is no preset "${name}"`);
1170
- if (!PROSE_PROMPTS.includes(id)) throw new Error(`a preset carries only ${PROSE_PROMPTS.join(", ")}`);
1616
+ const directory = this.existing(name);
1617
+ if (!id.startsWith("roleplay/")) throw new Error(`"${id}" is not a prompt of the story`);
1171
1618
  if (text === void 0) await deleteWorldPrompt(directory, language, id);
1172
1619
  else await writeWorldPrompt(directory, language, id, text);
1173
1620
  return loadPreset(this.deps.root(), name).summary;
1174
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
+ }
1175
1635
  /** Like `importFile`, under a name made from the title that is not yet taken. */
1176
1636
  async importTitled(title, file, language) {
1177
- 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";
1178
1641
  const taken = new Set(listPresets(this.deps.root()).map((entry) => entry.summary.name));
1179
1642
  let name = base;
1180
1643
  for (let index = 2; taken.has(name); index += 1) name = `${base}-${index}`;
1181
- 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 };
1182
1666
  }
1183
1667
  /** Opens the authoring chat of a preset. */
1184
1668
  async author(name, language) {
@@ -1189,7 +1673,7 @@ var Presets = class {
1189
1673
  async importFile(name, file, language, title) {
1190
1674
  const uploaded = readPreset(file, name);
1191
1675
  const root = this.deps.root();
1192
- const directory = await reservePreset(root, name, title ?? uploaded.name);
1676
+ const directory = await reservePreset(root, name, title ?? uploaded.name, uploaded.sampling);
1193
1677
  try {
1194
1678
  await mkdir(join(directory, IMPORT_FOLDER), { recursive: true });
1195
1679
  await writeFile(join(directory, IMPORT_FOLDER, PRESET_FILE), file);
@@ -1211,6 +1695,13 @@ var Presets = class {
1211
1695
  ...failure === void 0 ? {} : { failure }
1212
1696
  };
1213
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
+ }
1214
1705
  async remove(name) {
1215
1706
  await deletePreset(this.deps.root(), name);
1216
1707
  }
@@ -1232,70 +1723,283 @@ var Presets = class {
1232
1723
  //#endregion
1233
1724
  //#region src/host/presets/routes.ts
1234
1725
  /** Not found is 404 and a request the library refuses is 422 with its reason; anything else is a fault. */
1235
- function failure(res, error) {
1726
+ function failure$1(res, error) {
1727
+ if (error instanceof ImportNotFoundError) return sendError(res, 404, error.message);
1236
1728
  if (error instanceof SessionNotFoundError || error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
1237
1729
  if (error instanceof PresetBusyError) return sendError(res, 409, error.message);
1238
1730
  if (error instanceof Error) return sendError(res, 422, error.message);
1239
1731
  throw error;
1240
1732
  }
1241
1733
  function samplingOf(value) {
1242
- if (value === void 0) return {};
1243
- if (typeof value !== "object" || value === null || Array.isArray(value)) return "\"sampling\" must be an object";
1244
- const { master, characters } = value;
1245
- for (const number of [master, characters]) if (number !== void 0 && typeof number !== "number") return "sampling values must be numbers";
1246
- return {
1247
- ...master === void 0 ? {} : { master },
1248
- ...characters === void 0 ? {} : { characters }
1249
- };
1734
+ const problems = [];
1735
+ const sampling = parseSampling(value, "sampling", problems);
1736
+ return problems.length === 0 ? sampling : problems.join("; ");
1250
1737
  }
1251
1738
  function presetRoutes(api) {
1252
1739
  return {
1253
1740
  "/presets": {
1254
1741
  GET: async (_req, res) => {
1255
1742
  try {
1256
- sendJson(res, 200, api.list());
1743
+ sendJson(res, 200, api.list());
1744
+ } catch (error) {
1745
+ failure$1(res, error);
1746
+ }
1747
+ },
1748
+ POST: async (req, res) => {
1749
+ const { name, title, description, sampling, fromWorld } = await readJsonBody(req);
1750
+ if (typeof name !== "string" || name === "") return sendError(res, 400, "\"name\" is required");
1751
+ 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");
1752
+ if (title !== void 0 && typeof title !== "string" || description !== void 0 && typeof description !== "string") return sendError(res, 400, "\"title\" and \"description\" must be text");
1753
+ const given = samplingOf(sampling);
1754
+ if (typeof given === "string") return sendError(res, 400, given);
1755
+ try {
1756
+ sendJson(res, 201, await api.create({
1757
+ name,
1758
+ ...fromWorld === void 0 ? {} : { fromWorld },
1759
+ ...title === void 0 ? {} : { title },
1760
+ ...description === void 0 ? {} : { description },
1761
+ sampling: given
1762
+ }));
1763
+ } catch (error) {
1764
+ failure$1(res, error);
1765
+ }
1766
+ }
1767
+ },
1768
+ "/presets/item": {
1769
+ GET: async (_req, res, url) => {
1770
+ try {
1771
+ sendJson(res, 200, api.read(url.searchParams.get("name") ?? ""));
1772
+ } catch (error) {
1773
+ failure$1(res, error);
1774
+ }
1775
+ },
1776
+ PUT: async (req, res, url) => {
1777
+ const { title, description, sampling } = await readJsonBody(req);
1778
+ if (title !== void 0 && typeof title !== "string" || description !== void 0 && typeof description !== "string") return sendError(res, 400, "\"title\" and \"description\" must be text");
1779
+ const given = sampling === void 0 ? void 0 : samplingOf(sampling);
1780
+ if (typeof given === "string") return sendError(res, 400, given);
1781
+ try {
1782
+ sendJson(res, 200, await api.updateInfo(url.searchParams.get("name") ?? "", {
1783
+ ...title === void 0 ? {} : { title },
1784
+ ...description === void 0 ? {} : { description },
1785
+ ...given === void 0 ? {} : { sampling: given }
1786
+ }));
1787
+ } catch (error) {
1788
+ failure$1(res, error);
1789
+ }
1790
+ },
1791
+ DELETE: async (_req, res, url) => {
1792
+ try {
1793
+ await api.remove(url.searchParams.get("name") ?? "");
1794
+ res.statusCode = 204;
1795
+ res.end();
1796
+ } catch (error) {
1797
+ failure$1(res, error);
1798
+ }
1799
+ }
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
+ } },
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
+ },
1816
+ PUT: async (req, res, url) => {
1817
+ const { text } = await readJsonBody(req);
1818
+ if (typeof text !== "string" || text.trim() === "") return sendError(res, 400, "\"text\" is required");
1819
+ try {
1820
+ sendJson(res, 200, await api.writePrompt(url.searchParams.get("name") ?? "", languageOf(url.searchParams.get("language") ?? ""), url.searchParams.get("id") ?? "", text));
1821
+ } catch (error) {
1822
+ failure$1(res, error);
1823
+ }
1824
+ },
1825
+ DELETE: async (_req, res, url) => {
1826
+ try {
1827
+ sendJson(res, 200, await api.writePrompt(url.searchParams.get("name") ?? "", languageOf(url.searchParams.get("language") ?? ""), url.searchParams.get("id") ?? "", void 0));
1828
+ } catch (error) {
1829
+ failure$1(res, error);
1830
+ }
1831
+ }
1832
+ },
1833
+ "/presets/authoring": { POST: async (req, res, url) => {
1834
+ const { language } = await readJsonBody(req);
1835
+ if (language !== void 0 && typeof language !== "string") return sendError(res, 400, "\"language\" must be text");
1836
+ try {
1837
+ sendJson(res, 200, await api.author(url.searchParams.get("name") ?? "", language === void 0 ? void 0 : languageOf(language)));
1838
+ } catch (error) {
1839
+ failure$1(res, error);
1840
+ }
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
+ } },
1879
+ "/presets/import": { POST: async (req, res, url) => {
1880
+ const language = url.searchParams.get("language");
1881
+ try {
1882
+ sendJson(res, 200, await api.importFile(url.searchParams.get("name") ?? "", await readBinaryBody(req, api.maxUploadBytes), language === null ? void 0 : languageOf(language)));
1883
+ } catch (error) {
1884
+ failure$1(res, error);
1885
+ }
1886
+ } },
1887
+ "/sessions/preset": {
1888
+ GET: async (_req, res, url) => {
1889
+ try {
1890
+ sendJson(res, 200, api.status(url.searchParams.get("id") ?? ""));
1891
+ } catch (error) {
1892
+ failure$1(res, error);
1893
+ }
1894
+ },
1895
+ POST: async (req, res, url) => {
1896
+ const { name } = await readJsonBody(req);
1897
+ 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");
1898
+ try {
1899
+ sendJson(res, 200, api.apply(url.searchParams.get("id") ?? "", typeof name === "string" ? name : void 0));
1900
+ } catch (error) {
1901
+ failure$1(res, error);
1902
+ }
1903
+ }
1904
+ }
1905
+ };
1906
+ }
1907
+ //#endregion
1908
+ //#region src/host/lorebooks/routes.ts
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. */
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);
1914
+ if (error instanceof Error) return sendError(res, 422, error.message);
1915
+ throw error;
1916
+ }
1917
+ const texts = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string");
1918
+ /** Reads the body of an entry, or says what is wrong with it. */
1919
+ function entryOf(id, body) {
1920
+ const { title, kind, scope, knownBy, summary, body: text, related } = body;
1921
+ if (typeof title !== "string") return "\"title\" must be text";
1922
+ if (typeof kind !== "string" || !LORE_KINDS.includes(kind)) return `"kind" must be one of ${LORE_KINDS.join(", ")}`;
1923
+ if (typeof scope !== "string" || !LORE_SCOPES.includes(scope)) return `"scope" must be one of ${LORE_SCOPES.join(", ")}`;
1924
+ if (knownBy !== void 0 && !texts(knownBy)) return "\"knownBy\" must be a list of text";
1925
+ if (related !== void 0 && !texts(related)) return "\"related\" must be a list of text";
1926
+ if (summary !== void 0 && typeof summary !== "string" || text !== void 0 && typeof text !== "string") return "\"summary\" and \"body\" must be text";
1927
+ return {
1928
+ id,
1929
+ title,
1930
+ kind,
1931
+ scope,
1932
+ knownBy: knownBy?.map((entry) => entry.trim()).filter((entry) => entry !== "") ?? [],
1933
+ summary: summary ?? "",
1934
+ body: text ?? "",
1935
+ related: related ?? []
1936
+ };
1937
+ }
1938
+ function lorebookRoutes(api) {
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
+ },
1965
+ "/lorebooks": {
1966
+ GET: async (_req, res) => {
1967
+ try {
1968
+ sendJson(res, 200, await api.list());
1257
1969
  } catch (error) {
1258
1970
  failure(res, error);
1259
1971
  }
1260
1972
  },
1261
1973
  POST: async (req, res) => {
1262
- const { name, title, description, sampling, fromWorld } = await readJsonBody(req);
1974
+ const { name, title, description } = await readJsonBody(req);
1263
1975
  if (typeof name !== "string" || name === "") return sendError(res, 400, "\"name\" is required");
1264
- 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");
1265
1976
  if (title !== void 0 && typeof title !== "string" || description !== void 0 && typeof description !== "string") return sendError(res, 400, "\"title\" and \"description\" must be text");
1266
- const given = samplingOf(sampling);
1267
- if (typeof given === "string") return sendError(res, 400, given);
1268
1977
  try {
1269
1978
  sendJson(res, 201, await api.create({
1270
1979
  name,
1271
- ...fromWorld === void 0 ? {} : { fromWorld },
1272
1980
  ...title === void 0 ? {} : { title },
1273
- ...description === void 0 ? {} : { description },
1274
- sampling: given
1981
+ ...description === void 0 ? {} : { description }
1275
1982
  }));
1276
1983
  } catch (error) {
1277
1984
  failure(res, error);
1278
1985
  }
1279
1986
  }
1280
1987
  },
1281
- "/presets/item": {
1988
+ "/lorebooks/item": {
1282
1989
  GET: async (_req, res, url) => {
1283
1990
  try {
1284
- sendJson(res, 200, api.read(url.searchParams.get("name") ?? ""));
1991
+ sendJson(res, 200, await api.read(url.searchParams.get("name") ?? ""));
1285
1992
  } catch (error) {
1286
1993
  failure(res, error);
1287
1994
  }
1288
1995
  },
1289
1996
  PUT: async (req, res, url) => {
1290
- const { title, description, sampling } = await readJsonBody(req);
1997
+ const { title, description } = await readJsonBody(req);
1291
1998
  if (title !== void 0 && typeof title !== "string" || description !== void 0 && typeof description !== "string") return sendError(res, 400, "\"title\" and \"description\" must be text");
1292
- const given = sampling === void 0 ? void 0 : samplingOf(sampling);
1293
- if (typeof given === "string") return sendError(res, 400, given);
1294
1999
  try {
1295
2000
  sendJson(res, 200, await api.updateInfo(url.searchParams.get("name") ?? "", {
1296
2001
  ...title === void 0 ? {} : { title },
1297
- ...description === void 0 ? {} : { description },
1298
- ...given === void 0 ? {} : { sampling: given }
2002
+ ...description === void 0 ? {} : { description }
1299
2003
  }));
1300
2004
  } catch (error) {
1301
2005
  failure(res, error);
@@ -1311,25 +2015,25 @@ function presetRoutes(api) {
1311
2015
  }
1312
2016
  }
1313
2017
  },
1314
- "/presets/prompt": {
2018
+ "/lorebooks/entry": {
1315
2019
  PUT: async (req, res, url) => {
1316
- const { text } = await readJsonBody(req);
1317
- if (typeof text !== "string" || text.trim() === "") return sendError(res, 400, "\"text\" is required");
2020
+ const entry = entryOf(url.searchParams.get("id") ?? "", await readJsonBody(req));
2021
+ if (typeof entry === "string") return sendError(res, 400, entry);
1318
2022
  try {
1319
- sendJson(res, 200, await api.writePrompt(url.searchParams.get("name") ?? "", languageOf(url.searchParams.get("language") ?? ""), url.searchParams.get("id") ?? "", text));
2023
+ sendJson(res, 200, await api.writeEntry(url.searchParams.get("name") ?? "", entry));
1320
2024
  } catch (error) {
1321
2025
  failure(res, error);
1322
2026
  }
1323
2027
  },
1324
2028
  DELETE: async (_req, res, url) => {
1325
2029
  try {
1326
- sendJson(res, 200, await api.writePrompt(url.searchParams.get("name") ?? "", languageOf(url.searchParams.get("language") ?? ""), url.searchParams.get("id") ?? "", void 0));
2030
+ sendJson(res, 200, await api.removeEntry(url.searchParams.get("name") ?? "", url.searchParams.get("id") ?? ""));
1327
2031
  } catch (error) {
1328
2032
  failure(res, error);
1329
2033
  }
1330
2034
  }
1331
2035
  },
1332
- "/presets/authoring": { POST: async (req, res, url) => {
2036
+ "/lorebooks/authoring": { POST: async (req, res, url) => {
1333
2037
  const { language } = await readJsonBody(req);
1334
2038
  if (language !== void 0 && typeof language !== "string") return sendError(res, 400, "\"language\" must be text");
1335
2039
  try {
@@ -1338,32 +2042,53 @@ function presetRoutes(api) {
1338
2042
  failure(res, error);
1339
2043
  }
1340
2044
  } },
1341
- "/presets/import": { POST: async (req, res, url) => {
1342
- const language = url.searchParams.get("language");
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");
1343
2052
  try {
1344
- sendJson(res, 200, await api.importFile(url.searchParams.get("name") ?? "", await readBinaryBody(req, api.maxUploadBytes), language === null ? void 0 : languageOf(language)));
2053
+ sendJson(res, 200, await api.importVerbatim({
2054
+ ...choice,
2055
+ knownBy,
2056
+ ...name === void 0 ? {} : { name },
2057
+ ...title === void 0 ? {} : { title }
2058
+ }));
1345
2059
  } catch (error) {
1346
2060
  failure(res, error);
1347
2061
  }
1348
2062
  } },
1349
- "/sessions/preset": {
1350
- GET: async (_req, res, url) => {
1351
- try {
1352
- sendJson(res, 200, api.status(url.searchParams.get("id") ?? ""));
1353
- } catch (error) {
1354
- failure(res, error);
1355
- }
1356
- },
1357
- POST: async (req, res, url) => {
1358
- const { name } = await readJsonBody(req);
1359
- 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");
1360
- try {
1361
- sendJson(res, 200, api.apply(url.searchParams.get("id") ?? "", typeof name === "string" ? name : void 0));
1362
- } catch (error) {
1363
- failure(res, error);
1364
- }
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);
1365
2082
  }
1366
- }
2083
+ } },
2084
+ "/lorebooks/import": { POST: async (req, res, url) => {
2085
+ const language = url.searchParams.get("language");
2086
+ try {
2087
+ sendJson(res, 200, await api.importFile(url.searchParams.get("name") ?? "", await readBinaryBody(req, api.maxUploadBytes), language === null ? void 0 : languageOf(language)));
2088
+ } catch (error) {
2089
+ failure(res, error);
2090
+ }
2091
+ } }
1367
2092
  };
1368
2093
  }
1369
2094
  /** The headers of every file of a pack. */
@@ -2131,7 +2856,8 @@ const CATALOGUE_STATUS = {
2131
2856
  unknown: 404,
2132
2857
  upstream: 502,
2133
2858
  invalid: 422,
2134
- conflict: 409
2859
+ conflict: 409,
2860
+ unavailable: 503
2135
2861
  };
2136
2862
  /** A catalogue failure with the status that says whose fault it is; anything else is not ours to describe. */
2137
2863
  function catalogueFailure(res, error) {
@@ -2163,7 +2889,7 @@ function languageField(value) {
2163
2889
  throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
2164
2890
  }
2165
2891
  }
2166
- function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld, translation, worldCharacters, importer, avatars, worldFiles, worldEditor, sessions, packs, presets, connection, speech, externalTools }) {
2892
+ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld, translation, worldCharacters, importer, avatars, worldFiles, worldEditor, sessions, packs, presets, lorebooks, connection, speech, externalTools }) {
2167
2893
  const routes = {
2168
2894
  "/speech/capabilities": { GET: async (_req, res) => {
2169
2895
  sendJson(res, 200, { streaming: speech.streaming() });
@@ -2207,14 +2933,40 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
2207
2933
  }
2208
2934
  },
2209
2935
  "/catalogue/sources": { GET: async (_req, res) => {
2210
- sendJson(res, 200, catalogue.sources());
2936
+ try {
2937
+ sendJson(res, 200, await catalogue.sources());
2938
+ } catch (error) {
2939
+ return catalogueFailure(res, error);
2940
+ }
2211
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
+ },
2212
2960
  "/catalogue/worlds": { GET: async (_req, res, url) => {
2213
2961
  const offset = Number(url.searchParams.get("offset") ?? 0);
2214
2962
  const sort = url.searchParams.get("sort") === "popular" ? "popular" : "recent";
2215
2963
  try {
2216
2964
  sendJson(res, 200, await catalogue.worlds(url.searchParams.get("source") ?? "", {
2217
- kind: ["card", "preset"].find((entry) => entry === url.searchParams.get("kind")) ?? "world",
2965
+ kind: [
2966
+ "card",
2967
+ "preset",
2968
+ "lorebook"
2969
+ ].find((entry) => entry === url.searchParams.get("kind")) ?? "world",
2218
2970
  search: url.searchParams.get("search") ?? "",
2219
2971
  offset: Number.isFinite(offset) ? offset : 0,
2220
2972
  sort
@@ -2281,6 +3033,34 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
2281
3033
  return error instanceof CatalogueError ? catalogueFailure(res, error) : importFailure(res, error);
2282
3034
  }
2283
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
+ } },
2284
3064
  "/catalogue/convert/preset": { POST: async (req, res) => {
2285
3065
  const body = await readJsonBody(req);
2286
3066
  if (typeof body.source !== "string" || typeof body.versionId !== "string") return sendError(res, 400, "source and versionId must be text");
@@ -2297,6 +3077,36 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
2297
3077
  return error instanceof CatalogueError ? catalogueFailure(res, error) : importFailure(res, error);
2298
3078
  }
2299
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
+ } },
3094
+ "/catalogue/convert/lorebook": { POST: async (req, res) => {
3095
+ const body = await readJsonBody(req);
3096
+ if (typeof body.source !== "string" || typeof body.versionId !== "string") return sendError(res, 400, "source and versionId must be text");
3097
+ if (body.title !== void 0 && typeof body.title !== "string") return sendError(res, 400, "title must be text");
3098
+ try {
3099
+ const language = languageField(body.language);
3100
+ sendJson(res, 201, await catalogue.convertLorebook({
3101
+ source: body.source,
3102
+ versionId: body.versionId,
3103
+ ...body.title === void 0 ? {} : { title: body.title },
3104
+ ...language === void 0 ? {} : { language }
3105
+ }));
3106
+ } catch (error) {
3107
+ return error instanceof CatalogueError ? catalogueFailure(res, error) : importFailure(res, error);
3108
+ }
3109
+ } },
2300
3110
  "/worlds/starter": {
2301
3111
  GET: async (_req, res) => {
2302
3112
  sendJson(res, 200, await starter.list());
@@ -2330,6 +3140,49 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
2330
3140
  return importFailure(res, error);
2331
3141
  }
2332
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
+ } },
2333
3186
  "/worlds/import": {
2334
3187
  GET: async (_req, res, url) => {
2335
3188
  try {
@@ -2952,7 +3805,7 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
2952
3805
  sendJson(res, 200, sessions.list());
2953
3806
  },
2954
3807
  POST: async (req, res) => {
2955
- const { worldId, playerCharacterId, playerAvatar, avatars: brought, name, settings, opening, startingTime, preset } = await readJsonBody(req);
3808
+ const { worldId, playerCharacterId, playerAvatar, avatars: brought, name, settings, opening, startingTime, preset, lorebooks } = await readJsonBody(req);
2956
3809
  if (typeof worldId !== "string" || worldId.trim() === "") return sendError(res, 400, "\"worldId\" is required");
2957
3810
  if (playerCharacterId === void 0 && playerAvatar === void 0) return sendError(res, 400, "\"playerCharacterId\" or \"playerAvatar\" is required");
2958
3811
  if (playerCharacterId !== void 0 && (typeof playerCharacterId !== "string" || playerCharacterId.trim() === "")) return sendError(res, 400, "\"playerCharacterId\" must be text");
@@ -2962,9 +3815,11 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
2962
3815
  if (opening !== void 0 && (typeof opening !== "number" || !Number.isInteger(opening))) return sendError(res, 400, "\"opening\" must be a whole number");
2963
3816
  if (startingTime !== void 0 && typeof startingTime !== "string") return sendError(res, 400, "\"startingTime\" must be text");
2964
3817
  if (preset !== void 0 && typeof preset !== "string") return sendError(res, 400, "\"preset\" must be text");
3818
+ 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");
2965
3819
  try {
2966
3820
  sendJson(res, 201, await sessions.start({
2967
3821
  ...preset === void 0 || preset === "" ? {} : { preset },
3822
+ ...lorebooks === void 0 ? {} : { lorebooks },
2968
3823
  ...opening === void 0 ? {} : { opening },
2969
3824
  ...startingTime === void 0 ? {} : { startingTime },
2970
3825
  worldId,
@@ -3352,6 +4207,7 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
3352
4207
  } },
3353
4208
  ...interfaceRoutes(packs),
3354
4209
  ...presetRoutes(presets),
4210
+ ...lorebookRoutes(lorebooks),
3355
4211
  "/worlds/cover": { GET: async (_req, res, url) => {
3356
4212
  const cover = await worlds.cover(url.searchParams.get("id") ?? "");
3357
4213
  if (cover === void 0) return sendError(res, 404, "no cover");
@@ -3619,7 +4475,7 @@ async function editRoutine(world, key, windows) {
3619
4475
  const { calendar } = await loadCalendar(world.directory);
3620
4476
  const places = routineProblems([parsed.value], locations, calendar);
3621
4477
  if (places.length > 0) throw new InvalidEditProblems(places);
3622
- await replaceFile$1(file, next);
4478
+ await replaceFile(file, next);
3623
4479
  return await readRoutines(world);
3624
4480
  }
3625
4481
  /** The variables the world declares, as the file writes them. */
@@ -3661,7 +4517,7 @@ async function editVariables(world, declarations) {
3661
4517
  }
3662
4518
  async function replaceFileOrCreate(file, text) {
3663
4519
  try {
3664
- await replaceFile$1(file, text);
4520
+ await replaceFile(file, text);
3665
4521
  } catch (error) {
3666
4522
  if (error.code !== "ENOENT") throw error;
3667
4523
  await writeFile(file, text, { flag: "wx" });
@@ -3935,6 +4791,8 @@ function worldOf$1(session, sessionsDir) {
3935
4791
  key: entry.sourceId ?? String(entry.id),
3936
4792
  title: entry.title,
3937
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),
3938
4796
  summary: entry.summary,
3939
4797
  body: entry.body,
3940
4798
  ...entry.startsAt === void 0 ? {} : { startsAt: entry.startsAt },
@@ -4072,7 +4930,21 @@ function editWorldLore(deps, id, key, edit) {
4072
4930
  const session = sessionOf(deps, id);
4073
4931
  const entry = session.lore.list().find((candidate) => (candidate.sourceId ?? String(candidate.id)) === key);
4074
4932
  if (entry === void 0) throw new InvalidEditProblems([`there is no lore "${key}"`]);
4075
- 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
+ });
4076
4948
  return worldOf$1(session, deps.sessionsDir());
4077
4949
  }
4078
4950
  function editWorldPlots(deps, id, edit) {
@@ -4604,121 +5476,6 @@ async function addAvatarsToWorld(avatars, world, keys, locations) {
4604
5476
  }
4605
5477
  return brought.map((entry) => entry.id);
4606
5478
  }
4607
- //#endregion
4608
- //#region src/host/worlds/world-info.ts
4609
- async function replaceFile(file, text) {
4610
- const temporary = join(dirname(file), `.${basename(file)}.${process.pid}.${randomUUID()}.tmp`);
4611
- try {
4612
- const { mode } = await stat(file);
4613
- await writeFile(temporary, text, { mode });
4614
- await chmod(temporary, mode);
4615
- await rename(temporary, file);
4616
- } catch (error) {
4617
- await rm(temporary, { force: true });
4618
- throw error;
4619
- }
4620
- }
4621
- const textOf = (value) => typeof value === "string" ? value : "";
4622
- const toolsOf = (value) => {
4623
- const board = value === void 0 ? {} : parseSwitchboard(value, "tools");
4624
- return typeof board === "string" ? {} : board;
4625
- };
4626
- function infoOf(document) {
4627
- const opening = document["opening_message"];
4628
- const parts = Array.isArray(opening) && opening.some((part) => typeof part === "object" && part !== null && part["type"] === "utterance");
4629
- const plain = typeof opening === "string" ? opening : Array.isArray(opening) ? opening.map((part) => textOf(part?.["text"])).filter((text) => text !== "").join("\n\n") : "";
4630
- const metadata = typeof document["metadata"] === "object" && document["metadata"] !== null ? document["metadata"] : {};
4631
- const author = typeof document["author"] === "object" && document["author"] !== null ? document["author"] : {};
4632
- const rules = document["rules"];
4633
- return {
4634
- name: textOf(document["name"]),
4635
- description: textOf(document["description"]),
4636
- tags: Array.isArray(metadata["tags"]) ? metadata["tags"].filter((tag) => typeof tag === "string") : [],
4637
- rules: typeof rules === "string" ? [rules] : Array.isArray(rules) ? rules.filter((rule) => typeof rule === "string") : [],
4638
- opening: plain,
4639
- openingParts: parts,
4640
- authorName: textOf(author["name"]),
4641
- authorUrl: textOf(author["url"]),
4642
- timeZone: textOf(document["time_zone"]),
4643
- startingTime: textOf(document["starting_time"]),
4644
- preset: textOf(document["preset"]),
4645
- version: typeof document["version"] === "number" ? String(document["version"]) : textOf(document["version"]),
4646
- tools: toolsOf(document["tools"]),
4647
- alternateOpenings: Array.isArray(document["alternate_openings"]) ? document["alternate_openings"].flatMap((entry) => typeof entry === "object" && entry !== null && typeof entry["text"] === "string" ? [{
4648
- title: textOf(entry["title"]),
4649
- text: entry["text"],
4650
- ...textOf(entry["character"]) === "" ? {} : { character: textOf(entry["character"]) }
4651
- }] : []) : []
4652
- };
4653
- }
4654
- async function readDocument(directory) {
4655
- const text = await readFile(join(directory, WORLD_FILE_NAME), "utf8");
4656
- return {
4657
- text,
4658
- document: JSON.parse(text.replace(/^/, ""))
4659
- };
4660
- }
4661
- async function readWorldInfo(directory) {
4662
- return infoOf((await readDocument(directory)).document);
4663
- }
4664
- function setOrRemove(document, key, value) {
4665
- if (value === "") delete document[key];
4666
- else document[key] = value;
4667
- }
4668
- /**
4669
- * 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
4670
- * back as the world will be read before it is written.
4671
- * @throws {InvalidEditProblems} when the world would no longer be valid.
4672
- */
4673
- async function editWorldInfo(directory, edit) {
4674
- const { text, document } = await readDocument(directory);
4675
- const before = infoOf(document);
4676
- 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"]);
4677
- if (edit.name !== void 0) document["name"] = edit.name;
4678
- if (edit.description !== void 0) document["description"] = edit.description;
4679
- if (edit.tags !== void 0) document["metadata"] = {
4680
- ...typeof document["metadata"] === "object" && document["metadata"] !== null ? document["metadata"] : {},
4681
- tags: edit.tags
4682
- };
4683
- if (edit.rules !== void 0) {
4684
- if (edit.rules.length === 0) delete document["rules"];
4685
- else document["rules"] = edit.rules;
4686
- }
4687
- if (edit.opening !== void 0 && !before.openingParts) setOrRemove(document, "opening_message", edit.opening);
4688
- if (edit.authorName !== void 0 || edit.authorUrl !== void 0) {
4689
- const name = edit.authorName ?? before.authorName;
4690
- const url = edit.authorUrl ?? before.authorUrl;
4691
- if (name === "" && url !== "") throw new InvalidEditProblems(["an author link needs the author's name"]);
4692
- if (name === "") delete document["author"];
4693
- else document["author"] = {
4694
- ...typeof document["author"] === "object" && document["author"] !== null ? document["author"] : {},
4695
- name,
4696
- ...url === "" ? {} : { url }
4697
- };
4698
- if (url === "" && typeof document["author"] === "object") delete document["author"]["url"];
4699
- }
4700
- if (edit.timeZone !== void 0) setOrRemove(document, "time_zone", edit.timeZone);
4701
- if (edit.startingTime !== void 0) setOrRemove(document, "starting_time", edit.startingTime);
4702
- if (edit.version !== void 0) setOrRemove(document, "version", edit.version);
4703
- if (edit.preset !== void 0) setOrRemove(document, "preset", edit.preset);
4704
- if (edit.alternateOpenings !== void 0) {
4705
- if (edit.alternateOpenings.length === 0) delete document["alternate_openings"];
4706
- else document["alternate_openings"] = edit.alternateOpenings.map((entry) => ({
4707
- title: entry.title === "" ? entry.text.slice(0, 40) : entry.title,
4708
- text: entry.text,
4709
- ...entry.character === void 0 || entry.character === "" ? {} : { character: entry.character }
4710
- }));
4711
- }
4712
- if (edit.tools !== void 0) {
4713
- if (Object.keys(edit.tools).length === 0) delete document["tools"];
4714
- else document["tools"] = edit.tools;
4715
- }
4716
- const next = JSON.stringify(document, null, /^([ \t]+)"/m.exec(text)?.[1] ?? " ") + (text.endsWith("\n") ? "\n" : "");
4717
- const parsed = parseWorldFile(next);
4718
- if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
4719
- await replaceFile(join(directory, WORLD_FILE_NAME), next);
4720
- return infoOf(document);
4721
- }
4722
5479
  /**
4723
5480
  * Start a new session for a world: create its folder and database and fill it
4724
5481
  * from the world. Either the whole session exists afterwards or nothing does.
@@ -4784,16 +5541,34 @@ async function startSession(deps, request) {
4784
5541
  tools
4785
5542
  };
4786
5543
  const { preset, unavailable } = presetFor(deps, request.preset, world.preset);
4787
- if (preset !== void 0) {
4788
- const given = request.settings?.sampling ?? {};
4789
- settings = {
4790
- ...settings,
4791
- sampling: {
4792
- ...settings.sampling,
4793
- ...Object.fromEntries(Object.entries(preset.summary.sampling).filter(([key]) => given[key] === void 0))
4794
- }
4795
- };
5544
+ const asked = request.lorebooks !== void 0;
5545
+ const wanted = request.lorebooks ?? world.lorebooks ?? [];
5546
+ let books = {
5547
+ definitions: [],
5548
+ applied: [],
5549
+ notes: []
5550
+ };
5551
+ if (wanted.length > 0) {
5552
+ if (deps.root === void 0) throw new InvalidStartError("the lorebook library is not available");
5553
+ try {
5554
+ books = await lorebookLore(deps.root(), wanted, asked, (reference) => knowsCharacter(characters, reference), new Set(authoredLore.lore.map((entry) => entry.id)));
5555
+ } catch (error) {
5556
+ throw new InvalidStartError(error instanceof Error ? error.message : String(error));
5557
+ }
5558
+ unavailable.push(...books.notes);
4796
5559
  }
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
+ };
4797
5572
  let startsAt = world.clock?.startingTime;
4798
5573
  if (request.startingTime !== void 0 && request.startingTime.trim() !== "") {
4799
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");
@@ -4824,7 +5599,8 @@ async function startSession(deps, request) {
4824
5599
  populateDice(session, checks);
4825
5600
  populateRoutines(session, characters);
4826
5601
  populateItems(session, items, slots, locations);
4827
- populateLore(session, authoredLore.lore);
5602
+ populateLore(session, [...authoredLore.lore, ...books.definitions]);
5603
+ if (books.applied.length > 0) session.metadata.setValue(LOREBOOKS_KEY, books.applied);
4828
5604
  populateKnowledge(session, characters);
4829
5605
  populateVariables(session, declared.defs, {
4830
5606
  characters,
@@ -5248,6 +6024,7 @@ async function worldCharacters(worlds, worldId) {
5248
6024
  startingTime: world.clock?.startingTime === void 0 ? "" : localInstant(world.clock.startingTime, world.clock.timeZone ?? "UTC"),
5249
6025
  timeZone: world.clock?.timeZone ?? "",
5250
6026
  ...world.preset === void 0 ? {} : { preset: world.preset },
6027
+ ...world.lorebooks === void 0 ? {} : { lorebooks: world.lorebooks },
5251
6028
  problems
5252
6029
  };
5253
6030
  }
@@ -5266,9 +6043,12 @@ var RoleplayRoot = class extends Service {
5266
6043
  super(ctx, "roleplayRoot");
5267
6044
  this.source = source;
5268
6045
  this.current = resolveRootPath(source.get());
5269
- this.prepare(this.current);
5270
6046
  ctx.on("loader/volatile-update", () => this.refresh());
5271
6047
  }
6048
+ /** Prepare the configured root after construction. */
6049
+ start() {
6050
+ this.prepare(this.current);
6051
+ }
5272
6052
  /** Absolute path of the active root. */
5273
6053
  get path() {
5274
6054
  return this.current;
@@ -5391,7 +6171,7 @@ async function scanWorlds(worldsDir) {
5391
6171
  return result;
5392
6172
  }
5393
6173
  async function loadWorld(folder, dir, file, problems) {
5394
- const world = await readDocument$1(file, parseWorldFile, problems);
6174
+ const world = await readDocument(file, parseWorldFile, problems);
5395
6175
  if (world === void 0) return void 0;
5396
6176
  let id = world.id;
5397
6177
  if (id === void 0) try {
@@ -5421,7 +6201,9 @@ async function loadWorld(folder, dir, file, problems) {
5421
6201
  ...world.rules === void 0 ? {} : { rules: world.rules },
5422
6202
  ...world.tools === void 0 ? {} : { tools: world.tools },
5423
6203
  ...world.narrationVoice === void 0 ? {} : { narrationVoice: world.narrationVoice },
5424
- ...world.preset === void 0 ? {} : { preset: world.preset }
6204
+ ...world.sampling === void 0 ? {} : { sampling: world.sampling },
6205
+ ...world.preset === void 0 ? {} : { preset: world.preset },
6206
+ ...world.lorebooks === void 0 ? {} : { lorebooks: world.lorebooks }
5425
6207
  };
5426
6208
  if (world.coverMediaId !== void 0) try {
5427
6209
  record.cover = await resolveCover(dir, world.coverMediaId);
@@ -5550,8 +6332,19 @@ var WorldCatalog = class extends Service {
5550
6332
  };
5551
6333
  //#endregion
5552
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
+ }
5553
6345
  const CATALOGUE_CARD_TYPE = "sillytavern/character";
5554
6346
  const CATALOGUE_PRESET_TYPE = "sillytavern/preset";
6347
+ const CATALOGUE_LOREBOOK_TYPE = "sillytavern/lorebook";
5555
6348
  const CATALOGUE_WORLD_TYPE = "dsh-agentic-roleplay/world";
5556
6349
  //#endregion
5557
6350
  //#region src/host/catalogue/origin.ts
@@ -5965,7 +6758,7 @@ async function fetchAddress(address, options) {
5965
6758
  const vetted = vetUrl(url.href);
5966
6759
  if (typeof vetted === "string") throw new CatalogueError(`${url.href} ${vetted}`, "input");
5967
6760
  }
5968
- const key = source?.apiKey;
6761
+ const key = source === void 0 ? void 0 : await options.sources.key(source);
5969
6762
  let reply;
5970
6763
  try {
5971
6764
  reply = await transport(url, {
@@ -6014,11 +6807,12 @@ const object = (value, what) => {
6014
6807
  };
6015
6808
  const text = (value) => typeof value === "string" ? value : "";
6016
6809
  const count = (value) => typeof value === "number" && Number.isFinite(value) ? value : 0;
6017
- const kindOf = (type) => type === "sillytavern/character" ? "card" : type === "sillytavern/preset" ? "preset" : "world";
6810
+ const kindOf = (type) => type === "sillytavern/character" ? "card" : type === "sillytavern/preset" ? "preset" : type === "sillytavern/lorebook" ? "lorebook" : "world";
6018
6811
  const TYPES = {
6019
6812
  world: CATALOGUE_WORLD_TYPE,
6020
6813
  card: CATALOGUE_CARD_TYPE,
6021
- preset: CATALOGUE_PRESET_TYPE
6814
+ preset: CATALOGUE_PRESET_TYPE,
6815
+ lorebook: CATALOGUE_LOREBOOK_TYPE
6022
6816
  };
6023
6817
  function worldOf(value) {
6024
6818
  const item = object(value, "a world entry");
@@ -6063,8 +6857,16 @@ var Catalogue = class {
6063
6857
  constructor(deps) {
6064
6858
  this.deps = deps;
6065
6859
  }
6066
- sources() {
6067
- 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);
6068
6870
  }
6069
6871
  async worlds(name, query) {
6070
6872
  const source = this.deps.sources.get(name);
@@ -6084,7 +6886,7 @@ var Catalogue = class {
6084
6886
  return {
6085
6887
  items: answer["items"].map(worldOf),
6086
6888
  ...typeof next === "number" ? { nextOffset: next } : {},
6087
- withKey: source.apiKey !== void 0
6889
+ withKey: await this.deps.sources.key(source) !== void 0
6088
6890
  };
6089
6891
  }
6090
6892
  async world(name, id) {
@@ -6230,13 +7032,7 @@ var Catalogue = class {
6230
7032
  async convert(request) {
6231
7033
  const source = this.deps.sources.get(request.source);
6232
7034
  const release = await this.download(source, request.versionId, CATALOGUE_CARD_TYPE, "a character card");
6233
- const png = release.body.subarray(0, 4).equals(Buffer.from([
6234
- 137,
6235
- 80,
6236
- 78,
6237
- 71
6238
- ]));
6239
- 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);
6240
7036
  const record = await this.deps.worlds.find(converted.worldId);
6241
7037
  if (record === void 0) throw new CatalogueError("the world was made but cannot be found", "upstream");
6242
7038
  await writeOrigin(record.directory, {
@@ -6248,6 +7044,32 @@ var Catalogue = class {
6248
7044
  });
6249
7045
  return converted;
6250
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
+ }
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. */
7069
+ async convertLorebook(request) {
7070
+ const release = await this.download(this.deps.sources.get(request.source), request.versionId, CATALOGUE_LOREBOOK_TYPE, "a lorebook");
7071
+ return await this.deps.importLorebook(release.body, request.title ?? "", request.language);
7072
+ }
6251
7073
  /** 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. */
6252
7074
  async convertPreset(request) {
6253
7075
  const release = await this.download(this.deps.sources.get(request.source), request.versionId, CATALOGUE_PRESET_TYPE, "a preset");
@@ -6255,11 +7077,7 @@ var Catalogue = class {
6255
7077
  }
6256
7078
  /** A release of the given type, downloaded with the catalogue's key and checked against the checksum it published. */
6257
7079
  async download(source, versionIdText, type, what) {
6258
- const versionId = this.identifier(versionIdText);
6259
- const version = object(await this.json(source, `/versions/${versionId}`), "a version");
6260
- if (text(version["resourceType"]) !== type) throw new CatalogueError(`that release is not ${what}`, "invalid");
6261
- const resourceId = text(version["resourceId"]);
6262
- if (!ID.test(resourceId)) throw unexpected("a version without a resource id");
7080
+ const { version, versionId, resourceId } = await this.describe(source, versionIdText, type, what);
6263
7081
  const reply = await fetchAddress(this.address(source, `/versions/${versionId}/download`), {
6264
7082
  sources: this.deps.sources,
6265
7083
  maxBytes: this.deps.maxCardBytes(),
@@ -6275,6 +7093,24 @@ var Catalogue = class {
6275
7093
  version: text(version["version"])
6276
7094
  };
6277
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
+ }
6278
7114
  /** The catalogue release an address names, when it is a release download on a configured catalogue. */
6279
7115
  async provenance(url) {
6280
7116
  const source = this.deps.sources.match(url);
@@ -6358,8 +7194,11 @@ const prefixLength = (prefix, path) => prefix === "" || path === prefix || path.
6358
7194
  /** The catalogues the person configured, read afresh on every use so an edit applies at once. */
6359
7195
  var Sources = class {
6360
7196
  read;
6361
- 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) {
6362
7200
  this.read = read;
7201
+ this.store = store;
6363
7202
  }
6364
7203
  resolved() {
6365
7204
  const seen = /* @__PURE__ */ new Set();
@@ -6379,7 +7218,12 @@ var Sources = class {
6379
7218
  source,
6380
7219
  problem: `address ${base}`
6381
7220
  };
6382
- 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
+ };
6383
7227
  return {
6384
7228
  source,
6385
7229
  resolved: {
@@ -6387,19 +7231,74 @@ var Sources = class {
6387
7231
  root: `${base.origin}${prefix}`,
6388
7232
  origin: base.origin,
6389
7233
  prefix,
6390
- apiKey: source.apiKey.trim() === "" ? void 0 : source.apiKey.trim()
7234
+ keyRef,
7235
+ legacyKey: source.apiKey.trim() === "" ? void 0 : source.apiKey.trim()
6391
7236
  }
6392
7237
  };
6393
7238
  });
6394
7239
  }
6395
- status() {
6396
- return this.resolved().map(({ source, resolved, problem }) => ({
6397
- name: source.name.trim(),
6398
- baseUrl: source.baseUrl.trim(),
6399
- hasKey: source.apiKey.trim() !== "",
6400
- ...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
+ };
6401
7269
  }));
6402
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
+ }
6403
7302
  /** @throws {CatalogueError} when no usable catalogue has the name. */
6404
7303
  get(name) {
6405
7304
  const entry = this.resolved().find((candidate) => candidate.source.name.trim() === name);
@@ -6496,8 +7395,10 @@ const Config = z.object({
6496
7395
  catalogues: z.array(z.object({
6497
7396
  name: z.string().required(),
6498
7397
  baseUrl: z.string().required(),
7398
+ apiKeyRef: z.string().default(""),
6499
7399
  apiKey: z.string().default("")
6500
7400
  })).default([]).volatile(),
7401
+ authoringTools: z.dict(z.dict(z.boolean())).default({}).volatile(),
6501
7402
  catalogueMaxBytes: z.number().min(1024).default(268435456),
6502
7403
  catalogueTrashDays: z.number().min(0).default(30),
6503
7404
  importMaxUploadBytes: z.number().min(1024).default(104857600),
@@ -6521,26 +7422,34 @@ function apply(ctx, config) {
6521
7422
  const helper = childSamplingOf(id);
6522
7423
  if (helper !== void 0) return helper;
6523
7424
  const session = roleplaySessionOf(id);
6524
- return session === void 0 ? void 0 : {
6525
- 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),
6526
7430
  priority: "foreground"
6527
7431
  };
6528
7432
  }), "roleplay: request controls");
6529
7433
  });
6530
7434
  ctx.effect(() => useChildReasoning(config.childReasoning), "roleplay: helper thinking level");
6531
7435
  const root = new RoleplayRoot(ctx, config.rootPath);
6532
- new RoleplayOrchestration(ctx);
7436
+ root.start();
7437
+ const orchestration = new RoleplayOrchestration(ctx);
6533
7438
  const worlds = new WorldCatalog(ctx, root);
6534
7439
  const prompts = new PromptLibrary(ctx, root);
6535
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")}`);
6536
7443
  installFirstPartyPacks(root.path);
6537
7444
  const languages = new AuthoringLanguages(ctx, () => join(root.path, "worlds"));
7445
+ const authoringTools = new AuthoringTools(ctx, () => config.authoringTools.get());
6538
7446
  const agent = new AgentSessions(agentServicesOf(ctx), () => root.path);
6539
7447
  const authoring = new AuthoringSessions(agentServicesOf(ctx), () => root.path, prompts, languages);
6540
7448
  const presetAuthoring = new PresetAuthoringSessions(agentServicesOf(ctx), () => root.path, prompts, languages);
7449
+ const lorebookAuthoring = new LorebookAuthoringSessions(agentServicesOf(ctx), () => root.path, prompts, languages);
6541
7450
  const doctors = new DoctorSessions(agentServicesOf(ctx), () => root.path, prompts);
6542
7451
  const imports = new ImportStore(() => root.path);
6543
- new RoleplayImport(ctx, {
7452
+ const roleplayImport = new RoleplayImport(ctx, {
6544
7453
  maxUploadBytes: config.importMaxUploadBytes,
6545
7454
  concurrency: config.importConcurrency,
6546
7455
  reasoning: config.importReasoning,
@@ -6553,11 +7462,12 @@ function apply(ctx, config) {
6553
7462
  clockMode: (id) => ctx.roleplayState.openSession(join(root.path, "sessions"), id).clock.get()?.mode,
6554
7463
  pendingConsolidation: (id) => ctx.roleplayState.openSession(join(root.path, "sessions"), id).consolidation.pending().length,
6555
7464
  vectors: (id) => vectorStatus(ctx.roleplayState.openSession(join(root.path, "sessions"), id)),
6556
- 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))),
6557
7466
  activity: (id) => readActivity(ctx.roleplayState.openSession(join(root.path, "sessions"), id)),
6558
7467
  usage: (id) => readUsage(ctx.roleplayState.openSession(join(root.path, "sessions"), id)),
6559
7468
  interventions: (id) => readInterventions(ctx.roleplayState.openSession(join(root.path, "sessions"), id))
6560
7469
  };
7470
+ const staging = new ImportStaging();
6561
7471
  const purgeChat = purgeOf(ctx, config.sessionStorePath);
6562
7472
  const deps = {
6563
7473
  worlds,
@@ -6573,10 +7483,24 @@ function apply(ctx, config) {
6573
7483
  authoring: presetAuthoring,
6574
7484
  importMessage: narrationImportMessage,
6575
7485
  maxUploadBytes: config.importMaxUploadBytes,
6576
- playing: (id) => ctx.roleplayOrchestration.playing(chatSessionId(id))
7486
+ staging,
7487
+ playing: (id) => orchestration.playing(chatSessionId(id))
7488
+ });
7489
+ const lorebookLibrary = new Lorebooks({
7490
+ root: () => root.path,
7491
+ authoring: lorebookAuthoring,
7492
+ importMessage: lorebookImportMessage,
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))
6577
7501
  });
6578
7502
  const catalogue = new Catalogue({
6579
- sources: new Sources(() => config.catalogues.get()),
7503
+ sources: new Sources(() => config.catalogues.get(), () => ctx.get("credentials")),
6580
7504
  worlds,
6581
7505
  maxBytes: () => config.catalogueMaxBytes,
6582
7506
  maxCardBytes: () => config.importMaxUploadBytes,
@@ -6584,7 +7508,16 @@ function apply(ctx, config) {
6584
7508
  problem: (message) => {
6585
7509
  ctx.logger.warn(message);
6586
7510
  },
7511
+ stage: (kind, file, name) => staging.stage(kind, file, name),
6587
7512
  importPreset: async (file, title, language) => await presetLibrary.importTitled(title, file, language),
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),
6588
7521
  importCard: async (file, name, language) => {
6589
7522
  const preview = await imports.create(readCard(file, name), isPng(file) ? pictureOf(file) : void 0);
6590
7523
  return await startImport({
@@ -6599,6 +7532,7 @@ function apply(ctx, config) {
6599
7532
  registerApi(ctx, {
6600
7533
  catalogue,
6601
7534
  presets: presetLibrary,
7535
+ lorebooks: lorebookLibrary,
6602
7536
  packs: new InterfaceService({
6603
7537
  open: (id) => ctx.roleplayState.openSession(deps.sessionsDir(), id),
6604
7538
  root: () => root.path,
@@ -6648,7 +7582,26 @@ function apply(ctx, config) {
6648
7582
  uploadPreset: (worldId, file, name, language) => uploadPreset({
6649
7583
  worlds,
6650
7584
  authoring
6651
- }, 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
+ }
6652
7605
  },
6653
7606
  worldCharacters: (worldId) => worldCharacters(worlds, worldId),
6654
7607
  avatars: {
@@ -6854,6 +7807,11 @@ function apply(ctx, config) {
6854
7807
  }
6855
7808
  }
6856
7809
  });
7810
+ return {
7811
+ orchestration,
7812
+ authoringTools,
7813
+ roleplayImport
7814
+ };
6857
7815
  }
6858
7816
  /** The folder of a session whose images are listed. @throws {SessionNotFoundError} when there is no such session. */
6859
7817
  function galleryFolder(sessionsDir, id) {