@dsh-agentic-roleplay/core 0.7.3 → 0.8.2

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 (58) hide show
  1. package/README.md +1 -1
  2. package/lib/{access-DtOxFKBK.js → access-CfQWbNZP.js} +4 -7
  3. package/lib/authoring-tools-BgmC2oqU.js +3691 -0
  4. package/lib/authoring.js +59 -24
  5. package/lib/{child-CyCViUKa.js → child-lYYeOwl2.js} +147 -46
  6. package/lib/client.js +931 -860
  7. package/lib/client.js.map +1 -1
  8. package/lib/compaction.js +8 -13
  9. package/lib/{doctor-chat-ByDfCMeo.js → doctor-chat-hL1a61hp.js} +2 -3
  10. package/lib/doctor.js +6 -8
  11. package/lib/{gallery-DmBZ2L5l.js → gallery-D1V4h8vh.js} +3 -4
  12. package/lib/{generator-BmdoTIL2.js → generator-CLPosooC.js} +3 -4
  13. package/lib/helper.js +2 -3
  14. package/lib/{hooks-C8eELrni.js → hooks-rQTTeOC4.js} +144 -88
  15. package/lib/images.js +4 -4
  16. package/lib/index.js +1024 -913
  17. package/lib/{library-lVNf9qG_.js → library-Dfu0dgRj.js} +32 -21
  18. package/lib/{lorebook-author-tools-BDOs4i5C.js → lorebook-author-tools-BAaAqZZm.js} +11 -14
  19. package/lib/lorebook-authoring.js +5 -6
  20. package/lib/{narration-DvFBqmqe.js → narration-CjB_KwwY.js} +58 -20
  21. package/lib/orchestration.js +138 -72
  22. package/lib/{pack-jail-DeTscGT2.js → pack-jail-CN-314ln.js} +94 -137
  23. package/lib/{packs-CY8ms8v_.js → packs-DIj5BEfq.js} +6 -10
  24. package/lib/{presenter-agent-cFR4sos3.js → presenter-agent-DR0KvLE0.js} +13 -19
  25. package/lib/{preset-n4-j6k4S.js → preset-CscHj1-Y.js} +5 -5
  26. package/lib/{preset-author-tools-2m4BLtws.js → preset-author-tools-CxluF8qc.js} +13 -15
  27. package/lib/preset-authoring.js +6 -7
  28. package/lib/presets-HB8kJTaE.js +3993 -0
  29. package/lib/{reflection-CJB5s0ip.js → reflection-Dg1xtOTW.js} +137 -148
  30. package/lib/{text-Cwl5s0j0.js → text-DyRN4nDP.js} +13 -7
  31. package/lib/{turn-guard-BvCs1VxB.js → turn-guard-g_hDn0jR.js} +6 -7
  32. package/package.json +29 -29
  33. package/prompts/en/import/casting.md +14 -0
  34. package/prompts/en/import/character.md +1 -0
  35. package/prompts/en/import/classifier.md +9 -0
  36. package/prompts/en/import/finish-draft.md +1 -0
  37. package/prompts/en/import/generator.md +8 -0
  38. package/prompts/en/import/notice-repair.md +4 -0
  39. package/prompts/en/import/repair-again.md +3 -0
  40. package/prompts/en/import/roster.md +1 -0
  41. package/prompts/en/import/variables.md +1 -0
  42. package/prompts/en/roleplay/game-master.md +3 -0
  43. package/prompts/en/roleplay/standing.md +1 -0
  44. package/prompts/en/world/author.md +1 -1
  45. package/prompts/zh/import/casting.md +14 -0
  46. package/prompts/zh/import/character.md +1 -0
  47. package/prompts/zh/import/classifier.md +9 -0
  48. package/prompts/zh/import/finish-draft.md +1 -0
  49. package/prompts/zh/import/generator.md +8 -0
  50. package/prompts/zh/import/notice-repair.md +4 -0
  51. package/prompts/zh/import/repair-again.md +3 -0
  52. package/prompts/zh/import/roster.md +1 -0
  53. package/prompts/zh/import/variables.md +1 -0
  54. package/prompts/zh/roleplay/game-master.md +3 -0
  55. package/prompts/zh/roleplay/standing.md +1 -0
  56. package/prompts/zh/world/author.md +1 -1
  57. package/lib/authoring-tools-CIsWbq0B.js +0 -6317
  58. package/lib/route-C6SHz9j2.js +0 -518
package/lib/index.js CHANGED
@@ -1,28 +1,28 @@
1
- import { a as chatSessionId, i as VARIABLE_VISIBILITIES, n as VARIABLE_KINDS, o as roleplaySessionOf, r as VARIABLE_SUBJECTS } from "./access-DtOxFKBK.js";
2
- import { $ as parseCalendarFile, B as populateLocations, Bt as deleteLorebook, Dt as IMPORT_FOLDER, E as vetUrl, Et as parseCharacterFile, F as populateClock, Ft as WORLD_FILE_NAME, G as routineProblems, Gt as loadLorebook, H as populateRoutines, Ht as entriesOf, I as populateDice, It as parseWorldFile, J as DICE_FILE_NAME, Jt as reserveLorebook, K as TRIGGERS_FILE_NAME, Kt as lorebookDirectory, L as populateFactions, Lt as parseWorldInfoEdit, M as knowsCharacter, Mt as parseChoices, N as populateCalendar, Ot as ImportNotFoundError, P as populateCharacters, Q as loadCalendar, R as populateItems, Rt as addLorebookEntries, Tt as CHARACTER_FILE_NAME, U as populateTriggers, Ut as isLorebookName, V as populateLore, Vt as deleteLorebookEntry, W as populateVariables, Wt as listLorebooks, X as parseDiceFile, Xt as writeLorebookEntry, Y as loadDice, Yt as updateLorebookInfo, Z as CALENDAR_FILE_NAME, _ as readOrigin, _n as DICE_READINGS, _t as parseVariablesFile, an as parseLoreEdit, cn as parseThingEdit, dn as isPng, fn as pictureOf, g as localChanges, gn as DICE_COMPARISONS, gt as loadVariables, h as isUnchanged, hn as LORE_SCOPES, ht as VARIABLES_FILE_NAME, in as parseFactionEdit, j as loadValidatedWorld, kt as ImportStore, ln as IMPORT_COMMAND, m as hashWorld, mn as LORE_KINDS, mt as withPlayer, nn as InvalidEditProblems, on as parsePlaceEdit, ot as CHARACTERS_DIR, p as describeChanges, pn as readCard, pt as partsOf, rn as parseCharacterEdit, rt as loadItems, sn as parseRelationEdit, st as loadCharacters, t as AuthoringTools, tn as subfolders, tt as loadLocations, u as markReady, un as ImportCardError, v as writeOrigin, vn as DICE_RESULTS, vt as variableProblems, w as guardedLookup, y as CatalogueError, yn as authoredWorldOf, z as populateKnowledge, zt as createLorebook } from "./authoring-tools-CIsWbq0B.js";
3
- import { a as lorebookImportMessage, c as readLorebook, d as lorebookOfChat, l as selectEntries, s as previewLorebook, t as LOREBOOK_UPLOAD, u as lorebookChatSessionId } from "./lorebook-author-tools-BDOs4i5C.js";
4
- import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-2m4BLtws.js";
5
- import { C as readWorldPrompt, S as listWorldPrompts, _ as savePresetFromWorld, d as isPresetName, f as listPresets, g as reservePreset, l as createPresetFromShipped, m as presetDirectory, p as loadPreset, s as PRESET_FILE, u as deletePreset, w as writeWorldPrompt, x as deleteWorldPrompt, y as updatePresetInfo } from "./route-C6SHz9j2.js";
6
- import { c as copyPreset, d as switchPreset, f as readTimeline, h as defaultBoundaries, i as reflectionStatus, l as presetStatus, m as pathTo, o as TimelineError, p as writeTimeline, u as recordPreset } from "./reflection-CJB5s0ip.js";
7
- import { a as liveSettings, c as writeSettings, d as parseSettings, i as InvalidSettingsError, l as DEFAULT_SETTINGS, o as readSettings, p as WORLD_RULES_KEY, s as useChildReasoning, u as SETTINGS_SPEC } from "./narration-DvFBqmqe.js";
8
- import { C as readNotes, G as formatIssue, H as plotReferenceProblems, K as errorMessage, M as plotProgressOf, N as populatePlots, O as zoneOf, Q as languageOf, S as notesOfSession, U as readDocument, V as parsePlotsFile, X as copyWorldPrompts, Y as PromptLibrary, _ as readRunDetail, at as InvalidWorldError, b as readWithdrawn, ct as SessionNotFoundError, g as readActivity, h as readDecisionStats, i as externalTools, it as InvalidStartError, j as PLOTS_METADATA_KEY, lt as WorldNotFoundError, m as readUsage, ot as ReflectionRefusedError, rt as AgentUnavailableError, st as SessionArchivedError, tt as shippedLanguages, w as observeAsPlayer, x as addToNote } from "./hooks-C8eELrni.js";
9
- import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-Cwl5s0j0.js";
10
- import { A as worldEntityImageFile, B as readWorldInfo, C as readWorldEditor, D as uploadWorldCharacterPortrait, E as replaceFile, F as loadWorldParts, G as findTargets, I as PRESET_FILE$1, J as revertUpdate, L as presetMessage, O as uploadWorldEntityImage, S as generateWorldEntityImage, T as removeWorldTrigger, U as languageOfDocuments, V as translateMessage, W as readWorldDocuments, X as updateStatus, Y as startUpdate, _ as editWorldPlots$1, a as deleteWorldPackFile, at as authoringTitle, b as entityFolder, c as createAuthoredEntity, ct as ensureAgentChat, dt as appendNarratedTurn, f as editWorldCharacter$1, ft as storeAuthoringOpening, g as editWorldPlace$1, h as editWorldNarrationVoice, it as AuthoringSessions, j as writeWorldTrigger, k as worldCharacterPortraitFile, l as deleteAuthoredEntity, lt as isStored, m as editWorldLore$1, n as packFileProblem, ot as AgentSessions, p as editWorldFaction$1, pt as storeDoctorOpening, st as agentServicesOf, t as MAX_PACK_TEXT, u as readAuthoredEntityDocument, ut as appendEmptyTurn, v as editWorldRelation$1, w as readWorldTrigger, x as generateWorldCharacterPortrait, y as editWorldThing$1, z as editWorldInfo } from "./pack-jail-DeTscGT2.js";
11
- import { d as sharedSamplingOf, i as childSamplingOf, u as parseSampling } from "./child-CyCViUKa.js";
12
- import { S as slug, d as sceneImagePath, s as inheritImages, t as addToLibrary, u as referenceImagePath, w as uniqueKey } from "./library-lVNf9qG_.js";
13
- import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-n4-j6k4S.js";
14
- import { t as doctorChatSessionId } from "./doctor-chat-ByDfCMeo.js";
15
- 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-CY8ms8v_.js";
16
- import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-BmdoTIL2.js";
17
- import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-DmBZ2L5l.js";
1
+ import { a as chatSessionId, i as VARIABLE_VISIBILITIES, n as VARIABLE_KINDS, o as roleplaySessionOf, r as VARIABLE_SUBJECTS } from "./access-CfQWbNZP.js";
2
+ import { $ as loadValidatedWorld, A as vetUrl, At as CHARACTERS_DIR, B as createLorebook, Bt as DICE_RESULTS, C as CatalogueError, Dt as CALENDAR_FILE_NAME, Et as parseDiceFile, Ft as isPng, G as listLorebooks, H as deleteLorebookEntry, I as WORLD_FILE_NAME, It as pictureOf, K as loadLorebook, L as parseWorldFile, Lt as readCard, Mt as subfolders, Nt as knownOutputCeiling, O as guardedLookup, Ot as loadCalendar, Pt as ImportCardError, Q as checkWorld, R as parseWorldInfoEdit, Rt as DICE_COMPARISONS, S as writeOrigin, Tt as loadDice, U as entriesOf, V as deleteLorebook, Vt as authoredWorldOf, W as isLorebookName, X as updateLorebookInfo, Y as reserveLorebook, Z as writeLorebookEntry, _ as describeChanges, at as populateFactions, b as localChanges, c as importPhase, ct as populateLocations, d as markReady, dt as populateTriggers, et as knowsCharacter, f as settleDraft, ft as populateVariables, it as populateDice, jt as loadCharacters, kt as parseCalendarFile, lt as populateLore, mt as TRIGGERS_FILE_NAME, nt as populateCharacters, ot as populateItems, p as structureImport, pt as routineProblems, q as lorebookDirectory, rt as populateClock, st as populateKnowledge, t as AuthoringTools, tt as populateCalendar, u as keepDraft, ut as populateRoutines, v as hashWorld, wt as DICE_FILE_NAME, x as readOrigin, xt as loadItems, y as isUnchanged, yt as loadLocations, z as addLorebookEntries, zt as DICE_READINGS } from "./authoring-tools-BgmC2oqU.js";
3
+ import { a as lorebookImportMessage, c as readLorebook, d as lorebookOfChat, l as selectEntries, s as previewLorebook, t as LOREBOOK_UPLOAD, u as lorebookChatSessionId } from "./lorebook-author-tools-BAaAqZZm.js";
4
+ import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-CxluF8qc.js";
5
+ import { a as liveSettings, c as writeSettings, d as DEFAULT_SETTINGS, f as SETTINGS_SPEC, h as WORLD_RULES_KEY, i as InvalidSettingsError, l as atomicWrite, o as readSettings, p as parseSettings, s as useChildReasoning } from "./narration-CjB_KwwY.js";
6
+ import { A as worldEntityImageFile, B as readWorldInfo, C as readWorldEditor, D as uploadWorldCharacterPortrait, E as replaceFile, F as loadWorldParts, G as findTargets, I as PRESET_FILE, J as revertUpdate, L as presetMessage, O as uploadWorldEntityImage, S as generateWorldEntityImage, T as removeWorldTrigger, U as languageOfDocuments, V as translateMessage, W as readWorldDocuments, X as updateStatus, Y as startUpdate, _ as editWorldPlots$1, a as deleteWorldPackFile, at as authoringTitle, b as entityFolder, c as createAuthoredEntity, ct as agentServicesOf, dt as appendNarratedTurn, f as editWorldCharacter$1, g as editWorldPlace$1, h as editWorldNarrationVoice, it as AuthoringSessions, j as writeWorldTrigger, k as worldCharacterPortraitFile, l as deleteAuthoredEntity, lt as DOCTOR_OPENING_SOURCE, m as editWorldLore$1, n as packFileProblem, ot as ensureAuthoringChat, p as editWorldFaction$1, st as AgentSessions, t as MAX_PACK_TEXT, u as readAuthoredEntityDocument, ut as appendEmptyTurn, v as editWorldRelation$1, w as readWorldTrigger, x as generateWorldCharacterPortrait, y as editWorldThing$1, z as editWorldInfo } from "./pack-jail-CN-314ln.js";
7
+ import { d as sharedSamplingOf, i as childSamplingOf, u as parseSampling } from "./child-lYYeOwl2.js";
8
+ import { $ as copyWorldPrompts, C as readNotes, H as plotReferenceProblems, J as formatIssue, K as readDocument, M as plotProgressOf, N as populatePlots, O as zoneOf, Q as PromptLibrary, S as notesOfSession, U as COMMANDS_KEY, V as parsePlotsFile, Y as errorMessage, _ as readRunDetail, b as readWithdrawn, ct as InvalidStartError, dt as SessionArchivedError, ft as SessionNotFoundError, g as readActivity, h as readDecisionStats, i as externalTools, it as shippedLanguages, j as PLOTS_METADATA_KEY, lt as InvalidWorldError, m as readUsage, pt as WorldNotFoundError, st as AgentUnavailableError, tt as languageOf, ut as ReflectionRefusedError, w as observeAsPlayer, x as addToNote } from "./hooks-rQTTeOC4.js";
9
+ import { $ as ImportNotFoundError, At as parsePlaceEdit, Ct as parseCharacterFile, Dt as parseCharacterEdit, Et as InvalidEditProblems, G as listWorldPrompts, K as readWorldPrompt, Mt as parseThingEdit, Nt as LORE_KINDS, Ot as parseFactionEdit, Pt as LORE_SCOPES, Q as IMPORT_FOLDER, St as CHARACTER_FILE_NAME, W as deleteWorldPrompt, X as partsOf, Z as withPlayer, a as isPresetName, c as presetDirectory, ct as VARIABLES_FILE_NAME, d as savePresetFromWorld, dt as variableProblems, et as ImportStore, i as deletePreset, jt as parseRelationEdit, kt as parseLoreEdit, lt as loadVariables, o as listPresets, ot as IMPORT_COMMAND, p as updatePresetInfo, q as writeWorldPrompt, r as createPresetFromShipped, rt as parseChoices, s as loadPreset, t as PRESET_FILE$1, u as reservePreset, ut as parseVariablesFile } from "./presets-HB8kJTaE.js";
10
+ import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-DyRN4nDP.js";
11
+ import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-CscHj1-Y.js";
12
+ import { S as slug, d as sceneImagePath, s as inheritImages, t as addToLibrary, u as referenceImagePath, w as uniqueKey } from "./library-Dfu0dgRj.js";
13
+ import { t as doctorChatSessionId } from "./doctor-chat-hL1a61hp.js";
14
+ import { c as readTimeline, d as copyPreset, f as presetStatus, h as defaultBoundaries, i as reflectionStatus, l as writeTimeline, m as switchPreset, o as TimelineError, p as recordPreset, u as pathTo } from "./reflection-Dg1xtOTW.js";
15
+ 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-DIj5BEfq.js";
16
+ import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-CLPosooC.js";
17
+ import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-D1V4h8vh.js";
18
18
  import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
