@dsh-agentic-roleplay/core 0.8.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/lib/{access-DtOxFKBK.js → access-CfQWbNZP.js} +4 -7
  2. package/lib/{authoring-tools-DNnx0Nts.js → authoring-tools-CdHlvx32.js} +2125 -152
  3. package/lib/authoring.js +143 -47
  4. package/lib/{child-D6mpkkCE.js → child-lYYeOwl2.js} +28 -51
  5. package/lib/client.js +611 -774
  6. package/lib/client.js.map +1 -1
  7. package/lib/compaction.js +8 -13
  8. package/lib/{doctor-chat-ByDfCMeo.js → doctor-chat-hL1a61hp.js} +2 -3
  9. package/lib/doctor.js +6 -8
  10. package/lib/{gallery-D9nG3C78.js → gallery-BKh7eu80.js} +3 -4
  11. package/lib/{generator-r1Czm7oi.js → generator-DdZ1-sgv.js} +3 -4
  12. package/lib/helper.js +2 -3
  13. package/lib/{hooks-BQCzgggH.js → hooks-CcQj_dJo.js} +69 -97
  14. package/lib/images.js +4 -4
  15. package/lib/index.js +195 -265
  16. package/lib/{library-zI-2tG7h.js → library-QFL6Z_Nr.js} +9 -15
  17. package/lib/{lorebook-author-tools-ywaYicwd.js → lorebook-author-tools-DWBnYo1E.js} +10 -13
  18. package/lib/lorebook-authoring.js +5 -6
  19. package/lib/{narration-CnBlVure.js → narration-CjB_KwwY.js} +9 -15
  20. package/lib/orchestration.js +53 -64
  21. package/lib/{pack-jail-5EJ-WYyW.js → pack-jail-BMy6NcCY.js} +81 -788
  22. package/lib/{packs-Cv8hanXJ.js → packs-BREPSfHy.js} +6 -10
  23. package/lib/{presenter-agent-BSaMSd3G.js → presenter-agent-B49-_iUm.js} +12 -18
  24. package/lib/{preset-CWI3-0r1.js → preset-BqgY1Tz4.js} +5 -6
  25. package/lib/{preset-author-tools-BrJYa2cr.js → preset-author-tools-BB_Dcv2o.js} +12 -14
  26. package/lib/preset-authoring.js +6 -7
  27. package/lib/{presets-MwOSMMyu.js → presets-Bwnrx7p0.js} +69 -63
  28. package/lib/{reflection-zSaMsjKj.js → reflection-CUWG-6Qg.js} +19 -30
  29. package/lib/{text-BzudpQLS.js → text-CbGQhK1-.js} +9 -10
  30. package/lib/{turn-guard-Cv8pfHEA.js → turn-guard-Bb8Ew-1z.js} +6 -11
  31. package/package.json +29 -29
  32. package/prompts/en/checks/decide-sheet.md +1 -0
  33. package/prompts/en/checks/fidelity.md +7 -0
  34. package/prompts/en/checks/gaps.md +4 -0
  35. package/prompts/en/checks/notice.md +3 -0
  36. package/prompts/en/import/casting.md +1 -1
  37. package/prompts/en/import/character.md +1 -0
  38. package/prompts/en/import/finish-draft.md +1 -1
  39. package/prompts/en/import/finish-ok.md +3 -1
  40. package/prompts/en/import/notice-repair.md +2 -2
  41. package/prompts/en/import/repair-again.md +2 -2
  42. package/prompts/zh/checks/decide-sheet.md +1 -0
  43. package/prompts/zh/checks/fidelity.md +7 -0
  44. package/prompts/zh/checks/gaps.md +4 -0
  45. package/prompts/zh/checks/notice.md +3 -0
  46. package/prompts/zh/import/casting.md +1 -1
  47. package/prompts/zh/import/character.md +1 -0
  48. package/prompts/zh/import/finish-draft.md +1 -1
  49. package/prompts/zh/import/finish-ok.md +3 -1
  50. package/prompts/zh/import/notice-repair.md +2 -2
  51. package/prompts/zh/import/repair-again.md +2 -2
