@dsh-agentic-roleplay/core 0.3.3 → 0.3.5

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 (36) hide show
  1. package/lib/authoring.js +7 -256
  2. package/lib/{child-lPncV1ps.js → child-CFjnaTZt.js} +62 -7
  3. package/lib/client.js +10950 -7439
  4. package/lib/client.js.map +1 -1
  5. package/lib/{deliver-De62a8i9.js → deliver-Cl6bjp7g.js} +49 -11
  6. package/lib/doctor.js +83 -7
  7. package/lib/{gallery-CtFDL22W.js → gallery-DIEgETzU.js} +2 -2
  8. package/lib/generator-DJ48HxPI.js +145 -0
  9. package/lib/{hooks-Ka22sFNy.js → hooks-DdO_tNhu.js} +58 -17
  10. package/lib/images.js +4 -3
  11. package/lib/index.js +1761 -71
  12. package/lib/language-BgyxtB2h.js +38 -0
  13. package/lib/{generator-B6FxlKOV.js → library-9JB9zw5a.js} +2 -143
  14. package/lib/{language-DWVwi1R7.js → load-Clkl0T7C.js} +6 -40
  15. package/lib/orchestration.js +23 -26
  16. package/lib/pack-jail-ClMpVc__.js +1979 -0
  17. package/lib/{packs-BYjrAen6.js → packs-BC2A3geF.js} +3 -29
  18. package/lib/{presenter-agent-Dt21K96b.js → presenter-agent-DnNEG_Mn.js} +5 -4
  19. package/lib/{documents-Do4lz4SB.js → preset-ClQm7KPQ.js} +67 -1656
  20. package/lib/preset-author-tools-Dibp-LY9.js +270 -0
  21. package/lib/preset-authoring.js +53 -0
  22. package/lib/presets-DNjNxQL5.js +335 -0
  23. package/lib/{reflection-md7BCYCl.js → reflection-Bju_LPFn.js} +131 -9
  24. package/package.json +3 -2
  25. package/prompts/en/doctor/procedure.md +1 -1
  26. package/prompts/en/import/character.md +1 -1
  27. package/prompts/en/preset/persona.md +1 -0
  28. package/prompts/en/preset/procedure.md +1 -0
  29. package/prompts/en/preset/welcome.md +1 -0
  30. package/prompts/en/roleplay/record-keeper.md +2 -2
  31. package/prompts/zh/doctor/procedure.md +1 -1
  32. package/prompts/zh/import/character.md +1 -1
  33. package/prompts/zh/preset/persona.md +1 -0
  34. package/prompts/zh/preset/procedure.md +1 -0
  35. package/prompts/zh/preset/welcome.md +1 -0
  36. package/prompts/zh/roleplay/record-keeper.md +2 -2
package/lib/index.js CHANGED
@@ -1,25 +1,32 @@
1
1
  import { n as chatSessionId, r as roleplaySessionOf } from "./access-EbNdZFbk.js";
2
- import { $ as parseDiceFile, At as parsePlaceEdit, B as populateDice, Bt as DICE_RESULTS, C as presetMessage, Ct as WORLD_FILE_NAME, Dt as parseCharacterEdit, E as translateMessage, Et as InvalidEditProblems, F as markReady, Ft as isPng, G as populateLore, H as populateItems, I as loadValidatedWorld, It as pictureOf, J as populateVariables, K as populateRoutines, L as populateCalendar, Lt as readCard, M as languageOfDocuments, Mt as parseThingEdit, N as readWorldDocuments, Nt as IMPORT_COMMAND, Ot as parseFactionEdit, Pt as ImportCardError, Q as loadDice, R as populateCharacters, Rt as DICE_COMPARISONS, S as PRESET_FILE, St as parseChoices, T as readPreset, Tt as parseWorldInfoEdit, U as populateKnowledge, V as populateFactions, W as populateLocations, X as TRIGGERS_FILE_NAME, Y as routineProblems, Z as DICE_FILE_NAME, _ as replaceFile$1, _t as CHARACTER_FILE_NAME, at as CHARACTERS_DIR, bt as ImportNotFoundError, c as editWorldLore$1, d as editWorldPlots$1, dt as readWorldPrompt, et as CALENDAR_FILE_NAME, f as editWorldRelation$1, ft as writeWorldPrompt, g as readWorldEditor, gt as variableProblems, h as generateWorldCharacterPortrait, ht as parseVariablesFile, i as readAuthoredEntityDocument, it as loadItems, j as authoringChatSessionId, jt as parseRelationEdit, kt as parseLoreEdit, l as editWorldNarrationVoice, lt as deleteWorldPrompt, m as entityFolder, mt as loadVariables, n as createAuthoredEntity, nt as parseCalendarFile, o as editWorldCharacter$1, ot as loadCharacters, p as editWorldThing$1, pt as VARIABLES_FILE_NAME, q as populateTriggers, r as deleteAuthoredEntity, rt as loadLocations, s as editWorldFaction$1, st as subfolders, tt as loadCalendar, u as editWorldPlace$1, ut as listWorldPrompts, v as uploadWorldCharacterPortrait, vt as parseCharacterFile, wt as parseWorldFile, x as loadWorldParts, xt as ImportStore, y as worldCharacterPortraitFile, yt as IMPORT_FOLDER, z as populateClock, zt as DICE_READINGS } from "./documents-Do4lz4SB.js";
3
- import { _ as API_PREFIX, a as packIds, c as describePack, f as readPack, l as isPackId, m as PACK_LIMITS, n as anyTab, o as syncWorldPacks, r as copyWorldPacks, s as worldPackStates, t as activePack, u as packFile } from "./packs-BYjrAen6.js";
4
- import { c as readTimeline, i as reflectionStatus, l as pathTo, o as TimelineError, u as defaultBoundaries } from "./reflection-md7BCYCl.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
5
  import { a as WORLD_RULES_KEY, c as VARIABLE_SUBJECTS, i as parseSwitchboard, l as VARIABLE_VISIBILITIES, n as SETTINGS_SPEC, r as parseSettings, s as VARIABLE_KINDS, t as DEFAULT_SETTINGS } from "./settings-CA6icLL_.js";
6
- import { A as WorldNotFoundError, D as ReflectionRefusedError, E as InvalidWorldError, O as SessionArchivedError, T as InvalidStartError, c as parsePlotsFile, d as errorMessage, g as copyWorldPrompts, h as PromptLibrary, k as SessionNotFoundError, l as plotReferenceProblems, p as formatIssue, u as readDocument$1, v as languageOf, w as AgentUnavailableError } from "./language-DWVwi1R7.js";
7
- import { C as addToNote, D as readNotes, L as zoneOf, O as observeAsPlayer, T as notesOfSession, _ as plotProgressOf, a as readActivity, l as externalTools, n as readWithdrawn, o as readRunDetail, p as PLOTS_METADATA_KEY, v as populatePlots } from "./deliver-De62a8i9.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
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-lPncV1ps.js";
10
- import { T as uniqueKey, a as uploadReferenceImage, m as sceneImagePath, o as addToLibrary, p as referenceImagePath, t as generateReferenceImage, u as inheritImages, w as slug } from "./generator-B6FxlKOV.js";
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";
11
13
  import { t as doctorChatSessionId } from "./doctor-chat-ByDfCMeo.js";
