@dsh-agentic-roleplay/core 0.12.0 → 0.12.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 (44) hide show
  1. package/cordis.patch.yml +108 -0
  2. package/lib/{access-DAw54-NI.js → access-Csp80TFX.js} +2 -2
  3. package/lib/{authoring-tools-4NgDhIJV.js → authoring-tools-BZr4bgBy.js} +25 -771
  4. package/lib/authoring.js +136 -12
  5. package/lib/{child-D3QUNb3m.js → child-DTdY14S9.js} +54 -6
  6. package/lib/client.js +16457 -1938
  7. package/lib/client.js.map +1 -1
  8. package/lib/compaction.js +3 -3
  9. package/lib/dev-context-Cgv_wZbG.js +50 -0
  10. package/lib/doctor.js +6 -3
  11. package/lib/{gallery-Ct6nm4UQ.js → gallery-BNg0rPTp.js} +3 -3
  12. package/lib/{generator-CI8fOnXy.js → generator-9-5at9cZ.js} +2 -2
  13. package/lib/helper.js +5 -9
  14. package/lib/{hooks-BNeoGMHZ.js → hooks-Dtq5KZQX.js} +47 -16
  15. package/lib/images.js +4 -4
  16. package/lib/index.js +152 -476
  17. package/lib/{jail-BIF79PJO.js → jail-DVbPSC0R.js} +2 -2
  18. package/lib/{library-BF9ZMSFz.js → library-DTxakw0z.js} +2 -2
  19. package/lib/{lorebook-author-tools-DBk-V0hp.js → lorebook-author-tools-BjcEUo22.js} +19 -6
  20. package/lib/lorebook-authoring.js +13 -5
  21. package/lib/{narration-xvErE2yp.js → narration--K2XVIHI.js} +2 -2
  22. package/lib/orchestration.js +33 -12
  23. package/lib/{pack-jail-C8EyX9Ix.js → pack-jail-Dt0VTsu0.js} +558 -23
  24. package/lib/{packs-S0SzrVv-.js → packs-DWfR2Ted.js} +2 -2
  25. package/lib/{presenter-agent-Bc478nTA.js → presenter-agent-vFOxIuWv.js} +9 -9
  26. package/lib/{preset-SJZyw0kt.js → preset-Dv5YF2qj.js} +4 -4
  27. package/lib/{preset-author-tools-CzogjK42.js → preset-author-tools-BUzO9mTW.js} +8 -7
  28. package/lib/preset-authoring.js +12 -6
  29. package/lib/{reflection-buQiSdvq.js → reflection-Dd3pEiZB.js} +14 -15
  30. package/lib/{presets-DQ5rioMh.js → serial-BUaJGwVy.js} +1241 -390
  31. package/lib/{turn-guard-BSAba8sp.js → turn-guard-87NE-Cnp.js} +3 -3
  32. package/locale/de.json +6 -0
  33. package/locale/en.json +6 -0
  34. package/locale/es.json +6 -0
  35. package/locale/fr.json +6 -0
  36. package/locale/ja.json +6 -0
  37. package/locale/pt.json +6 -0
  38. package/locale/ru.json +6 -0
  39. package/locale/zh.json +6 -0
  40. package/package.json +34 -34
  41. package/prompts/en/import/style.md +2 -1
  42. package/prompts/en/world/procedure.md +1 -1
  43. package/prompts/zh/import/style.md +2 -1
  44. package/prompts/zh/world/procedure.md +1 -1