package/lib/index.js CHANGED
@@ -1,20 +1,20 @@
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 knowsCharacter, At as loadCharacters, B as deleteLorebook, Bt as authoredWorldOf, Ct as DICE_FILE_NAME, D as guardedLookup, Dt as loadCalendar, Et as CALENDAR_FILE_NAME, F as WORLD_FILE_NAME, Ft as pictureOf, G as loadLorebook, H as entriesOf, I as parseWorldFile, It as readCard, J as reserveLorebook, K as lorebookDirectory, L as parseWorldInfoEdit, Lt as DICE_COMPARISONS, Mt as knownOutputCeiling, Nt as ImportCardError, Ot as parseCalendarFile, Pt as isPng, Q as loadValidatedWorld, R as addLorebookEntries, Rt as DICE_READINGS, S as CatalogueError, Tt as parseDiceFile, U as isLorebookName, V as deleteLorebookEntry, W as listLorebooks, X as writeLorebookEntry, Y as updateLorebookInfo, Z as checkWorld, _ as hashWorld, at as populateItems, b as readOrigin, bt as loadItems, c as importPhase, ct as populateLore, d as markReady, dt as populateVariables, et as populateCalendar, f as settleDraft, ft as routineProblems, g as describeChanges, it as populateFactions, jt as subfolders, k as vetUrl, kt as CHARACTERS_DIR, lt as populateRoutines, nt as populateClock, ot as populateKnowledge, pt as TRIGGERS_FILE_NAME, rt as populateDice, st as populateLocations, t as AuthoringTools, tt as populateCharacters, u as keepDraft, ut as populateTriggers, v as isUnchanged, vt as loadLocations, wt as loadDice, x as writeOrigin, y as localChanges, z as createLorebook, zt as DICE_RESULTS } from "./authoring-tools-DNnx0Nts.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-ywaYicwd.js";
4
- import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-BrJYa2cr.js";
5
- import { B as readWorldPrompt, Ct as parseLoreEdit, Dt as LORE_KINDS, Et as parseThingEdit, G as withPlayer, J as ImportStore, K as IMPORT_FOLDER, Ot as LORE_SCOPES, R as deleteWorldPrompt, St as parseFactionEdit, Tt as parseRelationEdit, V as writeWorldPrompt, W as partsOf, Z as parseChoices, _t as parseCharacterFile, a as isPresetName, at as variableProblems, bt as InvalidEditProblems, c as presetDirectory, d as savePresetFromWorld, et as IMPORT_COMMAND, gt as CHARACTER_FILE_NAME, i as deletePreset, it as parseVariablesFile, nt as VARIABLES_FILE_NAME, o as listPresets, p as updatePresetInfo, q as ImportNotFoundError, r as createPresetFromShipped, rt as loadVariables, s as loadPreset, t as PRESET_FILE, u as reservePreset, wt as parsePlaceEdit, xt as parseCharacterEdit, z as listWorldPrompts } from "./presets-MwOSMMyu.js";
6
- 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-zSaMsjKj.js";
7
- 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-CnBlVure.js";
8
- import { $ as copyWorldPrompts, C as notesOfSession, H as parsePlotsFile, J as formatIssue, K as readDocument, M as PLOTS_METADATA_KEY, N as plotProgressOf, P as populatePlots, Q as PromptLibrary, S as addToNote, T as observeAsPlayer, U as plotReferenceProblems, W as COMMANDS_KEY, Y as errorMessage, _ as readActivity, ct as InvalidStartError, dt as SessionArchivedError, ft as SessionNotFoundError, g as readDecisionStats, h as readUsage, i as externalTools, it as shippedLanguages, k as zoneOf, lt as InvalidWorldError, pt as WorldNotFoundError, st as AgentUnavailableError, tt as languageOf, ut as ReflectionRefusedError, v as readRunDetail, w as readNotes, x as readWithdrawn } from "./hooks-BQCzgggH.js";
9
- import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-BzudpQLS.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-5EJ-WYyW.js";
11
- import { d as sharedSamplingOf, i as childSamplingOf, u as parseSampling } from "./child-D6mpkkCE.js";
12
- import { S as slug, d as sceneImagePath, s as inheritImages, t as addToLibrary, u as referenceImagePath, w as uniqueKey } from "./library-zI-2tG7h.js";
13
- import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-CWI3-0r1.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-Cv8hanXJ.js";
16
- import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-r1Czm7oi.js";
17
- import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-D9nG3C78.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 WORLD_FILE_NAME, $t as pictureOf, At as routineProblems, B as localChanges, Ct as populateItems, Dt as populateRoutines, Et as populateLore, Gt as loadCalendar, H as writeOrigin, Ht as loadDice, It as loadLocations, J as guardedLookup, Jt as loadCharacters, Kt as parseCalendarFile, L as describeChanges, Ot as populateTriggers, Qt as isPng, R as hashWorld, Rt as loadItems, St as populateFactions, T as loadWorldParts, Tt as populateLocations, U as CatalogueError, Ut as parseDiceFile, V as readOrigin, Vt as DICE_FILE_NAME, Wt as CALENDAR_FILE_NAME, X as vetUrl, Xt as knownOutputCeiling, Yt as subfolders, Zt as ImportCardError, _t as knowsCharacter, at as deleteLorebookEntry, bt as populateClock, c as importPhase, ct as listLorebooks, d as markReady, en as readCard, et as parseWorldFile, f as settleDraft, ft as reserveLorebook, gt as loadValidatedWorld, ht as checkWorld, in as authoredWorldOf, it as deleteLorebook, jt as TRIGGERS_FILE_NAME, kt as populateVariables, lt as loadLorebook, mt as writeLorebookEntry, nn as DICE_READINGS, nt as addLorebookEntries, ot as entriesOf, p as structureImport, pt as updateLorebookInfo, qt as CHARACTERS_DIR, rn as DICE_RESULTS, rt as createLorebook, st as isLorebookName, t as AuthoringTools, tn as DICE_COMPARISONS, tt as parseWorldInfoEdit, u as keepDraft, ut as lorebookDirectory, v as editWorldInfo, vt as populateCalendar, wt as populateKnowledge, xt as populateDice, y as readWorldInfo, yt as populateCharacters, z as isUnchanged } from "./authoring-tools-CdHlvx32.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-DWBnYo1E.js";
4
+ import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-BB_Dcv2o.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 { $ as DOCTOR_OPENING_SOURCE, A as worldEntityImageFile, B as languageOfDocuments, C as readWorldEditor, D as uploadWorldCharacterPortrait, E as replaceFile, F as PRESET_FILE, G as revertUpdate, H as findTargets, I as presetMessage, J as AuthoringSessions, K as startUpdate, O as uploadWorldEntityImage, Q as agentServicesOf, R as translateMessage, S as generateWorldEntityImage, T as removeWorldTrigger, V as readWorldDocuments, X as ensureAuthoringChat, Y as authoringTitle, Z as AgentSessions, _ as editWorldPlots$1, a as deleteWorldPackFile, b as entityFolder, c as createAuthoredEntity, et as appendEmptyTurn, f as editWorldCharacter$1, g as editWorldPlace$1, h as editWorldNarrationVoice, j as writeWorldTrigger, k as worldCharacterPortraitFile, l as deleteAuthoredEntity, m as editWorldLore$1, n as packFileProblem, p as editWorldFaction$1, q as updateStatus, t as MAX_PACK_TEXT, tt as appendNarratedTurn, u as readAuthoredEntityDocument, v as editWorldRelation$1, w as readWorldTrigger, x as generateWorldCharacterPortrait, y as editWorldThing$1 } from "./pack-jail-BMy6NcCY.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-CcQj_dJo.js";
9
+ import { $ as ImportNotFoundError, At as parseLoreEdit, Ct as CHARACTER_FILE_NAME, Dt as InvalidEditProblems, Ft as LORE_SCOPES, G as listWorldPrompts, K as readWorldPrompt, Mt as parseRelationEdit, Nt as parseThingEdit, Ot as parseCharacterEdit, Pt as LORE_KINDS, Q as IMPORT_FOLDER, W as deleteWorldPrompt, X as partsOf, Z as withPlayer, a as isPresetName, c as presetDirectory, d as savePresetFromWorld, dt as parseVariablesFile, et as ImportStore, ft as variableProblems, i as deletePreset, jt as parsePlaceEdit, kt as parseFactionEdit, lt as VARIABLES_FILE_NAME, 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 loadVariables, wt as parseCharacterFile } from "./presets-Bwnrx7p0.js";
10
+ import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-CbGQhK1-.js";
11
+ import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-BqgY1Tz4.js";
12
+ import { S as slug, d as sceneImagePath, s as inheritImages, t as addToLibrary, u as referenceImagePath, w as uniqueKey } from "./library-QFL6Z_Nr.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-CUWG-6Qg.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-BREPSfHy.js";
16
+ import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-DdZ1-sgv.js";
17
+ import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-BKh7eu80.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";
@@ -26,11 +26,11 @@ import { Service } from "@deepseek-ai/cordis";
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";
29
- import { pipeline } from "node:stream/promises";
30
29
  import { homedir } from "node:os";
30
+ import { pipeline } from "node:stream/promises";
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,7 @@ var RoleplayImport = class extends Service {
76
75
  return this.read();
77
76
  }
78
77
  };