19
19
  import { cpSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
20
20
  import { createHash, randomBytes, randomUUID } from "node:crypto";
21
+ import { copyFile, cp, lstat, mkdir, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
21
22
  import { Session, SessionId } from "@deepseek-ai/dsh-session";
22
23
  import { inflateRawSync } from "node:zlib";
23
24
  import { fileURLToPath } from "node:url";
24
25
  import { Service } from "@deepseek-ai/cordis";
25
- import { chmod, copyFile, cp, lstat, mkdir, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
26
26
  import { addLocalDays, createSessionStore, describeInstant, describeValue, holidaysOn, isSessionId, itemKey, lintWorld, locationKey, parseInstant, readCalendar, seasonOf, sessionDatabase, sessionFolder, shownVariables, systemTimeZone } from "@dsh-agentic-roleplay/state";
27
27
  import { request } from "node:http";
28
28
  import { request as request$1 } from "node:https";
@@ -30,7 +30,7 @@ import { pipeline } from "node:stream/promises";
30
30
  import { homedir } from "node:os";
31
31
  import { spawn } from "node:child_process";
32
32
  import z from "@deepseek-ai/schemastery";
33
- //#region src/host/worlds/authoring-language.ts
33
+ // src/host/worlds/authoring-language.ts
34
34
  /**
35
35
  * The language the person was using when they last worked on a world with the authoring assistant. The assistant's instructions
36
36
  * follow it. Kept beside the worlds, not in them, so that a world folder holds only the world.
@@ -62,8 +62,7 @@ var AuthoringLanguages = class extends Service {
62
62
  return join(this.worldsDirectory(), ".authoring", `${encodeURIComponent(worldId)}.json`);
63
63
  }
64
64
  };
65
- //#endregion
66
- //#region src/host/import/service.ts
65
+ // src/host/import/service.ts
67
66
  /** What an import is configured to do, for the parts of the plugin that run in other scopes (the authoring chat's tools). */
68
67
  var RoleplayImport = class extends Service {
69
68
  read;
@@ -76,8 +75,17 @@ var RoleplayImport = class extends Service {
76
75
  return this.read();
77
76
  }
78
77
  };
79
- //#endregion
80
- //#region src/host/worlds/create-world.ts
78
+ // src/host/worlds/draft.ts
79
+ /** Whether the world is an import that was written but would not start yet: its import state (kept in the world's `.import` folder) says it is being repaired. */
80
+ async function isDraftWorld(directory) {
81
+ try {
82
+ return JSON.parse(await readFile(join(directory, ".import", "state.json"), "utf8")).phase === "repair";
83
+ } catch (error) {
84
+ if (error.code === "ENOENT") return false;
85
+ throw error;
86
+ }
87
+ }
88
+ // src/host/worlds/create-world.ts
81
89
  const FOLDER = /^[\p{L}\p{N}][\p{L}\p{N}._ -]{0,99}$/u;
82
90
  var WorldFolderExistsError = class extends Error {};
83
91
  /** Create the smallest valid authored world, exclusively, then make the catalogue see it. */
@@ -118,8 +126,7 @@ async function createWorld(catalog, input) {
118
126
  if (created === void 0) throw new Error(`created world "${name}" but it was not found when the catalogue refreshed`);
119
127
  return created;
120
128
  }
121
- //#endregion
122
- //#region src/host/import/start-import.ts
129
+ // src/host/import/start-import.ts
123
130
  const FOLDER_CHARS = /[^\p{L}\p{N}._ -]+/gu;
124
131
  /** A name that can be the folder of a world: letters, digits and a few marks, trimmed, not ending in a dot or space. */
125
132
  function folderNameOf(name) {
@@ -135,10 +142,31 @@ function importMessage(language) {
135
142
  return `${IMPORT_COMMAND} ${IMPORT_FOLDER}/card.json ${tr("Import this card into this newly created world.")}`;
136
143
  }
137
144
  /**
138
- * Turns an uploaded card into a new empty world with its authoring chat, and has the chat start importing it on the person's behalf.
139
- * @throws {InvalidEditProblems} when the choices cannot be used. @throws {ImportNotFoundError} when the upload is gone.
145
+ * Has the chat of a world whose import stopped before it was done carry on from the step it reached (the import hooks tell the chat which step that is). An import is lost
146
+ * to a server restart, a refused finish or a chat that ended early; the card and what was extracted stay in the world's import folder.
147
+ * @throws {WorldNotFoundError} when the world is gone. @throws {InvalidEditProblems} when no import is waiting in it.
140
148
  */
141
- async function startImport(deps, id, choices, language) {
149
+ async function resumeImport(deps, worldId, language) {
150
+ const record = await deps.worlds.find(worldId);
151
+ if (record === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
152
+ const phase = await importPhase(record.directory);
153
+ if (phase === void 0 || phase === "done") throw new InvalidEditProblems(["no import is waiting in this world"]);
154
+ const chatSessionId = await deps.authoring.ensure(record.summary.id, record.summary.name, authoringTitle(record.summary.name, language), language);
155
+ let failure;
156
+ try {
157
+ await deps.authoring.send(chatSessionId, importMessage(language));
158
+ } catch (error) {
159
+ failure = error instanceof Error ? error.message : String(error);
160
+ }
161
+ return {
162
+ worldId: record.summary.id,
163
+ chatSessionId,
164
+ started: failure === void 0,
165
+ ...failure === void 0 ? {} : { failure }
166
+ };
167
+ }
168
+ /** Makes the new world a card is imported into, in a folder named after the world, and moves the staged upload into it. */
169
+ async function createImportedWorld(deps, id, choices) {
142
170
  await deps.store.choose(id, choices);
143
171
  let world;
144
172
  const base = folderNameOf(choices.name);
@@ -157,6 +185,17 @@ async function startImport(deps, id, choices, language) {
157
185
  if (record === void 0) throw new WorldNotFoundError(`the world "${world.name}" was made but cannot be found`);
158
186
  await deps.store.adopt(id, record.directory);
159
187
  await markReady(record.directory);
188
+ return {
189
+ world,
190
+ directory: record.directory
191
+ };
192
+ }
193
+ /**
194
+ * Turns an uploaded card into a new empty world with its authoring chat, and has the chat start importing it on the person's behalf.
195
+ * @throws {InvalidEditProblems} when the choices cannot be used. @throws {ImportNotFoundError} when the upload is gone.
196
+ */
197
+ async function startImport(deps, id, choices, language) {
198
+ const { world } = await createImportedWorld(deps, id, choices);
160
199
  const chatSessionId = await deps.authoring.ensure(world.id, world.name, authoringTitle(world.name, language), language);
161
200
  let failure;
162
201
  try {
@@ -171,8 +210,69 @@ async function startImport(deps, id, choices, language) {
171
210
  ...failure === void 0 ? {} : { failure }
172
211
  };
173
212
  }
174
- //#endregion
175
- //#region src/host/translate/service.ts
213
+ /**
214
+ * Imports an uploaded card into a new world without a model: its own character, its lorebook and its instructions are carried over as they are written, and nothing is read for places, factions or other people.
215
+ * @throws {InvalidEditProblems} when the choices cannot be used. @throws {ImportNotFoundError} when the upload is gone.
216
+ */
217
+ async function importWithoutModel(deps, id, choices, language) {
218
+ const { world, directory } = await createImportedWorld(deps, id, choices);
219
+ const done = await structureImport(directory, language);
220
+ return {
221
+ worldId: world.id,
222
+ report: done.report,
223
+ draft: done.draft !== void 0
224
+ };
225
+ }
226
+ // src/host/import/draft.ts
227
+ async function draftOf(worlds, worldId) {
228
+ const record = await worlds.find(worldId);
229
+ if (record === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
230
+ return record;
231
+ }
232
+ async function draftStatus(worlds, worldId) {
233
+ const record = await draftOf(worlds, worldId);
234
+ if (!await isDraftWorld(record.directory)) return { draft: false };
235
+ if (await settleDraft(record.directory)) {
236
+ await worlds.list({ refresh: true });
237
+ return { draft: false };
238
+ }
239
+ return {
240
+ draft: true,
241
+ check: await checkWorld({
242
+ directory: record.directory,
243
+ summary: record.summary,
244
+ ...record.variables === void 0 ? {} : { variables: record.variables }
245
+ })
246
+ };
247
+ }
248
+ /**
249
+ * What the person decides about a draft: have the assistant try again (with the card at hand), keep it as it is (an ordinary world that cannot be played until it is mended),
250
+ * or discard it (the folder goes to the root's trash, where it can still be found).
251
+ * @throws {InvalidEditProblems} when the world is not a draft.
252
+ */
253
+ async function actOnDraft(deps, worldId, action, language) {
254
+ const record = await draftOf(deps.worlds, worldId);
255
+ if (!await isDraftWorld(record.directory)) throw new InvalidEditProblems(["this world is not a draft"]);
256
+ if (action === "ask") return {
257
+ action,
258
+ started: await resumeImport(deps, worldId, language)
259
+ };
260
+ if (action === "keep") {
261
+ await keepDraft(record.directory);
262
+ await deps.worlds.list({ refresh: true });
263
+ return { action };
264
+ }
265
+ const trash = join(deps.root(), ".trash", "worlds");
266
+ await mkdir(trash, { recursive: true });
267
+ const destination = join(trash, `${basename(record.directory)}-${Date.now()}`);
268
+ await rename(record.directory, destination);
269
+ await deps.worlds.list({ refresh: true });
270
+ return {
271
+ action,
272
+ keptIn: relative(deps.root(), destination)
273
+ };
274
+ }
275
+ // src/host/translate/service.ts
176
276
  async function recordOf(worlds, id) {
177
277
  const record = await worlds.find(id);
178
278
  if (record === void 0) throw new WorldNotFoundError(`there is no world with id "${id}"`);
@@ -204,8 +304,7 @@ async function startTranslation(deps, id, to, title, language) {
204
304
  };
205
305
  }
206
306
  }
207
- //#endregion
208
- //#region src/host/presets/verbatim.ts
307
+ // src/host/presets/verbatim.ts
209
308
  /**
210
309
  * The chosen prompts of a SillyTavern preset as they are, with no model between: their texts, in the order the preset sends them, become one writing guidance (the narration style).
211
310
  * The preset's own macros are played and its names for the characters are replaced as for any import; only what a prompt file cannot hold is changed, so that `${` and `{{` in the text
@@ -221,8 +320,7 @@ function verbatimStyle(file, fileName) {
221
320
  text
222
321
  };
223
322
  }
224
- //#endregion
225
- //#region src/host/import/upload-preset.ts
323
+ // src/host/import/upload-preset.ts
226
324
  /**
227
325
  * Keeps an uploaded narration preset in the world's import folder and has the world's authoring chat apply it, which asks the person before it changes a prompt.
228
326
  * @throws {ImportCardError} when the file is not a preset. @throws {WorldNotFoundError} when the world does not exist.
@@ -232,7 +330,7 @@ async function uploadPreset(deps, worldId, file, name, language) {
232
330
  if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
233
331
  const preset = readPreset(file, name);
234
332
  await mkdir(join(world.directory, IMPORT_FOLDER), { recursive: true });
235
- await writeFile(join(world.directory, IMPORT_FOLDER, PRESET_FILE$1), file);
333
+ await writeFile(join(world.directory, IMPORT_FOLDER, PRESET_FILE), file);
236
334
  const chatSessionId = await deps.authoring.ensure(world.summary.id, world.summary.name, authoringTitle(world.summary.name, language), language);
237
335
  let failure;
238
336
  try {
@@ -274,8 +372,7 @@ async function applyPresetVerbatim(deps, worldId, file, name) {
274
372
  replaced
275
373
  };
276
374
  }
277
- //#endregion
278
- //#region src/host/import/staging.ts
375
+ // src/host/import/staging.ts
279
376
  const KEEP_MS = 36e5;
280
377
  const MAX_STAGED = 12;
281
378
  /**
@@ -340,10 +437,12 @@ function parseSelectionChoice(body) {
340
437
  sampling: sampling !== false
341
438
  };
342
439
  }
343
- //#endregion
344
- //#region src/host/agent/preset-authoring-sessions.ts
345
- const PRESET_AUTHORING_PROJECT_TITLE = "Preset Authoring";
346
- const PRESET_AUTHORING_PRESET = "preset-authoring";
440
+ const KIND$2 = {
441
+ folder: "presets",
442
+ projectTitle: "Preset Authoring",
443
+ agentPreset: "preset-authoring",
444
+ welcome: "preset/welcome"
445
+ };
347
446
  /** Creates or reopens the dedicated authoring chat of a library preset, and speaks in it for the person when asked to. */
348
447
  var PresetAuthoringSessions = class {
349
448
  services;
@@ -357,28 +456,14 @@ var PresetAuthoringSessions = class {
357
456
  this.languages = languages;
358
457
  }
359
458
  async ensure(name, title, language) {
360
- this.languages.set(`preset:${name}`, language);
361
- const services = this.services();
362
- const projectPath = join(this.roleplayRoot(), "presets");
363
- const project = await services.registry.create(projectPath, PRESET_AUTHORING_PROJECT_TITLE);
364
- const sessionId = presetChatSessionId(name);
365
- const stored = !project.sessionIds.includes(sessionId) && await isStored(services.persistence, sessionId);
366
- if (!project.sessionIds.includes(sessionId) && !stored) {
367
- if (services.persistence === void 0) throw new AgentUnavailableError("this DSH profile cannot store the opening of an authoring chat");
368
- await storeAuthoringOpening(services.persistence, {
369
- id: sessionId,
370
- cwd: project.path,
371
- agentPreset: PRESET_AUTHORING_PRESET
372
- }, this.prompts.text("preset/welcome", this.languages.get(`preset:${name}`), { preset: title }));
373
- }
374
- return await ensureAgentChat(services, {
375
- projectPath,
376
- projectTitle: PRESET_AUTHORING_PROJECT_TITLE,
377
- sessionId,
378
- agentPreset: PRESET_AUTHORING_PRESET,
459
+ return await ensureAuthoringChat(this.services(), this.roleplayRoot(), this.prompts, this.languages, KIND$2, {
460
+ chatId: presetChatSessionId(name),
461
+ languageKey: `preset:${name}`,
379
462
  title: `Preset ${title}`,
463
+ language,
464
+ welcome: { preset: title },
380
465
  renameExisting: true
381
- }, project);
466
+ });
382
467
  }
383
468
  async send(sessionId, text) {
384
469
  await this.services().controller.prompt({
@@ -392,10 +477,12 @@ var PresetAuthoringSessions = class {
392
477
  }, new AbortController().signal);
393
478
  }
394
479
  };
395
- //#endregion
396
- //#region src/host/agent/lorebook-authoring-sessions.ts
397
- const LOREBOOK_AUTHORING_PROJECT_TITLE = "Lorebook Authoring";
398
- const LOREBOOK_AUTHORING_PRESET = "lorebook-authoring";
480
+ const KIND$1 = {
481
+ folder: "lorebooks",
482
+ projectTitle: "Lorebook Authoring",
483
+ agentPreset: "lorebook-authoring",
484
+ welcome: "lorebook/welcome"
485
+ };
399
486
  /** Creates or reopens the dedicated authoring chat of a library lorebook, and speaks in it for the person when asked to. */
400
487
  var LorebookAuthoringSessions = class {
401
488
  services;
@@ -409,28 +496,14 @@ var LorebookAuthoringSessions = class {
409
496
  this.languages = languages;
410
497
  }
411
498
  async ensure(name, title, language) {
412
- this.languages.set(`lorebook:${name}`, language);
413
- const services = this.services();
414
- const projectPath = join(this.roleplayRoot(), "lorebooks");
415
- const project = await services.registry.create(projectPath, LOREBOOK_AUTHORING_PROJECT_TITLE);
416
- const sessionId = lorebookChatSessionId(name);
417
- const stored = !project.sessionIds.includes(sessionId) && await isStored(services.persistence, sessionId);
418
- if (!project.sessionIds.includes(sessionId) && !stored) {
419
- if (services.persistence === void 0) throw new AgentUnavailableError("this DSH profile cannot store the opening of an authoring chat");
420
- await storeAuthoringOpening(services.persistence, {
421
- id: sessionId,
422
- cwd: project.path,
423
- agentPreset: LOREBOOK_AUTHORING_PRESET
424
- }, this.prompts.text("lorebook/welcome", this.languages.get(`lorebook:${name}`), { lorebook: title }));
425
- }
426
- return await ensureAgentChat(services, {
427
- projectPath,
428
- projectTitle: LOREBOOK_AUTHORING_PROJECT_TITLE,
429
- sessionId,
430
- agentPreset: LOREBOOK_AUTHORING_PRESET,
499
+ return await ensureAuthoringChat(this.services(), this.roleplayRoot(), this.prompts, this.languages, KIND$1, {
500
+ chatId: lorebookChatSessionId(name),
501
+ languageKey: `lorebook:${name}`,
431
502
  title: `Lorebook ${title}`,
503
+ language,
504
+ welcome: { lorebook: title },
432
505
  renameExisting: true
433
- }, project);
506
+ });
434
507
  }
435
508
  async send(sessionId, text) {
436
509
  await this.services().controller.prompt({
@@ -444,8 +517,7 @@ var LorebookAuthoringSessions = class {
444
517
  }, new AbortController().signal);
445
518
  }
446
519
  };
447
- //#endregion
448
- //#region src/host/lorebooks/apply.ts
520
+ // src/host/lorebooks/apply.ts
449
521
  /** Which lorebooks a story was started with: kept in the story's own metadata, because the library may change afterwards. */
450
522
  const LOREBOOKS_KEY = "roleplay.lorebooks";
451
523
  /** The id an entry has in a story, so that books and the world's own lore never clash. */
@@ -493,8 +565,7 @@ async function lorebookLore(root, names, chosen, knows, taken) {
493
565
  }
494
566
  return result;
495
567
  }
496
- //#endregion
497
- //#region src/host/lorebooks/story.ts
568
+ // src/host/lorebooks/story.ts
498
569
  /** The lorebooks a story holds now. */
499
570
  function lorebooksOf(session) {
500
571
  return session.metadata.getValue("roleplay.lorebooks") ?? [];
@@ -550,8 +621,7 @@ function removeLorebook(session, name) {
550
621
  });
551
622
  return leaving.length;
552
623
  }
553
- //#endregion
554
- //#region src/host/lorebooks/verbatim.ts
624
+ // src/host/lorebooks/verbatim.ts
555
625
  const MAX_TITLE$1 = 100;
556
626
  /**
557
627
  * The entries of a SillyTavern lorebook as they are, with no model between: each keeps its text word for word (an entry longer than a lore entry may be is cut at a paragraph, in order),
@@ -581,8 +651,7 @@ function verbatimEntries(file, fileName, knownBy) {
581
651
  entries
582
652
  };
583
653
  }
584
- //#endregion
585
- //#region src/host/lorebooks/service.ts
654
+ // src/host/lorebooks/service.ts
586
655
  /** The story's lore cannot change right now. */
587
656
  var LorebookBusyError = class extends Error {};
588
657
  /** The lorebook library. Refusals are plain `Error`s with the reason. */
@@ -727,10 +796,13 @@ var Lorebooks = class {
727
796
  };
728
797
  }
729
798
  };
730
- //#endregion
731
- //#region src/host/agent/doctor-sessions.ts
732
- const DOCTOR_PROJECT_TITLE = "Session Doctor";
733
- const DOCTOR_AGENT_PRESET = "session-doctor";
799
+ const KIND = {
800
+ folder: "sessions",
801
+ projectTitle: "Session Doctor",
802
+ agentPreset: "session-doctor",
803
+ welcome: "doctor/welcome",
804
+ openingSource: DOCTOR_OPENING_SOURCE
805
+ };
734
806
  /** Creates or reopens the chat in which a bystander reads one session's records and proposes fixes. */
735
807
  var DoctorSessions = class {
736
808
  services;
@@ -742,29 +814,16 @@ var DoctorSessions = class {
742
814
  this.prompts = prompts;
743
815
  }
744
816
  async ensure(session, title, language) {
745
- const services = this.services();
746
- const projectPath = join(this.roleplayRoot(), "sessions");
747
- const project = await services.registry.create(projectPath, DOCTOR_PROJECT_TITLE);
748
- const sessionId = doctorChatSessionId(session.id);
749
- if (!project.sessionIds.includes(sessionId) && !await isStored(services.persistence, sessionId)) {
750
- if (services.persistence === void 0) throw new AgentUnavailableError("this DSH profile cannot store the opening of a session doctor chat");
751
- await storeDoctorOpening(services.persistence, {
752
- id: sessionId,
753
- cwd: project.path,
754
- agentPreset: DOCTOR_AGENT_PRESET
755
- }, this.prompts.text("doctor/welcome", language, { session: session.name }));
756
- }
757
- return await ensureAgentChat(services, {
758
- projectPath,
759
- projectTitle: DOCTOR_PROJECT_TITLE,
760
- sessionId,
761
- agentPreset: DOCTOR_AGENT_PRESET,
762
- title
763
- }, project);
817
+ return await ensureAuthoringChat(this.services(), this.roleplayRoot(), this.prompts, void 0, KIND, {
818
+ chatId: doctorChatSessionId(session.id),
819
+ title,
820
+ language,
821
+ welcome: { session: session.name },
822
+ renameExisting: false
823
+ });
764
824
  }
765
825
  };
766
- //#endregion
767
- //#region src/host/orchestration/service.ts
826
+ // src/host/orchestration/service.ts
768
827
  /**
769
828
  * The extension points of a roleplay turn. Another plugin changes how the turn
770
829
  * behaves by replacing a boundary; the change applies from the next call on.
@@ -807,439 +866,45 @@ var RoleplayOrchestration = class extends Service {
807
866
  };
808
867
  }
809
868
  };
810
- //#endregion
811
- //#region src/shared/world-dice.ts
812
- const isObject$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
813
- const CHECK_FIELDS = [
814
- "key",
815
- "name",
816
- "use",
817
- "dice",
818
- "reading",
819
- "hit",
820
- "compare",
821
- "modifier",
822
- "bands"
823
- ];
824
- const BAND_FIELDS = [
825
- "min",
826
- "max",
827
- "label",
828
- "result",
829
- "critical"
830
- ];
831
- /** Reads a body that came from the browser: the shape of every field is checked here, and what the checks mean when the world is validated. */
832
- function parseDiceEdit(value) {
833
- const problems = [];
834
- if (!isObject$1(value) || !Array.isArray(value["checks"])) throw new InvalidEditProblems(["the dice must be { checks: [...] }"]);
835
- const checks = value["checks"].map((entry, index) => {
836
- const at = `checks[${index}]`;
837
- const empty = {
838
- key: "",
839
- name: "",
840
- use: "",
841
- dice: "",
842
- bands: []
843
- };
844
- if (!isObject$1(entry)) {
845
- problems.push(`${at} must be an object`);
846
- return empty;
847
- }
848
- for (const key of Object.keys(entry)) if (!CHECK_FIELDS.includes(key)) problems.push(`${at}.${key} is not a field of a check`);
849
- for (const key of [
850
- "key",
851
- "name",
852
- "use",
853
- "dice"
854
- ]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
855
- if (entry["reading"] !== void 0 && !DICE_READINGS.includes(entry["reading"])) problems.push(`${at}.reading must be one of: ${DICE_READINGS.join(", ")}`);
856
- if (entry["compare"] !== void 0 && !DICE_COMPARISONS.includes(entry["compare"])) problems.push(`${at}.compare must be one of: ${DICE_COMPARISONS.join(", ")}`);
857
- if (entry["hit"] !== void 0 && (typeof entry["hit"] !== "number" || !Number.isInteger(entry["hit"]))) problems.push(`${at}.hit must be a whole number`);
858
- if (entry["modifier"] !== void 0 && typeof entry["modifier"] !== "string") problems.push(`${at}.modifier must be text`);
859
- const bands = Array.isArray(entry["bands"]) ? entry["bands"] : void 0;
860
- if (bands === void 0) problems.push(`${at}.bands must be a list`);
861
- const text = (field) => typeof field === "string" ? field.trim() : "";
862
- const hit = entry["hit"];
863
- return {
864
- key: text(entry["key"]),
865
- name: text(entry["name"]),
866
- use: text(entry["use"]),
867
- dice: text(entry["dice"]),
868
- ...entry["reading"] === void 0 ? {} : { reading: entry["reading"] },
869
- ...typeof hit === "number" ? { hit } : {},
870
- ...entry["compare"] === void 0 ? {} : { compare: entry["compare"] },
871
- ...text(entry["modifier"]) === "" ? {} : { modifier: text(entry["modifier"]) },
872
- bands: (bands ?? []).map((band, bandIndex) => {
873
- const where = `${at}.bands[${bandIndex}]`;
874
- if (!isObject$1(band)) {
875
- problems.push(`${where} must be an object`);
876
- return {
877
- label: "",
878
- result: "failed"
879
- };
880
- }
881
- for (const key of Object.keys(band)) if (!BAND_FIELDS.includes(key)) problems.push(`${where}.${key} is not a field of a band`);
882
- for (const key of ["min", "max"]) if (band[key] !== void 0 && (typeof band[key] !== "number" || !Number.isFinite(band[key]))) problems.push(`${where}.${key} must be a number`);
883
- if (typeof band["label"] !== "string") problems.push(`${where}.label must be text`);
884
- if (!DICE_RESULTS.includes(band["result"])) problems.push(`${where}.result must be one of: ${DICE_RESULTS.join(", ")}`);
885
- const min = band["min"];
886
- const max = band["max"];
887
- return {
888
- label: text(band["label"]),
889
- result: band["result"],
890
- ...typeof min === "number" ? { min } : {},
891
- ...typeof max === "number" ? { max } : {},
892
- ...band["critical"] === true ? { critical: true } : {}
893
- };
894
- })
895
- };
896
- });
897
- if (problems.length > 0) throw new InvalidEditProblems(problems);
898
- return { checks };
869
+ // src/host/http/respond.ts
870
+ function sendJson(res, status, payload) {
871
+ res.statusCode = status;
872
+ res.setHeader("content-type", "application/json; charset=utf-8");
873
+ res.setHeader("cache-control", "no-store");
874
+ res.end(JSON.stringify(payload));
899
875
  }
900
- //#endregion
901
- //#region src/shared/world-daily.ts
902
- const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
903
- const ROUTINE_FIELDS = [
904
- "days",
905
- "on",
906
- "from",
907
- "to",
908
- "activity",
909
- "location",
910
- "feature",
911
- "position",
912
- "interruptible"
913
- ];
914
- /**
915
- * The windows of a day as the browser sends them.
916
- * @throws {InvalidEditProblems} naming every field that has the wrong shape; whether the times and places are acceptable is checked when the file is read back.
917
- */
918
- function parseRoutineEdit(value) {
919
- const problems = [];
920
- const list = isObject(value) && Array.isArray(value["windows"]) ? value["windows"] : void 0;
921
- if (list === void 0) throw new InvalidEditProblems(["the day must be { windows: [...] }"]);
922
- const windows = list.map((entry, index) => {
923
- const at = `windows[${index}]`;
924
- if (!isObject(entry)) {
925
- problems.push(`${at} must be an object`);
926
- return {
927
- days: [],
928
- from: "",
929
- to: "",
930
- activity: "",
931
- interruptible: true
932
- };
933
- }
934
- for (const key of Object.keys(entry)) if (!ROUTINE_FIELDS.includes(key)) problems.push(`${at}.${key} is not a field of a window`);
935
- for (const key of [
936
- "from",
937
- "to",
938
- "activity"
939
- ]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
940
- for (const key of [
941
- "location",
942
- "feature",
943
- "position"
944
- ]) if (entry[key] !== void 0 && typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
945
- if (entry["days"] !== void 0 && !(Array.isArray(entry["days"]) && entry["days"].every((day) => typeof day === "string"))) problems.push(`${at}.days must be a list of days`);
946
- if (entry["interruptible"] !== void 0 && typeof entry["interruptible"] !== "boolean") problems.push(`${at}.interruptible must be true or false`);
947
- const text = (key) => typeof entry[key] === "string" ? entry[key].trim() : "";
876
+ function sendError(res, status, message) {
877
+ sendJson(res, status, { message });
878
+ }
879
+ /** A failure with the status the client should see. */
880
+ var HttpError = class extends Error {
881
+ status;
882
+ constructor(status, message) {
883
+ super(message);
884
+ this.status = status;
885
+ }
886
+ };
887
+ // src/host/presets/service.ts
888
+ /** The story's prompts cannot change right now. */
889
+ var PresetBusyError = class extends Error {};
890
+ /** The preset library and the presets of stories. Refusals are plain `Error`s with the reason; unknown stories and worlds are not-found errors. */
891
+ var Presets = class {
892
+ deps;
893
+ constructor(deps) {
894
+ this.deps = deps;
895
+ }
896
+ get maxUploadBytes() {
897
+ return this.deps.maxUploadBytes;
898
+ }
899
+ list() {
900
+ return listPresets(this.deps.root()).map((entry) => entry.summary);
901
+ }
902
+ /** A preset with the text of each prompt it carries, keyed `<language>/<id>`. */
903
+ read(name) {
904
+ const loaded = loadPreset(this.deps.root(), name);
948
905
  return {
949
- days: Array.isArray(entry["days"]) ? entry["days"].map((day) => day.trim().toLowerCase()).filter((day) => day !== "") : [],
950
- ...Array.isArray(entry["on"]) && entry["on"].length > 0 ? { on: entry["on"].map((day) => String(day).trim()).filter((day) => day !== "") } : {},
951
- from: text("from"),
952
- to: text("to"),
953
- activity: text("activity"),
954
- ...text("location") === "" ? {} : { location: text("location") },
955
- ...text("feature") === "" ? {} : { feature: text("feature") },
956
- ...text("position") === "" ? {} : { position: text("position") },
957
- interruptible: entry["interruptible"] !== false
958
- };
959
- });
960
- if (problems.length > 0) throw new InvalidEditProblems(problems);
961
- return windows;
962
- }
963
- const VARIABLE_FIELDS = [
964
- "key",
965
- "name",
966
- "kind",
967
- "subject",
968
- "visibility",
969
- "description",
970
- "min",
971
- "max",
972
- "integer",
973
- "baseline",
974
- "always",
975
- "default",
976
- "only",
977
- "options",
978
- "bands"
979
- ];
980
- /**
981
- * The declarations as the browser sends them, with empty fields left out. Whether they are acceptable together is checked against the world's files.
982
- * @throws {InvalidEditProblems} naming every field that has the wrong shape.
983
- */
984
- function parseVariablesEdit(value) {
985
- const problems = [];
986
- const list = isObject(value) && Array.isArray(value["variables"]) ? value["variables"] : void 0;
987
- if (list === void 0) throw new InvalidEditProblems(["the variables must be { variables: [...] }"]);
988
- const declarations = list.flatMap((entry, index) => {
989
- const at = `variables[${index}]`;
990
- if (!isObject(entry)) {
991
- problems.push(`${at} must be an object`);
992
- return [];
993
- }
994
- for (const key of Object.keys(entry)) if (!VARIABLE_FIELDS.includes(key)) problems.push(`${at}.${key} is not a field of a variable`);
995
- const text = (key) => typeof entry[key] === "string" ? entry[key].trim() : "";
996
- const number = (key) => {
997
- if (entry[key] === void 0 || entry[key] === null || entry[key] === "") return void 0;
998
- if (typeof entry[key] !== "number" || !Number.isFinite(entry[key])) {
999
- problems.push(`${at}.${key} must be a number`);
1000
- return;
1001
- }
1002
- return entry[key];
1003
- };
1004
- const flag = (key) => {
1005
- if (entry[key] === void 0) return void 0;
1006
- if (typeof entry[key] !== "boolean") {
1007
- problems.push(`${at}.${key} must be true or false`);
1008
- return;
1009
- }
1010
- return entry[key];
1011
- };
1012
- const strings = (key) => {
1013
- if (entry[key] === void 0) return [];
1014
- if (!(Array.isArray(entry[key]) && entry[key].every((item) => typeof item === "string"))) {
1015
- problems.push(`${at}.${key} must be a list of text`);
1016
- return [];
1017
- }
1018
- return entry[key].map((item) => item.trim()).filter((item) => item !== "");
1019
- };
1020
- const bands = Array.isArray(entry["bands"]) ? entry["bands"].flatMap((band) => isObject(band) && typeof band["up_to"] === "number" && typeof band["label"] === "string" && band["label"].trim() !== "" ? [{
1021
- up_to: band["up_to"],
1022
- label: band["label"].trim()
1023
- }] : (problems.push(`${at}.bands needs { up_to, label } entries`), [])) : [];
1024
- const rawDefault = entry["default"];
1025
- if (rawDefault !== void 0 && rawDefault !== null && rawDefault !== "" && typeof rawDefault !== "number" && typeof rawDefault !== "boolean" && typeof rawDefault !== "string") problems.push(`${at}.default must be a number, true or false, or text`);
1026
- for (const [key, allowed] of [
1027
- ["kind", VARIABLE_KINDS],
1028
- ["subject", VARIABLE_SUBJECTS],
1029
- ["visibility", VARIABLE_VISIBILITIES]
1030
- ]) if (!allowed.includes(text(key))) problems.push(`${at}.${key} must be one of: ${allowed.join(", ")}`);
1031
- const [min, max] = [number("min"), number("max")];
1032
- const [integer, baseline, always] = [
1033
- flag("integer"),
1034
- flag("baseline"),
1035
- flag("always")
1036
- ];
1037
- const only = strings("only");
1038
- const options = strings("options");
1039
- return [{
1040
- key: text("key"),
1041
- name: text("name"),
1042
- kind: text("kind"),
1043
- subject: text("subject"),
1044
- visibility: text("visibility"),
1045
- ...text("description") === "" ? {} : { description: text("description") },
1046
- ...min === void 0 ? {} : { min },
1047
- ...max === void 0 ? {} : { max },
1048
- ...integer === true ? { integer } : {},
1049
- ...baseline === true ? { baseline } : {},
1050
- ...always === true ? { always } : {},
1051
- ...rawDefault === void 0 || rawDefault === null || rawDefault === "" ? {} : { default: rawDefault },
1052
- ...only.length === 0 ? {} : { only },
1053
- ...options.length === 0 ? {} : { options },
1054
- ...bands.length === 0 ? {} : { bands }
1055
- }];
1056
- });
1057
- if (problems.length > 0) throw new InvalidEditProblems(problems);
1058
- return declarations;
1059
- }
1060
- /**
1061
- * The calendar as the browser sends it.
1062
- * @throws {InvalidEditProblems} naming every field that has the wrong shape; whether the days and ids are acceptable is checked as the file is read.
1063
- */
1064
- function parseCalendarEdit(value) {
1065
- const problems = [];
1066
- if (!isObject(value)) throw new InvalidEditProblems(["the calendar must be { hemisphere, holidays: [...] }"]);
1067
- if (value["hemisphere"] !== "north" && value["hemisphere"] !== "south") problems.push("hemisphere must be \"north\" or \"south\"");
1068
- const list = Array.isArray(value["holidays"]) ? value["holidays"] : void 0;
1069
- if (list === void 0) problems.push("holidays must be a list");
1070
- const holidays = (list ?? []).map((entry, index) => {
1071
- const at = `holidays[${index}]`;
1072
- if (!isObject(entry)) {
1073
- problems.push(`${at} must be an object`);
1074
- return {
1075
- id: "",
1076
- name: "",
1077
- on: []
1078
- };
1079
- }
1080
- for (const key of Object.keys(entry)) if (![
1081
- "id",
1082
- "name",
1083
- "on"
1084
- ].includes(key)) problems.push(`${at}.${key} is not a field of a holiday`);
1085
- for (const key of ["id", "name"]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
1086
- if (!(Array.isArray(entry["on"]) && entry["on"].every((day) => typeof day === "string"))) problems.push(`${at}.on must be a list of days`);
1087
- return {
1088
- id: typeof entry["id"] === "string" ? entry["id"].trim() : "",
1089
- name: typeof entry["name"] === "string" ? entry["name"].trim() : "",
1090
- on: Array.isArray(entry["on"]) ? entry["on"].map((day) => String(day).trim()).filter((day) => day !== "") : []
1091
- };
1092
- });
1093
- if (problems.length > 0) throw new InvalidEditProblems(problems);
1094
- return {
1095
- hemisphere: value["hemisphere"],
1096
- holidays
1097
- };
1098
- }
1099
- //#endregion
1100
- //#region src/host/worlds/starter.ts
1101
- const STARTER_FOLDER = "starter-worlds";
1102
- /** Names a starter world that the package does not ship. */
1103
- var UnknownStarterError = class extends Error {};
1104
- /** The folder of the worlds that ship with the package, found from this module so that it works from source and from the build. */
1105
- function starterDirectory(from = dirname(fileURLToPath(import.meta.url))) {
1106
- for (let directory = from;; directory = dirname(directory)) {
1107
- const candidate = join(directory, STARTER_FOLDER);
1108
- if (existsSync(join(directory, "package.json")) && existsSync(candidate)) return candidate;
1109
- if (dirname(directory) === directory) throw new Error("the starter worlds shipped with the package were not found");
1110
- }
1111
- }
1112
- async function shipped(directory) {
1113
- const found = [];
1114
- for (const entry of await readdir(directory, { withFileTypes: true })) {
1115
- if (!entry.isDirectory()) continue;
1116
- const document = JSON.parse(await readFile(join(directory, entry.name, WORLD_FILE_NAME), "utf8"));
1117
- if (typeof document.id !== "string" || typeof document.name !== "string") throw new Error(`the starter world "${entry.name}" has no id or name`);
1118
- found.push({
1119
- folder: entry.name,
1120
- id: document.id,
1121
- name: document.name,
1122
- description: typeof document.description === "string" ? document.description : "",
1123
- tags: Array.isArray(document.metadata?.tags) ? document.metadata.tags.filter((tag) => typeof tag === "string") : []
1124
- });
1125
- }
1126
- return found.sort((a, b) => a.folder.localeCompare(b.folder));
1127
- }
1128
- /** The worlds the package ships, each with whether the person's worlds have it already. */
1129
- async function listStarterWorlds(catalog, directory = starterDirectory()) {
1130
- const known = await catalog.list();
1131
- return (await shipped(directory)).map(({ id, ...world }) => ({
1132
- ...world,
1133
- installed: known.worlds.some((existing) => existing.id === id) || existsSync(join(catalog.directory, world.folder))
1134
- }));
1135
- }
1136
- /**
1137
- * Copies a shipped world into the person's worlds, as a world of their own to play and edit, and makes the catalogue see it. Nothing is overwritten.
1138
- * @throws {UnknownStarterError} when the package ships no such world.
1139
- * @throws {WorldFolderExistsError} when the person already has that folder or a world with the same id.
1140
- */
1141
- async function addStarterWorld(catalog, folder, directory = starterDirectory()) {
1142
- const world = (await shipped(directory)).find((candidate) => candidate.folder === folder);
1143
- if (world === void 0) throw new UnknownStarterError(`there is no starter world "${folder}"`);
1144
- if ((await catalog.list({ refresh: true })).worlds.some((existing) => existing.id === world.id)) throw new WorldFolderExistsError(`you already have "${world.name}"`);
1145
- const target = join(catalog.directory, world.folder);
1146
- if (existsSync(target)) throw new WorldFolderExistsError(`a world folder named "${world.folder}" already exists`);
1147
- await mkdir(catalog.directory, { recursive: true });
1148
- try {
1149
- await cp(join(directory, world.folder), target, {
1150
- recursive: true,
1151
- errorOnExist: true,
1152
- force: false
1153
- });
1154
- } catch (error) {
1155
- await rm(target, {
1156
- recursive: true,
1157
- force: true
1158
- });
1159
- throw error;
1160
- }
1161
- const added = (await catalog.list({ refresh: true })).worlds.find((candidate) => candidate.id === world.id);
1162
- if (added === void 0) throw new Error(`added "${world.name}" but it was not found when the catalogue refreshed`);
1163
- return added;
1164
- }
1165
- //#endregion
1166
- //#region src/host/http/respond.ts
1167
- function sendJson(res, status, payload) {
1168
- res.statusCode = status;
1169
- res.setHeader("content-type", "application/json; charset=utf-8");
1170
- res.setHeader("cache-control", "no-store");
1171
- res.end(JSON.stringify(payload));
1172
- }
1173
- function sendError(res, status, message) {
1174
- sendJson(res, status, { message });
1175
- }
1176
- /** A failure with the status the client should see. */
1177
- var HttpError = class extends Error {
1178
- status;
1179
- constructor(status, message) {
1180
- super(message);
1181
- this.status = status;
1182
- }
1183
- };
1184
- //#endregion
1185
- //#region src/host/http/body.ts
1186
- /** Request bodies here are small JSON objects; anything larger is not one. */
1187
- const MAX_BODY_BYTES = 16384;
1188
- /** Read a request body that must be a JSON object. */
1189
- async function readJsonBody(req) {
1190
- if (String(req.headers["content-type"] ?? "").split(";", 1)[0]?.trim().toLowerCase() !== "application/json") throw new HttpError(415, "content-type must be application/json");
1191
- const chunks = [];
1192
- let size = 0;
1193
- for await (const chunk of req) {
1194
- size += chunk.length;
1195
- if (size > MAX_BODY_BYTES) throw new HttpError(413, "request body is too large");
1196
- chunks.push(chunk);
1197
- }
1198
- let body;
1199
- try {
1200
- body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
1201
- } catch {
1202
- throw new HttpError(400, "request body is not valid JSON");
1203
- }
1204
- if (typeof body !== "object" || body === null || Array.isArray(body)) throw new HttpError(400, "request body must be a JSON object");
1205
- return body;
1206
- }
1207
- /** Reads a request body of any kind up to `limit` bytes; a larger one is refused as soon as it is known to be, without being read. */
1208
- async function readBinaryBody(req, limit) {
1209
- const declared = Number(req.headers["content-length"]);
1210
- if (Number.isFinite(declared) && declared > limit) throw new HttpError(413, `the upload is larger than ${Math.round(limit / 1024 / 1024)} MB`);
1211
- const chunks = [];
1212
- let size = 0;
1213
- for await (const chunk of req) {
1214
- size += chunk.length;
1215
- if (size > limit) throw new HttpError(413, `the upload is larger than ${Math.round(limit / 1024 / 1024)} MB`);
1216
- chunks.push(chunk);
1217
- }
1218
- if (size === 0) throw new HttpError(400, "the upload is empty");
1219
- return Buffer.concat(chunks);
1220
- }
1221
- //#endregion
1222
- //#region src/host/presets/service.ts
1223
- /** The story's prompts cannot change right now. */
1224
- var PresetBusyError = class extends Error {};
1225
- /** The preset library and the presets of stories. Refusals are plain `Error`s with the reason; unknown stories and worlds are not-found errors. */
1226
- var Presets = class {
1227
- deps;
1228
- constructor(deps) {
1229
- this.deps = deps;
1230
- }
1231
- get maxUploadBytes() {
1232
- return this.deps.maxUploadBytes;
1233
- }
1234
- list() {
1235
- return listPresets(this.deps.root()).map((entry) => entry.summary);
1236
- }
1237
- /** A preset with the text of each prompt it carries, keyed `<language>/<id>`. */
1238
- read(name) {
1239
- const loaded = loadPreset(this.deps.root(), name);
1240
- return {
1241
- summary: loaded.summary,
1242
- prompts: Object.fromEntries([...loaded.files].map(([path, text]) => [path.slice(0, -3), text]))
906
+ summary: loaded.summary,
907
+ prompts: Object.fromEntries([...loaded.files].map(([path, text]) => [path.slice(0, -3), text]))
1243
908
  };
1244
909
  }
1245
910
  async saveFromWorld(request) {
@@ -1323,7 +988,7 @@ var Presets = class {
1323
988
  const directory = await reservePreset(root, name, title ?? uploaded.name, uploaded.sampling);
1324
989
  try {
1325
990
  await mkdir(join(directory, IMPORT_FOLDER), { recursive: true });
1326
- await writeFile(join(directory, IMPORT_FOLDER, PRESET_FILE), file);
991
+ await writeFile(join(directory, IMPORT_FOLDER, PRESET_FILE$1), file);
1327
992
  } catch (error) {
1328
993
  await deletePreset(root, name);
1329
994
  throw error;
@@ -1367,8 +1032,43 @@ var Presets = class {
1367
1032
  return sessionFolder(sessions, id);
1368
1033
  }
1369
1034
  };
1370
- //#endregion
1371
- //#region src/host/presets/routes.ts
1035
+ // src/host/http/body.ts
1036
+ /** Request bodies here are small JSON objects; anything larger is not one. */
1037
+ const MAX_BODY_BYTES = 16384;
1038
+ /** Read a request body that must be a JSON object. */
1039
+ async function readJsonBody(req) {
1040
+ if (String(req.headers["content-type"] ?? "").split(";", 1)[0]?.trim().toLowerCase() !== "application/json") throw new HttpError(415, "content-type must be application/json");
1041
+ const chunks = [];
1042
+ let size = 0;
1043
+ for await (const chunk of req) {
1044
+ size += chunk.length;
1045
+ if (size > MAX_BODY_BYTES) throw new HttpError(413, "request body is too large");
1046
+ chunks.push(chunk);
1047
+ }
1048
+ let body;
1049
+ try {
1050
+ body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
1051
+ } catch {
1052
+ throw new HttpError(400, "request body is not valid JSON");
1053
+ }
1054
+ if (typeof body !== "object" || body === null || Array.isArray(body)) throw new HttpError(400, "request body must be a JSON object");
1055
+ return body;
1056
+ }
1057
+ /** Reads a request body of any kind up to `limit` bytes; a larger one is refused as soon as it is known to be, without being read. */
1058
+ async function readBinaryBody(req, limit) {
1059
+ const declared = Number(req.headers["content-length"]);
1060
+ if (Number.isFinite(declared) && declared > limit) throw new HttpError(413, `the upload is larger than ${Math.round(limit / 1024 / 1024)} MB`);
1061
+ const chunks = [];
1062
+ let size = 0;
1063
+ for await (const chunk of req) {
1064
+ size += chunk.length;
1065
+ if (size > limit) throw new HttpError(413, `the upload is larger than ${Math.round(limit / 1024 / 1024)} MB`);
1066
+ chunks.push(chunk);
1067
+ }
1068
+ if (size === 0) throw new HttpError(400, "the upload is empty");
1069
+ return Buffer.concat(chunks);
1070
+ }
1071
+ // src/host/presets/routes.ts
1372
1072
  /** Not found is 404 and a request the library refuses is 422 with its reason; anything else is a fault. */
1373
1073
  function failure$2(res, error) {
1374
1074
  if (error instanceof ImportNotFoundError) return sendError(res, 404, error.message);
@@ -1551,8 +1251,7 @@ function presetRoutes(api) {
1551
1251
  }
1552
1252
  };
1553
1253
  }
1554
- //#endregion
1555
- //#region src/host/lorebooks/routes.ts
1254
+ // src/host/lorebooks/routes.ts
1556
1255
  /** Not found is 404, a story in the middle of a turn 409, and a request the library refuses 422 with its reason; anything else is a fault. */
1557
1256
  function failure$1(res, error) {
1558
1257
  if (error instanceof ImportNotFoundError) return sendError(res, 404, error.message);
@@ -1738,22 +1437,7 @@ function lorebookRoutes(api) {
1738
1437
  } }
1739
1438
  };
1740
1439
  }
1741
- //#endregion
1742
- //#region src/host/sync/errors.ts
1743
- /** A run, or a choice, cannot be made now. */
1744
- var SyncRefusedError = class extends Error {};
1745
- /** rclone could not be started or reported a failure. */
1746
- var RcloneError = class extends Error {
1747
- code;
1748
- constructor(message, code) {
1749
- super(message);
1750
- this.code = code;
1751
- }
1752
- };
1753
- /** The unit is being synced: nothing may write to it or read from it until the run is over. */
1754
- var UnitLockedError = class extends Error {};
1755
- //#endregion
1756
- //#region src/shared/catalogue.ts
1440
+ // src/shared/catalogue.ts
1757
1441
  /** What a credential reference is: letters, digits and `_`, not starting with a digit (DSH's grammar). */
1758
1442
  const CREDENTIAL_REF = /^[A-Za-z_][A-Za-z0-9_]*$/;
1759
1443
  /** The credential a catalogue's key is stored under when its entry names none. Names with other characters get a short checksum so that two of them never share a key. */
@@ -1768,8 +1452,20 @@ const CATALOGUE_CARD_TYPE = "sillytavern/character";
1768
1452
  const CATALOGUE_PRESET_TYPE = "sillytavern/preset";
1769
1453
  const CATALOGUE_LOREBOOK_TYPE = "sillytavern/lorebook";
1770
1454
  const CATALOGUE_WORLD_TYPE = "dsh-agentic-roleplay/world";
1771
- //#endregion
1772
- //#region src/host/sync/routes.ts
1455
+ // src/host/sync/errors.ts
1456
+ /** A run, or a choice, cannot be made now. */
1457
+ var SyncRefusedError = class extends Error {};
1458
+ /** rclone could not be started or reported a failure. */
1459
+ var RcloneError = class extends Error {
1460
+ code;
1461
+ constructor(message, code) {
1462
+ super(message);
1463
+ this.code = code;
1464
+ }
1465
+ };
1466
+ /** The unit is being synced: nothing may write to it or read from it until the run is over. */
1467
+ var UnitLockedError = class extends Error {};
1468
+ // src/host/sync/routes.ts
1773
1469
  function failure(res, error) {
1774
1470
  if (error instanceof UnitLockedError) return sendError(res, 423, error.message);
1775
1471
  if (error instanceof SyncRefusedError) return sendError(res, 409, error.message);
@@ -1953,8 +1649,7 @@ function withBridge(html) {
1953
1649
  }
1954
1650
  return `${script}${html}`;
1955
1651
  }
1956
- //#endregion
1957
- //#region src/host/interface/player-view.ts
1652
+ // src/host/interface/player-view.ts
1958
1653
  const keyOf$2 = (character) => character.sourceId ?? String(character.id);
1959
1654
  /** What a variable shows, in one line of data. */
1960
1655
  function shown(subject, entries) {
@@ -2099,8 +1794,7 @@ function finish(view, session) {
2099
1794
  revision
2100
1795
  };
2101
1796
  }
2102
- //#endregion
2103
- //#region src/host/interface/preview.ts
1797
+ // src/host/interface/preview.ts
2104
1798
  /** What a story shows for suggestions when a pack is looked at before any story exists. */
2105
1799
  const SAMPLE_SUGGESTIONS = [
2106
1800
  "Look around.",
@@ -2152,8 +1846,7 @@ async function previewViewOf(world, wall) {
2152
1846
  scratch.close();
2153
1847
  }
2154
1848
  }
2155
- //#endregion
2156
- //#region src/host/interface/storage.ts
1849
+ // src/host/interface/storage.ts
2157
1850
  const keyOf$1 = (pack) => `roleplay.interface.${pack}`;
2158
1851
  function checkedKey(key) {
2159
1852
  if (key === "" || key.length > 100) throw new RangeError("a key is 1 to 100 characters");
@@ -2195,8 +1888,7 @@ var PackStorage = class {
2195
1888
  this.session.metadata.setValue(keyOf$1(this.pack), rest);
2196
1889
  }
2197
1890
  };
2198
- //#endregion
2199
- //#region src/host/interface/service.ts
1891
+ // src/host/interface/service.ts
2200
1892
  /** The packs of a world cannot be brought into a story because some of them have problems. */
2201
1893
  var InvalidPacksError = class extends Error {
2202
1894
  problems;
@@ -2441,8 +2133,7 @@ var InterfaceService = class {
2441
2133
  ]) };
2442
2134
  }
2443
2135
  };
2444
- //#endregion
2445
- //#region src/host/interface/routes.ts
2136
+ // src/host/interface/routes.ts
2446
2137
  /** The address under which the files of a session's pack are served to the page: `<prefix>/<session id>/<path of the file>`. */
2447
2138
  const PACK_FILES = "/sessions/interface/pack/";
2448
2139
  /**
@@ -2554,28 +2245,115 @@ async function sendPackFile(api, path, res) {
2554
2245
  if (session === void 0) return sendError(res, 404, "not found");
2555
2246
  let file;
2556
2247
  try {
2557
- file = api.file(session, rest.slice(slash + 1).split("/").map(decodeURIComponent).join("/"));
2248
+ file = api.file(session, rest.slice(slash + 1).split("/").map(decodeURIComponent).join("/"));
2249
+ } catch (error) {
2250
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
2251
+ if (error instanceof URIError) return sendError(res, 400, "the path is not valid");
2252
+ throw error;
2253
+ }
2254
+ if (file === void 0) return sendError(res, 404, "the pack has no such file");
2255
+ res.statusCode = 200;
2256
+ for (const [name, value] of Object.entries(PACK_HEADERS)) res.setHeader(name, value);
2257
+ res.setHeader("content-type", file.mediaType);
2258
+ if (framed) res.setHeader("access-control-allow-origin", "*");
2259
+ if (file.kind === "page") {
2260
+ const body = Buffer.from(file.body);
2261
+ res.setHeader("content-length", body.length);
2262
+ res.end(body);
2263
+ return;
2264
+ }
2265
+ res.setHeader("content-length", file.size);
2266
+ await pipeline(createReadStream(file.file), res);
2267
+ }
2268
+ // src/host/http/routes/speech.ts
2269
+ /** The routes of the API for speech. */
2270
+ function speechRoutes({ speech }) {
2271
+ return {
2272
+ "/speech/capabilities": { GET: async (_req, res) => {
2273
+ sendJson(res, 200, { streaming: speech.streaming() });
2274
+ } },
2275
+ "/speech/voices": { GET: async (_req, res) => {
2276
+ sendJson(res, 200, await speech.voices());
2277
+ } },
2278
+ "/speech/synthesize": { POST: async (req, res) => {
2279
+ const body = await readJsonBody(req);
2280
+ if (!Array.isArray(body.parts)) return sendError(res, 400, "parts must be a list");
2281
+ const parts = body.parts.filter((part) => typeof part === "object" && part !== null && typeof part.text === "string");
2282
+ if (parts.length !== body.parts.length) return sendError(res, 400, "each speech part needs text");
2283
+ const audio = await speech.speak(parts);
2284
+ res.statusCode = 200;
2285
+ res.setHeader("content-type", audio.mediaType);
2286
+ res.setHeader("content-length", audio.bytes.length);
2287
+ res.end(audio.bytes);
2288
+ } }
2289
+ };
2290
+ }
2291
+ // src/host/worlds/starter.ts
2292
+ const STARTER_FOLDER = "starter-worlds";
2293
+ /** Names a starter world that the package does not ship. */
2294
+ var UnknownStarterError = class extends Error {};
2295
+ /** The folder of the worlds that ship with the package, found from this module so that it works from source and from the build. */
2296
+ function starterDirectory(from = dirname(fileURLToPath(import.meta.url))) {
2297
+ for (let directory = from;; directory = dirname(directory)) {
2298
+ const candidate = join(directory, STARTER_FOLDER);
2299
+ if (existsSync(join(directory, "package.json")) && existsSync(candidate)) return candidate;
2300
+ if (dirname(directory) === directory) throw new Error("the starter worlds shipped with the package were not found");
2301
+ }
2302
+ }
2303
+ async function shipped(directory) {
2304
+ const found = [];
2305
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
2306
+ if (!entry.isDirectory()) continue;
2307
+ const document = JSON.parse(await readFile(join(directory, entry.name, WORLD_FILE_NAME), "utf8"));
2308
+ if (typeof document.id !== "string" || typeof document.name !== "string") throw new Error(`the starter world "${entry.name}" has no id or name`);
2309
+ found.push({
2310
+ folder: entry.name,
2311
+ id: document.id,
2312
+ name: document.name,
2313
+ description: typeof document.description === "string" ? document.description : "",
2314
+ tags: Array.isArray(document.metadata?.tags) ? document.metadata.tags.filter((tag) => typeof tag === "string") : []
2315
+ });
2316
+ }
2317
+ return found.sort((a, b) => a.folder.localeCompare(b.folder));
2318
+ }
2319
+ /** The worlds the package ships, each with whether the person's worlds have it already. */
2320
+ async function listStarterWorlds(catalog, directory = starterDirectory()) {
2321
+ const known = await catalog.list();
2322
+ return (await shipped(directory)).map(({ id, ...world }) => ({
2323
+ ...world,
2324
+ installed: known.worlds.some((existing) => existing.id === id) || existsSync(join(catalog.directory, world.folder))
2325
+ }));
2326
+ }
2327
+ /**
2328
+ * Copies a shipped world into the person's worlds, as a world of their own to play and edit, and makes the catalogue see it. Nothing is overwritten.
2329
+ * @throws {UnknownStarterError} when the package ships no such world.
2330
+ * @throws {WorldFolderExistsError} when the person already has that folder or a world with the same id.
2331
+ */
2332
+ async function addStarterWorld(catalog, folder, directory = starterDirectory()) {
2333
+ const world = (await shipped(directory)).find((candidate) => candidate.folder === folder);
2334
+ if (world === void 0) throw new UnknownStarterError(`there is no starter world "${folder}"`);
2335
+ if ((await catalog.list({ refresh: true })).worlds.some((existing) => existing.id === world.id)) throw new WorldFolderExistsError(`you already have "${world.name}"`);
2336
+ const target = join(catalog.directory, world.folder);
2337
+ if (existsSync(target)) throw new WorldFolderExistsError(`a world folder named "${world.folder}" already exists`);
2338
+ await mkdir(catalog.directory, { recursive: true });
2339
+ try {
2340
+ await cp(join(directory, world.folder), target, {
2341
+ recursive: true,
2342
+ errorOnExist: true,
2343
+ force: false
2344
+ });
2558
2345
  } catch (error) {
2559
- if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
2560
- if (error instanceof URIError) return sendError(res, 400, "the path is not valid");
2346
+ await rm(target, {
2347
+ recursive: true,
2348
+ force: true
2349
+ });
2561
2350
  throw error;
2562
2351
  }
2563
- if (file === void 0) return sendError(res, 404, "the pack has no such file");
2564
- res.statusCode = 200;
2565
- for (const [name, value] of Object.entries(PACK_HEADERS)) res.setHeader(name, value);
2566
- res.setHeader("content-type", file.mediaType);
2567
- if (framed) res.setHeader("access-control-allow-origin", "*");
2568
- if (file.kind === "page") {
2569
- const body = Buffer.from(file.body);
2570
- res.setHeader("content-length", body.length);
2571
- res.end(body);
2572
- return;
2573
- }
2574
- res.setHeader("content-length", file.size);
2575
- await pipeline(createReadStream(file.file), res);
2352
+ const added = (await catalog.list({ refresh: true })).worlds.find((candidate) => candidate.id === world.id);
2353
+ if (added === void 0) throw new Error(`added "${world.name}" but it was not found when the catalogue refreshed`);
2354
+ return added;
2576
2355
  }
2577
- //#endregion
2578
- //#region src/host/http/api.ts
2356
+ // src/host/http/routes/shared.ts
2579
2357
  /** The largest picture that can be added to a gallery. */
2580
2358
  const MAX_UPLOAD_BYTES = 20971520;
2581
2359
  /** The changes to a picture's metadata a body asks for, or what is wrong with it. */
@@ -2635,7 +2413,6 @@ function importFailure(res, error) {
2635
2413
  if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
2636
2414
  throw error;
2637
2415
  }
2638
- /** Build the request handler mounted at `/${API_PREFIX}`. */
2639
2416
  /** The language a client says it is using, or nothing when it says none. */
2640
2417
  function languageField(value) {
2641
2418
  if (value === void 0) return void 0;
@@ -2646,25 +2423,10 @@ function languageField(value) {
2646
2423
  throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
2647
2424
  }
2648
2425
  }
2649
- function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld, translation, worldCharacters, importer, avatars, worldFiles, worldEditor, sessions, packs, presets, lorebooks, sync, locked, anyLocked, connection, speech, externalTools, redundantLayers }) {
2650
- const routes = {
2651
- "/speech/capabilities": { GET: async (_req, res) => {
2652
- sendJson(res, 200, { streaming: speech.streaming() });
2653
- } },
2654
- "/speech/voices": { GET: async (_req, res) => {
2655
- sendJson(res, 200, await speech.voices());
2656
- } },
2657
- "/speech/synthesize": { POST: async (req, res) => {
2658
- const body = await readJsonBody(req);
2659
- if (!Array.isArray(body.parts)) return sendError(res, 400, "parts must be a list");
2660
- const parts = body.parts.filter((part) => typeof part === "object" && part !== null && typeof part.text === "string");
2661
- if (parts.length !== body.parts.length) return sendError(res, 400, "each speech part needs text");
2662
- const audio = await speech.speak(parts);
2663
- res.statusCode = 200;
2664
- res.setHeader("content-type", audio.mediaType);
2665
- res.setHeader("content-length", audio.bytes.length);
2666
- res.end(audio.bytes);
2667
- } },
2426
+ // src/host/http/routes/worlds.ts
2427
+ /** The routes of the API for worlds. */
2428
+ function worldsRoutes({ worlds, createWorld, starter, authorWorld, translation, worldCharacters, avatars }) {
2429
+ return {
2668
2430
  "/worlds": {
2669
2431
  GET: async (_req, res) => {
2670
2432
  sendJson(res, 200, await worlds.list());
@@ -2689,6 +2451,125 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
2689
2451
  }
2690
2452
  }
2691
2453
  },
2454
+ "/worlds/starter": {
2455
+ GET: async (_req, res) => {
2456
+ sendJson(res, 200, await starter.list());
2457
+ },
2458
+ POST: async (req, res) => {
2459
+ const body = await readJsonBody(req);
2460
+ if (typeof body.folder !== "string") return sendError(res, 400, "folder must be text");
2461
+ try {
2462
+ sendJson(res, 201, await starter.add(body.folder));
2463
+ } catch (error) {
2464
+ if (error instanceof UnknownStarterError) return sendError(res, 404, error.message);
2465
+ if (error instanceof WorldFolderExistsError) return sendError(res, 409, error.message);
2466
+ throw error;
2467
+ }
2468
+ }
2469
+ },
2470
+ "/worlds/refresh": { POST: async (_req, res) => {
2471
+ sendJson(res, 200, await worlds.list({ refresh: true }));
2472
+ } },
2473
+ "/worlds/authoring": { POST: async (req, res, url) => {
2474
+ const body = await readJsonBody(req);
2475
+ if (typeof body.title !== "string" || body.title.trim() === "" || body.title.length > 300) return sendError(res, 400, "the request needs a valid chat title");
2476
+ try {
2477
+ sendJson(res, 200, await authorWorld(url.searchParams.get("id") ?? "", body.title.trim(), languageField(body.language)));
2478
+ } catch (error) {
2479
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2480
+ if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
2481
+ throw error;
2482
+ }
2483
+ } },
2484
+ "/worlds/language": { GET: async (_req, res, url) => {
2485
+ try {
2486
+ sendJson(res, 200, { language: await translation.language(url.searchParams.get("id") ?? "") ?? null });
2487
+ } catch (error) {
2488
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2489
+ throw error;
2490
+ }
2491
+ } },
2492
+ "/worlds/translate": { POST: async (req, res, url) => {
2493
+ const body = await readJsonBody(req);
2494
+ if (body.to !== "en" && body.to !== "zh") return sendError(res, 400, "to must be \"en\" or \"zh\"");
2495
+ if (typeof body.title !== "string" || body.title.trim() === "" || body.title.length > 300) return sendError(res, 400, "the request needs a valid chat title");
2496
+ try {
2497
+ sendJson(res, 200, await translation.start(url.searchParams.get("id") ?? "", body.to, body.title.trim(), languageField(body.language) ?? "en"));
2498
+ } catch (error) {
2499
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2500
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2501
+ message: error.message,
2502
+ problems: error.problems
2503
+ });
2504
+ if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
2505
+ throw error;
2506
+ }
2507
+ } },
2508
+ "/avatars": {
2509
+ POST: async (req, res) => {
2510
+ const body = await readJsonBody(req);
2511
+ if (typeof body.name !== "string" || body.name.trim() === "") return sendError(res, 400, "name must be text");
2512
+ try {
2513
+ sendJson(res, 201, { key: await avatars.create(body.name) });
2514
+ } catch (error) {
2515
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2516
+ message: error.message,
2517
+ problems: error.problems
2518
+ });
2519
+ throw error;
2520
+ }
2521
+ },
2522
+ DELETE: async (_req, res, url) => {
2523
+ try {
2524
+ await avatars.remove(url.searchParams.get("key") ?? "");
2525
+ sendJson(res, 200, { deleted: true });
2526
+ } catch (error) {
2527
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2528
+ message: error.message,
2529
+ problems: error.problems
2530
+ });
2531
+ throw error;
2532
+ }
2533
+ }
2534
+ },
2535
+ "/worlds/avatars": { POST: async (req, res, url) => {
2536
+ const body = await readJsonBody(req);
2537
+ if (!Array.isArray(body.avatars) || body.avatars.length === 0 || !body.avatars.every((key) => typeof key === "string")) return sendError(res, 400, "avatars must be a list of keys");
2538
+ try {
2539
+ sendJson(res, 200, { added: await avatars.addToWorld(url.searchParams.get("id") ?? "", body.avatars) });
2540
+ } catch (error) {
2541
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2542
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2543
+ message: error.message,
2544
+ problems: error.problems
2545
+ });
2546
+ throw error;
2547
+ }
2548
+ } },
2549
+ "/worlds/characters": { GET: async (_req, res, url) => {
2550
+ try {
2551
+ sendJson(res, 200, await worldCharacters(url.searchParams.get("id") ?? ""));
2552
+ } catch (error) {
2553
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2554
+ throw error;
2555
+ }
2556
+ } },
2557
+ "/worlds/cover": { GET: async (_req, res, url) => {
2558
+ const cover = await worlds.cover(url.searchParams.get("id") ?? "");
2559
+ if (cover === void 0) return sendError(res, 404, "no cover");
2560
+ res.statusCode = 200;
2561
+ res.setHeader("content-type", cover.contentType);
2562
+ res.setHeader("content-length", cover.size);
2563
+ res.setHeader("x-content-type-options", "nosniff");
2564
+ res.setHeader("cache-control", cover.version === url.searchParams.get("v") ? "private, max-age=31536000, immutable" : "no-cache");
2565
+ await pipeline(createReadStream(cover.file), res);
2566
+ } }
2567
+ };
2568
+ }
2569
+ // src/host/http/routes/catalogue.ts
2570
+ /** The routes of the API for catalogue. */
2571
+ function catalogueRoutes({ catalogue }) {
2572
+ return {
2692
2573
  "/catalogue/sources": { GET: async (_req, res) => {
2693
2574
  try {
2694
2575
  sendJson(res, 200, await catalogue.sources());
@@ -2865,23 +2746,13 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
2865
2746
  } catch (error) {
2866
2747
  return error instanceof CatalogueError ? catalogueFailure(res, error) : importFailure(res, error);
2867
2748
  }
2868
- } },
2869
- "/worlds/starter": {
2870
- GET: async (_req, res) => {
2871
- sendJson(res, 200, await starter.list());
2872
- },
2873
- POST: async (req, res) => {
2874
- const body = await readJsonBody(req);
2875
- if (typeof body.folder !== "string") return sendError(res, 400, "folder must be text");
2876
- try {
2877
- sendJson(res, 201, await starter.add(body.folder));
2878
- } catch (error) {
2879
- if (error instanceof UnknownStarterError) return sendError(res, 404, error.message);
2880
- if (error instanceof WorldFolderExistsError) return sendError(res, 409, error.message);
2881
- throw error;
2882
- }
2883
- }
2884
- },
2749
+ } }
2750
+ };
2751
+ }
2752
+ // src/host/http/routes/imports.ts
2753
+ /** The routes of the API for imports. */
2754
+ function importsRoutes({ importer }) {
2755
+ return {
2885
2756
  "/worlds/import/card": { POST: async (req, res, url) => {
2886
2757
  const name = decodeURIComponent(String(req.headers["x-file-name"] ?? url.searchParams.get("name") ?? "card"));
2887
2758
  try {
@@ -2993,92 +2864,340 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
2993
2864
  return importFailure(res, error);
2994
2865
  }
2995
2866
  } },
2996
- "/worlds/import/picture": { GET: async (_req, res, url) => {
2997
- try {
2998
- await sendImage(res, await importer.picture(url.searchParams.get("id") ?? ""));
2999
- } catch (error) {
3000
- return sendError(res, 404, error instanceof Error ? error.message : String(error));
3001
- }
3002
- } },
3003
- "/worlds/refresh": { POST: async (_req, res) => {
3004
- sendJson(res, 200, await worlds.list({ refresh: true }));
3005
- } },
3006
- "/worlds/authoring": { POST: async (req, res, url) => {
3007
- const body = await readJsonBody(req);
3008
- if (typeof body.title !== "string" || body.title.trim() === "" || body.title.length > 300) return sendError(res, 400, "the request needs a valid chat title");
3009
- try {
3010
- sendJson(res, 200, await authorWorld(url.searchParams.get("id") ?? "", body.title.trim(), languageField(body.language)));
3011
- } catch (error) {
3012
- if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
3013
- if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
3014
- throw error;
3015
- }
3016
- } },
3017
- "/worlds/language": { GET: async (_req, res, url) => {
3018
- try {
3019
- sendJson(res, 200, { language: await translation.language(url.searchParams.get("id") ?? "") ?? null });
3020
- } catch (error) {
3021
- if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
3022
- throw error;
3023
- }
3024
- } },
3025
- "/worlds/translate": { POST: async (req, res, url) => {
3026
- const body = await readJsonBody(req);
3027
- if (body.to !== "en" && body.to !== "zh") return sendError(res, 400, "to must be \"en\" or \"zh\"");
3028
- if (typeof body.title !== "string" || body.title.trim() === "" || body.title.length > 300) return sendError(res, 400, "the request needs a valid chat title");
2867
+ "/worlds/import/structure": { POST: async (req, res, url) => {
3029
2868
  try {
3030
- sendJson(res, 200, await translation.start(url.searchParams.get("id") ?? "", body.to, body.title.trim(), languageField(body.language) ?? "en"));
2869
+ const body = await readJsonBody(req);
2870
+ sendJson(res, 200, await importer.importStructure(url.searchParams.get("id") ?? "", parseChoices(body), languageField(body.language)));
3031
2871
  } catch (error) {
3032
- if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
3033
- if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
3034
- message: error.message,
3035
- problems: error.problems
3036
- });
3037
- if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
3038
- throw error;
2872
+ return importFailure(res, error);
3039
2873
  }
3040
2874
  } },
3041
- "/avatars": {
3042
- POST: async (req, res) => {
3043
- const body = await readJsonBody(req);
3044
- if (typeof body.name !== "string" || body.name.trim() === "") return sendError(res, 400, "name must be text");
3045
- try {
3046
- sendJson(res, 201, { key: await avatars.create(body.name) });
3047
- } catch (error) {
3048
- if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
3049
- message: error.message,
3050
- problems: error.problems
3051
- });
3052
- throw error;
2875
+ "/worlds/import/draft": {
2876
+ GET: async (_req, res, url) => {
2877
+ try {
2878
+ sendJson(res, 200, await importer.draftStatus(url.searchParams.get("id") ?? ""));
2879
+ } catch (error) {
2880
+ return importFailure(res, error);
3053
2881
  }
3054
2882
  },
3055
- DELETE: async (_req, res, url) => {
2883
+ POST: async (req, res, url) => {
3056
2884
  try {
3057
- await avatars.remove(url.searchParams.get("key") ?? "");
3058
- sendJson(res, 200, { deleted: true });
2885
+ const body = await readJsonBody(req);
2886
+ if (body.action !== "ask" && body.action !== "keep" && body.action !== "discard") return sendError(res, 400, "\"action\" must be ask, keep or discard");
2887
+ sendJson(res, 200, await importer.actOnDraft(url.searchParams.get("id") ?? "", body.action, languageField(body.language)));
3059
2888
  } catch (error) {
3060
- if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
3061
- message: error.message,
3062
- problems: error.problems
3063
- });
3064
- throw error;
2889
+ return importFailure(res, error);
3065
2890
  }
3066
2891
  }
3067
2892
  },
3068
- "/worlds/avatars": { POST: async (req, res, url) => {
3069
- const body = await readJsonBody(req);
3070
- if (!Array.isArray(body.avatars) || body.avatars.length === 0 || !body.avatars.every((key) => typeof key === "string")) return sendError(res, 400, "avatars must be a list of keys");
2893
+ "/worlds/import/resume": { POST: async (req, res, url) => {
3071
2894
  try {
3072
- sendJson(res, 200, { added: await avatars.addToWorld(url.searchParams.get("id") ?? "", body.avatars) });
2895
+ const body = await readJsonBody(req);
2896
+ sendJson(res, 200, await importer.resume(url.searchParams.get("id") ?? "", languageField(body.language)));
3073
2897
  } catch (error) {
3074
- if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
3075
- if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
3076
- message: error.message,
3077
- problems: error.problems
3078
- });
3079
- throw error;
2898
+ return importFailure(res, error);
3080
2899
  }
3081
2900
  } },
2901
+ "/worlds/import/picture": { GET: async (_req, res, url) => {
2902
+ try {
2903
+ await sendImage(res, await importer.picture(url.searchParams.get("id") ?? ""));
2904
+ } catch (error) {
2905
+ return sendError(res, 404, error instanceof Error ? error.message : String(error));
2906
+ }
2907
+ } }
2908
+ };
2909
+ }
2910
+ // src/shared/world-dice.ts
2911
+ const isObject$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2912
+ const CHECK_FIELDS = [
2913
+ "key",
2914
+ "name",
2915
+ "use",
2916
+ "dice",
2917
+ "reading",
2918
+ "hit",
2919
+ "compare",
2920
+ "modifier",
2921
+ "bands"
2922
+ ];
2923
+ const BAND_FIELDS = [
2924
+ "min",
2925
+ "max",
2926
+ "label",
2927
+ "result",
2928
+ "critical"
2929
+ ];
2930
+ /** Reads a body that came from the browser: the shape of every field is checked here, and what the checks mean when the world is validated. */
2931
+ function parseDiceEdit(value) {
2932
+ const problems = [];
2933
+ if (!isObject$1(value) || !Array.isArray(value["checks"])) throw new InvalidEditProblems(["the dice must be { checks: [...] }"]);
2934
+ const checks = value["checks"].map((entry, index) => {
2935
+ const at = `checks[${index}]`;
2936
+ const empty = {
2937
+ key: "",
2938
+ name: "",
2939
+ use: "",
2940
+ dice: "",
2941
+ bands: []
2942
+ };
2943
+ if (!isObject$1(entry)) {
2944
+ problems.push(`${at} must be an object`);
2945
+ return empty;
2946
+ }
2947
+ for (const key of Object.keys(entry)) if (!CHECK_FIELDS.includes(key)) problems.push(`${at}.${key} is not a field of a check`);
2948
+ for (const key of [
2949
+ "key",
2950
+ "name",
2951
+ "use",
2952
+ "dice"
2953
+ ]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
2954
+ if (entry["reading"] !== void 0 && !DICE_READINGS.includes(entry["reading"])) problems.push(`${at}.reading must be one of: ${DICE_READINGS.join(", ")}`);
2955
+ if (entry["compare"] !== void 0 && !DICE_COMPARISONS.includes(entry["compare"])) problems.push(`${at}.compare must be one of: ${DICE_COMPARISONS.join(", ")}`);
2956
+ if (entry["hit"] !== void 0 && (typeof entry["hit"] !== "number" || !Number.isInteger(entry["hit"]))) problems.push(`${at}.hit must be a whole number`);
2957
+ if (entry["modifier"] !== void 0 && typeof entry["modifier"] !== "string") problems.push(`${at}.modifier must be text`);
2958
+ const bands = Array.isArray(entry["bands"]) ? entry["bands"] : void 0;
2959
+ if (bands === void 0) problems.push(`${at}.bands must be a list`);
2960
+ const text = (field) => typeof field === "string" ? field.trim() : "";
2961
+ const hit = entry["hit"];
2962
+ return {
2963
+ key: text(entry["key"]),
2964
+ name: text(entry["name"]),
2965
+ use: text(entry["use"]),
2966
+ dice: text(entry["dice"]),
2967
+ ...entry["reading"] === void 0 ? {} : { reading: entry["reading"] },
2968
+ ...typeof hit === "number" ? { hit } : {},
2969
+ ...entry["compare"] === void 0 ? {} : { compare: entry["compare"] },
2970
+ ...text(entry["modifier"]) === "" ? {} : { modifier: text(entry["modifier"]) },
2971
+ bands: (bands ?? []).map((band, bandIndex) => {
2972
+ const where = `${at}.bands[${bandIndex}]`;
2973
+ if (!isObject$1(band)) {
2974
+ problems.push(`${where} must be an object`);
2975
+ return {
2976
+ label: "",
2977
+ result: "failed"
2978
+ };
2979
+ }
2980
+ for (const key of Object.keys(band)) if (!BAND_FIELDS.includes(key)) problems.push(`${where}.${key} is not a field of a band`);
2981
+ for (const key of ["min", "max"]) if (band[key] !== void 0 && (typeof band[key] !== "number" || !Number.isFinite(band[key]))) problems.push(`${where}.${key} must be a number`);
2982
+ if (typeof band["label"] !== "string") problems.push(`${where}.label must be text`);
2983
+ if (!DICE_RESULTS.includes(band["result"])) problems.push(`${where}.result must be one of: ${DICE_RESULTS.join(", ")}`);
2984
+ const min = band["min"];
2985
+ const max = band["max"];
2986
+ return {
2987
+ label: text(band["label"]),
2988
+ result: band["result"],
2989
+ ...typeof min === "number" ? { min } : {},
2990
+ ...typeof max === "number" ? { max } : {},
2991
+ ...band["critical"] === true ? { critical: true } : {}
2992
+ };
2993
+ })
2994
+ };
2995
+ });
2996
+ if (problems.length > 0) throw new InvalidEditProblems(problems);
2997
+ return { checks };
2998
+ }
2999
+ // src/shared/world-daily.ts
3000
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3001
+ const ROUTINE_FIELDS = [
3002
+ "days",
3003
+ "on",
3004
+ "from",
3005
+ "to",
3006
+ "activity",
3007
+ "location",
3008
+ "feature",
3009
+ "position",
3010
+ "interruptible"
3011
+ ];
3012
+ /**
3013
+ * The windows of a day as the browser sends them.
3014
+ * @throws {InvalidEditProblems} naming every field that has the wrong shape; whether the times and places are acceptable is checked when the file is read back.
3015
+ */
3016
+ function parseRoutineEdit(value) {
3017
+ const problems = [];
3018
+ const list = isObject(value) && Array.isArray(value["windows"]) ? value["windows"] : void 0;
3019
+ if (list === void 0) throw new InvalidEditProblems(["the day must be { windows: [...] }"]);
3020
+ const windows = list.map((entry, index) => {
3021
+ const at = `windows[${index}]`;
3022
+ if (!isObject(entry)) {
3023
+ problems.push(`${at} must be an object`);
3024
+ return {
3025
+ days: [],
3026
+ from: "",
3027
+ to: "",
3028
+ activity: "",
3029
+ interruptible: true
3030
+ };
3031
+ }
3032
+ for (const key of Object.keys(entry)) if (!ROUTINE_FIELDS.includes(key)) problems.push(`${at}.${key} is not a field of a window`);
3033
+ for (const key of [
3034
+ "from",
3035
+ "to",
3036
+ "activity"
3037
+ ]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
3038
+ for (const key of [
3039
+ "location",
3040
+ "feature",
3041
+ "position"
3042
+ ]) if (entry[key] !== void 0 && typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
3043
+ if (entry["days"] !== void 0 && !(Array.isArray(entry["days"]) && entry["days"].every((day) => typeof day === "string"))) problems.push(`${at}.days must be a list of days`);
3044
+ if (entry["interruptible"] !== void 0 && typeof entry["interruptible"] !== "boolean") problems.push(`${at}.interruptible must be true or false`);
3045
+ const text = (key) => typeof entry[key] === "string" ? entry[key].trim() : "";
3046
+ return {
3047
+ days: Array.isArray(entry["days"]) ? entry["days"].map((day) => day.trim().toLowerCase()).filter((day) => day !== "") : [],
3048
+ ...Array.isArray(entry["on"]) && entry["on"].length > 0 ? { on: entry["on"].map((day) => String(day).trim()).filter((day) => day !== "") } : {},
3049
+ from: text("from"),
3050
+ to: text("to"),
3051
+ activity: text("activity"),
3052
+ ...text("location") === "" ? {} : { location: text("location") },
3053
+ ...text("feature") === "" ? {} : { feature: text("feature") },
3054
+ ...text("position") === "" ? {} : { position: text("position") },
3055
+ interruptible: entry["interruptible"] !== false
3056
+ };
3057
+ });
3058
+ if (problems.length > 0) throw new InvalidEditProblems(problems);
3059
+ return windows;
3060
+ }
3061
+ const VARIABLE_FIELDS = [
3062
+ "key",
3063
+ "name",
3064
+ "kind",
3065
+ "subject",
3066
+ "visibility",
3067
+ "description",
3068
+ "min",
3069
+ "max",
3070
+ "integer",
3071
+ "baseline",
3072
+ "always",
3073
+ "default",
3074
+ "only",
3075
+ "options",
3076
+ "bands"
3077
+ ];
3078
+ /**
3079
+ * The declarations as the browser sends them, with empty fields left out. Whether they are acceptable together is checked against the world's files.
3080
+ * @throws {InvalidEditProblems} naming every field that has the wrong shape.
3081
+ */
3082
+ function parseVariablesEdit(value) {
3083
+ const problems = [];
3084
+ const list = isObject(value) && Array.isArray(value["variables"]) ? value["variables"] : void 0;
3085
+ if (list === void 0) throw new InvalidEditProblems(["the variables must be { variables: [...] }"]);
3086
+ const declarations = list.flatMap((entry, index) => {
3087
+ const at = `variables[${index}]`;
3088
+ if (!isObject(entry)) {
3089
+ problems.push(`${at} must be an object`);
3090
+ return [];
3091
+ }
3092
+ for (const key of Object.keys(entry)) if (!VARIABLE_FIELDS.includes(key)) problems.push(`${at}.${key} is not a field of a variable`);
3093
+ const text = (key) => typeof entry[key] === "string" ? entry[key].trim() : "";
3094
+ const number = (key) => {
3095
+ if (entry[key] === void 0 || entry[key] === null || entry[key] === "") return void 0;
3096
+ if (typeof entry[key] !== "number" || !Number.isFinite(entry[key])) {
3097
+ problems.push(`${at}.${key} must be a number`);
3098
+ return;
3099
+ }
3100
+ return entry[key];
3101
+ };
3102
+ const flag = (key) => {
3103
+ if (entry[key] === void 0) return void 0;
3104
+ if (typeof entry[key] !== "boolean") {
3105
+ problems.push(`${at}.${key} must be true or false`);
3106
+ return;
3107
+ }
3108
+ return entry[key];
3109
+ };
3110
+ const strings = (key) => {
3111
+ if (entry[key] === void 0) return [];
3112
+ if (!(Array.isArray(entry[key]) && entry[key].every((item) => typeof item === "string"))) {
3113
+ problems.push(`${at}.${key} must be a list of text`);
3114
+ return [];
3115
+ }
3116
+ return entry[key].map((item) => item.trim()).filter((item) => item !== "");
3117
+ };
3118
+ const bands = Array.isArray(entry["bands"]) ? entry["bands"].flatMap((band) => isObject(band) && typeof band["up_to"] === "number" && typeof band["label"] === "string" && band["label"].trim() !== "" ? [{
3119
+ up_to: band["up_to"],
3120
+ label: band["label"].trim()
3121
+ }] : (problems.push(`${at}.bands needs { up_to, label } entries`), [])) : [];
3122
+ const rawDefault = entry["default"];
3123
+ if (rawDefault !== void 0 && rawDefault !== null && rawDefault !== "" && typeof rawDefault !== "number" && typeof rawDefault !== "boolean" && typeof rawDefault !== "string") problems.push(`${at}.default must be a number, true or false, or text`);
3124
+ for (const [key, allowed] of [
3125
+ ["kind", VARIABLE_KINDS],
3126
+ ["subject", VARIABLE_SUBJECTS],
3127
+ ["visibility", VARIABLE_VISIBILITIES]
3128
+ ]) if (!allowed.includes(text(key))) problems.push(`${at}.${key} must be one of: ${allowed.join(", ")}`);
3129
+ const [min, max] = [number("min"), number("max")];
3130
+ const [integer, baseline, always] = [
3131
+ flag("integer"),
3132
+ flag("baseline"),
3133
+ flag("always")
3134
+ ];
3135
+ const only = strings("only");
3136
+ const options = strings("options");
3137
+ return [{
3138
+ key: text("key"),
3139
+ name: text("name"),
3140
+ kind: text("kind"),
3141
+ subject: text("subject"),
3142
+ visibility: text("visibility"),
3143
+ ...text("description") === "" ? {} : { description: text("description") },
3144
+ ...min === void 0 ? {} : { min },
3145
+ ...max === void 0 ? {} : { max },
3146
+ ...integer === true ? { integer } : {},
3147
+ ...baseline === true ? { baseline } : {},
3148
+ ...always === true ? { always } : {},
3149
+ ...rawDefault === void 0 || rawDefault === null || rawDefault === "" ? {} : { default: rawDefault },
3150
+ ...only.length === 0 ? {} : { only },
3151
+ ...options.length === 0 ? {} : { options },
3152
+ ...bands.length === 0 ? {} : { bands }
3153
+ }];
3154
+ });
3155
+ if (problems.length > 0) throw new InvalidEditProblems(problems);
3156
+ return declarations;
3157
+ }
3158
+ /**
3159
+ * The calendar as the browser sends it.
3160
+ * @throws {InvalidEditProblems} naming every field that has the wrong shape; whether the days and ids are acceptable is checked as the file is read.
3161
+ */
3162
+ function parseCalendarEdit(value) {
3163
+ const problems = [];
3164
+ if (!isObject(value)) throw new InvalidEditProblems(["the calendar must be { hemisphere, holidays: [...] }"]);
3165
+ if (value["hemisphere"] !== "north" && value["hemisphere"] !== "south") problems.push("hemisphere must be \"north\" or \"south\"");
3166
+ const list = Array.isArray(value["holidays"]) ? value["holidays"] : void 0;
3167
+ if (list === void 0) problems.push("holidays must be a list");
3168
+ const holidays = (list ?? []).map((entry, index) => {
3169
+ const at = `holidays[${index}]`;
3170
+ if (!isObject(entry)) {
3171
+ problems.push(`${at} must be an object`);
3172
+ return {
3173
+ id: "",
3174
+ name: "",
3175
+ on: []
3176
+ };
3177
+ }
3178
+ for (const key of Object.keys(entry)) if (![
3179
+ "id",
3180
+ "name",
3181
+ "on"
3182
+ ].includes(key)) problems.push(`${at}.${key} is not a field of a holiday`);
3183
+ for (const key of ["id", "name"]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
3184
+ if (!(Array.isArray(entry["on"]) && entry["on"].every((day) => typeof day === "string"))) problems.push(`${at}.on must be a list of days`);
3185
+ return {
3186
+ id: typeof entry["id"] === "string" ? entry["id"].trim() : "",
3187
+ name: typeof entry["name"] === "string" ? entry["name"].trim() : "",
3188
+ on: Array.isArray(entry["on"]) ? entry["on"].map((day) => String(day).trim()).filter((day) => day !== "") : []
3189
+ };
3190
+ });
3191
+ if (problems.length > 0) throw new InvalidEditProblems(problems);
3192
+ return {
3193
+ hemisphere: value["hemisphere"],
3194
+ holidays
3195
+ };
3196
+ }
3197
+ // src/host/http/routes/worldFiles.ts
3198
+ /** The routes of the API for worldFiles. */
3199
+ function worldFilesRoutes({ worldFiles, worldEditor, sessions }) {
3200
+ return {
3082
3201
  "/worlds/state": { GET: async (_req, res, url) => {
3083
3202
  try {
3084
3203
  sendJson(res, 200, await worldEditor.read(url.searchParams.get("id") ?? ""));
@@ -3568,15 +3687,13 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
3568
3687
  return sendError(res, 404, error instanceof Error ? error.message : String(error));
3569
3688
  }
3570
3689
  } }]
3571
- ])),
3572
- "/worlds/characters": { GET: async (_req, res, url) => {
3573
- try {
3574
- sendJson(res, 200, await worldCharacters(url.searchParams.get("id") ?? ""));
3575
- } catch (error) {
3576
- if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
3577
- throw error;
3578
- }
3579
- } },
3690
+ ]))
3691
+ };
3692
+ }
3693
+ // src/host/http/routes/sessions.ts
3694
+ /** The routes of the API for sessions. */
3695
+ function sessionsRoutes({ sessions, externalTools, redundantLayers }) {
3696
+ return {
3580
3697
  "/sessions": {
3581
3698
  GET: async (_req, res) => {
3582
3699
  sendJson(res, 200, sessions.list());
@@ -3793,6 +3910,82 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
3793
3910
  res.statusCode = 204;
3794
3911
  res.end();
3795
3912
  } },
3913
+ "/sessions/activity/run": { GET: async (_req, res, url) => {
3914
+ try {
3915
+ const detail = sessions.activityRun(url.searchParams.get("id") ?? "", url.searchParams.get("run") ?? "");
3916
+ if (detail === void 0) return sendError(res, 404, "this run was not kept, or has been dropped to make room");
3917
+ sendJson(res, 200, detail);
3918
+ } catch (error) {
3919
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
3920
+ if (error instanceof RangeError) return sendError(res, 400, error.message);
3921
+ throw error;
3922
+ }
3923
+ } },
3924
+ "/sessions/doctor": { POST: async (req, res, url) => {
3925
+ const body = await readJsonBody(req);
3926
+ if (typeof body.title !== "string" || body.title.trim() === "" || body.title.length > 300) return sendError(res, 400, "the request needs a valid chat title");
3927
+ try {
3928
+ sendJson(res, 200, await sessions.doctor(url.searchParams.get("id") ?? "", body.title.trim(), languageField(body.language) ?? "en"));
3929
+ } catch (error) {
3930
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
3931
+ if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
3932
+ throw error;
3933
+ }
3934
+ } },
3935
+ "/sessions/reflect": { POST: async (_req, res, url) => {
3936
+ try {
3937
+ await sessions.reflect(url.searchParams.get("id") ?? "");
3938
+ } catch (error) {
3939
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
3940
+ if (error instanceof ReflectionRefusedError) return sendError(res, 409, error.message);
3941
+ throw error;
3942
+ }
3943
+ res.statusCode = 202;
3944
+ res.end();
3945
+ } },
3946
+ "/sessions/vectors/reset": { POST: async (_req, res, url) => {
3947
+ try {
3948
+ sessions.resetVectors(url.searchParams.get("id") ?? "");
3949
+ } catch (error) {
3950
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
3951
+ throw error;
3952
+ }
3953
+ res.statusCode = 204;
3954
+ res.end();
3955
+ } },
3956
+ "/sessions/rename": { POST: async (req, res, url) => {
3957
+ const body = await readJsonBody(req);
3958
+ const name = typeof body === "object" && body !== null ? body.name : void 0;
3959
+ if (typeof name !== "string") return sendError(res, 400, "the request needs a \"name\"");
3960
+ try {
3961
+ await sessions.rename(url.searchParams.get("id") ?? "", name);
3962
+ } catch (error) {
3963
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
3964
+ if (error instanceof InvalidStartError) return sendError(res, 422, error.message);
3965
+ if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
3966
+ throw error;
3967
+ }
3968
+ res.statusCode = 204;
3969
+ res.end();
3970
+ } },
3971
+ "/sessions/item": { DELETE: async (_req, res, url) => {
3972
+ try {
3973
+ await sessions.delete(url.searchParams.get("id") ?? "", url.searchParams.get("everywhere") === "true");
3974
+ } catch (error) {
3975
+ if (error instanceof SyncRefusedError || error instanceof RcloneError) return failure(res, error);
3976
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
3977
+ if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
3978
+ throw error;
3979
+ }
3980
+ res.statusCode = 204;
3981
+ res.end();
3982
+ } }
3983
+ };
3984
+ }
3985
+ // src/host/http/routes/sessionWorld.ts
3986
+ /** The routes of the API for sessionWorld. */
3987
+ function sessionWorldRoutes({ sessions }) {
3988
+ return {
3796
3989
  "/sessions/world": { GET: async (_req, res, url) => {
3797
3990
  try {
3798
3991
  sendJson(res, 200, sessions.world(url.searchParams.get("id") ?? ""));
@@ -3923,91 +4116,25 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
3923
4116
  } catch (error) {
3924
4117
  return sendError(res, 404, error instanceof Error ? error.message : String(error));
3925
4118
  }
3926
- } },
3927
- "/sessions/activity/run": { GET: async (_req, res, url) => {
3928
- try {
3929
- const detail = sessions.activityRun(url.searchParams.get("id") ?? "", url.searchParams.get("run") ?? "");
3930
- if (detail === void 0) return sendError(res, 404, "this run was not kept, or has been dropped to make room");
3931
- sendJson(res, 200, detail);
3932
- } catch (error) {
3933
- if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
3934
- if (error instanceof RangeError) return sendError(res, 400, error.message);
3935
- throw error;
3936
- }
3937
- } },
3938
- "/sessions/doctor": { POST: async (req, res, url) => {
3939
- const body = await readJsonBody(req);
3940
- if (typeof body.title !== "string" || body.title.trim() === "" || body.title.length > 300) return sendError(res, 400, "the request needs a valid chat title");
3941
- try {
3942
- sendJson(res, 200, await sessions.doctor(url.searchParams.get("id") ?? "", body.title.trim(), languageField(body.language) ?? "en"));
3943
- } catch (error) {
3944
- if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
3945
- if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
3946
- throw error;
3947
- }
3948
- } },
3949
- "/sessions/reflect": { POST: async (_req, res, url) => {
3950
- try {
3951
- await sessions.reflect(url.searchParams.get("id") ?? "");
3952
- } catch (error) {
3953
- if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
3954
- if (error instanceof ReflectionRefusedError) return sendError(res, 409, error.message);
3955
- throw error;
3956
- }
3957
- res.statusCode = 202;
3958
- res.end();
3959
- } },
3960
- "/sessions/vectors/reset": { POST: async (_req, res, url) => {
3961
- try {
3962
- sessions.resetVectors(url.searchParams.get("id") ?? "");
3963
- } catch (error) {
3964
- if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
3965
- throw error;
3966
- }
3967
- res.statusCode = 204;
3968
- res.end();
3969
- } },
3970
- "/sessions/rename": { POST: async (req, res, url) => {
3971
- const body = await readJsonBody(req);
3972
- const name = typeof body === "object" && body !== null ? body.name : void 0;
3973
- if (typeof name !== "string") return sendError(res, 400, "the request needs a \"name\"");
3974
- try {
3975
- await sessions.rename(url.searchParams.get("id") ?? "", name);
3976
- } catch (error) {
3977
- if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
3978
- if (error instanceof InvalidStartError) return sendError(res, 422, error.message);
3979
- if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
3980
- throw error;
3981
- }
3982
- res.statusCode = 204;
3983
- res.end();
3984
- } },
3985
- "/sessions/item": { DELETE: async (_req, res, url) => {
3986
- try {
3987
- await sessions.delete(url.searchParams.get("id") ?? "", url.searchParams.get("everywhere") === "true");
3988
- } catch (error) {
3989
- if (error instanceof SyncRefusedError || error instanceof RcloneError) return failure(res, error);
3990
- if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
3991
- if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
3992
- throw error;
3993
- }
3994
- res.statusCode = 204;
3995
- res.end();
3996
- } },
4119
+ } }
4120
+ };
4121
+ }
4122
+ // src/host/http/api.ts
4123
+ /** Build the request handler mounted at `/${API_PREFIX}`. */
4124
+ function createApiHandler(deps) {
4125
+ const { packs, presets, lorebooks, sync, locked, anyLocked, connection } = deps;
4126
+ const routes = {
4127
+ ...speechRoutes(deps),
4128
+ ...worldsRoutes(deps),
4129
+ ...catalogueRoutes(deps),
4130
+ ...importsRoutes(deps),
4131
+ ...worldFilesRoutes(deps),
4132
+ ...sessionsRoutes(deps),
4133
+ ...sessionWorldRoutes(deps),
3997
4134
  ...interfaceRoutes(packs),
3998
4135
  ...presetRoutes(presets),
3999
4136
  ...lorebookRoutes(lorebooks),
4000
- ...syncRoutes(sync),
4001
- "/worlds/cover": { GET: async (_req, res, url) => {
4002
- const cover = await worlds.cover(url.searchParams.get("id") ?? "");
4003
- if (cover === void 0) return sendError(res, 404, "no cover");
4004
- res.statusCode = 200;
4005
- res.setHeader("content-type", cover.contentType);
4006
- res.setHeader("content-length", cover.size);
4007
- res.setHeader("x-content-type-options", "nosniff");
4008
- res.setHeader("cache-control", cover.version === url.searchParams.get("v") ? "private, max-age=31536000, immutable" : "no-cache");
4009
- await pipeline(createReadStream(cover.file), res);
4010
- } }
4137
+ ...syncRoutes(sync)
4011
4138
  };
4012
4139
  return async (req, res) => {
4013
4140
  const url = new URL(req.url ?? "/", "http://localhost");
@@ -4048,8 +4175,7 @@ function createApiHandler({ catalogue, worlds, createWorld, starter, authorWorld
4048
4175
  }
4049
4176
  };
4050
4177
  }
4051
- //#endregion
4052
- //#region src/host/http/index.ts
4178
+ // src/host/http/index.ts
4053
4179
  /** Mount the API once the web server and its authentication are available; profiles without them skip it. */
4054
4180
  function registerApi(ctx, deps) {
4055
4181
  ctx.inject(["webServer", "connection"], (webCtx) => {
@@ -4065,8 +4191,7 @@ function registerApi(ctx, deps) {
4065
4191
  }), "roleplay: http api");
4066
4192
  });