package/lib/index.js CHANGED
@@ -1,21 +1,21 @@
1
- import { A as chatSessionId, _ as RECOVERY_SHRINK, g as RECOVERY_FLOOR, h as sharedSamplingOf, i as childSamplingOf, j as roleplaySessionOf, m as parseSampling, s as isUnfinishedCall, w as totalTokens } from "./child-D3QUNb3m.js";
2
- import { $t as subfolders, At as populateLore, Bt as loadLocations, Ct as populateCharacters, Dt as populateItems, E as loadWorldParts, Et as populateFactions, F as localChanges, Ft as TRIGGERS_FILE_NAME, G as vetUrl, Gt as DICE_FILE_NAME, Ht as loadItems, I as readOrigin, Jt as CALENDAR_FILE_NAME, Kt as loadDice, L as writeOrigin, M as describeChanges, Mt as populateTriggers, N as hashWorld, Nt as populateVariables, Ot as populateKnowledge, P as isUnchanged, Pt as routineProblems, Qt as loadCharacters, R as CatalogueError, St as populateCalendar, T as readWorldInfo, Tt as populateDice, U as guardedLookup, Xt as parseCalendarFile, Yt as loadCalendar, Zt as CHARACTERS_DIR, _ as runChecks, _t as writeLorebookEntry, an as readCard, at as addLorebookEntries, c as importPhase, cn as DICE_RESULTS, ct as deleteLorebookEntry, d as markReady, dt as listLorebooks, en as knownOutputCeiling, et as WORLD_FILE_NAME, f as settleDraft, ft as loadLorebook, gt as updateLorebookInfo, ht as reserveLorebook, in as pictureOf, it as questionView, jt as populateRoutines, kt as populateLocations, ln as authoredWorldOf, lt as entriesOf, nn as cardFormat, nt as parseWorldInfoEdit, on as DICE_COMPARISONS, ot as createLorebook, p as structureImport, pt as lorebookDirectory, qt as parseDiceFile, rn as isPng, rt as combineAnswers, sn as DICE_READINGS, st as deleteLorebook, t as AuthoringTools, tn as ImportCardError, tt as parseWorldFile, u as keepDraft, ut as isLorebookName, vt as checkWorld, w as editWorldInfo, wt as populateClock, xt as knowsCharacter, yt as loadValidatedWorld } from "./authoring-tools-4NgDhIJV.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-DBk-V0hp.js";
4
- import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-CzogjK42.js";
5
- import { A as plotProgressOf, B as parsePlotsFile, C as readNotes, G as readDocument, H as COMMANDS_KEY, J as errorMessage, L as readUsage, Q as copyWorldPrompts, S as notesOfSession, T as defaultBoundaries, V as plotReferenceProblems, X as PROMPTS_FOLDER, Y as LANGUAGE_FOLDER, Z as PromptLibrary, _ as readTraces, b as readWithdrawn, ct as InvalidWorldError, dt as SessionNotFoundError, et as languageOf, ft as WorldNotFoundError, g as readRunDetail, h as readActivity, ht as zoneOf, j as populatePlots, k as PLOTS_METADATA_KEY, lt as ReflectionRefusedError, m as readDecisionStats, nt as promptProblem, o as externalTools, ot as AgentUnavailableError, q as formatIssue, rt as shippedLanguages, st as InvalidStartError, tt as listFiles, ut as SessionArchivedError, w as observeAsPlayer, x as addToNote } from "./hooks-BNeoGMHZ.js";
6
- 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-xvErE2yp.js";
7
- import { $ as IMPORT_FOLDER, Bt as LORE_KINDS, Ft as parseLoreEdit, G as deleteWorldPrompt, It as parsePlaceEdit, J as writeWorldPrompt, K as listWorldPrompts, Lt as parseRelationEdit, Mt as InvalidEditProblems, Nt as parseCharacterEdit, Ot as CHARACTER_FILE_NAME, Pt as parseFactionEdit, Q as withPlayer, Rt as parseThingEdit, Vt as LORE_SCOPES, Z as partsOf, _t as variableProblems, a as isPresetName, at as readImportFolder, c as presetDirectory, d as savePresetFromWorld, et as ImportNotFoundError, gt as parseVariablesFile, ht as loadVariables, i as deletePreset, it as parseChoices, kt as parseCharacterFile, mt as VARIABLES_FILE_NAME, o as listPresets, p as updatePresetInfo, pt as sourceSummary, q as readWorldPrompt, r as createPresetFromShipped, s as loadPreset, st as IMPORT_COMMAND, t as PRESET_FILE, tt as ImportStore, u as reservePreset, zt as guarded } from "./presets-DQ5rioMh.js";
8
- import { $ as DOCTOR_OPENING_SOURCE, A as worldEntityImageFile, B as languageOfDocuments, C as readWorldEditor, D as uploadWorldCharacterPortrait, E as replaceFile, F as PRESET_FILE$1, 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-C8EyX9Ix.js";
9
- import { a as VARIABLE_KINDS, i as atomicWriteSync, n as atomicWrite, o as VARIABLE_SUBJECTS, r as atomicWriteJson, s as VARIABLE_VISIBILITIES } from "./access-DAw54-NI.js";
1
+ import { A as chatSessionId, _ as RECOVERY_SHRINK, g as RECOVERY_FLOOR, h as sharedSamplingOf, i as childSamplingOf, j as roleplaySessionOf, m as parseSampling, s as isUnfinishedCall, w as totalTokens } from "./child-DTdY14S9.js";
2
+ import { Bt as isPng, E as loadWorldParts, F as localChanges, Ft as CHARACTERS_DIR, G as vetUrl, Ht as readCard, I as readOrigin, It as loadCharacters, Kt as authoredWorldOf, L as writeOrigin, Lt as knownOutputCeiling, M as describeChanges, N as hashWorld, P as isUnchanged, R as CatalogueError, Rt as ImportCardError, T as readWorldInfo, U as guardedLookup, Vt as pictureOf, _ as runChecks, at as populateCharacters, bt as loadLocations, c as importPhase, ct as populateFactions, d as markReady, dt as populateLocations, et as checkWorld, f as settleDraft, ft as populateLore, ht as populateVariables, it as populateCalendar, lt as populateItems, mt as populateTriggers, ot as populateClock, p as structureImport, pt as populateRoutines, qt as authoringChatSessionId, rt as knowsCharacter, st as populateDice, t as AuthoringTools, tt as loadValidatedWorld, u as keepDraft, ut as populateKnowledge, w as editWorldInfo, zt as cardFormat } from "./authoring-tools-BZr4bgBy.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-BjcEUo22.js";
4
+ import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-BUzO9mTW.js";
5
+ import { $ as copyWorldPrompts, A as plotProgressOf, B as parsePlotsFile, C as readNotes, G as readDocument, H as COMMANDS_KEY, J as errorMessage, L as readUsage, Q as PromptLibrary, S as notesOfSession, T as defaultBoundaries, V as plotReferenceProblems, Y as LANGUAGE_FOLDER, Z as PROMPTS_FOLDER, _ as readTraces, b as readWithdrawn, ct as InvalidStartError, dt as SessionArchivedError, ft as SessionNotFoundError, g as readRunDetail, gt as zoneOf, h as readActivity, it as shippedLanguages, j as populatePlots, k as PLOTS_METADATA_KEY, lt as InvalidWorldError, m as readDecisionStats, nt as listFiles, o as externalTools, pt as WorldNotFoundError, q as formatIssue, rt as promptProblem, st as AgentUnavailableError, tt as languageOf, ut as ReflectionRefusedError, w as observeAsPlayer, x as addToNote } from "./hooks-Dtq5KZQX.js";
6
+ 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--K2XVIHI.js";
7
+ import { $ as deleteWorldPrompt, $t as subfolders, Et as readImportFolder, F as parseWorldInfoEdit, G as loadPreset, H as deletePreset, I as combineAnswers, J as reservePreset, K as presetDirectory, L as questionView, M as WORLD_FILE_NAME, N as parseWorldFile, Ot as IMPORT_COMMAND, Pt as sourceSummary, Qt as parseCharacterFile, St as ImportStore, Tt as parseChoices, U as isPresetName, V as createPresetFromShipped, W as listPresets, Y as savePresetFromWorld, Z as updatePresetInfo, an as parseRelationEdit, at as deleteLorebook, bt as IMPORT_FOLDER, cn as LORE_KINDS, ct as isLorebookName, dt as lorebookDirectory, en as InvalidEditProblems, et as listWorldPrompts, ht as writeLorebookEntry, in as parsePlaceEdit, it as createLorebook, ln as LORE_SCOPES, lt as listLorebooks, mt as updateLorebookInfo, nn as parseFactionEdit, nt as writeWorldPrompt, on as parseThingEdit, ot as deleteLorebookEntry, pt as reserveLorebook, rn as parseLoreEdit, rt as addLorebookEntries, sn as guarded, st as entriesOf, tn as parseCharacterEdit, tt as readWorldPrompt, ut as loadLorebook, vt as partsOf, xt as ImportNotFoundError, yt as withPlayer, z as PRESET_FILE } from "./serial-BUaJGwVy.js";
8
+ import { $ as languageOfDocuments, A as generateWorldCharacterPortrait, C as editWorldFaction$1, D as editWorldPlots$1, E as editWorldPlace$1, F as uploadWorldCharacterPortrait, G as parseVariablesEdit, I as uploadWorldEntityImage, J as PRESET_FILE$1, K as parseDiceEdit, L as worldCharacterPortraitFile, M as readWorldEditor, N as readWorldTrigger, O as editWorldRelation$1, P as removeWorldTrigger, R as worldEntityImageFile, S as editWorldCharacter$1, T as editWorldNarrationVoice, U as parseCalendarEdit, W as parseRoutineEdit, Y as presetMessage, Z as translateMessage, _ as readCalendarDocument, a as deleteWorldPackFile, at as startUpdate, b as readRoutines, c as createAuthoredEntity, ct as authoringTitle, dt as agentServicesOf, et as readWorldDocuments, f as editCalendar, ft as DOCTOR_OPENING_SOURCE, g as editVariables, h as editRoutine, it as revertUpdate, j as generateWorldEntityImage, k as editWorldThing$1, l as deleteAuthoredEntity, lt as ensureAuthoringChat, m as editDice, mt as appendNarratedTurn, n as packFileProblem, ot as updateStatus, p as editCommands, pt as appendEmptyTurn, q as parseCommandsEdit, st as AuthoringSessions, t as MAX_PACK_TEXT, tt as findTargets, u as readAuthoredEntityDocument, ut as AgentSessions, v as readCommandsDocument, w as editWorldLore$1, x as readVariables, y as readDiceDocument, z as writeWorldTrigger } from "./pack-jail-Dt0VTsu0.js";
9
+ import { i as atomicWriteSync, n as atomicWrite, r as atomicWriteJson } from "./access-Csp80TFX.js";
10
10
  import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-Dfv8S8eq.js";
11
- import { _ as snapshotOf, c as copyPreset, d as switchPreset, f as readTimeline, g as pathTo, h as childrenOf, i as reflectionStatus, l as presetStatus, m as START_SNAPSHOT, o as TimelineError, p as writeTimeline, u as recordPreset } from "./reflection-buQiSdvq.js";
12
- import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-SJZyw0kt.js";
13
- import { C as slug, T as uniqueKey, d as sceneImagePath, s as inheritImages, t as addToLibrary, u as referenceImagePath } from "./library-BF9ZMSFz.js";
11
+ import { _ as snapshotOf, c as copyPreset, d as switchPreset, f as readTimeline, g as pathTo, h as childrenOf, i as reflectionStatus, l as presetStatus, m as START_SNAPSHOT, o as TimelineError, p as writeTimeline, u as recordPreset } from "./reflection-Dd3pEiZB.js";
12
+ import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-Dv5YF2qj.js";
13
+ import { C as slug, T as uniqueKey, d as sceneImagePath, s as inheritImages, t as addToLibrary, u as referenceImagePath } from "./library-DTxakw0z.js";
14
14
  import { o as FOLDER_ACCESS, r as InvalidFoldersError, t as StoryFoldersService } from "./service-mRKwpWjX.js";
15
15
  import { t as doctorChatSessionId } from "./doctor-chat-hL1a61hp.js";
16
- import { _ as API_PREFIX, a as packIds, c as describePack, d as packPath, f as readPack, l as isPackId, m as PACK_LIMITS, n as anyTab, o as syncWorldPacks, r as copyWorldPacks, s as worldPackStates, t as activePack, u as packFile } from "./packs-S0SzrVv-.js";
17
- import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-CI8fOnXy.js";
18
- import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-Ct6nm4UQ.js";
16
+ import { _ as API_PREFIX, a as packIds, c as describePack, d as packPath, f as readPack, l as isPackId, m as PACK_LIMITS, n as anyTab, o as syncWorldPacks, r as copyWorldPacks, s as worldPackStates, t as activePack, u as packFile } from "./packs-DWfR2Ted.js";
17
+ import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-9-5at9cZ.js";
18
+ import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-BNg0rPTp.js";
19
19
  import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
20
20
  import { SESSION_DATABASE_FILE, addLocalDays, createSessionStore, describeInstant, describeValue, holidaysOn, isSessionId, itemKey, lintWorld, locationKey, openSessionStore, parseInstant, readCalendar, seasonOf, sessionDatabase, sessionFolder, shownVariables, systemTimeZone } from "@dsh-agentic-roleplay/state";
21
21
  import { copyFileSync, cpSync, createReadStream, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
@@ -338,6 +338,15 @@ var RoleplayImport = class extends Service {
338
338
  super(ctx, "roleplayImport");
339
339
  this.read = read;
340
340
  }
341
+ turns = /* @__PURE__ */ new Map();
342
+ /** Notes that a turn of a chat ended; the authoring chats are the ones that report here. */
343
+ turnEnded(chat) {
344
+ this.turns.set(chat, (this.turns.get(chat) ?? 0) + 1);
345
+ }
346
+ /** How many turns of the chat have ended since the plugin started. */
347
+ turnsOf(chat) {
348
+ return this.turns.get(chat) ?? 0;
349
+ }
341
350
  /** The settings as they stand now: they are edited while the plugin runs. */
342
351
  get settings() {
343
352
  return this.read();
@@ -545,7 +554,7 @@ async function actOnDraft(deps, worldId, action, language) {
545
554
  await deps.worlds.list({ refresh: true });
546
555
  return {
547
556
  action,
548
- keptIn: relative(deps.root(), destination)
557
+ keptIn: relative(deps.root(), destination).split(sep).join("/")
549
558
  };
550
559
  }
551
560
  // src/host/sessions/statistics.ts
@@ -3263,7 +3272,7 @@ function languageField(value) {
3263
3272
  }
3264
3273
  // src/host/http/routes/worlds.ts
3265
3274
  /** The routes of the API for worlds. */
3266
- function worldsRoutes({ worlds, createWorld, starter, authorWorld, translation, worldCharacters, avatars, playtest }) {
3275
+ function worldsRoutes({ worlds, createWorld, starter, authorWorld, sayToAuthor, authoringStatus, chatStatus, forgetAuthoring, translation, worldCharacters, avatars, playtest }) {
3267
3276
  return {
3268
3277
  "/worlds": {
3269
3278
  GET: async (_req, res) => {
@@ -3319,9 +3328,44 @@ function worldsRoutes({ worlds, createWorld, starter, authorWorld, translation,
3319
3328
  throw error;
3320
3329
  }
3321
3330
  } },
3331
+ "/authoring/status": { GET: async (_req, res, url) => {
3332
+ sendJson(res, 200, chatStatus(url.searchParams.get("chat") ?? ""));
3333
+ } },
3334
+ "/worlds/authoring/chat": { DELETE: async (_req, res, url) => {
3335
+ try {
3336
+ await forgetAuthoring(url.searchParams.get("id") ?? "");
3337
+ sendJson(res, 200, { ok: true });
3338
+ } catch (error) {
3339
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
3340
+ throw error;
3341
+ }
3342
+ } },
3343
+ "/worlds/authoring/message": { POST: async (req, res, url) => {
3344
+ const body = await readJsonBody(req);
3345
+ if (typeof body.text !== "string" || body.text.trim() === "") return sendError(res, 400, "the request needs the text to say");
3346
+ try {
3347
+ sendJson(res, 202, await sayToAuthor(url.searchParams.get("id") ?? "", body.text, languageField(body.language)));
3348
+ } catch (error) {
3349
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
3350
+ if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
3351
+ throw error;
3352
+ }
3353
+ } },
3354
+ "/worlds/authoring/status": { GET: async (_req, res, url) => {
3355
+ try {
3356
+ sendJson(res, 200, await authoringStatus(url.searchParams.get("id") ?? ""));
3357
+ } catch (error) {
3358
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
3359
+ throw error;
3360
+ }
3361
+ } },
3322
3362
  "/worlds/language": { GET: async (_req, res, url) => {
3323
3363
  try {
3324
- sendJson(res, 200, { language: await translation.language(url.searchParams.get("id") ?? "") ?? null });
3364
+ const id = url.searchParams.get("id") ?? "";
3365
+ sendJson(res, 200, {
3366
+ language: await translation.language(id) ?? null,
3367
+ declared: await translation.declared(id) ?? null
3368
+ });
3325
3369
  } catch (error) {
3326
3370
  if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
3327
3371
  throw error;
@@ -3796,298 +3840,6 @@ function importsRoutes({ importer }) {
3796
3840
  } }
3797
3841
  };
3798
3842
  }
3799
- // src/shared/world-dice.ts
3800
- const isObject$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3801
- const CHECK_FIELDS = [
3802
- "key",
3803
- "name",
3804
- "use",
3805
- "dice",
3806
- "reading",
3807
- "hit",
3808
- "compare",
3809
- "modifier",
3810
- "bands"
3811
- ];
3812
- const BAND_FIELDS = [
3813
- "min",
3814
- "max",
3815
- "label",
3816
- "result",
3817
- "critical"
3818
- ];
3819
- /** 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. */
3820
- function parseDiceEdit(value) {
3821
- const problems = [];
3822
- if (!isObject$1(value) || !Array.isArray(value["checks"])) throw new InvalidEditProblems(["the dice must be { checks: [...] }"]);
3823
- const checks = value["checks"].map((entry, index) => {
3824
- const at = `checks[${index}]`;
3825
- const empty = {
3826
- key: "",
3827
- name: "",
3828
- use: "",
3829
- dice: "",
3830
- bands: []
3831
- };
3832
- if (!isObject$1(entry)) {
3833
- problems.push(`${at} must be an object`);
3834
- return empty;
3835
- }
3836
- for (const key of Object.keys(entry)) if (!CHECK_FIELDS.includes(key)) problems.push(`${at}.${key} is not a field of a check`);
3837
- for (const key of [
3838
- "key",
3839
- "name",
3840
- "use",
3841
- "dice"
3842
- ]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
3843
- if (entry["reading"] !== void 0 && !DICE_READINGS.includes(entry["reading"])) problems.push(`${at}.reading must be one of: ${DICE_READINGS.join(", ")}`);
3844
- if (entry["compare"] !== void 0 && !DICE_COMPARISONS.includes(entry["compare"])) problems.push(`${at}.compare must be one of: ${DICE_COMPARISONS.join(", ")}`);
3845
- if (entry["hit"] !== void 0 && (typeof entry["hit"] !== "number" || !Number.isInteger(entry["hit"]))) problems.push(`${at}.hit must be a whole number`);
3846
- if (entry["modifier"] !== void 0 && typeof entry["modifier"] !== "string") problems.push(`${at}.modifier must be text`);
3847
- const bands = Array.isArray(entry["bands"]) ? entry["bands"] : void 0;
3848
- if (bands === void 0) problems.push(`${at}.bands must be a list`);
3849
- const text = (field) => typeof field === "string" ? field.trim() : "";
3850
- const hit = entry["hit"];
3851
- return {
3852
- key: text(entry["key"]),
3853
- name: text(entry["name"]),
3854
- use: text(entry["use"]),
3855
- dice: text(entry["dice"]),
3856
- ...entry["reading"] === void 0 ? {} : { reading: entry["reading"] },
3857
- ...typeof hit === "number" ? { hit } : {},
3858
- ...entry["compare"] === void 0 ? {} : { compare: entry["compare"] },
3859
- ...text(entry["modifier"]) === "" ? {} : { modifier: text(entry["modifier"]) },
3860
- bands: (bands ?? []).map((band, bandIndex) => {
3861
- const where = `${at}.bands[${bandIndex}]`;
3862
- if (!isObject$1(band)) {
3863
- problems.push(`${where} must be an object`);
3864
- return {
3865
- label: "",
3866
- result: "failed"
3867
- };
3868
- }
3869
- for (const key of Object.keys(band)) if (!BAND_FIELDS.includes(key)) problems.push(`${where}.${key} is not a field of a band`);
3870
- 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`);
3871
- if (typeof band["label"] !== "string") problems.push(`${where}.label must be text`);
3872
- if (!DICE_RESULTS.includes(band["result"])) problems.push(`${where}.result must be one of: ${DICE_RESULTS.join(", ")}`);
3873
- const min = band["min"];
3874
- const max = band["max"];
3875
- return {
3876
- label: text(band["label"]),
3877
- result: band["result"],
3878
- ...typeof min === "number" ? { min } : {},
3879
- ...typeof max === "number" ? { max } : {},
3880
- ...band["critical"] === true ? { critical: true } : {}
3881
- };
3882
- })
3883
- };
3884
- });
3885
- if (problems.length > 0) throw new InvalidEditProblems(problems);
3886
- return { checks };
3887
- }
3888
- // src/shared/world-daily.ts
3889
- const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3890
- const ROUTINE_FIELDS = [
3891
- "days",
3892
- "on",
3893
- "from",
3894
- "to",
3895
- "activity",
3896
- "location",
3897
- "feature",
3898
- "position",
3899
- "interruptible",
3900
- "sleep"
3901
- ];
3902
- /**
3903
- * The windows of a day as the browser sends them.
3904
- * @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.
3905
- */
3906
- function parseRoutineEdit(value) {
3907
- const problems = [];
3908
- const list = isObject(value) && Array.isArray(value["windows"]) ? value["windows"] : void 0;
3909
- if (list === void 0) throw new InvalidEditProblems(["the day must be { windows: [...] }"]);
3910
- const windows = list.map((entry, index) => {
3911
- const at = `windows[${index}]`;
3912
- if (!isObject(entry)) {
3913
- problems.push(`${at} must be an object`);
3914
- return {
3915
- days: [],
3916
- from: "",
3917
- to: "",
3918
- activity: "",
3919
- interruptible: true
3920
- };
3921
- }
3922
- for (const key of Object.keys(entry)) if (!ROUTINE_FIELDS.includes(key)) problems.push(`${at}.${key} is not a field of a window`);
3923
- for (const key of [
3924
- "from",
3925
- "to",
3926
- "activity"
3927
- ]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
3928
- for (const key of [
3929
- "location",
3930
- "feature",
3931
- "position"
3932
- ]) if (entry[key] !== void 0 && typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
3933
- 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`);
3934
- if (entry["interruptible"] !== void 0 && typeof entry["interruptible"] !== "boolean") problems.push(`${at}.interruptible must be true or false`);
3935
- if (entry["sleep"] !== void 0 && typeof entry["sleep"] !== "boolean") problems.push(`${at}.sleep must be true or false`);
3936
- const text = (key) => typeof entry[key] === "string" ? entry[key].trim() : "";
3937
- return {
3938
- days: Array.isArray(entry["days"]) ? entry["days"].map((day) => day.trim().toLowerCase()).filter((day) => day !== "") : [],
3939
- ...Array.isArray(entry["on"]) && entry["on"].length > 0 ? { on: entry["on"].map((day) => String(day).trim()).filter((day) => day !== "") } : {},
3940
- from: text("from"),
3941
- to: text("to"),
3942
- activity: text("activity"),
3943
- ...text("location") === "" ? {} : { location: text("location") },
3944
- ...text("feature") === "" ? {} : { feature: text("feature") },
3945
- ...text("position") === "" ? {} : { position: text("position") },
3946
- interruptible: entry["interruptible"] !== false,
3947
- ...entry["sleep"] === true ? { sleep: true } : {}
3948
- };
3949
- });
3950
- if (problems.length > 0) throw new InvalidEditProblems(problems);
3951
- return windows;
3952
- }
3953
- const VARIABLE_FIELDS = [
3954
- "key",
3955
- "name",
3956
- "kind",
3957
- "subject",
3958
- "visibility",
3959
- "description",
3960
- "update",
3961
- "min",
3962
- "max",
3963
- "integer",
3964
- "baseline",
3965
- "always",
3966
- "default",
3967
- "only",
3968
- "options",
3969
- "bands"
3970
- ];
3971
- /**
3972
- * The declarations as the browser sends them, with empty fields left out. Whether they are acceptable together is checked against the world's files.
3973
- * @throws {InvalidEditProblems} naming every field that has the wrong shape.
3974
- */
3975
- function parseVariablesEdit(value) {
3976
- const problems = [];
3977
- const list = isObject(value) && Array.isArray(value["variables"]) ? value["variables"] : void 0;
3978
- if (list === void 0) throw new InvalidEditProblems(["the variables must be { variables: [...] }"]);
3979
- const declarations = list.flatMap((entry, index) => {
3980
- const at = `variables[${index}]`;
3981
- if (!isObject(entry)) {
3982
- problems.push(`${at} must be an object`);
3983
- return [];
3984
- }
3985
- for (const key of Object.keys(entry)) if (!VARIABLE_FIELDS.includes(key)) problems.push(`${at}.${key} is not a field of a variable`);
3986
- const text = (key) => typeof entry[key] === "string" ? entry[key].trim() : "";
3987
- const number = (key) => {
3988
- if (entry[key] === void 0 || entry[key] === null || entry[key] === "") return void 0;
3989
- if (typeof entry[key] !== "number" || !Number.isFinite(entry[key])) {
3990
- problems.push(`${at}.${key} must be a number`);
3991
- return;
3992
- }
3993
- return entry[key];
3994
- };
3995
- const flag = (key) => {
3996
- if (entry[key] === void 0) return void 0;
3997
- if (typeof entry[key] !== "boolean") {
3998
- problems.push(`${at}.${key} must be true or false`);
3999
- return;
4000
- }
4001
- return entry[key];
4002
- };
4003
- const strings = (key) => {
4004
- if (entry[key] === void 0) return [];
4005
- if (!(Array.isArray(entry[key]) && entry[key].every((item) => typeof item === "string"))) {
4006
- problems.push(`${at}.${key} must be a list of text`);
4007
- return [];
4008
- }
4009
- return entry[key].map((item) => item.trim()).filter((item) => item !== "");
4010
- };
4011
- const bands = Array.isArray(entry["bands"]) ? entry["bands"].flatMap((band) => isObject(band) && typeof band["up_to"] === "number" && typeof band["label"] === "string" && band["label"].trim() !== "" ? [{
4012
- up_to: band["up_to"],
4013
- label: band["label"].trim()
4014
- }] : (problems.push(`${at}.bands needs { up_to, label } entries`), [])) : [];
4015
- const rawDefault = entry["default"];
4016
- 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`);
4017
- for (const [key, allowed] of [
4018
- ["kind", VARIABLE_KINDS],
4019
- ["subject", VARIABLE_SUBJECTS],
4020
- ["visibility", VARIABLE_VISIBILITIES]
4021
- ]) if (!allowed.includes(text(key))) problems.push(`${at}.${key} must be one of: ${allowed.join(", ")}`);
4022
- const [min, max] = [number("min"), number("max")];
4023
- const [integer, baseline, always] = [
4024
- flag("integer"),
4025
- flag("baseline"),
4026
- flag("always")
4027
- ];
4028
- const only = strings("only");
4029
- const options = strings("options");
4030
- return [{
4031
- key: text("key"),
4032
- name: text("name"),
4033
- kind: text("kind"),
4034
- subject: text("subject"),
4035
- visibility: text("visibility"),
4036
- ...text("description") === "" ? {} : { description: text("description") },
4037
- ...text("update") === "" ? {} : { update: text("update") },
4038
- ...min === void 0 ? {} : { min },
4039
- ...max === void 0 ? {} : { max },
4040
- ...integer === true ? { integer } : {},
4041
- ...baseline === true ? { baseline } : {},
4042
- ...always === true ? { always } : {},
4043
- ...rawDefault === void 0 || rawDefault === null || rawDefault === "" ? {} : { default: rawDefault },
4044
- ...only.length === 0 ? {} : { only },
4045
- ...options.length === 0 ? {} : { options },
4046
- ...bands.length === 0 ? {} : { bands }
4047
- }];
4048
- });
4049
- if (problems.length > 0) throw new InvalidEditProblems(problems);
4050
- return declarations;
4051
- }
4052
- /**
4053
- * The calendar as the browser sends it.
4054
- * @throws {InvalidEditProblems} naming every field that has the wrong shape; whether the days and ids are acceptable is checked as the file is read.
4055
- */
4056
- function parseCalendarEdit(value) {
4057
- const problems = [];
4058
- if (!isObject(value)) throw new InvalidEditProblems(["the calendar must be { hemisphere, holidays: [...] }"]);
4059
- if (value["hemisphere"] !== "north" && value["hemisphere"] !== "south") problems.push("hemisphere must be \"north\" or \"south\"");
4060
- const list = Array.isArray(value["holidays"]) ? value["holidays"] : void 0;
4061
- if (list === void 0) problems.push("holidays must be a list");
4062
- const holidays = (list ?? []).map((entry, index) => {
4063
- const at = `holidays[${index}]`;
4064
- if (!isObject(entry)) {
4065
- problems.push(`${at} must be an object`);
4066
- return {
4067
- id: "",
4068
- name: "",
4069
- on: []
4070
- };
4071
- }
4072
- for (const key of Object.keys(entry)) if (![
4073
- "id",
4074
- "name",
4075
- "on"
4076
- ].includes(key)) problems.push(`${at}.${key} is not a field of a holiday`);
4077
- for (const key of ["id", "name"]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
4078
- if (!(Array.isArray(entry["on"]) && entry["on"].every((day) => typeof day === "string"))) problems.push(`${at}.on must be a list of days`);
4079
- return {
4080
- id: typeof entry["id"] === "string" ? entry["id"].trim() : "",
4081
- name: typeof entry["name"] === "string" ? entry["name"].trim() : "",
4082
- on: Array.isArray(entry["on"]) ? entry["on"].map((day) => String(day).trim()).filter((day) => day !== "") : []
4083
- };
4084
- });
4085
- if (problems.length > 0) throw new InvalidEditProblems(problems);
4086
- return {
4087
- hemisphere: value["hemisphere"],
4088
- holidays
4089
- };
4090
- }
4091
3843
  // src/host/http/routes/worldFiles.ts
4092
3844
  /** The routes of the API for worldFiles. */
4093
3845
  function worldFilesRoutes({ worldFiles, worldEditor, sessions }) {
@@ -4343,6 +4095,28 @@ function worldFilesRoutes({ worldFiles, worldEditor, sessions }) {
4343
4095
  }
4344
4096
  }
4345
4097
  },
4098
+ "/worlds/commands": {
4099
+ GET: async (_req, res, url) => {
4100
+ try {
4101
+ sendJson(res, 200, await worldFiles.commands(url.searchParams.get("id") ?? ""));
4102
+ } catch (error) {
4103
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
4104
+ throw error;
4105
+ }
4106
+ },
4107
+ PUT: async (req, res, url) => {
4108
+ try {
4109
+ sendJson(res, 200, await worldFiles.editCommands(url.searchParams.get("id") ?? "", parseCommandsEdit(await readJsonBody(req))));
4110
+ } catch (error) {
4111
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
4112
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
4113
+ message: error.message,
4114
+ problems: error.problems
4115
+ });
4116
+ throw error;
4117
+ }
4118
+ }
4119
+ },
4346
4120
  "/worlds/calendar": {
4347
4121
  GET: async (_req, res, url) => {
4348
4122
  try {
@@ -6061,13 +5835,23 @@ function purgeDepsOf(ctx, storePath) {
6061
5835
  const purgeOf = (ctx, storePath) => (chat) => purgeChat(purgeDepsOf(ctx, storePath), chat);
6062
5836
  // src/host/setup/rows.ts
6063
5837
  const ALL = ["@dsh-agentic-roleplay/all", "dsh-agentic-roleplay"];
6064
- const SINGLE = [
6065
- "@dsh-agentic-roleplay/core",
6066
- "@dsh-agentic-roleplay/state",
6067
- "dsh-agentic-roleplay-core",
6068
- "dsh-roleplay-state"
6069
- ];
6070
- /** The bundle layers the profile has selected, in order; none when the profile cannot be read. */
5838
+ const CORE = ["@dsh-agentic-roleplay/core", "dsh-agentic-roleplay-core"];
5839
+ const STATE = ["@dsh-agentic-roleplay/state", "dsh-roleplay-state"];
5840
+ /**
5841
+ * The profile directory DSH launched this plugin in: `DSH_PROFILE_DIR`, which a profile-launched Host carries, or
5842
+ * `DSH_HOME/profiles/<DSH_PROFILE>` when only those are set (a `dsh` CLI launch). Both are environment facts; a
5843
+ * Harness booted without a profile has none.
5844
+ */
5845
+ function profileDirectory() {
5846
+ if (process.env.DSH_PROFILE_DIR !== void 0) return process.env.DSH_PROFILE_DIR;
5847
+ const home = process.env.DSH_HOME;
5848
+ const profile = process.env.DSH_PROFILE;
5849
+ return home === void 0 || profile === void 0 ? void 0 : join(home, "profiles", profile);
5850
+ }
5851
+ /**
5852
+ * The bundle layers the profile has selected, in order; none when there is no profile to read. DSH exposes no
5853
+ * service for a profile's selected bundles, so this reads the profile's own manifest — never writes it.
5854
+ */
6071
5855
  function selectedBundles(profileDir) {
6072
5856
  if (profileDir === void 0) return [];
6073
5857
  try {
@@ -6077,166 +5861,13 @@ function selectedBundles(profileDir) {
6077
5861
  return [];
6078
5862
  }
6079
5863
  }
6080
- /**
6081
- * The layers of single packages that are selected next to the `all` layer. Each of them inserts the same plugin row as `all`, so the profile then holds the row twice
6082
- * and DSH, which writes a plugin's settings through its row, refuses every save of Settings → Role Play.
6083
- */
5864
+ /** Layers made redundant by a selected complete install. Duplicate rows prevent DSH from saving their settings. */
6084
5865
  function redundantLayers(bundles) {
6085
- return bundles.some((name) => ALL.includes(name)) ? bundles.filter((name) => SINGLE.includes(name)) : [];
5866
+ if (bundles.some((name) => ALL.includes(name))) return bundles.filter((name) => CORE.includes(name) || STATE.includes(name));
5867
+ return bundles.some((name) => CORE.includes(name)) ? bundles.filter((name) => STATE.includes(name)) : [];
6086
5868
  }
6087
5869
  function redundantLayersMessage(layers) {
6088
- 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`;
6089
- }
6090
- // src/host/worlds/daily-life.ts
6091
- /** The day each character lives, and the places its windows may name. */
6092
- async function readRoutines(world) {
6093
- const [{ characters }, { locations }] = await Promise.all([loadCharacters(world.directory), loadLocations(world.directory)]);
6094
- return {
6095
- characters: characters.map((character) => ({
6096
- key: character.id,
6097
- name: character.name,
6098
- routine: character.routine ?? []
6099
- })),
6100
- places: locations.map((place) => ({
6101
- key: place.id,
6102
- name: place.name,
6103
- features: place.features.map((feature) => ({
6104
- key: feature.key,
6105
- name: feature.name
6106
- }))
6107
- }))
6108
- };
6109
- }
6110
- /**
6111
- * Replaces the day of one character in its file, keeping everything else in it. The times, days and places are checked as the world is read at a start.
6112
- * @throws {InvalidEditProblems} when the character does not exist or a window is not acceptable; nothing is written.
6113
- */
6114
- async function editRoutine(world, key, windows) {
6115
- const folder = await entityFolder(world.directory, CHARACTERS_DIR, CHARACTER_FILE_NAME, key, parseCharacterFile);
6116
- if (folder === void 0) throw new InvalidEditProblems([`there is no character "${key}"`]);
6117
- const file = join(world.directory, CHARACTERS_DIR, folder, CHARACTER_FILE_NAME);
6118
- const text = (await readFile(file, "utf8")).replace(/^/, "");
6119
- const document = JSON.parse(text);
6120
- if (windows.length === 0) delete document["routine"];
6121
- else document["routine"] = windows;
6122
- const next = JSON.stringify(document, null, /^([ \t]+)"/m.exec(text)?.[1] ?? " ") + (text.endsWith("\n") ? "\n" : "");
6123
- const parsed = parseCharacterFile(next, folder);
6124
- if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
6125
- const { locations } = await loadLocations(world.directory);
6126
- const { calendar } = await loadCalendar(world.directory);
6127
- const places = routineProblems([parsed.value], locations, calendar);
6128
- if (places.length > 0) throw new InvalidEditProblems(places);
6129
- await replaceFile(file, next);
6130
- return await readRoutines(world);
6131
- }
6132
- /** The variables the world declares, as the file writes them. */
6133
- async function readVariables(world) {
6134
- try {
6135
- const parsed = JSON.parse((await readFile(join(world.directory, VARIABLES_FILE_NAME), "utf8")).replace(/^/, ""));
6136
- return Array.isArray(parsed) ? parsed : [];
6137
- } catch (error) {
6138
- if (error.code === "ENOENT") return [];
6139
- throw error;
6140
- }
6141
- }
6142
- /**
6143
- * Replaces the world's declarations. They are read as the world is at a start and checked against everything that has a value for one: a variable a
6144
- * character, item, place or the world still gives a value to cannot be removed, and a value must still fit its declaration.
6145
- * @throws {InvalidEditProblems} naming each problem; nothing is written.
6146
- */
6147
- async function editVariables(world, declarations) {
6148
- const text = `${JSON.stringify(declarations, null, 2)}\n`;
6149
- const parsed = parseVariablesFile(text);
6150
- if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
6151
- const [{ characters }, { locations }] = await Promise.all([loadCharacters(world.directory), loadLocations(world.directory)]);
6152
- const { items } = await loadItems(world.directory, {
6153
- characters: characters.map((character) => character.id),
6154
- locations
6155
- });
6156
- const worldFile = parseWorldFile(await readFile(join(world.directory, WORLD_FILE_NAME), "utf8"));
6157
- const problems = variableProblems({
6158
- defs: parsed.value,
6159
- characters,
6160
- items,
6161
- locations,
6162
- values: worldFile.ok ? worldFile.value.variables : void 0
6163
- });
6164
- if (problems.length > 0) throw new InvalidEditProblems(problems);
6165
- if (declarations.length === 0) await rm(join(world.directory, VARIABLES_FILE_NAME), { force: true });
6166
- else await replaceFileOrCreate(join(world.directory, VARIABLES_FILE_NAME), text);
6167
- return await readVariables(world);
6168
- }
6169
- async function replaceFileOrCreate(file, text) {
6170
- try {
6171
- await replaceFile(file, text);
6172
- } catch (error) {
6173
- if (error.code !== "ENOENT") throw error;
6174
- await writeFile(file, text, { flag: "wx" });
6175
- }
6176
- }
6177
- /** The calendar of the world as `calendar.json` writes it; a world without one has the northern seasons and no holidays. */
6178
- async function readCalendarDocument(world) {
6179
- const { calendar } = await loadCalendar(world.directory);
6180
- return {
6181
- hemisphere: calendar.hemisphere,
6182
- holidays: calendar.holidays.map((holiday) => ({
6183
- id: holiday.id,
6184
- name: holiday.name,
6185
- on: [...holiday.on]
6186
- }))
6187
- };
6188
- }
6189
- /**
6190
- * Replaces the calendar. The days are read as the file is at a start, and a holiday that a routine of a character or a trigger still names cannot be removed or renamed.
6191
- * A calendar with no holidays and the northern seasons is no file at all.
6192
- * @throws {InvalidEditProblems} naming each problem; nothing is written.
6193
- */
6194
- async function editCalendar(world, calendar) {
6195
- const text = `${JSON.stringify(calendar, null, 2)}\n`;
6196
- const parsed = parseCalendarFile(text);
6197
- if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
6198
- const [{ characters }, { locations }] = await Promise.all([loadCharacters(world.directory), loadLocations(world.directory)]);
6199
- const problems = routineProblems(characters, locations, parsed.value);
6200
- const triggers = await readFile(join(world.directory, TRIGGERS_FILE_NAME), "utf8").catch((error) => {
6201
- if (error.code === "ENOENT") return "";
6202
- throw error;
6203
- });
6204
- const named = new Set(calendar.holidays.map((holiday) => holiday.id));
6205
- for (const id of new Set([...triggers.matchAll(/holiday:([\p{L}\p{N}_-]+)/gu)].map((match) => match[1]))) if (!named.has(id)) problems.push(`a trigger names the holiday "${id}", which the calendar does not have`);
6206
- if (problems.length > 0) throw new InvalidEditProblems(problems);
6207
- if (calendar.holidays.length === 0 && calendar.hemisphere === "north") await rm(join(world.directory, CALENDAR_FILE_NAME), { force: true });
6208
- else await replaceFileOrCreate(join(world.directory, CALENDAR_FILE_NAME), text);
6209
- return await readCalendarDocument(world);
6210
- }
6211
- /** The checks of a world as its `dice.json` has them; none without the file. */
6212
- async function readDiceDocument(world) {
6213
- const { checks } = await loadDice(world.directory);
6214
- return { checks };
6215
- }
6216
- /**
6217
- * Replaces the world's checks. They are read as a story start reads them, and a quality of the character that a check adds must be a number the world
6218
- * declares for characters. No checks is no file at all.
6219
- * @throws {InvalidEditProblems} naming each problem; nothing is written.
6220
- */
6221
- async function editDice(world, dice) {
6222
- const written = dice.checks.map(({ reading, compare, ...check }) => ({
6223
- ...check,
6224
- ...reading === void 0 || reading === "total" ? {} : { reading },
6225
- ...compare === void 0 || compare === "absolute" ? {} : { compare }
6226
- }));
6227
- const text = `${JSON.stringify({ checks: written }, null, 2)}\n`;
6228
- const parsed = parseDiceFile(text);
6229
- if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
6230
- const declared = await loadVariables(world.directory);
6231
- const problems = parsed.value.flatMap((check) => {
6232
- if (check.modifier === void 0) return [];
6233
- const variable = declared.defs.find((def) => def.key === check.modifier);
6234
- return variable === void 0 || variable.kind !== "number" || variable.subject !== "character" ? [`the check "${check.key}" adds "${check.modifier}", which the world does not declare as a number about characters (Tracked values)`] : [];
6235
- });
6236
- if (problems.length > 0) throw new InvalidEditProblems(problems);
6237
- if (dice.checks.length === 0) await rm(join(world.directory, DICE_FILE_NAME), { force: true });
6238
- else await replaceFileOrCreate(join(world.directory, DICE_FILE_NAME), text);
6239
- return await readDiceDocument(world);
5870
+ return `the profile selects ${layers.map((name) => `"${name}"`).join(", ")} next to a layer that already inserts the same plugin rows (the all bundle, or the core package, which includes the state plugin), so DSH refuses to save the Role Play settings: deselect them (keep the packages installed) and restart`;
6240
5871
  }
6241
5872
  // src/host/worlds/lore-entries.ts
6242
5873
  const MAX_TITLE = 200;
@@ -7252,6 +6883,13 @@ async function startSession(deps, request) {
7252
6883
  mode: answers.clockMode
7253
6884
  }
7254
6885
  };
6886
+ if (world.language !== void 0 && (request.settings?.prompts)?.language === void 0) settings = {
6887
+ ...settings,
6888
+ prompts: {
6889
+ ...settings.prompts,
6890
+ language: world.language
6891
+ }
6892
+ };
7255
6893
  const givenAutonomy = (request.settings?.autonomy)?.enabled;
7256
6894
  if (world.autonomy === true && givenAutonomy === void 0) settings = {
7257
6895
  ...settings,
@@ -8047,6 +7685,7 @@ async function loadWorld(folder, dir, file, problems) {
8047
7685
  ...world.autonomy === void 0 ? {} : { autonomy: world.autonomy },
8048
7686
  ...world.narrationVoice === void 0 ? {} : { narrationVoice: world.narrationVoice },
8049
7687
  ...world.sampling === void 0 ? {} : { sampling: world.sampling },
7688
+ ...world.language === void 0 ? {} : { language: world.language },
8050
7689
  ...world.preset === void 0 ? {} : { preset: world.preset },
8051
7690
  ...world.lorebooks === void 0 ? {} : { lorebooks: world.lorebooks }
8052
7691
  };
@@ -8249,7 +7888,11 @@ async function installWorld(catalog, archive, maxBytes, options) {
8249
7888
  await mkdir(catalog.directory, { recursive: true });
8250
7889
  if (replacing !== void 0) {
8251
7890
  placed = basename(replacing.directory);
8252
- backup = join(".trash", "worlds", `${placed}-${stamp()}`);
7891
+ backup = [
7892
+ ".trash",
7893
+ "worlds",
7894
+ `${placed}-${stamp()}`
7895
+ ].join("/");
8253
7896
  await mkdir(join(root, dirname(backup)), { recursive: true });
8254
7897
  await rename(replacing.directory, join(root, backup));
8255
7898
  } else placed = freeFolder(catalog.directory, folder);
@@ -10107,7 +9750,7 @@ const name = "@dsh-agentic-roleplay/core";
10107
9750
  /** Sessions are kept by the state plugin, which the bundle installs with this one. */
10108
9751
  const inject = ["roleplayState"];
10109
9752
  function apply(ctx, config) {
10110
- const layers = () => redundantLayers(selectedBundles(ctx.get("profileContext")?.dir));
9753
+ const layers = () => redundantLayers(selectedBundles(profileDirectory()));
10111
9754
  const repeated = layers();
10112
9755
  if (repeated.length > 0) ctx.logger.error(redundantLayersMessage(repeated));
10113
9756
  ctx.inject(["aiProviders"], (scope) => {
@@ -10219,6 +9862,14 @@ function apply(ctx, config) {
10219
9862
  };
10220
9863
  const staging = new ImportStaging();
10221
9864
  const purgeChat = purgeOf(ctx, config.sessionStorePath);
9865
+ const chatStatus = (chatSessionId) => {
9866
+ const live = ctx.get("agents")?.get(SessionId(chatSessionId));
9867
+ return {
9868
+ chatSessionId,
9869
+ turns: roleplayImport.turnsOf(chatSessionId),
9870
+ running: live !== void 0 && live.status !== "idle"
9871
+ };
9872
+ };
10222
9873
  const deps = {
10223
9874
  worlds,
10224
9875
  state: ctx.roleplayState,
@@ -10394,8 +10045,31 @@ function apply(ctx, config) {
10394
10045
  if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
10395
10046
  return { chatSessionId: await authoring.ensure(world.summary.id, world.summary.name, title, language) };
10396
10047
  },
10048
+ sayToAuthor: async (worldId, text, language) => {
10049
+ const world = await worlds.find(worldId);
10050
+ if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
10051
+ const chatSessionId = await authoring.ensure(world.summary.id, world.summary.name, void 0, language);
10052
+ await authoring.send(chatSessionId, text);
10053
+ return { chatSessionId };
10054
+ },
10055
+ authoringStatus: async (worldId) => {
10056
+ const world = await worlds.find(worldId);
10057
+ if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
10058
+ return chatStatus(authoringChatSessionId(world.summary.id));
10059
+ },
10060
+ chatStatus,
10061
+ forgetAuthoring: async (worldId) => {
10062
+ const world = await worlds.find(worldId);
10063
+ if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
10064
+ await purgeChat(authoringChatSessionId(world.summary.id));
10065
+ },
10397
10066
  translation: {
10398
10067
  language: (id) => worldLanguage(worlds, id),
10068
+ declared: async (id) => {
10069
+ const record = await worlds.find(id);
10070
+ if (record === void 0) throw new WorldNotFoundError(`there is no world with id "${id}"`);
10071
+ return record.language;
10072
+ },
10399
10073
  start: (id, to, title, language) => startTranslation({
10400
10074
  worlds,
10401
10075
  authoring,
@@ -10499,6 +10173,8 @@ function apply(ctx, config) {
10499
10173
  editRoutine: async (worldId, key, windows) => await editRoutine(await editableWorld(worlds, worldId, root.path), key, windows),
10500
10174
  dice: async (worldId) => await readDiceDocument(await editableWorld(worlds, worldId, root.path)),
10501
10175
  editDice: async (worldId, dice) => await editDice(await editableWorld(worlds, worldId, root.path), dice),
10176
+ commands: async (worldId) => await readCommandsDocument(await editableWorld(worlds, worldId, root.path)),
10177
+ editCommands: async (worldId, commands) => await editCommands(await editableWorld(worlds, worldId, root.path), commands),
10502
10178
  calendar: async (worldId) => await readCalendarDocument(await editableWorld(worlds, worldId, root.path)),
10503
10179
  editCalendar: async (worldId, calendar) => await editCalendar(await editableWorld(worlds, worldId, root.path), calendar),
10504
10180
  variables: async (worldId) => await readVariables(await editableWorld(worlds, worldId, root.path)),