79
- //#endregion
80
- //#region src/host/worlds/draft.ts
78
+ // src/host/worlds/draft.ts
81
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. */
82
80
  async function isDraftWorld(directory) {
83
81
  try {
@@ -87,8 +85,7 @@ async function isDraftWorld(directory) {
87
85
  throw error;
88
86
  }
89
87
  }
90
- //#endregion
91
- //#region src/host/worlds/create-world.ts
88
+ // src/host/worlds/create-world.ts
92
89
  const FOLDER = /^[\p{L}\p{N}][\p{L}\p{N}._ -]{0,99}$/u;
93
90
  var WorldFolderExistsError = class extends Error {};
94
91
  /** Create the smallest valid authored world, exclusively, then make the catalogue see it. */
@@ -129,8 +126,7 @@ async function createWorld(catalog, input) {
129
126
  if (created === void 0) throw new Error(`created world "${name}" but it was not found when the catalogue refreshed`);
130
127
  return created;
131
128
  }
132
- //#endregion
133
- //#region src/host/import/start-import.ts
129
+ // src/host/import/start-import.ts
134
130
  const FOLDER_CHARS = /[^\p{L}\p{N}._ -]+/gu;
135
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. */
136
132
  function folderNameOf(name) {
@@ -169,11 +165,8 @@ async function resumeImport(deps, worldId, language) {
169
165
  ...failure === void 0 ? {} : { failure }
170
166
  };
171
167
  }
172
- /**
173
- * 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.
174
- * @throws {InvalidEditProblems} when the choices cannot be used. @throws {ImportNotFoundError} when the upload is gone.
175
- */
176
- async function startImport(deps, id, choices, language) {
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) {
177
170
  await deps.store.choose(id, choices);
178
171
  let world;
179
172
  const base = folderNameOf(choices.name);
@@ -192,6 +185,17 @@ async function startImport(deps, id, choices, language) {
192
185
  if (record === void 0) throw new WorldNotFoundError(`the world "${world.name}" was made but cannot be found`);
193
186
  await deps.store.adopt(id, record.directory);
194
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);
195
199
  const chatSessionId = await deps.authoring.ensure(world.id, world.name, authoringTitle(world.name, language), language);
196
200
  let failure;
197
201
  try {
@@ -206,8 +210,20 @@ async function startImport(deps, id, choices, language) {
206
210
  ...failure === void 0 ? {} : { failure }
207
211
  };
208
212
  }
209
- //#endregion
210
- //#region src/host/import/draft.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
211
227
  async function draftOf(worlds, worldId) {
212
228
  const record = await worlds.find(worldId);
213
229
  if (record === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
@@ -256,8 +272,7 @@ async function actOnDraft(deps, worldId, action, language) {
256
272
  keptIn: relative(deps.root(), destination)
257
273
  };
258
274
  }
259
- //#endregion
260
- //#region src/host/translate/service.ts
275
+ // src/host/translate/service.ts
261
276
  async function recordOf(worlds, id) {
262
277
  const record = await worlds.find(id);
263
278
  if (record === void 0) throw new WorldNotFoundError(`there is no world with id "${id}"`);
@@ -289,8 +304,7 @@ async function startTranslation(deps, id, to, title, language) {
289
304
  };
290
305
  }
291
306
  }
292
- //#endregion
293
- //#region src/host/presets/verbatim.ts
307
+ // src/host/presets/verbatim.ts
294
308
  /**
295
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).
296
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
@@ -306,8 +320,7 @@ function verbatimStyle(file, fileName) {
306
320
  text
307
321
  };
308
322
  }
309
- //#endregion
310
- //#region src/host/import/upload-preset.ts
323
+ // src/host/import/upload-preset.ts
311
324
  /**
312
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.
313
326
  * @throws {ImportCardError} when the file is not a preset. @throws {WorldNotFoundError} when the world does not exist.
@@ -317,7 +330,7 @@ async function uploadPreset(deps, worldId, file, name, language) {
317
330
  if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
318
331
  const preset = readPreset(file, name);
319
332
  await mkdir(join(world.directory, IMPORT_FOLDER), { recursive: true });
320
- await writeFile(join(world.directory, IMPORT_FOLDER, PRESET_FILE$1), file);
333
+ await writeFile(join(world.directory, IMPORT_FOLDER, PRESET_FILE), file);
321
334
  const chatSessionId = await deps.authoring.ensure(world.summary.id, world.summary.name, authoringTitle(world.summary.name, language), language);
322
335
  let failure;
323
336
  try {
@@ -359,8 +372,7 @@ async function applyPresetVerbatim(deps, worldId, file, name) {
359
372
  replaced
360
373
  };
361
374
  }
362
- //#endregion
363
- //#region src/host/import/staging.ts
375
+ // src/host/import/staging.ts
364
376
  const KEEP_MS = 36e5;
365
377
  const MAX_STAGED = 12;
366
378
  /**
@@ -425,10 +437,12 @@ function parseSelectionChoice(body) {
425
437
  sampling: sampling !== false
426
438
  };
427
439
  }
428
- //#endregion
429
- //#region src/host/agent/preset-authoring-sessions.ts
430
- const PRESET_AUTHORING_PROJECT_TITLE = "Preset Authoring";
431
- 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
+ };
432
446
  /** Creates or reopens the dedicated authoring chat of a library preset, and speaks in it for the person when asked to. */
433
447
  var PresetAuthoringSessions = class {
434
448
  services;
@@ -442,28 +456,14 @@ var PresetAuthoringSessions = class {
442
456
  this.languages = languages;
443
457
  }
444
458
  async ensure(name, title, language) {
445
- this.languages.set(`preset:${name}`, language);
446
- const services = this.services();
447
- const projectPath = join(this.roleplayRoot(), "presets");
448
- const project = await services.registry.create(projectPath, PRESET_AUTHORING_PROJECT_TITLE);
449
- const sessionId = presetChatSessionId(name);
450
- const stored = !project.sessionIds.includes(sessionId) && await isStored(services.persistence, sessionId);
451
- if (!project.sessionIds.includes(sessionId) && !stored) {
452
- if (services.persistence === void 0) throw new AgentUnavailableError("this DSH profile cannot store the opening of an authoring chat");
453
- await storeAuthoringOpening(services.persistence, {
454
- id: sessionId,
455
- cwd: project.path,
456
- agentPreset: PRESET_AUTHORING_PRESET
457
- }, this.prompts.text("preset/welcome", this.languages.get(`preset:${name}`), { preset: title }));
458
- }
459
- return await ensureAgentChat(services, {
460
- projectPath,
461
- projectTitle: PRESET_AUTHORING_PROJECT_TITLE,
462
- sessionId,
463
- 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}`,
464
462
  title: `Preset ${title}`,
463
+ language,
464
+ welcome: { preset: title },
465
465
  renameExisting: true
466
- }, project);
466
+ });
467
467
  }
468
468
  async send(sessionId, text) {
469
469
  await this.services().controller.prompt({
@@ -477,10 +477,12 @@ var PresetAuthoringSessions = class {
477
477
  }, new AbortController().signal);
478
478
  }
479
479
  };
480
- //#endregion
481
- //#region src/host/agent/lorebook-authoring-sessions.ts
482
- const LOREBOOK_AUTHORING_PROJECT_TITLE = "Lorebook Authoring";
483
- 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
+ };
484
486
  /** Creates or reopens the dedicated authoring chat of a library lorebook, and speaks in it for the person when asked to. */
485
487
  var LorebookAuthoringSessions = class {
486
488
  services;
@@ -494,28 +496,14 @@ var LorebookAuthoringSessions = class {
494
496
  this.languages = languages;
495
497
  }
496
498
  async ensure(name, title, language) {
497
- this.languages.set(`lorebook:${name}`, language);
498
- const services = this.services();
499
- const projectPath = join(this.roleplayRoot(), "lorebooks");
500
- const project = await services.registry.create(projectPath, LOREBOOK_AUTHORING_PROJECT_TITLE);
501
- const sessionId = lorebookChatSessionId(name);
502
- const stored = !project.sessionIds.includes(sessionId) && await isStored(services.persistence, sessionId);
503
- if (!project.sessionIds.includes(sessionId) && !stored) {
504
- if (services.persistence === void 0) throw new AgentUnavailableError("this DSH profile cannot store the opening of an authoring chat");
505
- await storeAuthoringOpening(services.persistence, {
506
- id: sessionId,
507
- cwd: project.path,
508
- agentPreset: LOREBOOK_AUTHORING_PRESET
509
- }, this.prompts.text("lorebook/welcome", this.languages.get(`lorebook:${name}`), { lorebook: title }));
510
- }
511
- return await ensureAgentChat(services, {
512
- projectPath,
513
- projectTitle: LOREBOOK_AUTHORING_PROJECT_TITLE,
514
- sessionId,
515
- 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}`,
516
502
  title: `Lorebook ${title}`,
503
+ language,
504
+ welcome: { lorebook: title },
517
505
  renameExisting: true
518
- }, project);
506
+ });
519
507
  }
520
508
  async send(sessionId, text) {
521
509
  await this.services().controller.prompt({
@@ -529,8 +517,7 @@ var LorebookAuthoringSessions = class {
529
517
  }, new AbortController().signal);
530
518
  }
531
519
  };
532
- //#endregion
533
- //#region src/host/lorebooks/apply.ts
520
+ // src/host/lorebooks/apply.ts
534
521
  /** Which lorebooks a story was started with: kept in the story's own metadata, because the library may change afterwards. */
535
522
  const LOREBOOKS_KEY = "roleplay.lorebooks";
536
523
  /** The id an entry has in a story, so that books and the world's own lore never clash. */
@@ -578,8 +565,7 @@ async function lorebookLore(root, names, chosen, knows, taken) {
578
565
  }
579
566
  return result;
580
567
  }
581
- //#endregion
582
- //#region src/host/lorebooks/story.ts
568
+ // src/host/lorebooks/story.ts
583
569
  /** The lorebooks a story holds now. */
584
570
  function lorebooksOf(session) {
585
571
  return session.metadata.getValue("roleplay.lorebooks") ?? [];
@@ -635,8 +621,7 @@ function removeLorebook(session, name) {
635
621
  });
636
622
  return leaving.length;
637
623
  }
638
- //#endregion
639
- //#region src/host/lorebooks/verbatim.ts
624
+ // src/host/lorebooks/verbatim.ts
640
625
  const MAX_TITLE$1 = 100;
641
626
  /**
642
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),
@@ -666,8 +651,7 @@ function verbatimEntries(file, fileName, knownBy) {
666
651
  entries
667
652
  };
668
653
  }
669
- //#endregion
670
- //#region src/host/lorebooks/service.ts
654
+ // src/host/lorebooks/service.ts
671
655
  /** The story's lore cannot change right now. */
672
656
  var LorebookBusyError = class extends Error {};