4067
4193
  }
4068
- //#endregion
4069
- //#region src/host/sessions/delete-session.ts
4194
+ // src/host/sessions/delete-session.ts
4070
4195
  /**
4071
4196
  * Delete a session for good: its chat and everything the chat started are removed from DSH's store, and then the session's folder
4072
4197
  * with its story, its turns and the states kept to go back to. When the chat cannot be removed completely the session is kept, so that
@@ -4080,8 +4205,7 @@ async function deleteSession(deps, id) {
4080
4205
  await deps.purgeChat(chatSessionId(id));
4081
4206
  deps.state.deleteSession(directory, id);
4082
4207
  }
4083
- //#endregion
4084
- //#region src/host/storage/root-path.ts
4208
+ // src/host/storage/root-path.ts
4085
4209
  /** Directories every roleplay root contains. */
4086
4210
  const ROOT_LAYOUT = [
4087
4211
  "characters",
@@ -4110,8 +4234,7 @@ async function ensureRootLayout(root) {
4110
4234
  await mkdir(root, { recursive: true });
4111
4235
  await Promise.all(ROOT_LAYOUT.map((name) => mkdir(join(root, name), { recursive: true })));
4112
4236
  }
4113
- //#endregion
4114
- //#region src/host/agent/purge.ts
4237
+ // src/host/agent/purge.ts
4115
4238
  /** A segment of a path for what is not a letter, digit or one of `._-`: `~` and four hex digits, as DSH writes it. */
4116
4239
  const segment = (raw) => {
4117
4240
  if (raw === "") throw new Error("cannot name the folder of a session with no id");
@@ -4204,8 +4327,7 @@ async function purgeChat(deps, chat) {
4204
4327
  if (failures.length > 0) throw new Error(`the chat could not be deleted completely (${removed.length} of ${victims.length} removed): ${failures.join("; ")}`);
4205
4328
  return removed;
4206
4329
  }
4207
- //#endregion
4208
- //#region src/host/agent/purge-services.ts
4330
+ // src/host/agent/purge-services.ts
4209
4331
  /** What DSH's services give and the purge needs, looked up when used: a profile without them cannot delete a chat. */
4210
4332
  function purgeDepsOf(ctx, storePath) {
4211
4333
  const service = (name) => ctx.get(name);
@@ -4229,8 +4351,7 @@ function purgeDepsOf(ctx, storePath) {
4229
4351
  };
4230
4352
  }
4231
4353
  const purgeOf = (ctx, storePath) => (chat) => purgeChat(purgeDepsOf(ctx, storePath), chat);
4232
- //#endregion
4233
- //#region src/host/setup/rows.ts
4354
+ // src/host/setup/rows.ts
4234
4355
  const ALL = ["@dsh-agentic-roleplay/all", "dsh-agentic-roleplay"];
4235
4356
  const SINGLE = [
4236
4357
  "@dsh-agentic-roleplay/core",
@@ -4258,8 +4379,7 @@ function redundantLayers(bundles) {
4258
4379
  function redundantLayersMessage(layers) {
4259
4380
  return `the profile selects ${layers.map((name) => `"${name}"`).join(", ")} next to the all bundle, which already inserts the same plugin rows, so DSH refuses to save the Role Play settings: deselect them (keep the packages installed) and restart`;
4260
4381
  }
4261
- //#endregion
4262
- //#region src/host/worlds/daily-life.ts
4382
+ // src/host/worlds/daily-life.ts
4263
4383
  /** The day each character lives, and the places its windows may name. */
4264
4384
  async function readRoutines(world) {
4265
4385
  const [{ characters }, { locations }] = await Promise.all([loadCharacters(world.directory), loadLocations(world.directory)]);
@@ -4410,8 +4530,7 @@ async function editDice(world, dice) {
4410
4530
  else await replaceFileOrCreate(join(world.directory, DICE_FILE_NAME), text);
4411
4531
  return await readDiceDocument(world);
4412
4532
  }
4413
- //#endregion
4414
- //#region src/host/worlds/lore-entries.ts
4533
+ // src/host/worlds/lore-entries.ts
4415
4534
  const MAX_TITLE = 200;
4416
4535
  /**
4417
4536
  * Adds an empty lore entry to the world's files, named by its title.
@@ -4455,8 +4574,7 @@ async function removeWorldLore(world, key) {
4455
4574
  await deleteAuthoredEntity(world, "lore", key);
4456
4575
  return await readWorldEditor(world);
4457
4576
  }
4458
- //#endregion
4459
- //#region src/host/sessions/world-state.ts
4577
+ // src/host/sessions/world-state.ts
4460
4578
  function sessionOf(deps, id) {
4461
4579
  const directory = deps.sessionsDir();
4462
4580
  if (!isSessionId(id) || !existsSync(sessionDatabase(directory, id))) throw new SessionNotFoundError(`no session "${id}"`);
@@ -5161,13 +5279,11 @@ async function sessionCharacterPortraitFile(deps, id, key) {
5161
5279
  size: (await stat(file)).size
5162
5280
  };
5163
5281
  }
5164
- //#endregion
5165
- //#region src/shared/avatars.ts
5282
+ // src/shared/avatars.ts
5166
5283
  /** The id under which the player avatars are served by the world editor's routes: they are edited as the cast of a world of their own. */
5167
5284
  const AVATARS_WORLD_ID = "@avatars";
5168
5285
  const AVATARS_FOLDER = "avatars";
5169
- //#endregion
5170
- //#region src/host/avatars/avatars.ts
5286
+ // src/host/avatars/avatars.ts
5171
5287
  const WORLD_FILE = "world.json";
5172
5288
  /** The folder the player avatars live in, with the file that makes it readable as a world of characters only. */
5173
5289
  async function avatarsWorld(rootPath) {
@@ -5299,8 +5415,7 @@ async function addAvatarsToWorld(avatars, world, keys, locations) {
5299
5415
  }
5300
5416
  return brought.map((entry) => entry.id);
5301
5417
  }
5302
- //#endregion
5303
- //#region src/host/agent/history.ts
5418
+ // src/host/agent/history.ts
5304
5419
  /** The unknown seq of a turn that is not in the log. */
5305
5420
  const NOT_IN_LOG = -1;
5306
5421
  /**
@@ -5383,7 +5498,7 @@ function worldFindings(session) {
5383
5498
  async function startSession(deps, request) {
5384
5499
  const world = await deps.worlds.find(request.worldId);
5385
5500
  if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${request.worldId}"`);
5386
- const { characters: authored, factions, locations, items, slots, authoredLore, declared, scripted, authoredPlots, calendar, checks } = await loadValidatedWorld(world);
5501
+ const { characters: authored, factions, locations, items, slots, authoredLore, declared, scripted, authoredPlots, calendar, checks, commands } = await loadValidatedWorld(world);
5387
5502
  if (request.opening !== void 0 && (!Number.isInteger(request.opening) || request.opening < 0 || request.opening >= (world.alternateOpenings?.length ?? 0))) throw new InvalidStartError(`the world has no alternate opening ${String(request.opening)}`);
5388
5503
  const opening = request.opening === void 0 ? openingOf(world, authored) : [{
5389
5504
  type: "narration",
@@ -5498,6 +5613,7 @@ async function startSession(deps, request) {
5498
5613
  populateTriggers(session, scripted.triggers);
5499
5614
  populatePlots(session.metadata, authoredPlots.plots);
5500
5615
  populateClock(session, settings.clock, startsAt === void 0 ? void 0 : { startingTime: startsAt }, (deps.now ?? Date.now)());
5616
+ if (commands.length > 0) session.metadata.setValue(COMMANDS_KEY, commands.map((command) => ({ ...command })));
5501
5617
  if (world.rules !== void 0) session.metadata.setValue(WORLD_RULES_KEY, world.rules);
5502
5618
  if (world.narrationVoice !== void 0) session.metadata.setValue("roleplay.tts.narrationVoice", world.narrationVoice);
5503
5619
  });
@@ -5579,8 +5695,7 @@ function openingOf(world, characters) {
5579
5695
  if (problems.length > 0) throw new InvalidWorldError(`the opening of "${world.summary.name}" has ${problems.length} problem(s)`, problems);
5580
5696
  return segments;
5581
5697
  }
5582
- //#endregion
5583
- //#region src/host/sessions/rename-session.ts
5698
+ // src/host/sessions/rename-session.ts
5584
5699
  /**
5585
5700
  * Give a session a new name, and its chat the same one.
5586
5701
  * @throws {SessionNotFoundError} when the id names no session. @throws {InvalidStartError} when the name is blank or too long.
@@ -5594,8 +5709,7 @@ async function renameSession(deps, id, name) {
5594
5709
  deps.state.openSession(directory, id).metadata.setName(trimmed);
5595
5710
  await deps.agent.rename(id, trimmed);
5596
5711
  }
5597
- //#endregion
5598
- //#region src/host/sessions/status.ts
5712
+ // src/host/sessions/status.ts
5599
5713
  const STATUS_FILE = "status.json";
5600
5714
  /**
5601
5715
  * @throws {Error} when the file is there and cannot be read as a status: it decides whether a session is shown, so it is not guessed at.
@@ -5618,8 +5732,7 @@ function writeStatus(folder, status) {
5618
5732
  writeFileSync(aside, JSON.stringify(status, null, 2));
5619
5733
  renameSync(aside, target);
5620
5734
  }
5621
- //#endregion
5622
- //#region src/host/sessions/archive-session.ts
5735
+ // src/host/sessions/archive-session.ts
5623
5736
  function folderOf$1(deps, id) {
5624
5737
  const directory = deps.sessionsDir();
5625
5738
  if (!isSessionId(id) || !existsSync(sessionDatabase(directory, id))) throw new SessionNotFoundError(`no session "${id}"`);
@@ -5647,8 +5760,7 @@ async function restoreSession(deps, id) {
5647
5760
  await deps.agent.restore(id);
5648
5761
  writeStatus(folder, {});
5649
5762
  }
5650
- //#endregion
5651
- //#region src/host/sessions/chat-settings.ts
5763
+ // src/host/sessions/chat-settings.ts
5652
5764
  function folderOf(deps, id) {
5653
5765
  const directory = deps.sessionsDir();
5654
5766
  if (!isSessionId(id) || !existsSync(sessionDatabase(directory, id))) throw new SessionNotFoundError(`no session "${id}"`);
@@ -5688,8 +5800,7 @@ function payloadOf(deps, id, settings) {
5688
5800
  ...clockMode === void 0 ? {} : { clockMode }
5689
5801
  };
5690
5802
  }
5691
- //#endregion
5692
- //#region src/host/interface/first-party.ts
5803
+ // src/host/interface/first-party.ts
5693
5804
  /** The folder of the packs shipped with the package. */
5694
5805
  const FIRST_PARTY_FOLDER = "packs";
5695
5806
  /** Found from this module, so that it works from source and from the build. */
@@ -5716,8 +5827,7 @@ function installFirstPartyPacks(root, shipped = firstPartyDirectory()) {
5716
5827
  }
5717
5828
  return installed;
5718
5829
  }
5719
- //#endregion
5720
- //#region src/host/sessions/vectors.ts
5830
+ // src/host/sessions/vectors.ts
5721
5831
  /** How many waiting texts are counted before saying "that many": the number is for reassurance, not accounting. */
5722
5832
  const MAX_COUNTED = 1e4;
5723
5833
  function vectorStatus(session) {
@@ -5739,8 +5849,7 @@ function vectorStatus(session) {
5739
5849
  function resetVectors(session) {
5740
5850
  session.recallIndex.reset();
5741
5851
  }
5742
- //#endregion
5743
- //#region src/host/authoring/pack-files.ts
5852
+ // src/host/authoring/pack-files.ts
5744
5853
  /** Where a text file of a pack is, once the pack name and the path are known to be allowed; otherwise why not. */
5745
5854
  function placeOf(directory, pack, path, tool, text = "") {
5746
5855
  if (!isPackId(pack)) throw new InvalidEditProblems([`"${pack}" is not a usable pack name (letters, digits, "-" and "_")`]);
@@ -5777,15 +5886,7 @@ async function readWorldPackFile(directory, pack, path) {
5777
5886
  async function writeWorldPackFile(directory, pack, path, text) {
5778
5887
  if (Buffer.byteLength(text) > 204800) throw new InvalidEditProblems([`a file holds at most ${MAX_PACK_TEXT / 1024} KB of text`]);
5779
5888
  const file = placeOf(directory, pack, path, "write", text);
5780
- await mkdir(dirname(file), { recursive: true });
5781
- const temporary = join(dirname(file), `.${process.pid}.${randomUUID()}.tmp`);
5782
- try {
5783
- await writeFile(temporary, text);
5784
- await rename(temporary, file);
5785
- } catch (error) {
5786
- await rm(temporary, { force: true });
5787
- throw error;
5788
- }
5889
+ await atomicWrite(file, text, { createDirectory: true });
5789
5890
  return problemsOf(directory, pack);
5790
5891
  }
5791
5892
  /** 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. */
@@ -5798,8 +5899,7 @@ async function createWorldPack(directory, pack, name) {
5798
5899
  api: 1
5799
5900
  }, null, 2)}\n`);
5800
5901
  }
5801
- //#endregion
5802
- //#region src/host/sessions/interventions.ts
5902
+ // src/host/sessions/interventions.ts
5803
5903
  /** What the story's triggers delivered lately and what became of each, oldest first. */
5804
5904
  function readInterventions(session) {
5805
5905
  const withdrawn = readWithdrawn(session);
@@ -5816,8 +5916,7 @@ function readInterventions(session) {
5816
5916
  };
5817
5917
  });
5818
5918
  }
5819
- //#endregion
5820
- //#region src/host/decisions/status.ts
5919
+ // src/host/decisions/status.ts
5821
5920
  /**
5822
5921
  * Whether a decision service is there, which one, and what was kept about how the story's decisions went.
5823
5922
  * @throws {SessionNotFoundError} for an id that names no session.
@@ -5835,8 +5934,7 @@ function decisionsOfSession(deps, id) {
5835
5934
  stats: readDecisionStats(sessionFolder(sessions, id))
5836
5935
  };
5837
5936
  }
5838
- //#endregion
5839
- //#region src/host/sessions/open-session.ts
5937
+ // src/host/sessions/open-session.ts
5840
5938
  /** Make sure a session has its DSH chat, so that it can be opened. */
5841
5939
  async function openSession(deps, id, options = {}) {
5842
5940
  if (!isSessionId(id) || !existsSync(sessionDatabase(deps.sessionsDir(), id))) throw new SessionNotFoundError(`no session "${id}"`);
@@ -5863,8 +5961,7 @@ async function openSession(deps, id, options = {}) {
5863
5961
  chatSessionId: chatSessionId$1
5864
5962
  };
5865
5963
  }
5866
- //#endregion
5867
- //#region src/host/sessions/list-sessions.ts
5964
+ // src/host/sessions/list-sessions.ts
5868
5965
  /** The sessions on disk, the most recently played first; a session never played counts from its creation. */
5869
5966
  function listSessions(deps) {
5870
5967
  const directory = deps.sessionsDir();
@@ -5902,8 +5999,7 @@ function listSessions(deps) {
5902
5999
  }))
5903
6000
  };
5904
6001
  }
5905
- //#endregion
5906
- //#region src/host/sessions/local-time.ts
6002
+ // src/host/sessions/local-time.ts
5907
6003
  /** An instant as the local date and time in a zone, written the way a world file writes it: `2024-05-01T08:00:00`. */
5908
6004
  function localInstant(instant, zone) {
5909
6005
  const parts = new Intl.DateTimeFormat("en-CA", {
@@ -5919,8 +6015,7 @@ function localInstant(instant, zone) {
5919
6015
  const part = (type) => parts.find((entry) => entry.type === type)?.value ?? "00";
5920
6016
  return `${part("year")}-${part("month")}-${part("day")}T${part("hour")}:${part("minute")}:${part("second")}`;
5921
6017
  }
5922
- //#endregion
5923
- //#region src/host/sessions/world-characters.ts
6018
+ // src/host/sessions/world-characters.ts
5924
6019
  /**
5925
6020
  * The cast of a world, as the start dialog needs it.
5926
6021
  * @throws {WorldNotFoundError} when no world has that id.
@@ -5949,8 +6044,7 @@ async function worldCharacters(worlds, worldId) {
5949
6044
  problems
5950
6045
  };
5951
6046
  }
5952
- //#endregion
5953
- //#region src/host/storage/roleplay-root.ts
6047
+ // src/host/storage/roleplay-root.ts
5954
6048
  /** Owns the roleplay root directory and keeps its baseline layout in place. */
5955
6049
  var RoleplayRoot = class extends Service {
5956
6050
  source;
@@ -5994,8 +6088,7 @@ var RoleplayRoot = class extends Service {
5994
6088
  }
5995
6089
  }
5996
6090
  };
5997
- //#endregion
5998
- //#region src/host/worlds/world-id.ts
6091
+ // src/host/worlds/world-id.ts
5999
6092
  /** The indentation the file already uses, so adding the id does not reformat it. */
6000
6093
  function indentOf(text) {
6001
6094
  return /^([ \t]+)"/m.exec(text)?.[1] ?? " ";
@@ -6017,20 +6110,10 @@ function withWorldId(text, id) {
6017
6110
  */
6018
6111
  async function assignWorldId(file) {
6019
6112
  const id = randomUUID();
6020
- const temporary = join(dirname(file), `.${basename(file)}.${process.pid}.tmp`);
6021
- try {
6022
- const { mode } = await stat(file);
6023
- await writeFile(temporary, withWorldId(await readFile(file, "utf8"), id), { mode });
6024
- await chmod(temporary, mode);
6025
- await rename(temporary, file);
6026
- } catch (error) {
6027
- await rm(temporary, { force: true });
6028
- throw error;
6029
- }
6113
+ await atomicWrite(file, withWorldId(await readFile(file, "utf8"), id));
6030
6114
  return id;
6031
6115
  }
6032
- //#endregion
6033
- //#region src/host/worlds/scan.ts
6116
+ // src/host/worlds/scan.ts
6034
6117
  /** Where a world bundle lists its media files. */
6035
6118
  const MEDIA_MANIFEST = "media/manifest.jsonl";
6036
6119
  /** Raster formats only: they cannot carry script when opened directly. */
@@ -6113,7 +6196,8 @@ async function loadWorld(folder, dir, file, problems) {
6113
6196
  description: world.description,
6114
6197
  tags: world.tags,
6115
6198
  ...world.author === void 0 ? {} : { author: world.author },
6116
- ...world.version === void 0 ? {} : { version: world.version }
6199
+ ...world.version === void 0 ? {} : { version: world.version },
6200
+ ...await isDraftWorld(dir) ? { draft: true } : {}
6117
6201
  },
6118
6202
  ...world.opening === void 0 ? {} : { opening: world.opening },
6119
6203
  ...world.clock === void 0 ? {} : { clock: world.clock },
@@ -6186,8 +6270,7 @@ async function resolveCover(worldDir, mediaId) {
6186
6270
  version: `${Math.trunc(info.mtimeMs).toString(36)}-${info.size.toString(36)}`
6187
6271
  };
6188
6272
  }
6189
- //#endregion
6190
- //#region src/host/worlds/catalog.ts
6273
+ // src/host/worlds/catalog.ts
6191
6274
  /** Worlds found under the roleplay root. Read lazily, kept until refreshed or the root moves. */
6192
6275
  var WorldCatalog = class extends Service {
6193
6276
  root;
@@ -6251,8 +6334,7 @@ var WorldCatalog = class extends Service {
6251
6334
  return run;
6252
6335
  }
6253
6336
  };
6254
- //#endregion
6255
- //#region src/host/catalogue/zip.ts
6337
+ // src/host/catalogue/zip.ts
6256
6338
  const END_SIGNATURE = 101010256;
6257
6339
  const CENTRAL_SIGNATURE = 33639248;
6258
6340
  const LOCAL_SIGNATURE = 67324752;
@@ -6333,8 +6415,7 @@ function readZip(archive, limits) {
6333
6415
  }
6334
6416
  return files;
6335
6417
  }
6336
- //#endregion
6337
- //#region src/host/catalogue/install.ts
6418
+ // src/host/catalogue/install.ts
6338
6419
  const FOLDER_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
6339
6420
  const MAX_FOLDER_COPIES = 99;
6340
6421
  /** The one top-level folder of a world archive and the files in it, or why the archive is not a world. */
@@ -6449,8 +6530,7 @@ async function installWorld(catalog, archive, maxBytes, options) {
6449
6530
  });
6450
6531
  }
6451
6532
  }
6452
- //#endregion
6453
- //#region src/host/catalogue/trash.ts
6533
+ // src/host/catalogue/trash.ts
6454
6534
  const DAY_MS = 864e5;
6455
6535
  const STAMP = /-(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z$/;
6456
6536
  /** Staging folders left by an interrupted install are removed after this long. */
@@ -6499,8 +6579,7 @@ async function pruneTrash(root, keepDays, now = Date.now()) {
6499
6579
  failures
6500
6580
  };
6501
6581
  }
6502
- //#endregion
6503
- //#region src/host/catalogue/transport.ts
6582
+ // src/host/catalogue/transport.ts
6504
6583
  const TIMEOUT_MS = 6e4;
6505
6584
  const MAX_REDIRECTS = 5;
6506
6585
  const nodeTransport = (url, ask) => new Promise((resolveReply, reject) => {
@@ -6996,8 +7075,7 @@ var Catalogue = class {
6996
7075
  }
6997
7076
  }
6998
7077
  };
6999
- //#endregion
7000
- //#region src/host/catalogue/sources.ts
7078
+ // src/host/catalogue/sources.ts
7001
7079
  /** A web address with no credentials, query or fragment, or the reason it is not one. */
7002
7080
  function parseBase(text) {
7003
7081
  let url;
@@ -7141,8 +7219,7 @@ var Sources = class {
7141
7219
  return best?.source;
7142
7220
  }
7143
7221
  };
7144
- //#endregion
7145
- //#region src/shared/sync.ts
7222
+ // src/shared/sync.ts
7146
7223
  const DEFAULT_SYNC = {
7147
7224
  remote: "",
7148
7225
  rclone: "",
@@ -7150,8 +7227,7 @@ const DEFAULT_SYNC = {
7150
7227
  passwordRef: "",
7151
7228
  intervalMinutes: 0
7152
7229
  };
7153
- //#endregion
7154
- //#region src/host/sync/gate.ts
7230
+ // src/host/sync/gate.ts
7155
7231
  /**
7156
7232
  * Which units are being synced. A locked unit is neither written nor read until it is released, so rclone never sees a half-written
7157
7233
  * unit and the app never sees a half-downloaded one.
@@ -7187,8 +7263,7 @@ var UnitGate = class {
7187
7263
  }
7188
7264
  }
7189
7265
  };
7190
- //#endregion
7191
- //#region src/host/sync/rclone.ts
7266
+ // src/host/sync/rclone.ts
7192
7267
  /** Runs the rclone the person named, with their configuration file, as a child of this process. */
7193
7268
  function spawnRclone(setup) {
7194
7269
  return { run: (args, options = {}) => new Promise((resolve, reject) => {
@@ -7232,14 +7307,25 @@ function spawnRclone(setup) {
7232
7307
  child.stdin.end(options.input ?? "");
7233
7308
  }) };
7234
7309
  }
7235
- /** What rclone said went wrong: its last error line, without the time and the colours, cut short. */
7310
+ const CHANGED_IN_TRANSIT = /corrupted on transfer: sizes? differ/;
7311
+ /** The files rclone named as arriving a different size than the server listed, up to a few. */
7312
+ function changedFiles(lines) {
7313
+ const names = lines.flatMap((line) => {
7314
+ const found = /^ERROR\s*: (.+?): .*corrupted on transfer/.exec(line);
7315
+ return found === null ? [] : [found[1]];
7316
+ });
7317
+ return [...new Set(names)].slice(0, 3);
7318
+ }
7319
+ /** What rclone said went wrong: its last error line, without the time and the colours, cut short. A file that arrives a different size than the server listed says what usually causes it. */
7236
7320
  function why(result) {
7237
7321
  const lines = (result.stderr || result.stdout).split("\n").map((line) => line.replace(/\u001b\[[0-9;]*m/g, "").replace(/^\d{4}\/\d\d\/\d\d \d\d:\d\d:\d\d /, "").trim()).filter((line) => line !== "");
7238
7322
  const line = lines.findLast((entry) => /^(ERROR|NOTICE: Failed|CRITICAL)/.test(entry)) ?? lines.at(-1) ?? `rclone stopped with code ${result.code}`;
7239
- return line.length > 300 ? `${line.slice(0, 300)}…` : line;
7323
+ const shown = line.length > 300 ? `${line.slice(0, 300)}…` : line;
7324
+ if (!CHANGED_IN_TRANSIT.test(line)) return shown;
7325
+ const files = changedFiles(lines);
7326
+ return `${shown} — something between this device and the server changes files on the way${files.length === 0 ? "" : ` (${files.join(", ")})`}; a proxy or CDN that adds content to HTML pages is the usual cause: turn off its response rewriting for the server, or reach the server directly`;
7240
7327
  }
7241
- //#endregion
7242
- //#region src/host/sync/state.ts
7328
+ // src/host/sync/state.ts
7243
7329
  const syncFolder = (root) => join(root, ".sync");
7244
7330
  /** What this device remembers about its syncing; it lives beside the root's content but is never a unit, so it is never synced. */
7245
7331
  function readStore(root) {
@@ -7267,8 +7353,7 @@ function writeStore(root, store) {
7267
7353
  writeFileSync(temporary, `${JSON.stringify(store, null, 2)}\n`);
7268
7354
  renameSync(temporary, join(folder, "state.json"));
7269
7355
  }
7270
- //#endregion
7271
- //#region src/host/sync/units.ts
7356
+ // src/host/sync/units.ts
7272
7357
  /** Folders of the root that are one unit each, whatever they hold. */
7273
7358
  const SHARED_UNITS = [
7274
7359
  "prompts",
@@ -7333,8 +7418,7 @@ async function conflictFiles(directory) {
7333
7418
  await walk("");
7334
7419
  return found.sort((left, right) => left.localeCompare(right));
7335
7420
  }
7336
- //#endregion
7337
- //#region src/host/sync/service.ts
7421
+ // src/host/sync/service.ts
7338
7422
  const DIVERGED = {
7339
7423
  none: void 0,
7340
7424
  first: "both sides have this and it was never synced here",
@@ -7941,8 +8025,7 @@ var SyncService = class {
7941
8025
  }
7942
8026
  }
7943
8027
  };
7944
- //#endregion
7945
- //#region src/host/sync/wire.ts
8028
+ // src/host/sync/wire.ts
7946
8029
  /** The folder that a request to the API writes or reads, if it is one of the syncable ones. */
7947
8030
  async function unitsOf(url, worlds) {
7948
8031
  const path = url.pathname.slice(`/${API_PREFIX}`.length);
@@ -8050,18 +8133,23 @@ function createSync(ctx, wiring) {
8050
8133
  locked: async (url) => (await unitsOf(url, wiring.worlds)).find((unit) => gate.isLocked(unit))
8051
8134
  };
8052
8135
  }
8053
- //#endregion
8054
- //#region src/host/speech/service.ts
8136
+ // src/host/speech/service.ts
8055
8137
  async function voicesOf(service) {
8056
8138
  return await service.voices();
8057
8139
  }
8058
8140
  /** Synthesize independently so every speaker keeps its voice, then join the audio in story order. */
8059
8141
  async function speakParts(service, parts) {
8060
8142
  if (parts.length === 0 || parts.some((part) => part.text.trim() === "")) throw new RangeError("speech needs non-empty text");
8061
- const results = await Promise.all(parts.map(async (part) => await service.synthesize(part.text, part.voice === void 0 || part.voice.trim() === "" ? {} : { voice: part.voice.trim() })));
8143
+ const results = await Promise.all(parts.map(async (part) => {
8144
+ const result = await service.synthesize(part.text, part.voice === void 0 || part.voice.trim() === "" ? {} : { voice: part.voice.trim() });
8145
+ return {
8146
+ mediaType: result.mediaType,
8147
+ bytes: new Uint8Array(await new Response(result.audio).arrayBuffer())
8148
+ };
8149
+ }));
8062
8150
  const mediaType = results[0].mediaType;
8063
8151
  if (results.some((result) => result.mediaType !== mediaType)) throw new Error("the speech provider returned incompatible audio formats");
8064
- const buffers = await Promise.all(results.map(async (result) => new Uint8Array(await new Response(result.audio).arrayBuffer())));
8152
+ const buffers = results.map((result) => result.bytes);
8065
8153
  if (mediaType === "audio/wav" || mediaType === "audio/x-wav") return {
8066
8154
  bytes: mergeWav(buffers),
8067
8155
  mediaType
@@ -8143,15 +8231,16 @@ const Config = z.object({
8143
8231
  importReasoning: z.string().default("").volatile(),
8144
8232
  childReasoning: z.string().default("").volatile(),
8145
8233
  importModel: z.string().default("").volatile(),
8146
- importMaxTokens: z.number().min(1e3).max(2e5).default(16e3).volatile(),
8234
+ importStructuredOutput: z.union(["tool", "schema"]).default("schema").volatile(),
8235
+ importMaxTokens: z.number().min(0).max(1e6).default(0).volatile(),
8236
+ importVariablesPerRequest: z.number().min(5).max(500).default(25).volatile(),
8147
8237
  importTemperature: z.number().min(0).max(2).default(.2).volatile(),
8148
8238
  importTimeoutMinutes: z.number().min(0).max(240).default(15).volatile(),
8149
8239
  importDecisions: z.union([z.const("llm"), z.const("decision")]).default("llm").volatile(),
8150
8240
  importConfidence: z.number().min(0).max(1).default(.7).volatile(),
8151
8241
  authoringApproval: z.union([z.const("ask"), z.const("auto")]).default("ask").volatile()
8152
8242
  });
8153
- //#endregion
8154
- //#region src/index.ts
8243
+ // src/index.ts
8155
8244
  const name = "@dsh-agentic-roleplay/core";
8156
8245
  /** Sessions are kept by the state plugin, which the bundle installs with this one. */
8157
8246
  const inject = ["roleplayState"];
@@ -8167,7 +8256,7 @@ function apply(ctx, config) {
8167
8256
  const helper = childSamplingOf(id);
8168
8257
  if (helper !== void 0) return helper;
8169
8258
  if (authoredWorldOf(id) !== void 0 || presetOfChat(id) !== void 0 || lorebookOfChat(id) !== void 0) return {
8170
- maxTokens: config.importMaxTokens.get(),
8259
+ maxTokens: knownOutputCeiling(config.importMaxTokens.get()),
8171
8260
  priority: "foreground"
8172
8261
  };
8173
8262
  const session = roleplaySessionOf(id);
@@ -8207,6 +8296,8 @@ function apply(ctx, config) {
8207
8296
  reasoning: config.importReasoning.get() || config.childReasoning.get(),
8208
8297
  model: config.importModel.get(),
8209
8298
  maxTokens: config.importMaxTokens.get(),
8299
+ variablesPerRequest: config.importVariablesPerRequest.get(),
8300
+ structured: config.importStructuredOutput.get(),
8210
8301
  temperature: config.importTemperature.get(),
8211
8302
  timeoutMinutes: config.importTimeoutMinutes.get(),
8212
8303
  decisions: config.importDecisions.get() === "decision" ? "decision" : "llm",
@@ -8368,7 +8459,28 @@ function apply(ctx, config) {
8368
8459
  choose: (id, choices) => imports.choose(id, choices),
8369
8460
  discard: (id) => imports.discard(id),
8370
8461
  start: begin,
8462
+ importStructure: async (id, choices, language) => {
8463
+ const done = await importWithoutModel({
8464
+ store: imports,
8465
+ worlds
8466
+ }, id, choices, language);
8467
+ await worlds.list({ refresh: true });
8468
+ return {
8469
+ worldId: done.worldId,
8470
+ draft: done.draft
8471
+ };
8472
+ },
8371
8473
  picture: (id) => imports.picture(id),
8474
+ resume: (worldId, language) => resumeImport({
8475
+ worlds,
8476
+ authoring
8477
+ }, worldId, language),
8478
+ draftStatus: (worldId) => draftStatus(worlds, worldId),
8479
+ actOnDraft: (worldId, action, language) => actOnDraft({
8480
+ worlds,
8481
+ authoring,
8482
+ root: () => root.path
8483
+ }, worldId, action, language),
8372
8484
  updateStatus: async (worldId) => await updateStatus((await editableWorld(worlds, worldId, root.path)).directory),
8373
8485
  revertUpdate: async (worldId) => {
8374
8486
  const directory = (await editableWorld(worlds, worldId, root.path)).directory;
@@ -8663,7 +8775,6 @@ function timelinesOf(ctx, sessionsDir, id) {
8663
8775
  if (timelines === void 0) throw new AgentUnavailableError("the story cannot be taken back: the orchestration is not running");
8664
8776
  return timelines;
8665
8777
  }
8666
- //#endregion
8667
8778
  export { Config, RoleplayOrchestration, apply, inject, name };
8668
8779
 
8669
8780
  //# sourceMappingURL=index.js.map