12
- import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-CtFDL22W.js";
13
- import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve } from "node:path";
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";
17
+ import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
14
18
  import { cpSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
15
19
  import { createHash, randomBytes, randomUUID } from "node:crypto";
16
20
  import { Session, SessionId } from "@deepseek-ai/dsh-session";
17
21
  import { ToolCallId, createMessage, createSystemMessage, createToolResultMessage } from "@deepseek-ai/dsh-llm";
18
22
  import { setApprovalPolicy } from "@deepseek-ai/dsh-user-approval";
23
+ import { inflateRawSync } from "node:zlib";
19
24
  import { fileURLToPath } from "node:url";
20
25
  import { Service } from "@deepseek-ai/cordis";
21
26
  import { chmod, copyFile, cp, lstat, mkdir, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
22
27
  import { addLocalDays, createSessionStore, describeInstant, describeValue, holidaysOn, isSessionId, itemKey, lintWorld, locationKey, parseInstant, readCalendar, seasonOf, sessionDatabase, sessionFolder, shownVariables, systemTimeZone } from "@dsh-agentic-roleplay/state";
28
+ import { request } from "node:http";
29
+ import { request as request$1 } from "node:https";
23
30
  import { pipeline } from "node:stream/promises";
24
31
  import { homedir } from "node:os";
25
32
  import z from "@deepseek-ai/schemastery";
@@ -376,6 +383,7 @@ async function createWorld(catalog, input) {
376
383
  if (folder === "" || !FOLDER.test(folder) || folder === "." || folder === ".." || /[. ]$/.test(folder)) problems.push("folder must be 1–100 letters, numbers, spaces, dots, underscores or hyphens; it cannot end in a dot or space");
377
384
  if (name === "") problems.push("world name is required");
378
385
  if (name.length > 200) problems.push("world name must be at most 200 characters");
386
+ if (input.preset !== void 0 && input.preset !== "" && !isPresetName(input.preset)) problems.push("preset must be the name of a preset in the library");
379
387
  if (problems.length > 0) throw new InvalidEditProblems(problems);
380
388
  await mkdir(catalog.directory, { recursive: true });
381
389
  const directory = join(catalog.directory, folder);
@@ -391,7 +399,8 @@ async function createWorld(catalog, input) {
391
399
  id,
392
400
  name,
393
401
  description: "",
394
- metadata: { tags: [] }
402
+ metadata: { tags: [] },
403
+ ...input.preset === void 0 || input.preset === "" ? {} : { preset: input.preset }
395
404
  }, null, 2) + "\n", {
396
405
  flag: "wx",
397
406
  mode: 420
@@ -495,7 +504,7 @@ async function uploadPreset(deps, worldId, file, name, language) {
495
504
  if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
496
505
  const preset = readPreset(file, name);
497
506
  await mkdir(join(world.directory, IMPORT_FOLDER), { recursive: true });
498
- await writeFile(join(world.directory, IMPORT_FOLDER, PRESET_FILE), file);
507
+ await writeFile(join(world.directory, IMPORT_FOLDER, PRESET_FILE$1), file);
499
508
  const chatSessionId = await deps.authoring.ensure(world.summary.id, world.summary.name, `Authoring ${world.summary.name}`, language);
500
509
  let failure;
501
510
  try {
@@ -565,6 +574,58 @@ var AuthoringSessions = class {
565
574
  }
566
575
  };
567
576
  //#endregion
577
+ //#region src/host/agent/preset-authoring-sessions.ts
578
+ const PRESET_AUTHORING_PROJECT_TITLE = "Preset Authoring";
579
+ const PRESET_AUTHORING_PRESET = "preset-authoring";
580
+ /** Creates or reopens the dedicated authoring chat of a library preset, and speaks in it for the person when asked to. */
581
+ var PresetAuthoringSessions = class {
582
+ services;
583
+ roleplayRoot;
584
+ prompts;
585
+ languages;
586
+ constructor(services, roleplayRoot, prompts, languages) {
587
+ this.services = services;
588
+ this.roleplayRoot = roleplayRoot;
589
+ this.prompts = prompts;
590
+ this.languages = languages;
591
+ }
592
+ async ensure(name, title, language) {
593
+ this.languages.set(`preset:${name}`, language);
594
+ const services = this.services();
595
+ const projectPath = join(this.roleplayRoot(), "presets");
596
+ const project = await services.registry.create(projectPath, PRESET_AUTHORING_PROJECT_TITLE);
597
+ const sessionId = presetChatSessionId(name);
598
+ const stored = !project.sessionIds.includes(sessionId) && await isStored(services.persistence, sessionId);
599
+ if (!project.sessionIds.includes(sessionId) && !stored) {
600
+ if (services.persistence === void 0) throw new AgentUnavailableError("this DSH profile cannot store the opening of an authoring chat");
601
+ await storeAuthoringOpening(services.persistence, {
602
+ id: sessionId,
603
+ cwd: project.path,
604
+ agentPreset: PRESET_AUTHORING_PRESET
605
+ }, this.prompts.text("preset/welcome", this.languages.get(`preset:${name}`), { preset: title }));
606
+ }
607
+ return await ensureAgentChat(services, {
608
+ projectPath,
609
+ projectTitle: PRESET_AUTHORING_PROJECT_TITLE,
610
+ sessionId,
611
+ agentPreset: PRESET_AUTHORING_PRESET,
612
+ title: `Preset ${title}`,
613
+ renameExisting: true
614
+ }, project);
615
+ }
616
+ async send(sessionId, text) {
617
+ await this.services().controller.prompt({
618
+ requestId: randomUUID(),
619
+ sessionId,
620
+ mode: "queue",
621
+ content: [{
622
+ type: "text",
623
+ text
624
+ }]
625
+ }, new AbortController().signal);
626
+ }
627
+ };
628
+ //#endregion
568
629
  //#region src/host/agent/doctor-sessions.ts
569
630
  const DOCTOR_PROJECT_TITLE = "Session Doctor";
570
631
  const DOCTOR_AGENT_PRESET = "session-doctor";
@@ -614,6 +675,8 @@ var RoleplayOrchestration = class extends Service {
614
675
  halt = () => Promise.resolve();
615
676
  /** Starts a reflection of a chat's characters on what they have taken in, in the background; there while the orchestration is. */
616
677
  reflect = () => Promise.reject(/* @__PURE__ */ new Error("the orchestration is not running"));
678
+ /** Whether a turn of the chat is being played; there while the orchestration is. */
679
+ playing = () => false;
617
680
  /** Whether a reflection of the chat is running; there while the orchestration is. */
618
681
  reflecting = () => false;
619
682
  /** What the story's turns are and taking the story back to one; there while the orchestration is. */
@@ -994,6 +1057,17 @@ async function addStarterWorld(catalog, folder, directory = starterDirectory())
994
1057
  return added;
995
1058
  }
996
1059
  //#endregion
1060
+ //#region src/host/catalogue/errors.ts
1061
+ var CatalogueError = class extends Error {
1062
+ failure;
1063
+ detail;
1064
+ constructor(message, failure, detail) {
1065
+ super(message);
1066
+ this.failure = failure;
1067
+ this.detail = detail;
1068
+ }
1069
+ };
1070
+ //#endregion
997
1071
  //#region src/host/http/respond.ts
998
1072
  function sendJson(res, status, payload) {
999
1073
  res.statusCode = status;
@@ -1049,6 +1123,249 @@ async function readBinaryBody(req, limit) {
1049
1123
  if (size === 0) throw new HttpError(400, "the upload is empty");
1050
1124
  return Buffer.concat(chunks);
1051
1125
  }
1126
+ //#endregion
1127
+ //#region src/host/presets/service.ts
1128
+ /** The story's prompts cannot change right now. */
1129
+ var PresetBusyError = class extends Error {};
1130
+ /** The preset library and the presets of stories. Refusals are plain `Error`s with the reason; unknown stories and worlds are not-found errors. */
1131
+ var Presets = class {
1132
+ deps;
1133
+ constructor(deps) {
1134
+ this.deps = deps;
1135
+ }
1136
+ get maxUploadBytes() {
1137
+ return this.deps.maxUploadBytes;
1138
+ }
1139
+ list() {
1140
+ return listPresets(this.deps.root()).map((entry) => entry.summary);
1141
+ }
1142
+ /** A preset with the text of each prompt it carries, keyed `<language>/<id>`. */
1143
+ read(name) {
1144
+ const loaded = loadPreset(this.deps.root(), name);
1145
+ return {
1146
+ summary: loaded.summary,
1147
+ prompts: Object.fromEntries([...loaded.files].map(([path, text]) => [path.slice(0, -3), text]))
1148
+ };
1149
+ }
1150
+ async saveFromWorld(request) {
1151
+ const directory = await this.deps.worldDirectory(request.fromWorld);
1152
+ if (directory === void 0) throw new WorldNotFoundError(`there is no world with id "${request.fromWorld}"`);
1153
+ return (await savePresetFromWorld(this.deps.root(), directory, request)).summary;
1154
+ }
1155
+ /** Makes a preset from a world's own prose prompts, or from the shipped ones as a starting point when no world is given. */
1156
+ async create(request) {
1157
+ if (request.fromWorld !== void 0) return await this.saveFromWorld({
1158
+ ...request,
1159
+ fromWorld: request.fromWorld
1160
+ });
1161
+ return (await createPresetFromShipped(this.deps.root(), request)).summary;
1162
+ }
1163
+ async updateInfo(name, change) {
1164
+ return (await updatePresetInfo(this.deps.root(), name, change)).summary;
1165
+ }
1166
+ /** Writes the person's own text of a prompt; `undefined` takes the preset's version out. */
1167
+ 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(", ")}`);
1171
+ if (text === void 0) await deleteWorldPrompt(directory, language, id);
1172
+ else await writeWorldPrompt(directory, language, id, text);
1173
+ return loadPreset(this.deps.root(), name).summary;
1174
+ }
1175
+ /** Like `importFile`, under a name made from the title that is not yet taken. */
1176
+ async importTitled(title, file, language) {
1177
+ const base = title.normalize("NFKD").replace(/[^A-Za-z0-9_-]+/g, "-").replace(/^[-_]+|[-_]+$/g, "").slice(0, 56) || "preset";
1178
+ const taken = new Set(listPresets(this.deps.root()).map((entry) => entry.summary.name));
1179
+ let name = base;
1180
+ 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));
1182
+ }
1183
+ /** Opens the authoring chat of a preset. */
1184
+ async author(name, language) {
1185
+ const loaded = loadPreset(this.deps.root(), name);
1186
+ return { chatSessionId: await this.deps.authoring.ensure(name, loaded.summary.title, language) };
1187
+ }
1188
+ /** Keeps an uploaded SillyTavern preset in a new library preset and has its authoring chat turn it into prompts. @throws {ImportCardError} when the file is not a preset. */
1189
+ async importFile(name, file, language, title) {
1190
+ const uploaded = readPreset(file, name);
1191
+ const root = this.deps.root();
1192
+ const directory = await reservePreset(root, name, title ?? uploaded.name);
1193
+ try {
1194
+ await mkdir(join(directory, IMPORT_FOLDER), { recursive: true });
1195
+ await writeFile(join(directory, IMPORT_FOLDER, PRESET_FILE), file);
1196
+ } catch (error) {
1197
+ await deletePreset(root, name);
1198
+ throw error;
1199
+ }
1200
+ const chatSessionId = await this.deps.authoring.ensure(name, title ?? uploaded.name, language);
1201
+ let failure;
1202
+ try {
1203
+ await this.deps.authoring.send(chatSessionId, this.deps.importMessage());
1204
+ } catch (problem) {
1205
+ failure = problem instanceof Error ? problem.message : String(problem);
1206
+ }
1207
+ return {
1208
+ name,
1209
+ chatSessionId,
1210
+ started: failure === void 0,
1211
+ ...failure === void 0 ? {} : { failure }
1212
+ };
1213
+ }
1214
+ async remove(name) {
1215
+ await deletePreset(this.deps.root(), name);
1216
+ }
1217
+ status(session) {
1218
+ return presetStatus(this.deps.root(), this.folder(session));
1219
+ }
1220
+ /** Puts the named preset into a story, or takes the story's preset out when no name is given. */
1221
+ apply(session, name) {
1222
+ const folder = this.folder(session);
1223
+ if (this.deps.playing(session)) throw new PresetBusyError("a turn is being played; change the preset when it is over");
1224
+ return { files: switchPreset(this.deps.root(), folder, name) };
1225
+ }
1226
+ folder(id) {
1227
+ const sessions = `${this.deps.root()}/sessions`;
1228
+ if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);
1229
+ return sessionFolder(sessions, id);
1230
+ }
1231
+ };
1232
+ //#endregion
1233
+ //#region src/host/presets/routes.ts
1234
+ /** 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) {
1236
+ if (error instanceof SessionNotFoundError || error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
1237
+ if (error instanceof PresetBusyError) return sendError(res, 409, error.message);
1238
+ if (error instanceof Error) return sendError(res, 422, error.message);
1239
+ throw error;
1240
+ }
1241
+ 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
+ };
1250
+ }
1251
+ function presetRoutes(api) {
1252
+ return {
1253
+ "/presets": {
1254
+ GET: async (_req, res) => {
1255
+ try {
1256
+ sendJson(res, 200, api.list());
1257
+ } catch (error) {
1258
+ failure(res, error);
1259
+ }
1260
+ },
1261
+ POST: async (req, res) => {
1262
+ const { name, title, description, sampling, fromWorld } = await readJsonBody(req);
1263
+ 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
+ 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
+ try {
1269
+ sendJson(res, 201, await api.create({
1270
+ name,
1271
+ ...fromWorld === void 0 ? {} : { fromWorld },
1272
+ ...title === void 0 ? {} : { title },
1273
+ ...description === void 0 ? {} : { description },
1274
+ sampling: given
1275
+ }));
1276
+ } catch (error) {
1277
+ failure(res, error);
1278
+ }
1279
+ }
1280
+ },
1281
+ "/presets/item": {
1282
+ GET: async (_req, res, url) => {
1283
+ try {
1284
+ sendJson(res, 200, api.read(url.searchParams.get("name") ?? ""));
1285
+ } catch (error) {
1286
+ failure(res, error);
1287
+ }
1288
+ },
1289
+ PUT: async (req, res, url) => {
1290
+ const { title, description, sampling } = await readJsonBody(req);
1291
+ 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
+ try {
1295
+ sendJson(res, 200, await api.updateInfo(url.searchParams.get("name") ?? "", {
1296
+ ...title === void 0 ? {} : { title },
1297
+ ...description === void 0 ? {} : { description },
1298
+ ...given === void 0 ? {} : { sampling: given }
1299
+ }));
1300
+ } catch (error) {
1301
+ failure(res, error);
1302
+ }
1303
+ },
1304
+ DELETE: async (_req, res, url) => {
1305
+ try {
1306
+ await api.remove(url.searchParams.get("name") ?? "");
1307
+ res.statusCode = 204;
1308
+ res.end();
1309
+ } catch (error) {
1310
+ failure(res, error);
1311
+ }
1312
+ }
1313
+ },
1314
+ "/presets/prompt": {
1315
+ 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");
1318
+ try {
1319
+ sendJson(res, 200, await api.writePrompt(url.searchParams.get("name") ?? "", languageOf(url.searchParams.get("language") ?? ""), url.searchParams.get("id") ?? "", text));
1320
+ } catch (error) {
1321
+ failure(res, error);
1322
+ }
1323
+ },
1324
+ DELETE: async (_req, res, url) => {
1325
+ try {
1326
+ sendJson(res, 200, await api.writePrompt(url.searchParams.get("name") ?? "", languageOf(url.searchParams.get("language") ?? ""), url.searchParams.get("id") ?? "", void 0));
1327
+ } catch (error) {
1328
+ failure(res, error);
1329
+ }
1330
+ }
1331
+ },
1332
+ "/presets/authoring": { POST: async (req, res, url) => {
1333
+ const { language } = await readJsonBody(req);
1334
+ if (language !== void 0 && typeof language !== "string") return sendError(res, 400, "\"language\" must be text");
1335
+ try {
1336
+ sendJson(res, 200, await api.author(url.searchParams.get("name") ?? "", language === void 0 ? void 0 : languageOf(language)));
1337
+ } catch (error) {
1338
+ failure(res, error);
1339
+ }
1340
+ } },
1341
+ "/presets/import": { POST: async (req, res, url) => {
1342
+ const language = url.searchParams.get("language");
1343
+ try {
1344
+ sendJson(res, 200, await api.importFile(url.searchParams.get("name") ?? "", await readBinaryBody(req, api.maxUploadBytes), language === null ? void 0 : languageOf(language)));
1345
+ } catch (error) {
1346
+ failure(res, error);
1347
+ }
1348
+ } },
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
+ }
1365
+ }
1366
+ }
1367
+ };
1368
+ }
1052
1369
  /** The headers of every file of a pack. */
1053
1370
  const PACK_HEADERS = {
1054
1371
  "content-security-policy": [
@@ -1809,6 +2126,21 @@ async function sendImage(res, image) {
1809
2126
  res.setHeader("cache-control", "private, max-age=31536000, immutable");
1810
2127
  await pipeline(createReadStream(image.file), res);
1811
2128
  }
2129
+ const CATALOGUE_STATUS = {
2130
+ input: 400,
2131
+ unknown: 404,
2132
+ upstream: 502,
2133
+ invalid: 422,
2134
+ conflict: 409
2135
+ };
2136
+ /** A catalogue failure with the status that says whose fault it is; anything else is not ours to describe. */
2137
+ function catalogueFailure(res, error) {
2138
+ if (error instanceof CatalogueError) return error.detail === void 0 ? sendError(res, CATALOGUE_STATUS[error.failure], error.message) : sendJson(res, CATALOGUE_STATUS[error.failure], {
2139
+ message: error.message,
2140
+ ...error.detail
2141
+ });
2142
+ throw error;
2143
+ }
1812
2144
  /** The status an import failure is shown with: what is wrong with the card or the choices is the person's to fix. */
1813
2145
  function importFailure(res, error) {
1814
2146
  if (error instanceof ImportCardError) return sendError(res, 422, error.message);
@@ -1831,7 +2163,7 @@ function languageField(value) {
1831
2163
  throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
1832
2164
  }
1833
2165
  }
1834
- function createApiHandler({ worlds, createWorld, starter, authorWorld, translation, worldCharacters, importer, avatars, worldFiles, worldEditor, sessions, packs, connection, speech, externalTools }) {
2166
+ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld, translation, worldCharacters, importer, avatars, worldFiles, worldEditor, sessions, packs, presets, connection, speech, externalTools }) {
1835
2167
  const routes = {
1836
2168
  "/speech/capabilities": { GET: async (_req, res) => {
1837
2169
  sendJson(res, 200, { streaming: speech.streaming() });
@@ -1858,9 +2190,11 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, translati
1858
2190
  try {
1859
2191
  const body = await readJsonBody(req);
1860
2192
  if (typeof body.folder !== "string" || typeof body.name !== "string") return sendError(res, 400, "folder and name must be text");
2193
+ if (body.preset !== void 0 && typeof body.preset !== "string") return sendError(res, 400, "preset must be text");
1861
2194
  sendJson(res, 201, await createWorld({
1862
2195
  folder: body.folder,
1863
- name: body.name
2196
+ name: body.name,
2197
+ ...body.preset === void 0 ? {} : { preset: body.preset }
1864
2198
  }));
1865
2199
  } catch (error) {
1866
2200
  if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
@@ -1872,6 +2206,97 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, translati
1872
2206
  }
1873
2207
  }
1874
2208
  },
2209
+ "/catalogue/sources": { GET: async (_req, res) => {
2210
+ sendJson(res, 200, catalogue.sources());
2211
+ } },
2212
+ "/catalogue/worlds": { GET: async (_req, res, url) => {
2213
+ const offset = Number(url.searchParams.get("offset") ?? 0);
2214
+ const sort = url.searchParams.get("sort") === "popular" ? "popular" : "recent";
2215
+ try {
2216
+ sendJson(res, 200, await catalogue.worlds(url.searchParams.get("source") ?? "", {
2217
+ kind: ["card", "preset"].find((entry) => entry === url.searchParams.get("kind")) ?? "world",
2218
+ search: url.searchParams.get("search") ?? "",
2219
+ offset: Number.isFinite(offset) ? offset : 0,
2220
+ sort
2221
+ }));
2222
+ } catch (error) {
2223
+ return catalogueFailure(res, error);
2224
+ }
2225
+ } },
2226
+ "/catalogue/world": { GET: async (_req, res, url) => {
2227
+ try {
2228
+ sendJson(res, 200, await catalogue.world(url.searchParams.get("source") ?? "", url.searchParams.get("id") ?? ""));
2229
+ } catch (error) {
2230
+ return catalogueFailure(res, error);
2231
+ }
2232
+ } },
2233
+ "/catalogue/cover": { GET: async (_req, res, url) => {
2234
+ try {
2235
+ const cover = await catalogue.cover(url.searchParams.get("source") ?? "", url.searchParams.get("id") ?? "");
2236
+ res.statusCode = 200;
2237
+ res.setHeader("content-type", cover.type);
2238
+ res.setHeader("content-length", cover.body.length);
2239
+ res.setHeader("x-content-type-options", "nosniff");
2240
+ res.setHeader("cache-control", "private, no-cache");
2241
+ res.end(cover.body);
2242
+ } catch (error) {
2243
+ return catalogueFailure(res, error);
2244
+ }
2245
+ } },
2246
+ "/catalogue/updates": { GET: async (_req, res, url) => {
2247
+ try {
2248
+ sendJson(res, 200, await catalogue.updates(url.searchParams.get("source") ?? ""));
2249
+ } catch (error) {
2250
+ return catalogueFailure(res, error);
2251
+ }
2252
+ } },
2253
+ "/catalogue/install": { POST: async (req, res) => {
2254
+ const body = await readJsonBody(req);
2255
+ if (typeof body.url !== "string") return sendError(res, 400, "url must be text");
2256
+ if (body.sha256 !== void 0 && typeof body.sha256 !== "string") return sendError(res, 400, "sha256 must be text");
2257
+ if (body.mode !== void 0 && body.mode !== "new" && body.mode !== "update" && body.mode !== "copy") return sendError(res, 400, "mode must be new, update or copy");
2258
+ if (body.overwriteChanges !== void 0 && typeof body.overwriteChanges !== "boolean") return sendError(res, 400, "overwriteChanges must be true or false");
2259
+ try {
2260
+ sendJson(res, 201, await catalogue.install({
2261
+ url: body.url,
2262
+ ...body.sha256 === void 0 ? {} : { sha256: body.sha256 },
2263
+ ...body.mode === void 0 ? {} : { mode: body.mode },
2264
+ ...body.overwriteChanges === void 0 ? {} : { overwriteChanges: body.overwriteChanges }
2265
+ }));
2266
+ } catch (error) {
2267
+ return catalogueFailure(res, error);
2268
+ }
2269
+ } },
2270
+ "/catalogue/convert": { POST: async (req, res) => {
2271
+ const body = await readJsonBody(req);
2272
+ if (typeof body.source !== "string" || typeof body.versionId !== "string") return sendError(res, 400, "source and versionId must be text");
2273
+ try {
2274
+ const language = languageField(body.language);
2275
+ sendJson(res, 201, await catalogue.convert({
2276
+ source: body.source,
2277
+ versionId: body.versionId,
2278
+ ...language === void 0 ? {} : { language }
2279
+ }));
2280
+ } catch (error) {
2281
+ return error instanceof CatalogueError ? catalogueFailure(res, error) : importFailure(res, error);
2282
+ }
2283
+ } },
2284
+ "/catalogue/convert/preset": { POST: async (req, res) => {
2285
+ const body = await readJsonBody(req);
2286
+ if (typeof body.source !== "string" || typeof body.versionId !== "string") return sendError(res, 400, "source and versionId must be text");
2287
+ if (body.title !== void 0 && typeof body.title !== "string") return sendError(res, 400, "title must be text");
2288
+ try {
2289
+ const language = languageField(body.language);
2290
+ sendJson(res, 201, await catalogue.convertPreset({
2291
+ source: body.source,
2292
+ versionId: body.versionId,
2293
+ ...body.title === void 0 ? {} : { title: body.title },
2294
+ ...language === void 0 ? {} : { language }
2295
+ }));
2296
+ } catch (error) {
2297
+ return error instanceof CatalogueError ? catalogueFailure(res, error) : importFailure(res, error);
2298
+ }
2299
+ } },
1875
2300
  "/worlds/starter": {
1876
2301
  GET: async (_req, res) => {
1877
2302
  sendJson(res, 200, await starter.list());
@@ -2120,43 +2545,46 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, translati
2120
2545
  }
2121
2546
  }
2122
2547
  },
2123
- "/worlds/state/plots": { PUT: async (req, res, url) => {
2124
- try {
2125
- const body = await readJsonBody(req);
2126
- if (!Array.isArray(body.plots)) return sendError(res, 400, "plots must be a list");
2127
- sendJson(res, 200, await worldEditor.editPlots(url.searchParams.get("id") ?? "", { plots: body.plots }));
2128
- } catch (error) {
2129
- if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2130
- if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2131
- message: error.message,
2132
- problems: error.problems
2133
- });
2134
- throw error;
2135
- }
2136
- } },
2137
- "/worlds/state/relation": { PUT: async (req, res, url) => {
2138
- try {
2139
- sendJson(res, 200, await worldEditor.editRelation(url.searchParams.get("id") ?? "", parseRelationEdit(await readJsonBody(req))));
2140
- } catch (error) {
2141
- if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2142
- if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2143
- message: error.message,
2144
- problems: error.problems
2145
- });
2146
- throw error;
2147
- }
2148
- } },
2149
- "/worlds/routines": { GET: async (_req, res, url) => {
2150
- try {
2151
- sendJson(res, 200, await worldFiles.routines(url.searchParams.get("id") ?? ""));
2152
- } catch (error) {
2153
- if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2154
- throw error;
2548
+ "/worlds/interface/file": {
2549
+ GET: async (_req, res, url) => {
2550
+ try {
2551
+ sendJson(res, 200, { text: await worldEditor.readPackFile(url.searchParams.get("id") ?? "", url.searchParams.get("pack") ?? "", url.searchParams.get("path") ?? "") });
2552
+ } catch (error) {
2553
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2554
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2555
+ message: error.message,
2556
+ problems: error.problems
2557
+ });
2558
+ throw error;
2559
+ }
2560
+ },
2561
+ PUT: async (req, res, url) => {
2562
+ try {
2563
+ const body = await readJsonBody(req);
2564
+ if (typeof body?.text !== "string") throw new InvalidEditProblems(["text must be text"]);
2565
+ sendJson(res, 200, { problems: await worldEditor.writePackFile(url.searchParams.get("id") ?? "", url.searchParams.get("pack") ?? "", url.searchParams.get("path") ?? "", body.text) });
2566
+ } catch (error) {
2567
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2568
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2569
+ message: error.message,
2570
+ problems: error.problems
2571
+ });
2572
+ throw error;
2573
+ }
2574
+ },
2575
+ DELETE: async (_req, res, url) => {
2576
+ try {
2577
+ sendJson(res, 200, { problems: await worldEditor.deletePackFile(url.searchParams.get("id") ?? "", url.searchParams.get("pack") ?? "", url.searchParams.get("path") ?? "") });
2578
+ } catch (error) {
2579
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2580
+ return sendError(res, 422, error instanceof Error ? error.message : String(error));
2581
+ }
2155
2582
  }
2156
- } },
2157
- "/worlds/routines/item": { PUT: async (req, res, url) => {
2583
+ },
2584
+ "/worlds/interface/pack": { POST: async (req, res, url) => {
2158
2585
  try {
2159
- sendJson(res, 200, await worldFiles.editRoutine(url.searchParams.get("id") ?? "", url.searchParams.get("key") ?? "", parseRoutineEdit(await readJsonBody(req))));
2586
+ const body = await readJsonBody(req);
2587
+ sendJson(res, 201, { problems: await worldEditor.createPack(url.searchParams.get("id") ?? "", url.searchParams.get("pack") ?? "", typeof body?.name === "string" ? body.name : "") });
2160
2588
  } catch (error) {
2161
2589
  if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2162
2590
  if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
@@ -2166,18 +2594,22 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, translati
2166
2594
  throw error;
2167
2595
  }
2168
2596
  } },
2169
- "/worlds/dice": {
2597
+ "/worlds/state/trigger": {
2170
2598
  GET: async (_req, res, url) => {
2171
2599
  try {
2172
- sendJson(res, 200, await worldFiles.dice(url.searchParams.get("id") ?? ""));
2600
+ sendJson(res, 200, await worldEditor.readTrigger(url.searchParams.get("id") ?? "", url.searchParams.get("key") ?? ""));
2173
2601
  } catch (error) {
2174
2602
  if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2603
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2604
+ message: error.message,
2605
+ problems: error.problems
2606
+ });
2175
2607
  throw error;
2176
2608
  }
2177
2609
  },
2178
2610
  PUT: async (req, res, url) => {
2179
2611
  try {
2180
- sendJson(res, 200, await worldFiles.editDice(url.searchParams.get("id") ?? "", parseDiceEdit(await readJsonBody(req))));
2612
+ sendJson(res, 200, await worldEditor.writeTrigger(url.searchParams.get("id") ?? "", url.searchParams.get("key") ?? "", await readJsonBody(req)));
2181
2613
  } catch (error) {
2182
2614
  if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2183
2615
  if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
@@ -2186,8 +2618,88 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, translati
2186
2618
  });
2187
2619
  throw error;
2188
2620
  }
2189
- }
2190
- },
2621
+ },
2622
+ DELETE: async (_req, res, url) => {
2623
+ try {
2624
+ sendJson(res, 200, await worldEditor.removeTrigger(url.searchParams.get("id") ?? "", url.searchParams.get("key") ?? ""));
2625
+ } catch (error) {
2626
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2627
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2628
+ message: error.message,
2629
+ problems: error.problems
2630
+ });
2631
+ throw error;
2632
+ }
2633
+ }
2634
+ },
2635
+ "/worlds/state/plots": { PUT: async (req, res, url) => {
2636
+ try {
2637
+ const body = await readJsonBody(req);
2638
+ if (!Array.isArray(body.plots)) return sendError(res, 400, "plots must be a list");
2639
+ sendJson(res, 200, await worldEditor.editPlots(url.searchParams.get("id") ?? "", { plots: body.plots }));
2640
+ } catch (error) {
2641
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2642
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2643
+ message: error.message,
2644
+ problems: error.problems
2645
+ });
2646
+ throw error;
2647
+ }
2648
+ } },
2649
+ "/worlds/state/relation": { PUT: async (req, res, url) => {
2650
+ try {
2651
+ sendJson(res, 200, await worldEditor.editRelation(url.searchParams.get("id") ?? "", parseRelationEdit(await readJsonBody(req))));
2652
+ } catch (error) {
2653
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2654
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2655
+ message: error.message,
2656
+ problems: error.problems
2657
+ });
2658
+ throw error;
2659
+ }
2660
+ } },
2661
+ "/worlds/routines": { GET: async (_req, res, url) => {
2662
+ try {
2663
+ sendJson(res, 200, await worldFiles.routines(url.searchParams.get("id") ?? ""));
2664
+ } catch (error) {
2665
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2666
+ throw error;
2667
+ }
2668
+ } },
2669
+ "/worlds/routines/item": { PUT: async (req, res, url) => {
2670
+ try {
2671
+ sendJson(res, 200, await worldFiles.editRoutine(url.searchParams.get("id") ?? "", url.searchParams.get("key") ?? "", parseRoutineEdit(await readJsonBody(req))));
2672
+ } catch (error) {
2673
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2674
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2675
+ message: error.message,
2676
+ problems: error.problems
2677
+ });
2678
+ throw error;
2679
+ }
2680
+ } },
2681
+ "/worlds/dice": {
2682
+ GET: async (_req, res, url) => {
2683
+ try {
2684
+ sendJson(res, 200, await worldFiles.dice(url.searchParams.get("id") ?? ""));
2685
+ } catch (error) {
2686
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2687
+ throw error;
2688
+ }
2689
+ },
2690
+ PUT: async (req, res, url) => {
2691
+ try {
2692
+ sendJson(res, 200, await worldFiles.editDice(url.searchParams.get("id") ?? "", parseDiceEdit(await readJsonBody(req))));
2693
+ } catch (error) {
2694
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2695
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2696
+ message: error.message,
2697
+ problems: error.problems
2698
+ });
2699
+ throw error;
2700
+ }
2701
+ }
2702
+ },
2191
2703
  "/worlds/calendar": {
2192
2704
  GET: async (_req, res, url) => {
2193
2705
  try {
@@ -2361,6 +2873,72 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, translati
2361
2873
  return sendError(res, 404, error instanceof Error ? error.message : String(error));
2362
2874
  }
2363
2875
  } },
2876
+ ...Object.fromEntries(["place", "thing"].flatMap((kind) => [
2877
+ [`/worlds/state/${kind}/image`, { POST: async (_req, res, url) => {
2878
+ try {
2879
+ sendJson(res, 200, await worldEditor.generateEntityImage(url.searchParams.get("id") ?? "", kind, url.searchParams.get("key") ?? ""));
2880
+ } catch (error) {
2881
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2882
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2883
+ message: error.message,
2884
+ problems: error.problems
2885
+ });
2886
+ return sendError(res, 409, error instanceof Error ? error.message : String(error));
2887
+ }
2888
+ } }],
2889
+ [`/worlds/state/${kind}/image/upload`, { POST: async (req, res, url) => {
2890
+ const name = decodeURIComponent(String(req.headers["x-file-name"] ?? "image.png"));
2891
+ try {
2892
+ sendJson(res, 200, await worldEditor.uploadEntityImage(url.searchParams.get("id") ?? "", kind, url.searchParams.get("key") ?? "", await readBinaryBody(req, MAX_UPLOAD_BYTES), name));
2893
+ } catch (error) {
2894
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2895
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2896
+ message: error.message,
2897
+ problems: error.problems
2898
+ });
2899
+ throw error;
2900
+ }
2901
+ } }],
2902
+ [`/worlds/state/${kind}/image/file`, { GET: async (_req, res, url) => {
2903
+ try {
2904
+ await sendImage(res, await worldEditor.entityImageFile(url.searchParams.get("id") ?? "", kind, url.searchParams.get("key") ?? ""));
2905
+ } catch (error) {
2906
+ return sendError(res, 404, error instanceof Error ? error.message : String(error));
2907
+ }
2908
+ } }],
2909
+ [`/sessions/world/${kind}/image`, { POST: async (_req, res, url) => {
2910
+ try {
2911
+ sendJson(res, 200, await sessions.generateEntityImage(url.searchParams.get("id") ?? "", kind, url.searchParams.get("key") ?? ""));
2912
+ } catch (error) {
2913
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
2914
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2915
+ message: error.message,
2916
+ problems: error.problems
2917
+ });
2918
+ return sendError(res, 409, error instanceof Error ? error.message : String(error));
2919
+ }
2920
+ } }],
2921
+ [`/sessions/world/${kind}/image/upload`, { POST: async (req, res, url) => {
2922
+ const name = decodeURIComponent(String(req.headers["x-file-name"] ?? "image.png"));
2923
+ try {
2924
+ sendJson(res, 200, await sessions.uploadEntityImage(url.searchParams.get("id") ?? "", kind, url.searchParams.get("key") ?? "", await readBinaryBody(req, MAX_UPLOAD_BYTES), name));
2925
+ } catch (error) {
2926
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
2927
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2928
+ message: error.message,
2929
+ problems: error.problems
2930
+ });
2931
+ throw error;
2932
+ }
2933
+ } }],
2934
+ [`/sessions/world/${kind}/image/file`, { GET: async (_req, res, url) => {
2935
+ try {
2936
+ await sendImage(res, await sessions.entityImageFile(url.searchParams.get("id") ?? "", kind, url.searchParams.get("key") ?? ""));
2937
+ } catch (error) {
2938
+ return sendError(res, 404, error instanceof Error ? error.message : String(error));
2939
+ }
2940
+ } }]
2941
+ ])),
2364
2942
  "/worlds/characters": { GET: async (_req, res, url) => {
2365
2943
  try {
2366
2944
  sendJson(res, 200, await worldCharacters(url.searchParams.get("id") ?? ""));
@@ -2374,7 +2952,7 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, translati
2374
2952
  sendJson(res, 200, sessions.list());
2375
2953
  },
2376
2954
  POST: async (req, res) => {
2377
- const { worldId, playerCharacterId, playerAvatar, avatars: brought, name, settings, opening, startingTime } = await readJsonBody(req);
2955
+ const { worldId, playerCharacterId, playerAvatar, avatars: brought, name, settings, opening, startingTime, preset } = await readJsonBody(req);
2378
2956
  if (typeof worldId !== "string" || worldId.trim() === "") return sendError(res, 400, "\"worldId\" is required");
2379
2957
  if (playerCharacterId === void 0 && playerAvatar === void 0) return sendError(res, 400, "\"playerCharacterId\" or \"playerAvatar\" is required");
2380
2958
  if (playerCharacterId !== void 0 && (typeof playerCharacterId !== "string" || playerCharacterId.trim() === "")) return sendError(res, 400, "\"playerCharacterId\" must be text");
@@ -2383,8 +2961,10 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, translati
2383
2961
  if (name !== void 0 && typeof name !== "string") return sendError(res, 400, "\"name\" must be a string");
2384
2962
  if (opening !== void 0 && (typeof opening !== "number" || !Number.isInteger(opening))) return sendError(res, 400, "\"opening\" must be a whole number");
2385
2963
  if (startingTime !== void 0 && typeof startingTime !== "string") return sendError(res, 400, "\"startingTime\" must be text");
2964
+ if (preset !== void 0 && typeof preset !== "string") return sendError(res, 400, "\"preset\" must be text");
2386
2965
  try {
2387
2966
  sendJson(res, 201, await sessions.start({
2967
+ ...preset === void 0 || preset === "" ? {} : { preset },
2388
2968
  ...opening === void 0 ? {} : { opening },
2389
2969
  ...startingTime === void 0 ? {} : { startingTime },
2390
2970
  worldId,
@@ -2771,6 +3351,7 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, translati
2771
3351
  res.end();
2772
3352
  } },
2773
3353
  ...interfaceRoutes(packs),
3354
+ ...presetRoutes(presets),
2774
3355
  "/worlds/cover": { GET: async (_req, res, url) => {
2775
3356
  const cover = await worlds.cover(url.searchParams.get("id") ?? "");
2776
3357
  if (cover === void 0) return sendError(res, 404, "no cover");
@@ -3203,7 +3784,7 @@ function sessionOf(deps, id) {
3203
3784
  return deps.state.openSession(directory, id);
3204
3785
  }
3205
3786
  const keyOf = (character) => character.sourceId ?? String(character.id);
3206
- function worldOf(session, sessionsDir) {
3787
+ function worldOf$1(session, sessionsDir) {
3207
3788
  const narrationVoice = session.metadata.getValue("roleplay.tts.narrationVoice");
3208
3789
  const characters = session.characters.list().map((character) => {
3209
3790
  const state = session.characterStates.get(character.id);
@@ -3267,6 +3848,7 @@ function worldOf(session, sessionsDir) {
3267
3848
  key: location.sourceId ?? String(location.id),
3268
3849
  name: location.name,
3269
3850
  description: location.description,
3851
+ ...imageOf(session, sessionsDir, "place", location),
3270
3852
  ...location.parentId === void 0 ? {} : { parent: {
3271
3853
  key: session.locations.get(location.parentId)?.sourceId ?? String(location.parentId),
3272
3854
  name: locationName(location.parentId)
@@ -3288,6 +3870,7 @@ function worldOf(session, sessionsDir) {
3288
3870
  key: item.sourceId ?? String(item.id),
3289
3871
  name: item.name,
3290
3872
  description: item.description,
3873
+ ...imageOf(session, sessionsDir, "thing", item),
3291
3874
  quantity: item.quantity,
3292
3875
  unique: item.unique,
3293
3876
  quality: item.quality,
@@ -3490,7 +4073,7 @@ function editWorldLore(deps, id, key, edit) {
3490
4073
  const entry = session.lore.list().find((candidate) => (candidate.sourceId ?? String(candidate.id)) === key);
3491
4074
  if (entry === void 0) throw new InvalidEditProblems([`there is no lore "${key}"`]);
3492
4075
  session.lore.update(entry.id, edit);
3493
- return worldOf(session, deps.sessionsDir());
4076
+ return worldOf$1(session, deps.sessionsDir());
3494
4077
  }
3495
4078
  function editWorldPlots(deps, id, edit) {
3496
4079
  const parsed = parsePlotsFile(JSON.stringify(edit.plots));
@@ -3518,13 +4101,13 @@ function editWorldPlots(deps, id, edit) {
3518
4101
  });
3519
4102
  }
3520
4103
  session.metadata.setValue(PLOTS_METADATA_KEY, merged);
3521
- return worldOf(session, deps.sessionsDir());
4104
+ return worldOf$1(session, deps.sessionsDir());
3522
4105
  }
3523
4106
  function editSessionNarrationVoice(deps, id, voice) {
3524
4107
  const session = sessionOf(deps, id);
3525
4108
  if (voice.trim() === "") session.metadata.deleteValue("roleplay.tts.narrationVoice");
3526
4109
  else session.metadata.setValue("roleplay.tts.narrationVoice", voice.trim());
3527
- return worldOf(session, deps.sessionsDir());
4110
+ return worldOf$1(session, deps.sessionsDir());
3528
4111
  }
3529
4112
  const relationKey = (...parts) => parts.map((part) => encodeURIComponent(part)).join(":");
3530
4113
  const relationParts = (key) => key.split(":").map((part) => decodeURIComponent(part));
@@ -3533,7 +4116,7 @@ const relationParts = (key) => key.split(":").map((part) => decodeURIComponent(p
3533
4116
  * @throws {SessionNotFoundError} when the id names no session.
3534
4117
  */
3535
4118
  function readWorldState(deps, id) {
3536
- return worldOf(sessionOf(deps, id), deps.sessionsDir());
4119
+ return worldOf$1(sessionOf(deps, id), deps.sessionsDir());
3537
4120
  }
3538
4121
  /**
3539
4122
  * Change a character of a session, all of it or none of it, and say how the world stands after.
@@ -3577,7 +4160,7 @@ function editWorldCharacter(deps, id, key, edit) {
3577
4160
  if (error instanceof Error && error.name === "InvalidValueError") throw new InvalidEditProblems([error.message]);
3578
4161
  throw error;
3579
4162
  }
3580
- return worldOf(session, deps.sessionsDir());
4163
+ return worldOf$1(session, deps.sessionsDir());
3581
4164
  }
3582
4165
  function editWorldPlace(deps, id, key, edit) {
3583
4166
  const session = sessionOf(deps, id);
@@ -3600,7 +4183,7 @@ function editWorldPlace(deps, id, key, edit) {
3600
4183
  if (error instanceof Error && (error.name === "InvalidValueError" || error.name === "ConflictError")) throw new InvalidEditProblems([error.message]);
3601
4184
  throw error;
3602
4185
  }
3603
- return worldOf(session, deps.sessionsDir());
4186
+ return worldOf$1(session, deps.sessionsDir());
3604
4187
  }
3605
4188
  function editWorldThing(deps, id, key, edit) {
3606
4189
  const session = sessionOf(deps, id);
@@ -3624,7 +4207,7 @@ function editWorldThing(deps, id, key, edit) {
3624
4207
  if (error instanceof Error && (error.name === "InvalidValueError" || error.name === "ConflictError")) throw new InvalidEditProblems([error.message]);
3625
4208
  throw error;
3626
4209
  }
3627
- return worldOf(session, deps.sessionsDir());
4210
+ return worldOf$1(session, deps.sessionsDir());
3628
4211
  }
3629
4212
  function editWorldFaction(deps, id, key, edit) {
3630
4213
  const session = sessionOf(deps, id);
@@ -3644,7 +4227,7 @@ function editWorldFaction(deps, id, key, edit) {
3644
4227
  if (error instanceof Error && (error.name === "InvalidValueError" || error.name === "ConflictError")) throw new InvalidEditProblems([error.message]);
3645
4228
  throw error;
3646
4229
  }
3647
- return worldOf(session, deps.sessionsDir());
4230
+ return worldOf$1(session, deps.sessionsDir());
3648
4231
  }
3649
4232
  function editWorldRelation(deps, id, edit) {
3650
4233
  const session = sessionOf(deps, id);
@@ -3703,7 +4286,7 @@ function editWorldRelation(deps, id, edit) {
3703
4286
  ].includes(error.name)) throw new InvalidEditProblems([error.message]);
3704
4287
  throw error;
3705
4288
  }
3706
- return worldOf(session, deps.sessionsDir());
4289
+ return worldOf$1(session, deps.sessionsDir());
3707
4290
  }
3708
4291
  const isNewRelation = (edit) => "create" in edit && edit.create === true;
3709
4292
  function createSessionRelation(session, sessionsDir, edit) {
@@ -3755,13 +4338,79 @@ function createSessionRelation(session, sessionsDir, edit) {
3755
4338
  ].includes(error.name)) throw new InvalidEditProblems([error.message]);
3756
4339
  throw error;
3757
4340
  }
3758
- return worldOf(session, sessionsDir);
4341
+ return worldOf$1(session, sessionsDir);
3759
4342
  }
3760
4343
  function characterOf(session, key) {
3761
4344
  const character = session.characters.list().find((candidate) => keyOf(candidate) === key);
3762
4345
  if (character === void 0) throw new InvalidEditProblems([`there is no character "${key}"`]);
3763
4346
  return character;
3764
4347
  }
4348
+ const IMAGE_SUBJECT = {
4349
+ place: "location",
4350
+ thing: "item"
4351
+ };
4352
+ function addressOf(session, kind, entity) {
4353
+ const identity = session.visualIdentities.get(IMAGE_SUBJECT[kind], entity.id);
4354
+ return {
4355
+ kind: IMAGE_SUBJECT[kind],
4356
+ localId: entity.sourceId ?? entity.id,
4357
+ ...identity?.globalId === void 0 ? {} : { globalId: identity.globalId }
4358
+ };
4359
+ }
4360
+ function imageOf(session, sessionsDir, kind, entity) {
4361
+ const id = session.metadata.get().id;
4362
+ const file = referenceImagePath(sessionFolder(sessionsDir, id), addressOf(session, kind, entity));
4363
+ return existsSync(file) ? { image: `/${API_PREFIX}/sessions/world/${kind}/image/file?id=${encodeURIComponent(id)}&key=${encodeURIComponent(entity.sourceId ?? String(entity.id))}&v=${statSync(file).mtimeMs}` } : {};
4364
+ }
4365
+ function entityOf(session, kind, key) {
4366
+ const found = (kind === "place" ? session.locations.list() : session.items.list()).find((candidate) => (candidate.sourceId ?? String(candidate.id)) === key);
4367
+ if (found === void 0) throw new InvalidEditProblems([`there is no ${kind} "${key}"`]);
4368
+ return found;
4369
+ }
4370
+ /** Generate or replace the reference picture of a session's place or thing from its copied identity. */
4371
+ async function generateSessionEntityImage(deps, id, kind, key, service) {
4372
+ const session = sessionOf(deps, id);
4373
+ const entity = entityOf(session, kind, key);
4374
+ const identity = session.visualIdentities.get(IMAGE_SUBJECT[kind], entity.id);
4375
+ if (identity === void 0) throw new InvalidEditProblems([`${entity.name} needs a visual identity before a picture can be generated`]);
4376
+ await generateReferenceImage(service, {
4377
+ root: sessionFolder(deps.sessionsDir(), id),
4378
+ subject: {
4379
+ ...addressOf(session, kind, entity),
4380
+ name: entity.name
4381
+ },
4382
+ identity
4383
+ });
4384
+ return worldOf$1(session, deps.sessionsDir());
4385
+ }
4386
+ /** The picture the player brought becomes the place's or thing's reference picture. */
4387
+ async function uploadSessionEntityImage(deps, id, kind, key, png, originalName) {
4388
+ const session = sessionOf(deps, id);
4389
+ const entity = entityOf(session, kind, key);
4390
+ try {
4391
+ await uploadReferenceImage({
4392
+ root: sessionFolder(deps.sessionsDir(), id),
4393
+ subject: {
4394
+ ...addressOf(session, kind, entity),
4395
+ name: entity.name
4396
+ },
4397
+ png,
4398
+ ...originalName === void 0 ? {} : { originalName }
4399
+ });
4400
+ } catch (error) {
4401
+ throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
4402
+ }
4403
+ return worldOf$1(session, deps.sessionsDir());
4404
+ }
4405
+ /** Resolve the picture through session state so request parameters cannot select arbitrary files. */
4406
+ async function sessionEntityImageFile(deps, id, kind, key) {
4407
+ const session = sessionOf(deps, id);
4408
+ const file = referenceImagePath(sessionFolder(deps.sessionsDir(), id), addressOf(session, kind, entityOf(session, kind, key)));
4409
+ return {
4410
+ file,
4411
+ size: (await stat(file)).size
4412
+ };
4413
+ }
3765
4414
  /** Generate or replace a session character's stable reference portrait from its copied identity. */
3766
4415
  async function generateSessionCharacterPortrait(deps, id, key, service) {
3767
4416
  const session = sessionOf(deps, id);
@@ -3778,7 +4427,7 @@ async function generateSessionCharacterPortrait(deps, id, key, service) {
3778
4427
  },
3779
4428
  identity
3780
4429
  });
3781
- return worldOf(session, deps.sessionsDir());
4430
+ return worldOf$1(session, deps.sessionsDir());
3782
4431
  }
3783
4432
  /** The picture the player brought becomes the session character's portrait. */
3784
4433
  async function uploadSessionCharacterPortrait(deps, id, key, png, originalName) {
@@ -3800,7 +4449,7 @@ async function uploadSessionCharacterPortrait(deps, id, key, png, originalName)
3800
4449
  } catch (error) {
3801
4450
  throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
3802
4451
  }
3803
- return worldOf(session, deps.sessionsDir());
4452
+ return worldOf$1(session, deps.sessionsDir());
3804
4453
  }
3805
4454
  /** Resolve a portrait through session state so request parameters cannot select arbitrary files. */
3806
4455
  async function sessionCharacterPortraitFile(deps, id, key) {
@@ -3992,6 +4641,7 @@ function infoOf(document) {
3992
4641
  authorUrl: textOf(author["url"]),
3993
4642
  timeZone: textOf(document["time_zone"]),
3994
4643
  startingTime: textOf(document["starting_time"]),
4644
+ preset: textOf(document["preset"]),
3995
4645
  version: typeof document["version"] === "number" ? String(document["version"]) : textOf(document["version"]),
3996
4646
  tools: toolsOf(document["tools"]),
3997
4647
  alternateOpenings: Array.isArray(document["alternate_openings"]) ? document["alternate_openings"].flatMap((entry) => typeof entry === "object" && entry !== null && typeof entry["text"] === "string" ? [{
@@ -4050,6 +4700,7 @@ async function editWorldInfo(directory, edit) {
4050
4700
  if (edit.timeZone !== void 0) setOrRemove(document, "time_zone", edit.timeZone);
4051
4701
  if (edit.startingTime !== void 0) setOrRemove(document, "starting_time", edit.startingTime);
4052
4702
  if (edit.version !== void 0) setOrRemove(document, "version", edit.version);
4703
+ if (edit.preset !== void 0) setOrRemove(document, "preset", edit.preset);
4053
4704
  if (edit.alternateOpenings !== void 0) {
4054
4705
  if (edit.alternateOpenings.length === 0) delete document["alternate_openings"];
4055
4706
  else document["alternate_openings"] = edit.alternateOpenings.map((entry) => ({
@@ -4132,6 +4783,17 @@ async function startSession(deps, request) {
4132
4783
  },
4133
4784
  tools
4134
4785
  };
4786
+ 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
+ };
4796
+ }
4135
4797
  let startsAt = world.clock?.startingTime;
4136
4798
  if (request.startingTime !== void 0 && request.startingTime.trim() !== "") {
4137
4799
  if (settings.clock.mode === "real") throw new InvalidStartError("the story's time follows the wall clock, so it has no starting time to choose");
@@ -4178,12 +4840,18 @@ async function startSession(deps, request) {
4178
4840
  });
4179
4841
  await inheritImages(world.directory, sessionFolder(sessionsDir, id), []);
4180
4842
  if (avatars !== void 0) for (const entry of brought) await copyPortrait(avatars, entry.from, entry.document, sessionFolder(sessionsDir, id), entry.id);
4181
- const promptProblems = copyWorldPrompts(world.directory, sessionFolder(sessionsDir, id));
4843
+ const folder = sessionFolder(sessionsDir, id);
4844
+ if (preset !== void 0 && request.preset === void 0) copyPreset(preset, folder);
4845
+ const promptProblems = copyWorldPrompts(world.directory, folder);
4182
4846
  if (promptProblems.length > 0) throw new InvalidWorldError(`the prompts of "${world.summary.name}" have ${promptProblems.length} problem(s)`, promptProblems);
4847
+ if (preset !== void 0) {
4848
+ if (request.preset !== void 0) copyPreset(preset, folder);
4849
+ recordPreset(folder, preset);
4850
+ }
4183
4851
  const packProblems = copyWorldPacks(world.directory, sessionFolder(sessionsDir, id));
4184
4852
  if (packProblems.length > 0) throw new InvalidWorldError(`the interface packs of "${world.summary.name}" have ${packProblems.length} problem(s)`, packProblems);
4185
4853
  writeSettings(sessionFolder(sessionsDir, id), settings);
4186
- addToNote(session, "world", 1, worldFindings(session));
4854
+ addToNote(session, "world", 1, [...unavailable, ...worldFindings(session)]);
4187
4855
  chatSessionId = await deps.agent.ensure(id, name, opening);
4188
4856
  } catch (error) {
4189
4857
  deps.state.deleteSession(sessionsDir, id);
@@ -4199,6 +4867,30 @@ async function startSession(deps, request) {
4199
4867
  characterCount: characters.length
4200
4868
  };
4201
4869
  }
4870
+ /**
4871
+ * The preset a story uses: the one asked for, else the one the world suggests. Asking for one that cannot be used refuses the start;
4872
+ * a suggestion that cannot be followed is told to the player instead, because the world may come from someone whose library differs.
4873
+ */
4874
+ function presetFor(deps, asked, suggested) {
4875
+ const name = asked ?? suggested;
4876
+ if (name === void 0 || name === "none") return { unavailable: [] };
4877
+ const load = () => {
4878
+ if (deps.root === void 0) throw new Error("the preset library is not available");
4879
+ const loaded = loadPreset(deps.root(), name);
4880
+ if (loaded.summary.problems.length > 0) throw new Error(`it has problems: ${loaded.summary.problems.join("; ")}`);
4881
+ return loaded;
4882
+ };
4883
+ try {
4884
+ return {
4885
+ preset: load(),
4886
+ unavailable: []
4887
+ };
4888
+ } catch (error) {
4889
+ const reason = error instanceof Error ? error.message : String(error);
4890
+ if (asked !== void 0) throw new InvalidStartError(`the preset "${name}" cannot be used: ${reason}`);
4891
+ return { unavailable: [`The world suggests the preset "${name}", which cannot be used here (${reason}), so the story is told in the default style.`] };
4892
+ }
4893
+ }
4202
4894
  /** What a story opens with when its world gives no opening: a chat with nothing in it is DSH's start screen, which has none of the story's tabs. */
4203
4895
  const DEFAULT_OPENING = "The story begins.";
4204
4896
  /** The opening of the world with each speaker's name, or the reason it cannot be used. */
@@ -4327,6 +5019,7 @@ function payloadOf(deps, id, settings) {
4327
5019
  pendingRecords: deps.pendingRecords(id),
4328
5020
  pendingConsolidation: deps.pendingConsolidation(id),
4329
5021
  activity: deps.activity(id),
5022
+ usage: deps.usage(id),
4330
5023
  interventions: deps.interventions(id),
4331
5024
  vectors: deps.vectors(id),
4332
5025
  reflection: deps.reflection(id),
@@ -4385,6 +5078,65 @@ function resetVectors(session) {
4385
5078
  session.recallIndex.reset();
4386
5079
  }
4387
5080
  //#endregion
5081
+ //#region src/host/authoring/pack-files.ts
5082
+ /** Where a text file of a pack is, once the pack name and the path are known to be allowed; otherwise why not. */
5083
+ function placeOf(directory, pack, path, tool, text = "") {
5084
+ if (!isPackId(pack)) throw new InvalidEditProblems([`"${pack}" is not a usable pack name (letters, digits, "-" and "_")`]);
5085
+ const relative = packPath(path);
5086
+ if (relative === void 0) throw new InvalidEditProblems([`"${path}" is not a path inside a pack`]);
5087
+ const file = join(directory, "ui", pack, ...relative.split("/"));
5088
+ const problem = packFileProblem(tool, file, directory, [text]);
5089
+ if (problem !== void 0) throw new InvalidEditProblems([problem]);
5090
+ return file;
5091
+ }
5092
+ const problemsOf = (directory, pack) => {
5093
+ const folder = join(directory, "ui", pack);
5094
+ return existsSync(join(folder, "pack.json")) ? readPack(folder, pack, (file) => file).problems : [{
5095
+ file: "pack.json",
5096
+ message: "the pack has no pack.json"
5097
+ }];
5098
+ };
5099
+ /** The text of one file of a pack, as the editor shows it. @throws {InvalidEditProblems} when the file is not a text file of a pack or is not there. */
5100
+ async function readWorldPackFile(directory, pack, path) {
5101
+ const file = placeOf(directory, pack, path, "read");
5102
+ try {
5103
+ return await readFile(file, "utf8");
5104
+ } catch (error) {
5105
+ if (error.code === "ENOENT") throw new InvalidEditProblems([`the pack "${pack}" has no file "${path}"`]);
5106
+ throw error;
5107
+ }
5108
+ }
5109
+ /**
5110
+ * Writes one text file of a pack, making the pack's folder when it is not there yet. The file is written whole (to a temporary file that is renamed), and the pack is read
5111
+ * again as a story start reads it.
5112
+ * @returns what is wrong with the pack now; the file is kept even then, so that it can be put right.
5113
+ * @throws {InvalidEditProblems} when the name, the path, the kind of file or the size is not allowed.
5114
+ */
5115
+ async function writeWorldPackFile(directory, pack, path, text) {
5116
+ if (Buffer.byteLength(text) > 204800) throw new InvalidEditProblems([`a file holds at most ${MAX_PACK_TEXT / 1024} KB of text`]);
5117
+ const file = placeOf(directory, pack, path, "write", text);
5118
+ await mkdir(dirname(file), { recursive: true });
5119
+ const temporary = join(dirname(file), `.${process.pid}.${randomUUID()}.tmp`);
5120
+ try {
5121
+ await writeFile(temporary, text);
5122
+ await rename(temporary, file);
5123
+ } catch (error) {
5124
+ await rm(temporary, { force: true });
5125
+ throw error;
5126
+ }
5127
+ return problemsOf(directory, pack);
5128
+ }
5129
+ /** Makes a pack with a manifest that names it and nothing else yet. @throws {InvalidEditProblems} when the name is not usable or the pack exists. */
5130
+ async function createWorldPack(directory, pack, name) {
5131
+ if (!isPackId(pack)) throw new InvalidEditProblems([`"${pack}" is not a usable pack name (letters, digits, "-" and "_")`]);
5132
+ if (existsSync(join(directory, "ui", pack))) throw new InvalidEditProblems([`the world already carries a pack "${pack}"`]);
5133
+ return await writeWorldPackFile(directory, pack, "pack.json", `${JSON.stringify({
5134
+ name: name.trim() === "" ? pack : name.trim(),
5135
+ version: "1",
5136
+ api: 1
5137
+ }, null, 2)}\n`);
5138
+ }
5139
+ //#endregion
4388
5140
  //#region src/host/sessions/interventions.ts
4389
5141
  /** What the story's triggers delivered lately and what became of each, oldest first. */
4390
5142
  function readInterventions(session) {
@@ -4495,6 +5247,7 @@ async function worldCharacters(worlds, worldId) {
4495
5247
  })),
4496
5248
  startingTime: world.clock?.startingTime === void 0 ? "" : localInstant(world.clock.startingTime, world.clock.timeZone ?? "UTC"),
4497
5249
  timeZone: world.clock?.timeZone ?? "",
5250
+ ...world.preset === void 0 ? {} : { preset: world.preset },
4498
5251
  problems
4499
5252
  };
4500
5253
  }
@@ -4667,7 +5420,8 @@ async function loadWorld(folder, dir, file, problems) {
4667
5420
  ...world.alternateOpenings === void 0 ? {} : { alternateOpenings: world.alternateOpenings },
4668
5421
  ...world.rules === void 0 ? {} : { rules: world.rules },
4669
5422
  ...world.tools === void 0 ? {} : { tools: world.tools },
4670
- ...world.narrationVoice === void 0 ? {} : { narrationVoice: world.narrationVoice }
5423
+ ...world.narrationVoice === void 0 ? {} : { narrationVoice: world.narrationVoice },
5424
+ ...world.preset === void 0 ? {} : { preset: world.preset }
4671
5425
  };
4672
5426
  if (world.coverMediaId !== void 0) try {
4673
5427
  record.cover = await resolveCover(dir, world.coverMediaId);
@@ -4795,6 +5549,879 @@ var WorldCatalog = class extends Service {
4795
5549
  }
4796
5550
  };
4797
5551
  //#endregion
5552
+ //#region src/shared/catalogue.ts
5553
+ const CATALOGUE_CARD_TYPE = "sillytavern/character";
5554
+ const CATALOGUE_PRESET_TYPE = "sillytavern/preset";
5555
+ const CATALOGUE_WORLD_TYPE = "dsh-agentic-roleplay/world";
5556
+ //#endregion
5557
+ //#region src/host/catalogue/origin.ts
5558
+ const ORIGIN_FILE = ".catalogue.json";
5559
+ const MAX_LISTED_CHANGES = 12;
5560
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5561
+ /** The origin recorded in a world's folder, or nothing when it has none. @throws {CatalogueError} when the record is damaged. */
5562
+ async function readOrigin(directory) {
5563
+ let text;
5564
+ try {
5565
+ text = await readFile(join(directory, ORIGIN_FILE), "utf8");
5566
+ } catch (error) {
5567
+ if (error.code === "ENOENT") return void 0;
5568
+ throw error;
5569
+ }
5570
+ const damaged = () => new CatalogueError(`${ORIGIN_FILE} in ${directory} is damaged`, "invalid");
5571
+ let value;
5572
+ try {
5573
+ value = JSON.parse(text);
5574
+ } catch {
5575
+ throw damaged();
5576
+ }
5577
+ if (!isRecord(value)) throw damaged();
5578
+ const { kind, root, resourceId, versionId, version, files } = value;
5579
+ if (kind !== "release" && kind !== "card" || typeof root !== "string" || typeof resourceId !== "string" || typeof versionId !== "string" || typeof version !== "string") throw damaged();
5580
+ if (kind === "card") return {
5581
+ kind,
5582
+ root,
5583
+ resourceId,
5584
+ versionId,
5585
+ version
5586
+ };
5587
+ if (!isRecord(files) || !Object.values(files).every((hash) => typeof hash === "string")) throw damaged();
5588
+ return {
5589
+ kind,
5590
+ root,
5591
+ resourceId,
5592
+ versionId,
5593
+ version,
5594
+ files
5595
+ };
5596
+ }
5597
+ async function writeOrigin(directory, origin) {
5598
+ const file = join(directory, ORIGIN_FILE);
5599
+ const temporary = `${file}.${randomUUID()}.tmp`;
5600
+ await writeFile(temporary, JSON.stringify(origin, null, 2));
5601
+ await rename(temporary, file);
5602
+ }
5603
+ /** SHA-256 of every file in a world folder; entries whose names start with a dot (this record, the trash, import state) are not the world's own. */
5604
+ async function hashWorld(directory) {
5605
+ const hashes = {};
5606
+ const walk = async (relative) => {
5607
+ for (const entry of await readdir(join(directory, relative), { withFileTypes: true })) {
5608
+ if (relative === "" && entry.name.startsWith(".")) continue;
5609
+ const path = relative === "" ? entry.name : `${relative}/${entry.name}`;
5610
+ if (entry.isDirectory()) await walk(path);
5611
+ else if (entry.isFile()) hashes[path] = createHash("sha256").update(await readFile(join(directory, path))).digest("hex");
5612
+ }
5613
+ };
5614
+ await walk("");
5615
+ return hashes;
5616
+ }
5617
+ function compare(recorded, current) {
5618
+ return {
5619
+ changed: Object.keys(recorded).filter((path) => current[path] !== void 0 && current[path] !== recorded[path]),
5620
+ added: Object.keys(current).filter((path) => recorded[path] === void 0),
5621
+ removed: Object.keys(recorded).filter((path) => current[path] === void 0)
5622
+ };
5623
+ }
5624
+ const isUnchanged = (changes) => changes.changed.length + changes.added.length + changes.removed.length === 0;
5625
+ /** The differences as short lines for a person to read, capped. */
5626
+ function describeChanges(changes) {
5627
+ const lines = [
5628
+ ...changes.changed.map((path) => `changed: ${path}`),
5629
+ ...changes.added.map((path) => `added: ${path}`),
5630
+ ...changes.removed.map((path) => `removed: ${path}`)
5631
+ ];
5632
+ return lines.length <= MAX_LISTED_CHANGES ? lines : [...lines.slice(0, MAX_LISTED_CHANGES), `and ${lines.length - MAX_LISTED_CHANGES} more`];
5633
+ }
5634
+ /** How a world's files compare with the release it came from: the differences, or `unverified` when no record of the release exists. */
5635
+ async function localChanges(directory) {
5636
+ const origin = await readOrigin(directory);
5637
+ if (origin?.kind !== "release") return "unverified";
5638
+ return compare(origin.files, await hashWorld(directory));
5639
+ }
5640
+ //#endregion
5641
+ //#region src/host/catalogue/zip.ts
5642
+ const END_SIGNATURE = 101010256;
5643
+ const CENTRAL_SIGNATURE = 33639248;
5644
+ const LOCAL_SIGNATURE = 67324752;
5645
+ const MAX_FILES = 5e3;
5646
+ const SYMBOLIC_LINK = 40960;
5647
+ const TYPE_MASK = 61440;
5648
+ const invalid = (message) => new CatalogueError(message, "invalid");
5649
+ /** An archive path that stays inside the folder it is unpacked to, or the reason it does not. */
5650
+ function archivePathProblem(name) {
5651
+ if (name.includes("\\") || name.includes("\0")) return "has a backslash or a NUL character";
5652
+ if (name.startsWith("/") || /^[A-Za-z]:/.test(name)) return "is absolute";
5653
+ const parts = name.split("/");
5654
+ if (parts.some((part) => part === "..")) return "climbs out of the folder";
5655
+ if (parts.some((part, index) => part === "." || part === "" && index !== parts.length - 1)) return "is ambiguous";
5656
+ }
5657
+ /**
5658
+ * Reads the files of a ZIP archive, refusing anything that could write outside the target or exhaust the machine: unsafe or repeated paths
5659
+ * (also by case), links, encryption, ZIP64, methods other than stored and deflate, too many files, and a total size past the limit
5660
+ * (checked from the sizes the archive declares and again from what inflating really produced).
5661
+ * @throws {CatalogueError} (`invalid`) when the archive is not acceptable.
5662
+ */
5663
+ function readZip(archive, limits) {
5664
+ let end = -1;
5665
+ for (let at = archive.length - 22; at >= Math.max(0, archive.length - 22 - 65535); at -= 1) if (archive.readUInt32LE(at) === END_SIGNATURE) {
5666
+ end = at;
5667
+ break;
5668
+ }
5669
+ if (end < 0) throw invalid("the file is not a ZIP archive");
5670
+ const count = archive.readUInt16LE(end + 10);
5671
+ const directorySize = archive.readUInt32LE(end + 12);
5672
+ let at = archive.readUInt32LE(end + 16);
5673
+ if (count === 65535 || directorySize === 4294967295 || at === 4294967295) throw invalid("ZIP64 archives are not supported");
5674
+ if (count > MAX_FILES) throw invalid(`the archive holds more than ${MAX_FILES} files`);
5675
+ const files = /* @__PURE__ */ new Map();
5676
+ const folded = /* @__PURE__ */ new Set();
5677
+ let declared = 0;
5678
+ let produced = 0;
5679
+ for (let index = 0; index < count; index += 1) {
5680
+ if (at + 46 > archive.length || archive.readUInt32LE(at) !== CENTRAL_SIGNATURE) throw invalid("the archive directory is damaged");
5681
+ const flags = archive.readUInt16LE(at + 8);
5682
+ const method = archive.readUInt16LE(at + 10);
5683
+ const compressed = archive.readUInt32LE(at + 20);
5684
+ const size = archive.readUInt32LE(at + 24);
5685
+ const nameLength = archive.readUInt16LE(at + 28);
5686
+ const extraLength = archive.readUInt16LE(at + 30);
5687
+ const commentLength = archive.readUInt16LE(at + 32);
5688
+ const attributes = archive.readUInt32LE(at + 38);
5689
+ const local = archive.readUInt32LE(at + 42);
5690
+ if (at + 46 + nameLength > archive.length) throw invalid("the archive directory is damaged");
5691
+ const name = archive.toString("utf8", at + 46, at + 46 + nameLength);
5692
+ at += 46 + nameLength + extraLength + commentLength;
5693
+ const problem = archivePathProblem(name);
5694
+ if (problem !== void 0) throw invalid(`the archive path "${name}" ${problem}`);
5695
+ if (name.endsWith("/")) continue;
5696
+ if ((attributes >>> 16 & TYPE_MASK) === SYMBOLIC_LINK) throw invalid(`the archive holds a link: ${name}`);
5697
+ if ((flags & 1) !== 0) throw invalid("encrypted archives are not supported");
5698
+ if (method !== 0 && method !== 8) throw invalid(`the archive entry ${name} uses an unsupported compression method`);
5699
+ if (compressed === 4294967295 || size === 4294967295) throw invalid("ZIP64 archives are not supported");
5700
+ const key = name.toLowerCase();
5701
+ if (files.has(name) || folded.has(key)) throw invalid(`the archive repeats a path (or differs only by case): ${name}`);
5702
+ declared += size;
5703
+ if (declared > limits.maxBytes) throw invalid(`the archive unpacks to more than ${limits.maxBytes} bytes`);
5704
+ if (local + 30 > archive.length || archive.readUInt32LE(local) !== LOCAL_SIGNATURE) throw invalid(`the archive entry ${name} is damaged`);
5705
+ const start = local + 30 + archive.readUInt16LE(local + 26) + archive.readUInt16LE(local + 28);
5706
+ if (start + compressed > archive.length) throw invalid(`the archive entry ${name} is cut short`);
5707
+ const raw = archive.subarray(start, start + compressed);
5708
+ let content;
5709
+ try {
5710
+ content = method === 0 ? Buffer.from(raw) : inflateRawSync(raw, { maxOutputLength: Math.max(size, 1) });
5711
+ } catch {
5712
+ throw invalid(`the archive entry ${name} cannot be unpacked`);
5713
+ }
5714
+ if (content.length !== size) throw invalid(`the archive entry ${name} does not match its declared size`);
5715
+ produced += content.length;
5716
+ if (produced > limits.maxBytes) throw invalid(`the archive unpacks to more than ${limits.maxBytes} bytes`);
5717
+ files.set(name, content);
5718
+ folded.add(key);
5719
+ }
5720
+ return files;
5721
+ }
5722
+ //#endregion
5723
+ //#region src/host/catalogue/install.ts
5724
+ const FOLDER_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
5725
+ const MAX_FOLDER_COPIES = 99;
5726
+ /** The one top-level folder of a world archive and the files in it, or why the archive is not a world. */
5727
+ function worldFolder(files) {
5728
+ const marks = [...files.keys()].filter((path) => path.split("/").pop() === WORLD_FILE_NAME);
5729
+ if (marks.length !== 1 || marks[0].split("/").length !== 2) throw new CatalogueError(`the archive must hold one top-level world folder with ${WORLD_FILE_NAME}`, "invalid");
5730
+ const folder = marks[0].split("/")[0];
5731
+ if (!FOLDER_NAME.test(folder)) throw new CatalogueError(`the world folder "${folder}" has an unsafe or unsupported name`, "invalid");
5732
+ const stray = [...files.keys()].find((path) => path.split("/")[0] !== folder);
5733
+ if (stray !== void 0) throw new CatalogueError(`every file must be inside the "${folder}" folder: ${stray}`, "invalid");
5734
+ return folder;
5735
+ }
5736
+ function freeFolder(directory, wanted) {
5737
+ for (let copy = 1; copy <= 100; copy += 1) {
5738
+ const candidate = copy === 1 ? wanted : `${wanted}-${copy}`;
5739
+ if (!existsSync(join(directory, candidate))) return candidate;
5740
+ }
5741
+ throw new CatalogueError(`there are already ${MAX_FOLDER_COPIES} world folders named like "${wanted}"`, "conflict");
5742
+ }
5743
+ /** The world file of a second copy: its own identity and a name that tells it from the first. */
5744
+ function asCopy(text, id, name) {
5745
+ const { id: _previous, name: _name, ...rest } = JSON.parse(text.replace(/^\uFEFF/, ""));
5746
+ return JSON.stringify({
5747
+ id,
5748
+ name,
5749
+ ...rest
5750
+ }, null, indentOf(text)) + (text.endsWith("\n") ? "\n" : "");
5751
+ }
5752
+ const stamp = () => (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
5753
+ /**
5754
+ * Unpacks a world archive into the person's worlds, after the same checks the worlds list makes of a world: it is written beside the
5755
+ * worlds first and only moved in when whole, and removed again if the catalogue then refuses it.
5756
+ *
5757
+ * `new` never replaces a world the person has. `update` replaces the world with the same identity, keeping its folder, after moving the
5758
+ * old files to `<root>/.trash/worlds/` so nothing is lost, and only when the files still match the release they came from (or the person
5759
+ * said to overwrite). `copy` gives the release a new identity and installs it beside the world the person has.
5760
+ * @throws {CatalogueError} `invalid` when the archive is not a valid world, `conflict` when the person has the world (`new`) or changed it (`update`).
5761
+ */
5762
+ async function installWorld(catalog, archive, maxBytes, options) {
5763
+ const files = readZip(archive, { maxBytes });
5764
+ const folder = worldFolder(files);
5765
+ const worldText = files.get(`${folder}/${WORLD_FILE_NAME}`).toString("utf8");
5766
+ const parsed = parseWorldFile(worldText.replace(/^\uFEFF/, ""));
5767
+ if (!parsed.ok) throw new CatalogueError(`${WORLD_FILE_NAME} is not valid: ${parsed.issues.map(formatIssue).join("; ")}`, "invalid");
5768
+ const world = parsed.value;
5769
+ const known = await catalog.list({ refresh: true });
5770
+ const existing = world.id === void 0 ? void 0 : known.worlds.find((candidate) => candidate.id === world.id);
5771
+ const record = existing === void 0 ? void 0 : await catalog.find(existing.id);
5772
+ if (existing !== void 0 && options.mode === "new") throw new CatalogueError(`you already have "${existing.name}"`, "conflict", { reason: "exists" });
5773
+ if (record !== void 0 && options.mode === "update" && !options.overwriteChanges) {
5774
+ const changes = await localChanges(record.directory);
5775
+ if (changes === "unverified") throw new CatalogueError(`"${existing.name}" has no record of the release it came from, so there is no telling whether you changed it`, "conflict", { reason: "unverified" });
5776
+ if (!isUnchanged(changes)) throw new CatalogueError(`you changed "${existing.name}" since you installed it`, "conflict", {
5777
+ reason: "modified",
5778
+ changes: describeChanges(changes)
5779
+ });
5780
+ }
5781
+ const replacing = options.mode === "update" ? record : void 0;
5782
+ const copyId = options.mode === "copy" && existing !== void 0 ? randomUUID() : void 0;
5783
+ const root = dirname(catalog.directory);
5784
+ const staging = join(root, ".install", randomUUID());
5785
+ const stagedFolder = join(staging, folder);
5786
+ let placed;
5787
+ let backup;
5788
+ try {
5789
+ for (const [path, content] of files) {
5790
+ const target = resolve(staging, path);
5791
+ if (!target.startsWith(`${resolve(stagedFolder)}${sep}`)) throw new CatalogueError(`the archive path "${path}" leaves the world folder`, "invalid");
5792
+ await mkdir(dirname(target), { recursive: true });
5793
+ await writeFile(target, path === `${folder}/world.json` && copyId !== void 0 ? asCopy(worldText, copyId, `${world.name} (copy)`) : content);
5794
+ }
5795
+ await mkdir(catalog.directory, { recursive: true });
5796
+ if (replacing !== void 0) {
5797
+ placed = basename(replacing.directory);
5798
+ backup = join(".trash", "worlds", `${placed}-${stamp()}`);
5799
+ await mkdir(join(root, dirname(backup)), { recursive: true });
5800
+ await rename(replacing.directory, join(root, backup));
5801
+ } else placed = freeFolder(catalog.directory, folder);
5802
+ await rename(stagedFolder, join(catalog.directory, placed));
5803
+ const payload = await catalog.list({ refresh: true });
5804
+ const wanted = copyId ?? world.id;
5805
+ const added = wanted === void 0 ? payload.worlds.find((candidate) => candidate.name === world.name) : payload.worlds.find((candidate) => candidate.id === wanted);
5806
+ if (added === void 0) {
5807
+ await rm(join(catalog.directory, placed), {
5808
+ recursive: true,
5809
+ force: true
5810
+ });
5811
+ if (replacing !== void 0 && backup !== void 0) await rename(join(root, backup), replacing.directory);
5812
+ await catalog.list({ refresh: true });
5813
+ const reasons = payload.problems.filter((problem) => problem.path.includes(placed)).map((problem) => problem.message);
5814
+ throw new CatalogueError(`the world was refused: ${reasons.length === 0 ? "it was not found when the worlds were read" : reasons.join("; ")}`, "invalid");
5815
+ }
5816
+ const tracked = options.provenance !== void 0 && copyId === void 0;
5817
+ if (tracked) {
5818
+ const directory = join(catalog.directory, placed);
5819
+ await writeOrigin(directory, {
5820
+ kind: "release",
5821
+ ...options.provenance,
5822
+ files: await hashWorld(directory)
5823
+ });
5824
+ }
5825
+ return {
5826
+ world: added,
5827
+ packs: [...files.keys()].map((path) => path.split("/")).filter((parts) => parts.length === 4 && parts[1] === "ui" && parts[3] === "pack.json").map((parts) => parts[2]),
5828
+ tracked,
5829
+ ...backup === void 0 ? {} : { backup }
5830
+ };
5831
+ } finally {
5832
+ await rm(staging, {
5833
+ recursive: true,
5834
+ force: true
5835
+ });
5836
+ }
5837
+ }
5838
+ //#endregion
5839
+ //#region src/host/catalogue/trash.ts
5840
+ const DAY_MS = 864e5;
5841
+ const STAMP = /-(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z$/;
5842
+ /** Staging folders left by an interrupted install are removed after this long. */
5843
+ const STALE_STAGING_MS = DAY_MS;
5844
+ /** When a world's old files were moved to the trash, read from the folder name the update gave them; entries without such a stamp are not ours. */
5845
+ function movedAt(name) {
5846
+ const match = STAMP.exec(name);
5847
+ if (match === null) return void 0;
5848
+ const time = Date.parse(`${match[1]}T${match[2]}:${match[3]}:${match[4]}.${match[5]}Z`);
5849
+ return Number.isNaN(time) ? void 0 : time;
5850
+ }
5851
+ async function entries(directory) {
5852
+ try {
5853
+ return await readdir(directory);
5854
+ } catch (error) {
5855
+ if (error.code === "ENOENT") return [];
5856
+ throw error;
5857
+ }
5858
+ }
5859
+ /**
5860
+ * Removes what updates and installs leave behind: world files moved to `.trash/worlds/` more than `keepDays` days ago (0 keeps them for
5861
+ * good), and staging folders of an install that never finished. A folder that cannot be removed is reported and the rest still goes.
5862
+ * @returns the folders removed and the failures.
5863
+ */
5864
+ async function pruneTrash(root, keepDays, now = Date.now()) {
5865
+ const removed = [];
5866
+ const failures = [];
5867
+ const drop = async (path, label) => {
5868
+ try {
5869
+ await rm(path, {
5870
+ recursive: true,
5871
+ force: true
5872
+ });
5873
+ removed.push(label);
5874
+ } catch (error) {
5875
+ failures.push(`${label}: ${error instanceof Error ? error.message : String(error)}`);
5876
+ }
5877
+ };
5878
+ if (keepDays > 0) for (const name of await entries(join(root, ".trash", "worlds"))) {
5879
+ const at = movedAt(name);
5880
+ if (at !== void 0 && now - at > keepDays * DAY_MS) await drop(join(root, ".trash", "worlds", name), `.trash/worlds/${name}`);
5881
+ }
5882
+ for (const name of await entries(join(root, ".install"))) if (now - (await stat(join(root, ".install", name))).mtimeMs > STALE_STAGING_MS) await drop(join(root, ".install", name), `.install/${name}`);
5883
+ return {
5884
+ removed,
5885
+ failures
5886
+ };
5887
+ }
5888
+ //#endregion
5889
+ //#region src/host/catalogue/transport.ts
5890
+ const TIMEOUT_MS = 6e4;
5891
+ const MAX_REDIRECTS = 5;
5892
+ const nodeTransport = (url, ask) => new Promise((resolveReply, reject) => {
5893
+ const request$2 = (url.protocol === "https:" ? request$1 : request)(url, {
5894
+ method: "GET",
5895
+ signal: ask.signal,
5896
+ timeout: TIMEOUT_MS,
5897
+ agent: false,
5898
+ headers: {
5899
+ "user-agent": "dsh-agentic-roleplay",
5900
+ "accept-encoding": "identity",
5901
+ ...ask.headers
5902
+ },
5903
+ ...ask.guarded ? { lookup: guardedLookup } : {}
5904
+ }, (response) => {
5905
+ const status = response.statusCode ?? 0;
5906
+ const location = typeof response.headers.location === "string" ? response.headers.location : void 0;
5907
+ const type = String(response.headers["content-type"] ?? "").split(";")[0].trim().toLowerCase();
5908
+ if (status >= 300 && status < 400 && location !== void 0) {
5909
+ response.destroy();
5910
+ resolveReply({
5911
+ status,
5912
+ type,
5913
+ location,
5914
+ body: Buffer.alloc(0)
5915
+ });
5916
+ return;
5917
+ }
5918
+ if (Number(response.headers["content-length"] ?? 0) > ask.maxBytes) {
5919
+ response.destroy();
5920
+ reject(new CatalogueError(`the answer is larger than ${ask.maxBytes} bytes`, "upstream"));
5921
+ return;
5922
+ }
5923
+ const chunks = [];
5924
+ let size = 0;
5925
+ response.on("data", (chunk) => {
5926
+ size += chunk.length;
5927
+ if (size > ask.maxBytes) {
5928
+ response.destroy();
5929
+ reject(new CatalogueError(`the answer is larger than ${ask.maxBytes} bytes`, "upstream"));
5930
+ return;
5931
+ }
5932
+ chunks.push(chunk);
5933
+ });
5934
+ response.on("end", () => {
5935
+ resolveReply({
5936
+ status,
5937
+ type,
5938
+ location,
5939
+ body: Buffer.concat(chunks)
5940
+ });
5941
+ });
5942
+ response.on("error", reject);
5943
+ });
5944
+ request$2.on("timeout", () => {
5945
+ request$2.destroy(/* @__PURE__ */ new Error("timed out"));
5946
+ });
5947
+ request$2.on("error", reject);
5948
+ request$2.end();
5949
+ });
5950
+ /**
5951
+ * Asks for an address. An address on a configured catalogue's site carries that catalogue's API key and may be a local address (the person
5952
+ * named that site); any other address is asked for plainly and only if it is a public one. A redirect is judged like a first address, so
5953
+ * the key never goes to another site.
5954
+ * @throws {CatalogueError} when the address cannot be used or the answer is not a success.
5955
+ */
5956
+ async function fetchAddress(address, options) {
5957
+ const transport = options.transport ?? nodeTransport;
5958
+ const signal = AbortSignal.any([AbortSignal.timeout(TIMEOUT_MS * 4), ...options.signal === void 0 ? [] : [options.signal]]);
5959
+ let url = new URL(address);
5960
+ for (let hop = 0;; hop += 1) {
5961
+ if (url.protocol !== "http:" && url.protocol !== "https:") throw new CatalogueError(`${url.href} is not a web address`, "input");
5962
+ if (url.username !== "" || url.password !== "") throw new CatalogueError(`${url.origin} must not carry a user name or password: use the API key field`, "input");
5963
+ const source = options.sources.match(url);
5964
+ if (source === void 0) {
5965
+ const vetted = vetUrl(url.href);
5966
+ if (typeof vetted === "string") throw new CatalogueError(`${url.href} ${vetted}`, "input");
5967
+ }
5968
+ const key = source?.apiKey;
5969
+ let reply;
5970
+ try {
5971
+ reply = await transport(url, {
5972
+ headers: {
5973
+ accept: options.accept,
5974
+ ...key === void 0 ? {} : { authorization: `Bearer ${key}` }
5975
+ },
5976
+ guarded: source === void 0,
5977
+ maxBytes: options.maxBytes,
5978
+ signal
5979
+ });
5980
+ } catch (error) {
5981
+ if (error instanceof CatalogueError) throw error;
5982
+ throw new CatalogueError(`could not reach ${url.origin}: ${error instanceof Error ? error.message : String(error)}`, "upstream");
5983
+ }
5984
+ if (reply.status >= 300 && reply.status < 400 && reply.location !== void 0) {
5985
+ if (hop >= MAX_REDIRECTS) throw new CatalogueError("too many redirects", "upstream");
5986
+ url = new URL(reply.location, url);
5987
+ continue;
5988
+ }
5989
+ if (reply.status >= 200 && reply.status < 300) return reply;
5990
+ throw new CatalogueError(refusal(url, reply.status, source !== void 0, key !== void 0), reply.status === 404 ? "unknown" : "upstream");
5991
+ }
5992
+ }
5993
+ function refusal(url, status, known, keyed) {
5994
+ if (status === 401 || status === 403) {
5995
+ if (keyed) return `${url.origin} refused the API key (answered ${status}): check it in Settings, Role Play`;
5996
+ return known ? `${url.origin} needs an API key (answered ${status}): add one for this catalogue in Settings, Role Play` : `${url.origin} needs a sign-in (answered ${status}): add its catalogue with an API key in Settings, Role Play`;
5997
+ }
5998
+ if (status === 404) return `${url.href} was not found${keyed ? "" : ", or it is private and needs an API key"}`;
5999
+ return `${url.origin} answered ${status} for ${url.pathname}`;
6000
+ }
6001
+ const MAX_JSON_BYTES = 8388608;
6002
+ const MAX_COVER_BYTES = 20971520;
6003
+ const ID = /^[A-Za-z0-9_-]{1,100}$/;
6004
+ const VISIBILITY = [
6005
+ "public",
6006
+ "authenticated",
6007
+ "private"
6008
+ ];
6009
+ const CHECKED_AT_ONCE = 4;
6010
+ const unexpected = (what) => new CatalogueError(`the catalogue answered with something unexpected: ${what}`, "upstream");
6011
+ const object = (value, what) => {
6012
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw unexpected(what);
6013
+ return value;
6014
+ };
6015
+ const text = (value) => typeof value === "string" ? value : "";
6016
+ const count = (value) => typeof value === "number" && Number.isFinite(value) ? value : 0;
6017
+ const kindOf = (type) => type === "sillytavern/character" ? "card" : type === "sillytavern/preset" ? "preset" : "world";
6018
+ const TYPES = {
6019
+ world: CATALOGUE_WORLD_TYPE,
6020
+ card: CATALOGUE_CARD_TYPE,
6021
+ preset: CATALOGUE_PRESET_TYPE
6022
+ };
6023
+ function worldOf(value) {
6024
+ const item = object(value, "a world entry");
6025
+ const metadata = object(item["metadata"], "a world entry without metadata");
6026
+ const id = text(item["id"]);
6027
+ if (!ID.test(id)) throw unexpected("a world entry without an id");
6028
+ const visibility = text(metadata["visibility"]);
6029
+ return {
6030
+ id,
6031
+ kind: kindOf(text(item["resourceType"])),
6032
+ name: text(metadata["name"]),
6033
+ description: text(metadata["description"]),
6034
+ tags: Array.isArray(metadata["tags"]) ? metadata["tags"].filter((tag) => typeof tag === "string") : [],
6035
+ author: text(item["authorUsername"]),
6036
+ visibility: VISIBILITY.includes(visibility) ? visibility : "private",
6037
+ language: text(metadata["language"]),
6038
+ views: count(item["viewCount"]),
6039
+ downloads: count(item["downloadCount"]),
6040
+ hasCover: typeof item["coverImageResourceId"] === "string" && item["coverImageResourceId"] !== ""
6041
+ };
6042
+ }
6043
+ function versionOf(value) {
6044
+ const item = object(value, "a version entry");
6045
+ const id = text(item["id"]);
6046
+ if (!ID.test(id)) throw unexpected("a version entry without an id");
6047
+ const visibility = text(item["visibility"]);
6048
+ return {
6049
+ number: count(item["versionNumber"]),
6050
+ version: {
6051
+ id,
6052
+ version: text(item["version"]),
6053
+ publishedAt: text(item["publishedAt"]),
6054
+ visibility: VISIBILITY.includes(visibility) ? visibility : "private",
6055
+ ...typeof item["artifactByteSize"] === "number" ? { byteSize: item["artifactByteSize"] } : {},
6056
+ ...typeof item["artifactSha256"] === "string" ? { sha256: item["artifactSha256"] } : {}
6057
+ }
6058
+ };
6059
+ }
6060
+ /** Browsing the worlds a catalogue holds and installing one; the catalogue's API key goes with every request that belongs to its site. */
6061
+ var Catalogue = class {
6062
+ deps;
6063
+ constructor(deps) {
6064
+ this.deps = deps;
6065
+ }
6066
+ sources() {
6067
+ return this.deps.sources.status();
6068
+ }
6069
+ async worlds(name, query) {
6070
+ const source = this.deps.sources.get(name);
6071
+ const offset = Math.max(0, Math.floor(query.offset ?? 0));
6072
+ const params = {
6073
+ resourceType: TYPES[query.kind ?? "world"],
6074
+ publishedOnly: "true",
6075
+ limit: String(24),
6076
+ offset: String(offset),
6077
+ sort: query.sort ?? "recent"
6078
+ };
6079
+ const search = query.search?.trim() ?? "";
6080
+ if (search !== "") params["search_string"] = search.slice(0, 200);
6081
+ const answer = object(await this.json(source, "/resources", params), "the list of worlds");
6082
+ if (!Array.isArray(answer["items"])) throw unexpected("the list of worlds has no items");
6083
+ const next = answer["nextOffset"];
6084
+ return {
6085
+ items: answer["items"].map(worldOf),
6086
+ ...typeof next === "number" ? { nextOffset: next } : {},
6087
+ withKey: source.apiKey !== void 0
6088
+ };
6089
+ }
6090
+ async world(name, id) {
6091
+ const source = this.deps.sources.get(name);
6092
+ const world = worldOf(await this.json(source, `/resources/${this.identifier(id)}`));
6093
+ const listed = await this.json(source, `/versions/resource/${this.identifier(id)}`);
6094
+ if (!Array.isArray(listed)) throw unexpected("the list of versions");
6095
+ const versions = listed.map(versionOf).sort((a, b) => b.number - a.number).map((entry) => entry.version);
6096
+ if (world.kind === "card") {
6097
+ const converted = (await this.origins()).filter(({ origin }) => origin?.kind === "card" && origin.resourceId === id && this.deps.sources.match(new URL(origin.root))?.name === source.name);
6098
+ return {
6099
+ ...world,
6100
+ versions,
6101
+ converted: converted.map(({ name: worldName, worldId, origin }) => ({
6102
+ worldId,
6103
+ name: worldName,
6104
+ version: origin?.version ?? ""
6105
+ }))
6106
+ };
6107
+ }
6108
+ const latest = versions[0];
6109
+ let installed;
6110
+ if (latest !== void 0) {
6111
+ const data = object(object(await this.json(source, `/versions/${latest.id}/data`), "the data of a version")["data"], "the data of a version");
6112
+ const worldId = text(data["worldId"]);
6113
+ const mine = worldId === "" ? void 0 : (await this.deps.worlds.list()).worlds.find((existing) => existing.id === worldId);
6114
+ if (mine !== void 0) {
6115
+ const record = await this.deps.worlds.find(mine.id);
6116
+ const origin = record === void 0 ? void 0 : await readOrigin(record.directory);
6117
+ const changes = record === void 0 ? "unverified" : await localChanges(record.directory);
6118
+ installed = {
6119
+ worldId: mine.id,
6120
+ name: mine.name,
6121
+ ...mine.version === void 0 ? {} : { version: mine.version },
6122
+ ...origin?.kind === "release" ? { versionId: origin.versionId } : {},
6123
+ modified: changes === "unverified" ? "unknown" : !isUnchanged(changes)
6124
+ };
6125
+ }
6126
+ }
6127
+ return {
6128
+ ...world,
6129
+ versions,
6130
+ ...installed === void 0 ? {} : { installed }
6131
+ };
6132
+ }
6133
+ /** Installed worlds with a newer release in the catalogue, and the worlds that could not be checked. */
6134
+ async updates(name) {
6135
+ const source = this.deps.sources.get(name);
6136
+ const mine = (await this.origins()).filter(({ origin, problem }) => problem !== void 0 || origin?.kind === "release" && this.deps.sources.match(new URL(origin.root))?.name === source.name);
6137
+ const result = {
6138
+ updates: [],
6139
+ problems: []
6140
+ };
6141
+ for (let from = 0; from < mine.length; from += CHECKED_AT_ONCE) await Promise.all(mine.slice(from, from + CHECKED_AT_ONCE).map(async ({ worldId, name: worldName, directory, origin, problem }) => {
6142
+ try {
6143
+ if (problem !== void 0) throw new CatalogueError(problem, "invalid");
6144
+ if (origin?.kind !== "release") return;
6145
+ const listed = await this.json(source, `/versions/resource/${this.identifier(origin.resourceId)}`);
6146
+ if (!Array.isArray(listed)) throw unexpected("the list of versions");
6147
+ const entries = listed.map(versionOf).sort((a, b) => b.number - a.number);
6148
+ const latest = entries[0];
6149
+ const installed = entries.find((entry) => entry.version.id === origin.versionId);
6150
+ if (latest === void 0 || latest.version.id === origin.versionId || installed !== void 0 && latest.number <= installed.number) return;
6151
+ const changes = await localChanges(directory);
6152
+ const update = {
6153
+ worldId,
6154
+ worldName,
6155
+ resourceId: origin.resourceId,
6156
+ installedVersion: origin.version,
6157
+ latest: latest.version,
6158
+ modified: changes === "unverified" ? true : !isUnchanged(changes)
6159
+ };
6160
+ result.updates.push(update);
6161
+ } catch (error) {
6162
+ result.problems.push({
6163
+ worldName,
6164
+ message: error instanceof Error ? error.message : String(error)
6165
+ });
6166
+ }
6167
+ }));
6168
+ result.updates.sort((a, b) => a.worldName.localeCompare(b.worldName));
6169
+ return result;
6170
+ }
6171
+ async cover(name, id) {
6172
+ const source = this.deps.sources.get(name);
6173
+ const reply = await fetchAddress(this.address(source, `/images/covers/resources/${this.identifier(id)}`), {
6174
+ sources: this.deps.sources,
6175
+ maxBytes: MAX_COVER_BYTES,
6176
+ accept: "image/*",
6177
+ ...this.deps.transport === void 0 ? {} : { transport: this.deps.transport }
6178
+ });
6179
+ if (!reply.type.startsWith("image/")) throw unexpected("the cover is not a picture");
6180
+ return {
6181
+ type: reply.type,
6182
+ body: reply.body
6183
+ };
6184
+ }
6185
+ /**
6186
+ * Downloads a world archive from an address and installs it. The address may be any ZIP link: one on a configured catalogue's site is asked
6187
+ * for with that catalogue's key, any other plainly (and only when it is a public address).
6188
+ * @throws {CatalogueError} when the address cannot be fetched, is not a world archive, or names a world the person has.
6189
+ */
6190
+ async install(request) {
6191
+ const address = request.url.trim();
6192
+ if (address === "") throw new CatalogueError("give the address of a world archive", "input");
6193
+ let url;
6194
+ try {
6195
+ url = new URL(address);
6196
+ } catch {
6197
+ throw new CatalogueError(`"${address}" is not an address`, "input");
6198
+ }
6199
+ const reply = await fetchAddress(url.href, {
6200
+ sources: this.deps.sources,
6201
+ maxBytes: this.deps.maxBytes(),
6202
+ accept: "application/zip, application/octet-stream;q=0.9, */*;q=0.1",
6203
+ ...this.deps.transport === void 0 ? {} : { transport: this.deps.transport }
6204
+ });
6205
+ if (reply.body.length < 4 || reply.body.readUInt32LE(0) !== 67324752) throw new CatalogueError(`${url.href} did not answer with a ZIP archive${reply.type === "" ? "" : ` (it sent ${reply.type})`}`, "invalid");
6206
+ if (request.sha256 !== void 0 && createHash("sha256").update(reply.body).digest("hex") !== request.sha256.toLowerCase()) throw new CatalogueError("the download does not match the checksum the catalogue published for it", "invalid");
6207
+ const provenance = await this.provenance(url);
6208
+ const installed = await installWorld(this.deps.worlds, reply.body, this.deps.maxBytes(), {
6209
+ mode: request.mode ?? "new",
6210
+ overwriteChanges: request.overwriteChanges === true,
6211
+ ...provenance === void 0 ? {} : { provenance }
6212
+ });
6213
+ if (installed.backup !== void 0) await this.tidy();
6214
+ return installed;
6215
+ }
6216
+ /** Deletes what updates left in the trash past the configured time; a failure is reported and never fails the request that triggered it. */
6217
+ async tidy() {
6218
+ try {
6219
+ const { failures } = await pruneTrash(dirname(this.deps.worlds.directory), this.deps.trashDays());
6220
+ for (const failure of failures) this.deps.problem(`could not remove old catalogue files: ${failure}`);
6221
+ } catch (error) {
6222
+ this.deps.problem(`could not clean the catalogue trash: ${error instanceof Error ? error.message : String(error)}`);
6223
+ }
6224
+ }
6225
+ /**
6226
+ * Turns a character card of a catalogue into a new world: the card is downloaded with the catalogue's key and handed to the importer, whose
6227
+ * authoring chat does the conversion. The conversion is made by an agent and differs from run to run, so it never replaces a world: converting
6228
+ * again makes another one.
6229
+ */
6230
+ async convert(request) {
6231
+ const source = this.deps.sources.get(request.source);
6232
+ 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);
6240
+ const record = await this.deps.worlds.find(converted.worldId);
6241
+ if (record === void 0) throw new CatalogueError("the world was made but cannot be found", "upstream");
6242
+ await writeOrigin(record.directory, {
6243
+ kind: "card",
6244
+ root: source.root,
6245
+ resourceId: release.resourceId,
6246
+ versionId: release.versionId,
6247
+ version: release.version
6248
+ });
6249
+ return converted;
6250
+ }
6251
+ /** 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
+ async convertPreset(request) {
6253
+ const release = await this.download(this.deps.sources.get(request.source), request.versionId, CATALOGUE_PRESET_TYPE, "a preset");
6254
+ return await this.deps.importPreset(release.body, request.title ?? "", request.language);
6255
+ }
6256
+ /** A release of the given type, downloaded with the catalogue's key and checked against the checksum it published. */
6257
+ 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");
6263
+ const reply = await fetchAddress(this.address(source, `/versions/${versionId}/download`), {
6264
+ sources: this.deps.sources,
6265
+ maxBytes: this.deps.maxCardBytes(),
6266
+ accept: "*/*",
6267
+ ...this.deps.transport === void 0 ? {} : { transport: this.deps.transport }
6268
+ });
6269
+ const sha256 = text(version["artifactSha256"]);
6270
+ if (sha256 !== "" && createHash("sha256").update(reply.body).digest("hex") !== sha256.toLowerCase()) throw new CatalogueError("the download does not match the checksum the catalogue published for it", "invalid");
6271
+ return {
6272
+ body: reply.body,
6273
+ versionId,
6274
+ resourceId,
6275
+ version: text(version["version"])
6276
+ };
6277
+ }
6278
+ /** The catalogue release an address names, when it is a release download on a configured catalogue. */
6279
+ async provenance(url) {
6280
+ const source = this.deps.sources.match(url);
6281
+ if (source === void 0) return void 0;
6282
+ const named = /^\/versions\/([A-Za-z0-9_-]{1,100})\/download$/.exec(url.pathname.slice(source.prefix.length));
6283
+ if (named === null) return void 0;
6284
+ const version = object(await this.json(source, `/versions/${named[1]}`), "a version");
6285
+ const resourceId = text(version["resourceId"]);
6286
+ if (!ID.test(resourceId)) throw unexpected("a version without a resource id");
6287
+ return {
6288
+ root: source.root,
6289
+ resourceId,
6290
+ versionId: named[1],
6291
+ version: text(version["version"])
6292
+ };
6293
+ }
6294
+ /** Every world with the record of where it came from, or why that record cannot be read. */
6295
+ async origins() {
6296
+ const found = [];
6297
+ for (const summary of (await this.deps.worlds.list()).worlds) {
6298
+ const record = await this.deps.worlds.find(summary.id);
6299
+ if (record === void 0) continue;
6300
+ try {
6301
+ const origin = await readOrigin(record.directory);
6302
+ found.push({
6303
+ worldId: summary.id,
6304
+ name: summary.name,
6305
+ directory: record.directory,
6306
+ ...origin === void 0 ? {} : { origin }
6307
+ });
6308
+ } catch (error) {
6309
+ found.push({
6310
+ worldId: summary.id,
6311
+ name: summary.name,
6312
+ directory: record.directory,
6313
+ problem: error instanceof Error ? error.message : String(error)
6314
+ });
6315
+ }
6316
+ }
6317
+ return found;
6318
+ }
6319
+ identifier(id) {
6320
+ if (!ID.test(id)) throw new CatalogueError("that is not a catalogue id", "input");
6321
+ return id;
6322
+ }
6323
+ address(source, path, params = {}) {
6324
+ const url = new URL(`${source.root}${path}`);
6325
+ for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);
6326
+ return url.href;
6327
+ }
6328
+ async json(source, path, params = {}) {
6329
+ const reply = await fetchAddress(this.address(source, path, params), {
6330
+ sources: this.deps.sources,
6331
+ maxBytes: MAX_JSON_BYTES,
6332
+ accept: "application/json",
6333
+ ...this.deps.transport === void 0 ? {} : { transport: this.deps.transport }
6334
+ });
6335
+ try {
6336
+ return JSON.parse(reply.body.toString("utf8"));
6337
+ } catch {
6338
+ throw unexpected("it is not JSON: is the address the catalogue's API root?");
6339
+ }
6340
+ }
6341
+ };
6342
+ //#endregion
6343
+ //#region src/host/catalogue/sources.ts
6344
+ /** A web address with no credentials, query or fragment, or the reason it is not one. */
6345
+ function parseBase(text) {
6346
+ let url;
6347
+ try {
6348
+ url = new URL(text.trim());
6349
+ } catch {
6350
+ return "is not an address";
6351
+ }
6352
+ if (url.protocol !== "http:" && url.protocol !== "https:") return "is not a web address";
6353
+ if (url.username !== "" || url.password !== "") return "must not carry a user name or password: use the API key field";
6354
+ if (url.search !== "" || url.hash !== "") return "must not have a query or fragment";
6355
+ return url;
6356
+ }
6357
+ const prefixLength = (prefix, path) => prefix === "" || path === prefix || path.startsWith(`${prefix}/`) ? prefix.length : -1;
6358
+ /** The catalogues the person configured, read afresh on every use so an edit applies at once. */
6359
+ var Sources = class {
6360
+ read;
6361
+ constructor(read) {
6362
+ this.read = read;
6363
+ }
6364
+ resolved() {
6365
+ const seen = /* @__PURE__ */ new Set();
6366
+ return this.read().map((source) => {
6367
+ const name = source.name.trim();
6368
+ if (name === "") return {
6369
+ source,
6370
+ problem: "has no name"
6371
+ };
6372
+ if (seen.has(name)) return {
6373
+ source,
6374
+ problem: "repeats the name of an earlier catalogue"
6375
+ };
6376
+ seen.add(name);
6377
+ const base = parseBase(source.baseUrl);
6378
+ if (typeof base === "string") return {
6379
+ source,
6380
+ problem: `address ${base}`
6381
+ };
6382
+ const prefix = base.pathname.replace(/\/+$/, "");
6383
+ return {
6384
+ source,
6385
+ resolved: {
6386
+ name,
6387
+ root: `${base.origin}${prefix}`,
6388
+ origin: base.origin,
6389
+ prefix,
6390
+ apiKey: source.apiKey.trim() === "" ? void 0 : source.apiKey.trim()
6391
+ }
6392
+ };
6393
+ });
6394
+ }
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" } : {}
6401
+ }));
6402
+ }
6403
+ /** @throws {CatalogueError} when no usable catalogue has the name. */
6404
+ get(name) {
6405
+ const entry = this.resolved().find((candidate) => candidate.source.name.trim() === name);
6406
+ if (entry === void 0) throw new CatalogueError(`there is no catalogue named "${name}"`, "unknown");
6407
+ if (entry.resolved === void 0) throw new CatalogueError(`the catalogue "${name}" ${entry.problem ?? "cannot be used"}`, "invalid");
6408
+ return entry.resolved;
6409
+ }
6410
+ /** The catalogue an address belongs to: the same site, preferring the one whose address is the longest start of the path. */
6411
+ match(url) {
6412
+ let best;
6413
+ for (const { resolved } of this.resolved()) {
6414
+ if (resolved === void 0 || resolved.origin !== url.origin) continue;
6415
+ const length = prefixLength(resolved.prefix, url.pathname);
6416
+ if (best === void 0 || length > best.length) best = {
6417
+ source: resolved,
6418
+ length
6419
+ };
6420
+ }
6421
+ return best?.source;
6422
+ }
6423
+ };
6424
+ //#endregion
4798
6425
  //#region src/host/speech/service.ts
4799
6426
  async function voicesOf(service) {
4800
6427
  return await service.voices();
@@ -4866,6 +6493,13 @@ function mergeWav(buffers) {
4866
6493
  const Config = z.object({
4867
6494
  rootPath: z.string().default("~/dsh-roleplay").volatile(),
4868
6495
  sessionStorePath: z.string().default("~/.dsh/sessions"),
6496
+ catalogues: z.array(z.object({
6497
+ name: z.string().required(),
6498
+ baseUrl: z.string().required(),
6499
+ apiKey: z.string().default("")
6500
+ })).default([]).volatile(),
6501
+ catalogueMaxBytes: z.number().min(1024).default(268435456),
6502
+ catalogueTrashDays: z.number().min(0).default(30),
4869
6503
  importMaxUploadBytes: z.number().min(1024).default(104857600),
4870
6504
  importConcurrency: z.number().min(1).max(16).default(4),
4871
6505
  importReasoning: z.string().default(""),
@@ -4903,6 +6537,7 @@ function apply(ctx, config) {
4903
6537
  const languages = new AuthoringLanguages(ctx, () => join(root.path, "worlds"));
4904
6538
  const agent = new AgentSessions(agentServicesOf(ctx), () => root.path);
4905
6539
  const authoring = new AuthoringSessions(agentServicesOf(ctx), () => root.path, prompts, languages);
6540
+ const presetAuthoring = new PresetAuthoringSessions(agentServicesOf(ctx), () => root.path, prompts, languages);
4906
6541
  const doctors = new DoctorSessions(agentServicesOf(ctx), () => root.path, prompts);
4907
6542
  const imports = new ImportStore(() => root.path);
4908
6543
  new RoleplayImport(ctx, {
@@ -4920,6 +6555,7 @@ function apply(ctx, config) {
4920
6555
  vectors: (id) => vectorStatus(ctx.roleplayState.openSession(join(root.path, "sessions"), id)),
4921
6556
  reflection: (id) => reflectionStatus(ctx.roleplayState.openSession(join(root.path, "sessions"), id), ctx.roleplayOrchestration.reflecting(chatSessionId(id))),
4922
6557
  activity: (id) => readActivity(ctx.roleplayState.openSession(join(root.path, "sessions"), id)),
6558
+ usage: (id) => readUsage(ctx.roleplayState.openSession(join(root.path, "sessions"), id)),
4923
6559
  interventions: (id) => readInterventions(ctx.roleplayState.openSession(join(root.path, "sessions"), id))
4924
6560
  };
4925
6561
  const purgeChat = purgeOf(ctx, config.sessionStorePath);
@@ -4928,9 +6564,41 @@ function apply(ctx, config) {
4928
6564
  state: ctx.roleplayState,
4929
6565
  agent,
4930
6566
  sessionsDir: () => join(root.path, "sessions"),
6567
+ root: () => root.path,
4931
6568
  avatars: () => avatarsWorld(root.path)
4932
6569
  };
6570
+ const presetLibrary = new Presets({
6571
+ root: () => root.path,
6572
+ worldDirectory: async (worldId) => (await worlds.find(worldId))?.directory,
6573
+ authoring: presetAuthoring,
6574
+ importMessage: narrationImportMessage,
6575
+ maxUploadBytes: config.importMaxUploadBytes,
6576
+ playing: (id) => ctx.roleplayOrchestration.playing(chatSessionId(id))
6577
+ });
6578
+ const catalogue = new Catalogue({
6579
+ sources: new Sources(() => config.catalogues.get()),
6580
+ worlds,
6581
+ maxBytes: () => config.catalogueMaxBytes,
6582
+ maxCardBytes: () => config.importMaxUploadBytes,
6583
+ trashDays: () => config.catalogueTrashDays,
6584
+ problem: (message) => {
6585
+ ctx.logger.warn(message);
6586
+ },
6587
+ importPreset: async (file, title, language) => await presetLibrary.importTitled(title, file, language),
6588
+ importCard: async (file, name, language) => {
6589
+ const preview = await imports.create(readCard(file, name), isPng(file) ? pictureOf(file) : void 0);
6590
+ return await startImport({
6591
+ store: imports,
6592
+ worlds,
6593
+ authoring,
6594
+ chatTitle: (title) => `Authoring ${title}`
6595
+ }, preview.id, preview.choices, language);
6596
+ }
6597
+ });
6598
+ catalogue.tidy();
4933
6599
  registerApi(ctx, {
6600
+ catalogue,
6601
+ presets: presetLibrary,
4934
6602
  packs: new InterfaceService({
4935
6603
  open: (id) => ctx.roleplayState.openSession(deps.sessionsDir(), id),
4936
6604
  root: () => root.path,
@@ -5038,14 +6706,36 @@ function apply(ctx, config) {
5038
6706
  editLore: async (worldId, key, edit) => await editWorldLore$1(await editableWorld(worlds, worldId, root.path), key, edit),
5039
6707
  addLore: async (worldId, title) => (await addWorldLore(await editableWorld(worlds, worldId, root.path), title)).state,
5040
6708
  removeLore: async (worldId, key) => await removeWorldLore(await editableWorld(worlds, worldId, root.path), key),
6709
+ readPackFile: async (worldId, pack, path) => await readWorldPackFile((await editableWorld(worlds, worldId, root.path)).directory, pack, path),
6710
+ writePackFile: async (worldId, pack, path, text) => await writeWorldPackFile((await editableWorld(worlds, worldId, root.path)).directory, pack, path, text),
6711
+ deletePackFile: async (worldId, pack, path) => (await deleteWorldPackFile((await editableWorld(worlds, worldId, root.path)).directory, pack, path)).problems,
6712
+ createPack: async (worldId, pack, name) => await createWorldPack((await editableWorld(worlds, worldId, root.path)).directory, pack, name),
6713
+ readTrigger: async (worldId, key) => await readWorldTrigger(await editableWorld(worlds, worldId, root.path), key),
6714
+ writeTrigger: async (worldId, key, document) => await writeWorldTrigger(await editableWorld(worlds, worldId, root.path), key, document),
6715
+ removeTrigger: async (worldId, key) => await removeWorldTrigger(await editableWorld(worlds, worldId, root.path), key),
5041
6716
  editPlots: async (worldId, edit) => await editWorldPlots$1(await editableWorld(worlds, worldId, root.path), edit),
5042
6717
  editRelation: async (worldId, edit) => await editWorldRelation$1(await editableWorld(worlds, worldId, root.path), edit),
5043
6718
  editNarrationVoice: async (worldId, voice) => await editWorldNarrationVoice(await editableWorld(worlds, worldId, root.path), voice),
5044
6719
  generatePortrait: async (worldId, key) => await generateWorldCharacterPortrait(await editableWorld(worlds, worldId, root.path), key, imageGenerationOf(ctx)),
5045
6720
  portraitFile: async (worldId, key) => await worldCharacterPortraitFile(await editableWorld(worlds, worldId, root.path), key),
5046
- uploadPortrait: async (worldId, key, png, name) => await uploadWorldCharacterPortrait(await editableWorld(worlds, worldId, root.path), key, png, name)
6721
+ uploadPortrait: async (worldId, key, png, name) => await uploadWorldCharacterPortrait(await editableWorld(worlds, worldId, root.path), key, png, name),
6722
+ generateEntityImage: async (worldId, kind, key) => await generateWorldEntityImage(await editableWorld(worlds, worldId, root.path), kind, key, imageGenerationOf(ctx)),
6723
+ entityImageFile: async (worldId, kind, key) => await worldEntityImageFile(await editableWorld(worlds, worldId, root.path), kind, key),
6724
+ uploadEntityImage: async (worldId, kind, key, png, name) => await uploadWorldEntityImage(await editableWorld(worlds, worldId, root.path), kind, key, png, name)
5047
6725
  },
5048
6726
  sessions: {
6727
+ generateEntityImage: (id, kind, key) => generateSessionEntityImage({
6728
+ state: ctx.roleplayState,
6729
+ sessionsDir: deps.sessionsDir
6730
+ }, id, kind, key, imageGenerationOf(ctx)),
6731
+ entityImageFile: (id, kind, key) => sessionEntityImageFile({
6732
+ state: ctx.roleplayState,
6733
+ sessionsDir: deps.sessionsDir
6734
+ }, id, kind, key),
6735
+ uploadEntityImage: (id, kind, key, png, name) => uploadSessionEntityImage({
6736
+ state: ctx.roleplayState,
6737
+ sessionsDir: deps.sessionsDir
6738
+ }, id, kind, key, png, name),
5049
6739
  list: () => listSessions(deps),
5050
6740
  start: (request) => startSession(deps, request),
5051
6741
  open: (id) => openSession(deps, id),