673
657
  /** The lorebook library. Refusals are plain `Error`s with the reason. */
@@ -812,10 +796,13 @@ var Lorebooks = class {
812
796
  };
813
797
  }
814
798
  };
815
- //#endregion
816
- //#region src/host/agent/doctor-sessions.ts
817
- const DOCTOR_PROJECT_TITLE = "Session Doctor";
818
- 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
+ };
819
806
  /** Creates or reopens the chat in which a bystander reads one session's records and proposes fixes. */
820
807
  var DoctorSessions = class {
821
808
  services;
@@ -827,29 +814,16 @@ var DoctorSessions = class {
827
814
  this.prompts = prompts;
828
815
  }
829
816
  async ensure(session, title, language) {
830
- const services = this.services();
831
- const projectPath = join(this.roleplayRoot(), "sessions");
832
- const project = await services.registry.create(projectPath, DOCTOR_PROJECT_TITLE);
833
- const sessionId = doctorChatSessionId(session.id);
834
- if (!project.sessionIds.includes(sessionId) && !await isStored(services.persistence, sessionId)) {
835
- if (services.persistence === void 0) throw new AgentUnavailableError("this DSH profile cannot store the opening of a session doctor chat");
836
- await storeDoctorOpening(services.persistence, {
837
- id: sessionId,
838
- cwd: project.path,
839
- agentPreset: DOCTOR_AGENT_PRESET
840
- }, this.prompts.text("doctor/welcome", language, { session: session.name }));
841
- }
842
- return await ensureAgentChat(services, {
843
- projectPath,
844
- projectTitle: DOCTOR_PROJECT_TITLE,
845
- sessionId,
846
- agentPreset: DOCTOR_AGENT_PRESET,
847
- title
848
- }, 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
+ });
849
824
  }
850
825
  };
851
- //#endregion
852
- //#region src/host/orchestration/service.ts
826
+ // src/host/orchestration/service.ts
853
827
  /**
854
828
  * The extension points of a roleplay turn. Another plugin changes how the turn
855
829
  * behaves by replacing a boundary; the change applies from the next call on.
@@ -892,8 +866,7 @@ var RoleplayOrchestration = class extends Service {
892
866
  };
893
867
  }
894
868
  };
895
- //#endregion
896
- //#region src/host/http/respond.ts
869
+ // src/host/http/respond.ts
897
870
  function sendJson(res, status, payload) {
898
871
  res.statusCode = status;
899
872
  res.setHeader("content-type", "application/json; charset=utf-8");
@@ -911,8 +884,7 @@ var HttpError = class extends Error {
911
884
  this.status = status;
912
885
  }
913
886
  };
914
- //#endregion
915
- //#region src/host/presets/service.ts
887
+ // src/host/presets/service.ts
916
888
  /** The story's prompts cannot change right now. */
917
889
  var PresetBusyError = class extends Error {};
918
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. */
@@ -1016,7 +988,7 @@ var Presets = class {
1016
988
  const directory = await reservePreset(root, name, title ?? uploaded.name, uploaded.sampling);
1017
989
  try {
1018
990
  await mkdir(join(directory, IMPORT_FOLDER), { recursive: true });
1019
- await writeFile(join(directory, IMPORT_FOLDER, PRESET_FILE), file);
991
+ await writeFile(join(directory, IMPORT_FOLDER, PRESET_FILE$1), file);
1020
992
  } catch (error) {
1021
993
  await deletePreset(root, name);
1022
994
  throw error;
@@ -1060,8 +1032,7 @@ var Presets = class {
1060
1032
  return sessionFolder(sessions, id);
1061
1033
  }
1062
1034
  };
1063
- //#endregion
1064
- //#region src/host/http/body.ts
1035
+ // src/host/http/body.ts
1065
1036
  /** Request bodies here are small JSON objects; anything larger is not one. */
1066
1037
  const MAX_BODY_BYTES = 16384;
1067
1038
  /** Read a request body that must be a JSON object. */
@@ -1097,8 +1068,7 @@ async function readBinaryBody(req, limit) {
1097
1068
  if (size === 0) throw new HttpError(400, "the upload is empty");
1098
1069
  return Buffer.concat(chunks);
1099
1070
  }
1100
- //#endregion
1101
- //#region src/host/presets/routes.ts
1071
+ // src/host/presets/routes.ts
1102
1072
  /** Not found is 404 and a request the library refuses is 422 with its reason; anything else is a fault. */
1103
1073
  function failure$2(res, error) {
1104
1074
  if (error instanceof ImportNotFoundError) return sendError(res, 404, error.message);
@@ -1281,8 +1251,7 @@ function presetRoutes(api) {
1281
1251
  }
1282
1252
  };
1283
1253
  }
1284
- //#endregion
1285
- //#region src/host/lorebooks/routes.ts
1254
+ // src/host/lorebooks/routes.ts
1286
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. */
1287
1256
  function failure$1(res, error) {
1288
1257
  if (error instanceof ImportNotFoundError) return sendError(res, 404, error.message);
@@ -1468,8 +1437,7 @@ function lorebookRoutes(api) {
1468
1437
  } }
1469
1438
  };
1470
1439
  }
1471
- //#endregion
1472
- //#region src/shared/catalogue.ts
1440
+ // src/shared/catalogue.ts
1473
1441
  /** What a credential reference is: letters, digits and `_`, not starting with a digit (DSH's grammar). */
1474
1442
  const CREDENTIAL_REF = /^[A-Za-z_][A-Za-z0-9_]*$/;
1475
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. */
@@ -1484,8 +1452,7 @@ const CATALOGUE_CARD_TYPE = "sillytavern/character";
1484
1452
  const CATALOGUE_PRESET_TYPE = "sillytavern/preset";
1485
1453
  const CATALOGUE_LOREBOOK_TYPE = "sillytavern/lorebook";
1486
1454
  const CATALOGUE_WORLD_TYPE = "dsh-agentic-roleplay/world";
1487
- //#endregion
1488
- //#region src/host/sync/errors.ts
1455
+ // src/host/sync/errors.ts
1489
1456
  /** A run, or a choice, cannot be made now. */
1490
1457
  var SyncRefusedError = class extends Error {};
1491
1458
  /** rclone could not be started or reported a failure. */
@@ -1498,8 +1465,7 @@ var RcloneError = class extends Error {
1498
1465
  };
1499
1466
  /** The unit is being synced: nothing may write to it or read from it until the run is over. */
1500
1467
  var UnitLockedError = class extends Error {};
1501
- //#endregion
1502
- //#region src/host/sync/routes.ts
1468
+ // src/host/sync/routes.ts
1503
1469
  function failure(res, error) {
1504
1470
  if (error instanceof UnitLockedError) return sendError(res, 423, error.message);
1505
1471
  if (error instanceof SyncRefusedError) return sendError(res, 409, error.message);
@@ -1683,8 +1649,7 @@ function withBridge(html) {
1683
1649
  }
1684
1650
  return `${script}${html}`;
1685
1651
  }
1686
- //#endregion
1687
- //#region src/host/interface/player-view.ts
1652
+ // src/host/interface/player-view.ts
1688
1653
  const keyOf$2 = (character) => character.sourceId ?? String(character.id);
1689
1654
  /** What a variable shows, in one line of data. */
1690
1655
  function shown(subject, entries) {
@@ -1829,8 +1794,7 @@ function finish(view, session) {
1829
1794
  revision
1830
1795
  };
1831
1796
  }
1832
- //#endregion
1833
- //#region src/host/interface/preview.ts
1797
+ // src/host/interface/preview.ts
1834
1798
  /** What a story shows for suggestions when a pack is looked at before any story exists. */
1835
1799
  const SAMPLE_SUGGESTIONS = [
1836
1800
  "Look around.",
@@ -1882,8 +1846,7 @@ async function previewViewOf(world, wall) {
1882
1846
  scratch.close();
1883
1847
  }
1884
1848
  }
1885
- //#endregion
1886
- //#region src/host/interface/storage.ts
1849
+ // src/host/interface/storage.ts
1887
1850
  const keyOf$1 = (pack) => `roleplay.interface.${pack}`;
1888
1851
  function checkedKey(key) {
1889
1852
  if (key === "" || key.length > 100) throw new RangeError("a key is 1 to 100 characters");
@@ -1925,8 +1888,7 @@ var PackStorage = class {
1925
1888
  this.session.metadata.setValue(keyOf$1(this.pack), rest);
1926
1889
  }
1927
1890
  };
1928
- //#endregion
1929
- //#region src/host/interface/service.ts
1891
+ // src/host/interface/service.ts
1930
1892
  /** The packs of a world cannot be brought into a story because some of them have problems. */
1931
1893
  var InvalidPacksError = class extends Error {
1932
1894
  problems;
@@ -2171,8 +2133,7 @@ var InterfaceService = class {
2171
2133
  ]) };
2172
2134
  }
2173
2135
  };
2174
- //#endregion
2175
- //#region src/host/interface/routes.ts
2136
+ // src/host/interface/routes.ts
2176
2137
  /** The address under which the files of a session's pack are served to the page: `<prefix>/<session id>/<path of the file>`. */
2177
2138
  const PACK_FILES = "/sessions/interface/pack/";
2178
2139
  /**
@@ -2304,8 +2265,7 @@ async function sendPackFile(api, path, res) {
2304
2265
  res.setHeader("content-length", file.size);
2305
2266
  await pipeline(createReadStream(file.file), res);
2306
2267
  }
2307
- //#endregion
2308
- //#region src/host/http/routes/speech.ts
2268
+ // src/host/http/routes/speech.ts
2309
2269
  /** The routes of the API for speech. */
2310
2270
  function speechRoutes({ speech }) {
2311
2271
  return {
@@ -2328,8 +2288,7 @@ function speechRoutes({ speech }) {
2328
2288
  } }
2329
2289
  };
2330
2290
  }
2331
- //#endregion
2332
- //#region src/host/worlds/starter.ts
2291
+ // src/host/worlds/starter.ts
2333
2292
  const STARTER_FOLDER = "starter-worlds";
2334
2293
  /** Names a starter world that the package does not ship. */
2335
2294
  var UnknownStarterError = class extends Error {};
@@ -2394,8 +2353,7 @@ async function addStarterWorld(catalog, folder, directory = starterDirectory())
2394
2353
  if (added === void 0) throw new Error(`added "${world.name}" but it was not found when the catalogue refreshed`);
2395
2354
  return added;
2396
2355
  }
2397
- //#endregion
2398
- //#region src/host/http/routes/shared.ts
2356
+ // src/host/http/routes/shared.ts
2399
2357
  /** The largest picture that can be added to a gallery. */
2400
2358
  const MAX_UPLOAD_BYTES = 20971520;
2401
2359
  /** The changes to a picture's metadata a body asks for, or what is wrong with it. */
@@ -2465,8 +2423,7 @@ function languageField(value) {
2465
2423
  throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
2466
2424
  }
2467
2425
  }
2468
- //#endregion
2469
- //#region src/host/http/routes/worlds.ts
2426
+ // src/host/http/routes/worlds.ts
2470
2427
  /** The routes of the API for worlds. */
2471
2428
  function worldsRoutes({ worlds, createWorld, starter, authorWorld, translation, worldCharacters, avatars }) {
2472
2429
  return {
@@ -2609,8 +2566,7 @@ function worldsRoutes({ worlds, createWorld, starter, authorWorld, translation,
2609
2566
  } }
2610
2567
  };
2611
2568
  }
2612
- //#endregion
2613
- //#region src/host/http/routes/catalogue.ts
2569
+ // src/host/http/routes/catalogue.ts
2614
2570
  /** The routes of the API for catalogue. */
2615
2571
  function catalogueRoutes({ catalogue }) {
2616
2572
  return {
@@ -2793,8 +2749,7 @@ function catalogueRoutes({ catalogue }) {
2793
2749
  } }
2794
2750
  };
2795
2751
  }
2796
- //#endregion
2797
- //#region src/host/http/routes/imports.ts
2752
+ // src/host/http/routes/imports.ts
2798
2753
  /** The routes of the API for imports. */
2799
2754
  function importsRoutes({ importer }) {
2800
2755
  return {
@@ -2909,6 +2864,14 @@ function importsRoutes({ importer }) {
2909
2864
  return importFailure(res, error);
2910
2865
  }
2911
2866
  } },
2867
+ "/worlds/import/structure": { POST: async (req, res, url) => {
2868
+ try {
2869
+ const body = await readJsonBody(req);
2870
+ sendJson(res, 200, await importer.importStructure(url.searchParams.get("id") ?? "", parseChoices(body), languageField(body.language)));
2871
+ } catch (error) {
2872
+ return importFailure(res, error);
2873
+ }
2874
+ } },
2912
2875
  "/worlds/import/draft": {
2913
2876
  GET: async (_req, res, url) => {
2914
2877
  try {
@@ -2944,8 +2907,7 @@ function importsRoutes({ importer }) {
2944
2907
  } }
2945
2908
  };
2946
2909
  }
2947
- //#endregion
2948
- //#region src/shared/world-dice.ts
2910
+ // src/shared/world-dice.ts
2949
2911
  const isObject$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2950
2912
  const CHECK_FIELDS = [
2951
2913
  "key",
@@ -3034,8 +2996,7 @@ function parseDiceEdit(value) {
3034
2996
  if (problems.length > 0) throw new InvalidEditProblems(problems);
3035
2997
  return { checks };
3036
2998
  }
3037
- //#endregion
3038
- //#region src/shared/world-daily.ts
2999
+ // src/shared/world-daily.ts
3039
3000
  const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3040
3001
  const ROUTINE_FIELDS = [
3041
3002
  "days",
@@ -3233,8 +3194,7 @@ function parseCalendarEdit(value) {
3233
3194
  holidays
3234
3195
  };
3235
3196
  }
3236
- //#endregion
3237
- //#region src/host/http/routes/worldFiles.ts
3197
+ // src/host/http/routes/worldFiles.ts
3238
3198
  /** The routes of the API for worldFiles. */
3239
3199
  function worldFilesRoutes({ worldFiles, worldEditor, sessions }) {
3240
3200
  return {
@@ -3730,8 +3690,7 @@ function worldFilesRoutes({ worldFiles, worldEditor, sessions }) {
3730
3690
  ]))
3731
3691
  };
3732
3692
  }
3733
- //#endregion
3734
- //#region src/host/http/routes/sessions.ts
3693
+ // src/host/http/routes/sessions.ts
3735
3694
  /** The routes of the API for sessions. */
3736
3695
  function sessionsRoutes({ sessions, externalTools, redundantLayers }) {
3737
3696
  return {
@@ -4023,8 +3982,7 @@ function sessionsRoutes({ sessions, externalTools, redundantLayers }) {
4023
3982
  } }
4024
3983
  };
4025
3984
  }
4026
- //#endregion
4027
- //#region src/host/http/routes/sessionWorld.ts
3985
+ // src/host/http/routes/sessionWorld.ts
4028
3986
  /** The routes of the API for sessionWorld. */
4029
3987
  function sessionWorldRoutes({ sessions }) {
4030
3988
  return {
@@ -4161,8 +4119,7 @@ function sessionWorldRoutes({ sessions }) {
4161
4119
  } }
4162
4120
  };
4163
4121
  }
4164
- //#endregion
4165
- //#region src/host/http/api.ts
4122
+ // src/host/http/api.ts
4166
4123
  /** Build the request handler mounted at `/${API_PREFIX}`. */
4167
4124
  function createApiHandler(deps) {
4168
4125
  const { packs, presets, lorebooks, sync, locked, anyLocked, connection } = deps;
@@ -4218,8 +4175,7 @@ function createApiHandler(deps) {
4218
4175
  }
4219
4176
  };
4220
4177
  }
4221
- //#endregion
4222
- //#region src/host/http/index.ts
4178
+ // src/host/http/index.ts
4223
4179
  /** Mount the API once the web server and its authentication are available; profiles without them skip it. */
4224
4180
  function registerApi(ctx, deps) {
4225
4181
  ctx.inject(["webServer", "connection"], (webCtx) => {
@@ -4235,8 +4191,7 @@ function registerApi(ctx, deps) {
4235
4191
  }), "roleplay: http api");
4236
4192
  });
4237
4193
  }
4238
- //#endregion
4239
- //#region src/host/sessions/delete-session.ts
4194
+ // src/host/sessions/delete-session.ts
4240
4195
  /**
4241
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
4242
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
@@ -4250,8 +4205,7 @@ async function deleteSession(deps, id) {
4250
4205
  await deps.purgeChat(chatSessionId(id));
4251
4206
  deps.state.deleteSession(directory, id);
4252
4207
  }
4253
- //#endregion
4254
- //#region src/host/storage/root-path.ts
4208
+ // src/host/storage/root-path.ts
4255
4209
  /** Directories every roleplay root contains. */
4256
4210
  const ROOT_LAYOUT = [
4257
4211
  "characters",
@@ -4280,8 +4234,7 @@ async function ensureRootLayout(root) {
4280
4234
  await mkdir(root, { recursive: true });
4281
4235
  await Promise.all(ROOT_LAYOUT.map((name) => mkdir(join(root, name), { recursive: true })));
4282
4236
  }
4283
- //#endregion
4284
- //#region src/host/agent/purge.ts
4237
+ // src/host/agent/purge.ts
4285
4238
  /** A segment of a path for what is not a letter, digit or one of `._-`: `~` and four hex digits, as DSH writes it. */
4286
4239
  const segment = (raw) => {
4287
4240
  if (raw === "") throw new Error("cannot name the folder of a session with no id");
@@ -4374,8 +4327,7 @@ async function purgeChat(deps, chat) {
4374
4327
  if (failures.length > 0) throw new Error(`the chat could not be deleted completely (${removed.length} of ${victims.length} removed): ${failures.join("; ")}`);
4375
4328
  return removed;
4376
4329
  }
4377
- //#endregion
4378
- //#region src/host/agent/purge-services.ts
4330
+ // src/host/agent/purge-services.ts
4379
4331
  /** What DSH's services give and the purge needs, looked up when used: a profile without them cannot delete a chat. */
4380
4332
  function purgeDepsOf(ctx, storePath) {
4381
4333
  const service = (name) => ctx.get(name);
@@ -4399,8 +4351,7 @@ function purgeDepsOf(ctx, storePath) {
4399
4351
  };
4400
4352
  }
4401
4353
  const purgeOf = (ctx, storePath) => (chat) => purgeChat(purgeDepsOf(ctx, storePath), chat);
4402
- //#endregion
4403
- //#region src/host/setup/rows.ts
4354
+ // src/host/setup/rows.ts
4404
4355
  const ALL = ["@dsh-agentic-roleplay/all", "dsh-agentic-roleplay"];
4405
4356
  const SINGLE = [
4406
4357
  "@dsh-agentic-roleplay/core",
@@ -4428,8 +4379,7 @@ function redundantLayers(bundles) {
4428
4379
  function redundantLayersMessage(layers) {
4429
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`;
4430
4381
  }
4431
- //#endregion
4432
- //#region src/host/worlds/daily-life.ts
4382
+ // src/host/worlds/daily-life.ts
4433
4383
  /** The day each character lives, and the places its windows may name. */
4434
4384
  async function readRoutines(world) {
4435
4385
  const [{ characters }, { locations }] = await Promise.all([loadCharacters(world.directory), loadLocations(world.directory)]);
@@ -4580,8 +4530,7 @@ async function editDice(world, dice) {
4580
4530
  else await replaceFileOrCreate(join(world.directory, DICE_FILE_NAME), text);
4581
4531
  return await readDiceDocument(world);
4582
4532
  }
4583
- //#endregion
4584
- //#region src/host/worlds/lore-entries.ts
4533
+ // src/host/worlds/lore-entries.ts
4585
4534
  const MAX_TITLE = 200;
4586
4535
  /**
4587
4536
  * Adds an empty lore entry to the world's files, named by its title.
@@ -4625,8 +4574,7 @@ async function removeWorldLore(world, key) {
4625
4574
  await deleteAuthoredEntity(world, "lore", key);
4626
4575
  return await readWorldEditor(world);
4627
4576
  }
4628
- //#endregion
4629
- //#region src/host/sessions/world-state.ts
4577
+ // src/host/sessions/world-state.ts
4630
4578
  function sessionOf(deps, id) {
4631
4579
  const directory = deps.sessionsDir();
4632
4580
  if (!isSessionId(id) || !existsSync(sessionDatabase(directory, id))) throw new SessionNotFoundError(`no session "${id}"`);
@@ -5331,13 +5279,11 @@ async function sessionCharacterPortraitFile(deps, id, key) {
5331
5279
  size: (await stat(file)).size
5332
5280
  };
5333
5281
  }
5334
- //#endregion
5335
- //#region src/shared/avatars.ts
5282
+ // src/shared/avatars.ts
5336
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. */
5337
5284
  const AVATARS_WORLD_ID = "@avatars";
5338
5285
  const AVATARS_FOLDER = "avatars";
5339
- //#endregion
5340
- //#region src/host/avatars/avatars.ts
5286
+ // src/host/avatars/avatars.ts
5341
5287
  const WORLD_FILE = "world.json";
5342
5288
  /** The folder the player avatars live in, with the file that makes it readable as a world of characters only. */
5343
5289
  async function avatarsWorld(rootPath) {
@@ -5469,8 +5415,7 @@ async function addAvatarsToWorld(avatars, world, keys, locations) {
5469
5415
  }
5470
5416
  return brought.map((entry) => entry.id);
5471
5417
  }
5472
- //#endregion
5473
- //#region src/host/agent/history.ts
5418
+ // src/host/agent/history.ts
5474
5419
  /** The unknown seq of a turn that is not in the log. */
5475
5420
  const NOT_IN_LOG = -1;
5476
5421
  /**
@@ -5750,8 +5695,7 @@ function openingOf(world, characters) {
5750
5695
  if (problems.length > 0) throw new InvalidWorldError(`the opening of "${world.summary.name}" has ${problems.length} problem(s)`, problems);
5751
5696
  return segments;
5752
5697
  }
5753
- //#endregion
5754
- //#region src/host/sessions/rename-session.ts
5698
+ // src/host/sessions/rename-session.ts
5755
5699
  /**
5756
5700
  * Give a session a new name, and its chat the same one.
5757
5701
  * @throws {SessionNotFoundError} when the id names no session. @throws {InvalidStartError} when the name is blank or too long.
@@ -5765,8 +5709,7 @@ async function renameSession(deps, id, name) {
5765
5709
  deps.state.openSession(directory, id).metadata.setName(trimmed);
5766
5710
  await deps.agent.rename(id, trimmed);
5767
5711
  }
5768
- //#endregion
5769
- //#region src/host/sessions/status.ts
5712
+ // src/host/sessions/status.ts
5770
5713
  const STATUS_FILE = "status.json";
5771
5714
  /**
5772
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.
@@ -5789,8 +5732,7 @@ function writeStatus(folder, status) {
5789
5732
  writeFileSync(aside, JSON.stringify(status, null, 2));
5790
5733
  renameSync(aside, target);
5791
5734
  }
5792
- //#endregion
5793
- //#region src/host/sessions/archive-session.ts
5735
+ // src/host/sessions/archive-session.ts
5794
5736
  function folderOf$1(deps, id) {
5795
5737
  const directory = deps.sessionsDir();
5796
5738
  if (!isSessionId(id) || !existsSync(sessionDatabase(directory, id))) throw new SessionNotFoundError(`no session "${id}"`);
@@ -5818,8 +5760,7 @@ async function restoreSession(deps, id) {
5818
5760
  await deps.agent.restore(id);
5819
5761
  writeStatus(folder, {});
5820
5762
  }
5821
- //#endregion
5822
- //#region src/host/sessions/chat-settings.ts
5763
+ // src/host/sessions/chat-settings.ts
5823
5764
  function folderOf(deps, id) {
5824
5765
  const directory = deps.sessionsDir();
5825
5766
  if (!isSessionId(id) || !existsSync(sessionDatabase(directory, id))) throw new SessionNotFoundError(`no session "${id}"`);
@@ -5859,8 +5800,7 @@ function payloadOf(deps, id, settings) {
5859
5800
  ...clockMode === void 0 ? {} : { clockMode }
5860
5801
  };
5861
5802
  }
5862
- //#endregion
5863
- //#region src/host/interface/first-party.ts
5803
+ // src/host/interface/first-party.ts
5864
5804
  /** The folder of the packs shipped with the package. */
5865
5805
  const FIRST_PARTY_FOLDER = "packs";
5866
5806
  /** Found from this module, so that it works from source and from the build. */
@@ -5887,8 +5827,7 @@ function installFirstPartyPacks(root, shipped = firstPartyDirectory()) {
5887
5827
  }
5888
5828
  return installed;
5889
5829
  }
5890
- //#endregion
5891
- //#region src/host/sessions/vectors.ts
5830
+ // src/host/sessions/vectors.ts
5892
5831
  /** How many waiting texts are counted before saying "that many": the number is for reassurance, not accounting. */
5893
5832
  const MAX_COUNTED = 1e4;
5894
5833
  function vectorStatus(session) {
@@ -5910,8 +5849,7 @@ function vectorStatus(session) {
5910
5849
  function resetVectors(session) {
5911
5850
  session.recallIndex.reset();
5912
5851
  }
5913
- //#endregion
5914
- //#region src/host/authoring/pack-files.ts
5852
+ // src/host/authoring/pack-files.ts
5915
5853
  /** Where a text file of a pack is, once the pack name and the path are known to be allowed; otherwise why not. */
5916
5854
  function placeOf(directory, pack, path, tool, text = "") {
5917
5855
  if (!isPackId(pack)) throw new InvalidEditProblems([`"${pack}" is not a usable pack name (letters, digits, "-" and "_")`]);
@@ -5961,8 +5899,7 @@ async function createWorldPack(directory, pack, name) {
5961
5899
  api: 1
5962
5900
  }, null, 2)}\n`);
5963
5901
  }
5964
- //#endregion
5965
- //#region src/host/sessions/interventions.ts
5902
+ // src/host/sessions/interventions.ts
5966
5903
  /** What the story's triggers delivered lately and what became of each, oldest first. */
5967
5904
  function readInterventions(session) {
5968
5905
  const withdrawn = readWithdrawn(session);
@@ -5979,8 +5916,7 @@ function readInterventions(session) {
5979
5916
  };
5980
5917
  });
5981
5918
  }
5982
- //#endregion
5983
- //#region src/host/decisions/status.ts
5919
+ // src/host/decisions/status.ts
5984
5920
  /**
5985
5921
  * Whether a decision service is there, which one, and what was kept about how the story's decisions went.
5986
5922
  * @throws {SessionNotFoundError} for an id that names no session.
@@ -5998,8 +5934,7 @@ function decisionsOfSession(deps, id) {
5998
5934
  stats: readDecisionStats(sessionFolder(sessions, id))
5999
5935
  };
6000
5936
  }
6001
- //#endregion
6002
- //#region src/host/sessions/open-session.ts
5937
+ // src/host/sessions/open-session.ts
6003
5938
  /** Make sure a session has its DSH chat, so that it can be opened. */
6004
5939
  async function openSession(deps, id, options = {}) {
6005
5940
  if (!isSessionId(id) || !existsSync(sessionDatabase(deps.sessionsDir(), id))) throw new SessionNotFoundError(`no session "${id}"`);
@@ -6026,8 +5961,7 @@ async function openSession(deps, id, options = {}) {
6026
5961
  chatSessionId: chatSessionId$1
6027
5962
  };
6028
5963
  }
6029
- //#endregion
6030
- //#region src/host/sessions/list-sessions.ts
5964
+ // src/host/sessions/list-sessions.ts
6031
5965
  /** The sessions on disk, the most recently played first; a session never played counts from its creation. */
6032
5966
  function listSessions(deps) {
6033
5967
  const directory = deps.sessionsDir();
@@ -6065,8 +5999,7 @@ function listSessions(deps) {
6065
5999
  }))
6066
6000
  };
6067
6001
  }
6068
- //#endregion
6069
- //#region src/host/sessions/local-time.ts
6002
+ // src/host/sessions/local-time.ts
6070
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`. */
6071
6004
  function localInstant(instant, zone) {
6072
6005
  const parts = new Intl.DateTimeFormat("en-CA", {
@@ -6082,8 +6015,7 @@ function localInstant(instant, zone) {
6082
6015
  const part = (type) => parts.find((entry) => entry.type === type)?.value ?? "00";
6083
6016
  return `${part("year")}-${part("month")}-${part("day")}T${part("hour")}:${part("minute")}:${part("second")}`;
6084
6017
  }
6085
- //#endregion
6086
- //#region src/host/sessions/world-characters.ts
6018
+ // src/host/sessions/world-characters.ts
6087
6019
  /**
6088
6020
  * The cast of a world, as the start dialog needs it.
6089
6021
  * @throws {WorldNotFoundError} when no world has that id.
@@ -6112,8 +6044,7 @@ async function worldCharacters(worlds, worldId) {
6112
6044
  problems
6113
6045
  };
6114
6046
  }
6115
- //#endregion
6116
- //#region src/host/storage/roleplay-root.ts
6047
+ // src/host/storage/roleplay-root.ts
6117
6048
  /** Owns the roleplay root directory and keeps its baseline layout in place. */
6118
6049
  var RoleplayRoot = class extends Service {
6119
6050
  source;
@@ -6157,8 +6088,7 @@ var RoleplayRoot = class extends Service {
6157
6088
  }
6158
6089
  }
6159
6090
  };
6160
- //#endregion
6161
- //#region src/host/worlds/world-id.ts
6091
+ // src/host/worlds/world-id.ts
6162
6092
  /** The indentation the file already uses, so adding the id does not reformat it. */
6163
6093
  function indentOf(text) {
6164
6094
  return /^([ \t]+)"/m.exec(text)?.[1] ?? " ";
@@ -6183,8 +6113,7 @@ async function assignWorldId(file) {
6183
6113
  await atomicWrite(file, withWorldId(await readFile(file, "utf8"), id));
6184
6114
  return id;
6185
6115
  }
6186
- //#endregion
6187
- //#region src/host/worlds/scan.ts
6116
+ // src/host/worlds/scan.ts
6188
6117
  /** Where a world bundle lists its media files. */
6189
6118
  const MEDIA_MANIFEST = "media/manifest.jsonl";
6190
6119
  /** Raster formats only: they cannot carry script when opened directly. */
@@ -6341,8 +6270,7 @@ async function resolveCover(worldDir, mediaId) {
6341
6270
  version: `${Math.trunc(info.mtimeMs).toString(36)}-${info.size.toString(36)}`
6342
6271
  };
6343
6272
  }
6344
- //#endregion
6345
- //#region src/host/worlds/catalog.ts
6273
+ // src/host/worlds/catalog.ts
6346
6274
  /** Worlds found under the roleplay root. Read lazily, kept until refreshed or the root moves. */
6347
6275
  var WorldCatalog = class extends Service {
6348
6276
  root;
@@ -6406,8 +6334,7 @@ var WorldCatalog = class extends Service {
6406
6334
  return run;
6407
6335
  }
6408
6336
  };
6409
- //#endregion
6410
- //#region src/host/catalogue/zip.ts
6337
+ // src/host/catalogue/zip.ts
6411
6338
  const END_SIGNATURE = 101010256;
6412
6339
  const CENTRAL_SIGNATURE = 33639248;
6413
6340
  const LOCAL_SIGNATURE = 67324752;
@@ -6488,8 +6415,7 @@ function readZip(archive, limits) {
6488
6415
  }
6489
6416
  return files;
6490
6417
  }
6491
- //#endregion
6492
- //#region src/host/catalogue/install.ts
6418
+ // src/host/catalogue/install.ts
6493
6419
  const FOLDER_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
6494
6420
  const MAX_FOLDER_COPIES = 99;
6495
6421
  /** The one top-level folder of a world archive and the files in it, or why the archive is not a world. */
@@ -6604,8 +6530,7 @@ async function installWorld(catalog, archive, maxBytes, options) {
6604
6530
  });
6605
6531
  }
6606
6532
  }
6607
- //#endregion
6608
- //#region src/host/catalogue/trash.ts
6533
+ // src/host/catalogue/trash.ts
6609
6534
  const DAY_MS = 864e5;
6610
6535
  const STAMP = /-(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})-(\d{3})Z$/;
6611
6536
  /** Staging folders left by an interrupted install are removed after this long. */
@@ -6654,8 +6579,7 @@ async function pruneTrash(root, keepDays, now = Date.now()) {
6654
6579
  failures
6655
6580
  };
6656
6581
  }
6657
- //#endregion
6658
- //#region src/host/catalogue/transport.ts
6582
+ // src/host/catalogue/transport.ts
6659
6583
  const TIMEOUT_MS = 6e4;
6660
6584
  const MAX_REDIRECTS = 5;
6661
6585
  const nodeTransport = (url, ask) => new Promise((resolveReply, reject) => {
@@ -7151,8 +7075,7 @@ var Catalogue = class {
7151
7075
  }
7152
7076
  }
7153
7077
  };
7154
- //#endregion
7155
- //#region src/host/catalogue/sources.ts
7078
+ // src/host/catalogue/sources.ts
7156
7079
  /** A web address with no credentials, query or fragment, or the reason it is not one. */
7157
7080
  function parseBase(text) {
7158
7081
  let url;
@@ -7296,8 +7219,7 @@ var Sources = class {
7296
7219
  return best?.source;
7297
7220
  }
7298
7221
  };
7299
- //#endregion
7300
- //#region src/shared/sync.ts
7222
+ // src/shared/sync.ts
7301
7223
  const DEFAULT_SYNC = {
7302
7224
  remote: "",
7303
7225
  rclone: "",
@@ -7305,8 +7227,7 @@ const DEFAULT_SYNC = {
7305
7227
  passwordRef: "",
7306
7228
  intervalMinutes: 0
7307
7229
  };
7308
- //#endregion
7309
- //#region src/host/sync/gate.ts
7230
+ // src/host/sync/gate.ts
7310
7231
  /**
7311
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
7312
7233
  * unit and the app never sees a half-downloaded one.
@@ -7342,8 +7263,7 @@ var UnitGate = class {
7342
7263
  }
7343
7264
  }
7344
7265
  };
7345
- //#endregion
7346
- //#region src/host/sync/rclone.ts
7266
+ // src/host/sync/rclone.ts
7347
7267
  /** Runs the rclone the person named, with their configuration file, as a child of this process. */
7348
7268
  function spawnRclone(setup) {
7349
7269
  return { run: (args, options = {}) => new Promise((resolve, reject) => {
@@ -7405,8 +7325,7 @@ function why(result) {
7405
7325
  const files = changedFiles(lines);
7406
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`;
7407
7327
  }
7408
- //#endregion
7409
- //#region src/host/sync/state.ts
7328
+ // src/host/sync/state.ts
7410
7329
  const syncFolder = (root) => join(root, ".sync");
7411
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. */
7412
7331
  function readStore(root) {
@@ -7434,8 +7353,7 @@ function writeStore(root, store) {
7434
7353
  writeFileSync(temporary, `${JSON.stringify(store, null, 2)}\n`);
7435
7354
  renameSync(temporary, join(folder, "state.json"));
7436
7355
  }
7437
- //#endregion
7438
- //#region src/host/sync/units.ts
7356
+ // src/host/sync/units.ts
7439
7357
  /** Folders of the root that are one unit each, whatever they hold. */
7440
7358
  const SHARED_UNITS = [
7441
7359
  "prompts",
@@ -7500,8 +7418,7 @@ async function conflictFiles(directory) {
7500
7418
  await walk("");
7501
7419
  return found.sort((left, right) => left.localeCompare(right));
7502
7420
  }
7503
- //#endregion
7504
- //#region src/host/sync/service.ts
7421
+ // src/host/sync/service.ts
7505
7422
  const DIVERGED = {
7506
7423
  none: void 0,
7507
7424
  first: "both sides have this and it was never synced here",
@@ -8108,8 +8025,7 @@ var SyncService = class {
8108
8025
  }
8109
8026
  }
8110
8027
  };
8111
- //#endregion
8112
- //#region src/host/sync/wire.ts
8028
+ // src/host/sync/wire.ts
8113
8029
  /** The folder that a request to the API writes or reads, if it is one of the syncable ones. */
8114
8030
  async function unitsOf(url, worlds) {
8115
8031
  const path = url.pathname.slice(`/${API_PREFIX}`.length);
@@ -8217,18 +8133,23 @@ function createSync(ctx, wiring) {
8217
8133
  locked: async (url) => (await unitsOf(url, wiring.worlds)).find((unit) => gate.isLocked(unit))
8218
8134
  };
8219
8135
  }
8220
- //#endregion
8221
- //#region src/host/speech/service.ts
8136
+ // src/host/speech/service.ts
8222
8137
  async function voicesOf(service) {
8223
8138
  return await service.voices();
8224
8139
  }
8225
8140
  /** Synthesize independently so every speaker keeps its voice, then join the audio in story order. */
8226
8141
  async function speakParts(service, parts) {
8227
8142
  if (parts.length === 0 || parts.some((part) => part.text.trim() === "")) throw new RangeError("speech needs non-empty text");
8228
- 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
+ }));
8229
8150
  const mediaType = results[0].mediaType;
8230
8151
  if (results.some((result) => result.mediaType !== mediaType)) throw new Error("the speech provider returned incompatible audio formats");
8231
- 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);
8232
8153
  if (mediaType === "audio/wav" || mediaType === "audio/x-wav") return {
8233
8154
  bytes: mergeWav(buffers),
8234
8155
  mediaType
@@ -8310,7 +8231,7 @@ const Config = z.object({
8310
8231
  importReasoning: z.string().default("").volatile(),
8311
8232
  childReasoning: z.string().default("").volatile(),
8312
8233
  importModel: z.string().default("").volatile(),
8313
- importStructuredOutput: z.union(["tool", "schema"]).default("tool").volatile(),
8234
+ importStructuredOutput: z.union(["tool", "schema"]).default("schema").volatile(),
8314
8235
  importMaxTokens: z.number().min(0).max(1e6).default(0).volatile(),
8315
8236
  importVariablesPerRequest: z.number().min(5).max(500).default(25).volatile(),
8316
8237
  importTemperature: z.number().min(0).max(2).default(.2).volatile(),
@@ -8319,8 +8240,7 @@ const Config = z.object({
8319
8240
  importConfidence: z.number().min(0).max(1).default(.7).volatile(),
8320
8241
  authoringApproval: z.union([z.const("ask"), z.const("auto")]).default("ask").volatile()
8321
8242
  });
8322
- //#endregion
8323
- //#region src/index.ts
8243
+ // src/index.ts
8324
8244
  const name = "@dsh-agentic-roleplay/core";
8325
8245
  /** Sessions are kept by the state plugin, which the bundle installs with this one. */
8326
8246
  const inject = ["roleplayState"];
@@ -8539,6 +8459,17 @@ function apply(ctx, config) {
8539
8459
  choose: (id, choices) => imports.choose(id, choices),
8540
8460
  discard: (id) => imports.discard(id),
8541
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
+ },
8542
8473
  picture: (id) => imports.picture(id),
8543
8474
  resume: (worldId, language) => resumeImport({
8544
8475
  worlds,
@@ -8844,7 +8775,6 @@ function timelinesOf(ctx, sessionsDir, id) {
8844
8775
  if (timelines === void 0) throw new AgentUnavailableError("the story cannot be taken back: the orchestration is not running");
8845
8776
  return timelines;
8846
8777
  }
8847
- //#endregion
8848
8778
  export { Config, RoleplayOrchestration, apply, inject, name };
8849
8779
 
8850
8780
  //# sourceMappingURL=index.js.map