@dsh-agentic-roleplay/core 0.11.1 → 0.12.1

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 (61) hide show
  1. package/lib/{access-Md1YTSX1.js → access-DifaiHrI.js} +3 -15
  2. package/lib/{authoring-tools-BFdw7ahj.js → authoring-tools-VOaXzr_R.js} +58 -766
  3. package/lib/authoring.js +136 -13
  4. package/lib/{child-C9nPIy9j.js → child-DzZ-aI6k.js} +130 -2
  5. package/lib/client.js +17093 -2269
  6. package/lib/client.js.map +1 -1
  7. package/lib/compaction.js +3 -3
  8. package/lib/dev-context-Bdm-eVer.js +40 -0
  9. package/lib/doctor.js +5 -3
  10. package/lib/{gallery-BWHmjogd.js → gallery-Ctz-UoFk.js} +3 -3
  11. package/lib/{generator-QCdm8nUh.js → generator-Cv6WWmZT.js} +2 -2
  12. package/lib/helper.js +15 -1
  13. package/lib/{hooks-C2U1-8ur.js → hooks-BdR3mBeM.js} +751 -344
  14. package/lib/images.js +4 -4
  15. package/lib/index.js +342 -463
  16. package/lib/jail-Cp4zEfip.js +107 -0
  17. package/lib/{library-4zmCAshR.js → library-BU2A_Dx8.js} +3 -3
  18. package/lib/{lorebook-author-tools-Bjfjt3bg.js → lorebook-author-tools-DUKcQu8P.js} +20 -7
  19. package/lib/lorebook-authoring.js +12 -5
  20. package/lib/{narration-b_VBEUWn.js → narration-CDsJ5wxH.js} +29 -2
  21. package/lib/orchestration.js +615 -48
  22. package/lib/{pack-jail-Ci9bIeDI.js → pack-jail-CzHQu0n3.js} +559 -23
  23. package/lib/{packs-CYkozh8Q.js → packs-BZ-45J4-.js} +2 -2
  24. package/lib/{presenter-agent-CqkAL03Q.js → presenter-agent-C2ZkoxZu.js} +9 -9
  25. package/lib/{preset-B-35yUmt.js → preset-BPnRPW-1.js} +4 -4
  26. package/lib/{preset-author-tools-BUymqZM5.js → preset-author-tools-DBqPwn-o.js} +9 -8
  27. package/lib/preset-authoring.js +11 -6
  28. package/lib/{reflection-B9N0z3KY.js → reflection-Cuy0YLv0.js} +22 -16
  29. package/lib/{presets-_U-xroo0.js → serial-BZNeK57v.js} +1305 -331
  30. package/lib/service-mRKwpWjX.js +140 -0
  31. package/lib/{text-C2AGl7Je.js → text-Dfv8S8eq.js} +27 -2
  32. package/lib/{turn-guard-C0M3rXEN.js → turn-guard-xaFxYc1T.js} +3 -3
  33. package/locale/de.json +6 -0
  34. package/locale/en.json +6 -0
  35. package/locale/es.json +6 -0
  36. package/locale/fr.json +6 -0
  37. package/locale/ja.json +6 -0
  38. package/locale/pt.json +6 -0
  39. package/locale/ru.json +6 -0
  40. package/locale/zh.json +6 -0
  41. package/package.json +34 -34
  42. package/prompts/en/import/finish-ok.md +1 -1
  43. package/prompts/en/import/generator.md +1 -1
  44. package/prompts/en/import/style.md +2 -1
  45. package/prompts/en/import/variables.md +2 -1
  46. package/prompts/en/roleplay/character-lookup.md +1 -1
  47. package/prompts/en/roleplay/decide-errand.md +1 -0
  48. package/prompts/en/roleplay/decide-message.md +1 -0
  49. package/prompts/en/roleplay/dream.md +1 -0
  50. package/prompts/en/roleplay/gate-repeat.md +1 -0
  51. package/prompts/en/world/procedure.md +1 -1
  52. package/prompts/zh/import/finish-ok.md +1 -1
  53. package/prompts/zh/import/generator.md +1 -1
  54. package/prompts/zh/import/style.md +2 -1
  55. package/prompts/zh/import/variables.md +2 -1
  56. package/prompts/zh/roleplay/character-lookup.md +1 -1
  57. package/prompts/zh/roleplay/decide-errand.md +1 -0
  58. package/prompts/zh/roleplay/decide-message.md +1 -0
  59. package/prompts/zh/roleplay/dream.md +1 -0
  60. package/prompts/zh/roleplay/gate-repeat.md +1 -0
  61. package/prompts/zh/world/procedure.md +1 -1
package/lib/index.js CHANGED
@@ -1,20 +1,21 @@
1
- import { a as VARIABLE_KINDS, c as chatSessionId, i as atomicWriteSync, l as roleplaySessionOf, n as atomicWrite, o as VARIABLE_SUBJECTS, r as atomicWriteJson, s as VARIABLE_VISIBILITIES } from "./access-Md1YTSX1.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-BFdw7ahj.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-Bjfjt3bg.js";
4
- import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-BUymqZM5.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, i as externalTools, j as populatePlots, k as PLOTS_METADATA_KEY, lt as ReflectionRefusedError, m as readDecisionStats, nt as promptProblem, 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-C2U1-8ur.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-b_VBEUWn.js";
7
- import { $ as IMPORT_FOLDER, At as InvalidEditProblems, Dt as parseCharacterFile, Et as CHARACTER_FILE_NAME, Ft as parseRelationEdit, G as deleteWorldPrompt, It as parseThingEdit, J as writeWorldPrompt, K as listWorldPrompts, Lt as guarded, Mt as parseFactionEdit, Nt as parseLoreEdit, Pt as parsePlaceEdit, Q as withPlayer, Rt as LORE_KINDS, Z as partsOf, a as isPresetName, at as readImportFolder, c as presetDirectory, ct as sourceSummary, d as savePresetFromWorld, et as ImportNotFoundError, ft as VARIABLES_FILE_NAME, ht as variableProblems, i as deletePreset, it as parseChoices, jt as parseCharacterEdit, lt as IMPORT_COMMAND, mt as parseVariablesFile, o as listPresets, p as updatePresetInfo, pt as loadVariables, q as readWorldPrompt, r as createPresetFromShipped, s as loadPreset, t as PRESET_FILE, tt as ImportStore, u as reservePreset, zt as LORE_SCOPES } from "./presets-_U-xroo0.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-Ci9bIeDI.js";
9
- import { d as parseSampling, f as sharedSamplingOf, i as childSamplingOf, m as RECOVERY_SHRINK, p as RECOVERY_FLOOR, s as isUnfinishedCall, x as totalTokens } from "./child-C9nPIy9j.js";
10
- import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-C2AGl7Je.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-B9N0z3KY.js";
12
- import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-B-35yUmt.js";
13
- import { C as slug, T as uniqueKey, d as sceneImagePath, s as inheritImages, t as addToLibrary, u as referenceImagePath } from "./library-4zmCAshR.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-DzZ-aI6k.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-VOaXzr_R.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-DUKcQu8P.js";
4
+ import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-DBqPwn-o.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-BdR3mBeM.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-CDsJ5wxH.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-BZNeK57v.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-CzHQu0n3.js";
9
+ import { i as atomicWriteSync, n as atomicWrite, r as atomicWriteJson } from "./access-DifaiHrI.js";
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-Cuy0YLv0.js";
12
+ import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-BPnRPW-1.js";
13
+ import { C as slug, T as uniqueKey, d as sceneImagePath, s as inheritImages, t as addToLibrary, u as referenceImagePath } from "./library-BU2A_Dx8.js";
14
+ import { o as FOLDER_ACCESS, r as InvalidFoldersError, t as StoryFoldersService } from "./service-mRKwpWjX.js";
14
15
  import { t as doctorChatSessionId } from "./doctor-chat-hL1a61hp.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-CYkozh8Q.js";
16
- import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-QCdm8nUh.js";
17
- import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-BWHmjogd.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-BZ-45J4-.js";
17
+ import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-Cv6WWmZT.js";
18
+ import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-Ctz-UoFk.js";
18
19
  import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
19
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";
20
21
  import { copyFileSync, cpSync, createReadStream, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
@@ -337,6 +338,15 @@ var RoleplayImport = class extends Service {
337
338
  super(ctx, "roleplayImport");
338
339
  this.read = read;
339
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
+ }
340
350
  /** The settings as they stand now: they are edited while the plugin runs. */
341
351
  get settings() {
342
352
  return this.read();
@@ -544,7 +554,7 @@ async function actOnDraft(deps, worldId, action, language) {
544
554
  await deps.worlds.list({ refresh: true });
545
555
  return {
546
556
  action,
547
- keptIn: relative(deps.root(), destination)
557
+ keptIn: relative(deps.root(), destination).split(sep).join("/")
548
558
  };
549
559
  }
550
560
  // src/host/sessions/statistics.ts
@@ -1464,6 +1474,49 @@ var Lorebooks = class {
1464
1474
  };
1465
1475
  }
1466
1476
  };
1477
+ // src/host/autonomy/ticker.ts
1478
+ /**
1479
+ * Looks at the stories that switched on going on while their player is away, one after the other and one at a time: a story that did not is never touched, and
1480
+ * a story that cannot be looked at is reported and left for the next time.
1481
+ */
1482
+ var AutonomyTicker = class {
1483
+ deps;
1484
+ running = false;
1485
+ constructor(deps) {
1486
+ this.deps = deps;
1487
+ }
1488
+ /** @returns how many stories were looked at. */
1489
+ async run(signal) {
1490
+ if (this.running) return 0;
1491
+ this.running = true;
1492
+ let looked = 0;
1493
+ try {
1494
+ for (const session of this.deps.sessions()) {
1495
+ if (signal.aborted) break;
1496
+ if (session.archived) continue;
1497
+ let on;
1498
+ try {
1499
+ const { autonomy, clock } = this.deps.settings(session.id);
1500
+ on = autonomy.enabled && clock.mode === "real";
1501
+ } catch (error) {
1502
+ this.deps.problem(`the settings of "${session.name}" could not be read: ${error instanceof Error ? error.message : String(error)}`);
1503
+ continue;
1504
+ }
1505
+ if (!on) continue;
1506
+ try {
1507
+ await this.deps.ensure(session.id, session.name);
1508
+ await this.deps.tick(`session-${session.id}`, signal);
1509
+ looked += 1;
1510
+ } catch (error) {
1511
+ if (!signal.aborted) this.deps.problem(`"${session.name}" could not be looked at while its player is away: ${error instanceof Error ? error.message : String(error)}`);
1512
+ }
1513
+ }
1514
+ } finally {
1515
+ this.running = false;
1516
+ }
1517
+ return looked;
1518
+ }
1519
+ };
1467
1520
  const KIND = {
1468
1521
  folder: "sessions",
1469
1522
  projectTitle: "Session Doctor",
@@ -1543,6 +1596,11 @@ var RoleplayOrchestration = class extends Service {
1543
1596
  recallPreview = () => Promise.reject(/* @__PURE__ */ new Error("the orchestration is not running"));
1544
1597
  /** Whether a turn of the chat is being played; there while the orchestration is. */
1545
1598
  playing = () => false;
1599
+ /** One look at a story that goes on while its player is away (the characters' days, and perhaps a message); there while the orchestration is. */
1600
+ autonomy = () => Promise.resolve({
1601
+ outcome: "off",
1602
+ moved: 0
1603
+ });
1546
1604
  /** Whether a reflection of the chat is running; there while the orchestration is. */
1547
1605
  reflecting = () => false;
1548
1606
  /** What the story's turns are and taking the story back to one; there while the orchestration is. */
@@ -2140,6 +2198,48 @@ function lorebookRoutes(api) {
2140
2198
  } }
2141
2199
  };
2142
2200
  }
2201
+ // src/host/workspace/routes.ts
2202
+ function parseFolders(body) {
2203
+ if (!Array.isArray(body["folders"])) return "\"folders\" must be a list";
2204
+ const folders = [];
2205
+ for (const entry of body["folders"]) {
2206
+ const folder = entry;
2207
+ if (typeof folder !== "object" || folder === null || typeof folder["path"] !== "string" || !FOLDER_ACCESS.includes(folder["access"])) return "each folder needs a \"path\" and an \"access\" of read or write";
2208
+ folders.push({
2209
+ path: folder["path"],
2210
+ access: folder["access"]
2211
+ });
2212
+ }
2213
+ return folders;
2214
+ }
2215
+ function folderRoutes(api) {
2216
+ const failed = (res, error) => {
2217
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
2218
+ if (error instanceof InvalidFoldersError) return sendJson(res, 422, {
2219
+ message: error.message,
2220
+ problems: error.problems
2221
+ });
2222
+ throw error;
2223
+ };
2224
+ return { "/sessions/folders": {
2225
+ GET: async (_req, res, url) => {
2226
+ try {
2227
+ sendJson(res, 200, await api.status(url.searchParams.get("id") ?? ""));
2228
+ } catch (error) {
2229
+ failed(res, error);
2230
+ }
2231
+ },
2232
+ PUT: async (req, res, url) => {
2233
+ const folders = parseFolders(await readJsonBody(req));
2234
+ if (typeof folders === "string") return sendError(res, 400, folders);
2235
+ try {
2236
+ sendJson(res, 200, await api.set(url.searchParams.get("id") ?? "", folders));
2237
+ } catch (error) {
2238
+ failed(res, error);
2239
+ }
2240
+ }
2241
+ } };
2242
+ }
2143
2243
  // src/host/prompts/routes.ts
2144
2244
  function promptRoutes(api) {
2145
2245
  const fail = (res, error) => {
@@ -2449,7 +2549,7 @@ function playerViewOf(session, options) {
2449
2549
  summary: player.summary,
2450
2550
  publicState: playerState?.publicState ?? ""
2451
2551
  };
2452
- view.variables.push(...shown(player.name, shownVariables(session, "character", player.id, keyOf$3(player), "others")));
2552
+ view.variables.push(...shown(player.name, shownVariables(session, "character", player.id, keyOf$3(player), "self")));
2453
2553
  const placement = session.placements.get("character", player.id);
2454
2554
  const here = placement === void 0 ? void 0 : session.locations.get(placement.locationId);
2455
2555
  const known = new Set(session.knowledge.list(player.id, "location").map((entry) => entry.subjectId));
@@ -3172,7 +3272,7 @@ function languageField(value) {
3172
3272
  }
3173
3273
  // src/host/http/routes/worlds.ts
3174
3274
  /** The routes of the API for worlds. */
3175
- 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 }) {
3176
3276
  return {
3177
3277
  "/worlds": {
3178
3278
  GET: async (_req, res) => {
@@ -3228,6 +3328,37 @@ function worldsRoutes({ worlds, createWorld, starter, authorWorld, translation,
3228
3328
  throw error;
3229
3329
  }
3230
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
+ } },
3231
3362
  "/worlds/language": { GET: async (_req, res, url) => {
3232
3363
  try {
3233
3364
  sendJson(res, 200, { language: await translation.language(url.searchParams.get("id") ?? "") ?? null });
@@ -3705,295 +3836,6 @@ function importsRoutes({ importer }) {
3705
3836
  } }
3706
3837
  };
3707
3838
  }
3708
- // src/shared/world-dice.ts
3709
- const isObject$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3710
- const CHECK_FIELDS = [
3711
- "key",
3712
- "name",
3713
- "use",
3714
- "dice",
3715
- "reading",
3716
- "hit",
3717
- "compare",
3718
- "modifier",
3719
- "bands"
3720
- ];
3721
- const BAND_FIELDS = [
3722
- "min",
3723
- "max",
3724
- "label",
3725
- "result",
3726
- "critical"
3727
- ];
3728
- /** 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. */
3729
- function parseDiceEdit(value) {
3730
- const problems = [];
3731
- if (!isObject$1(value) || !Array.isArray(value["checks"])) throw new InvalidEditProblems(["the dice must be { checks: [...] }"]);
3732
- const checks = value["checks"].map((entry, index) => {
3733
- const at = `checks[${index}]`;
3734
- const empty = {
3735
- key: "",
3736
- name: "",
3737
- use: "",
3738
- dice: "",
3739
- bands: []
3740
- };
3741
- if (!isObject$1(entry)) {
3742
- problems.push(`${at} must be an object`);
3743
- return empty;
3744
- }
3745
- for (const key of Object.keys(entry)) if (!CHECK_FIELDS.includes(key)) problems.push(`${at}.${key} is not a field of a check`);
3746
- for (const key of [
3747
- "key",
3748
- "name",
3749
- "use",
3750
- "dice"
3751
- ]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
3752
- if (entry["reading"] !== void 0 && !DICE_READINGS.includes(entry["reading"])) problems.push(`${at}.reading must be one of: ${DICE_READINGS.join(", ")}`);
3753
- if (entry["compare"] !== void 0 && !DICE_COMPARISONS.includes(entry["compare"])) problems.push(`${at}.compare must be one of: ${DICE_COMPARISONS.join(", ")}`);
3754
- if (entry["hit"] !== void 0 && (typeof entry["hit"] !== "number" || !Number.isInteger(entry["hit"]))) problems.push(`${at}.hit must be a whole number`);
3755
- if (entry["modifier"] !== void 0 && typeof entry["modifier"] !== "string") problems.push(`${at}.modifier must be text`);
3756
- const bands = Array.isArray(entry["bands"]) ? entry["bands"] : void 0;
3757
- if (bands === void 0) problems.push(`${at}.bands must be a list`);
3758
- const text = (field) => typeof field === "string" ? field.trim() : "";
3759
- const hit = entry["hit"];
3760
- return {
3761
- key: text(entry["key"]),
3762
- name: text(entry["name"]),
3763
- use: text(entry["use"]),
3764
- dice: text(entry["dice"]),
3765
- ...entry["reading"] === void 0 ? {} : { reading: entry["reading"] },
3766
- ...typeof hit === "number" ? { hit } : {},
3767
- ...entry["compare"] === void 0 ? {} : { compare: entry["compare"] },
3768
- ...text(entry["modifier"]) === "" ? {} : { modifier: text(entry["modifier"]) },
3769
- bands: (bands ?? []).map((band, bandIndex) => {
3770
- const where = `${at}.bands[${bandIndex}]`;
3771
- if (!isObject$1(band)) {
3772
- problems.push(`${where} must be an object`);
3773
- return {
3774
- label: "",
3775
- result: "failed"
3776
- };
3777
- }
3778
- for (const key of Object.keys(band)) if (!BAND_FIELDS.includes(key)) problems.push(`${where}.${key} is not a field of a band`);
3779
- 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`);
3780
- if (typeof band["label"] !== "string") problems.push(`${where}.label must be text`);
3781
- if (!DICE_RESULTS.includes(band["result"])) problems.push(`${where}.result must be one of: ${DICE_RESULTS.join(", ")}`);
3782
- const min = band["min"];
3783
- const max = band["max"];
3784
- return {
3785
- label: text(band["label"]),
3786
- result: band["result"],
3787
- ...typeof min === "number" ? { min } : {},
3788
- ...typeof max === "number" ? { max } : {},
3789
- ...band["critical"] === true ? { critical: true } : {}
3790
- };
3791
- })
3792
- };
3793
- });
3794
- if (problems.length > 0) throw new InvalidEditProblems(problems);
3795
- return { checks };
3796
- }
3797
- // src/shared/world-daily.ts
3798
- const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3799
- const ROUTINE_FIELDS = [
3800
- "days",
3801
- "on",
3802
- "from",
3803
- "to",
3804
- "activity",
3805
- "location",
3806
- "feature",
3807
- "position",
3808
- "interruptible"
3809
- ];
3810
- /**
3811
- * The windows of a day as the browser sends them.
3812
- * @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.
3813
- */
3814
- function parseRoutineEdit(value) {
3815
- const problems = [];
3816
- const list = isObject(value) && Array.isArray(value["windows"]) ? value["windows"] : void 0;
3817
- if (list === void 0) throw new InvalidEditProblems(["the day must be { windows: [...] }"]);
3818
- const windows = list.map((entry, index) => {
3819
- const at = `windows[${index}]`;
3820
- if (!isObject(entry)) {
3821
- problems.push(`${at} must be an object`);
3822
- return {
3823
- days: [],
3824
- from: "",
3825
- to: "",
3826
- activity: "",
3827
- interruptible: true
3828
- };
3829
- }
3830
- for (const key of Object.keys(entry)) if (!ROUTINE_FIELDS.includes(key)) problems.push(`${at}.${key} is not a field of a window`);
3831
- for (const key of [
3832
- "from",
3833
- "to",
3834
- "activity"
3835
- ]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
3836
- for (const key of [
3837
- "location",
3838
- "feature",
3839
- "position"
3840
- ]) if (entry[key] !== void 0 && typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
3841
- 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`);
3842
- if (entry["interruptible"] !== void 0 && typeof entry["interruptible"] !== "boolean") problems.push(`${at}.interruptible must be true or false`);
3843
- const text = (key) => typeof entry[key] === "string" ? entry[key].trim() : "";
3844
- return {
3845
- days: Array.isArray(entry["days"]) ? entry["days"].map((day) => day.trim().toLowerCase()).filter((day) => day !== "") : [],
3846
- ...Array.isArray(entry["on"]) && entry["on"].length > 0 ? { on: entry["on"].map((day) => String(day).trim()).filter((day) => day !== "") } : {},
3847
- from: text("from"),
3848
- to: text("to"),
3849
- activity: text("activity"),
3850
- ...text("location") === "" ? {} : { location: text("location") },
3851
- ...text("feature") === "" ? {} : { feature: text("feature") },
3852
- ...text("position") === "" ? {} : { position: text("position") },
3853
- interruptible: entry["interruptible"] !== false
3854
- };
3855
- });
3856
- if (problems.length > 0) throw new InvalidEditProblems(problems);
3857
- return windows;
3858
- }
3859
- const VARIABLE_FIELDS = [
3860
- "key",
3861
- "name",
3862
- "kind",
3863
- "subject",
3864
- "visibility",
3865
- "description",
3866
- "update",
3867
- "min",
3868
- "max",
3869
- "integer",
3870
- "baseline",
3871
- "always",
3872
- "default",
3873
- "only",
3874
- "options",
3875
- "bands"
3876
- ];
3877
- /**
3878
- * The declarations as the browser sends them, with empty fields left out. Whether they are acceptable together is checked against the world's files.
3879
- * @throws {InvalidEditProblems} naming every field that has the wrong shape.
3880
- */
3881
- function parseVariablesEdit(value) {
3882
- const problems = [];
3883
- const list = isObject(value) && Array.isArray(value["variables"]) ? value["variables"] : void 0;
3884
- if (list === void 0) throw new InvalidEditProblems(["the variables must be { variables: [...] }"]);
3885
- const declarations = list.flatMap((entry, index) => {
3886
- const at = `variables[${index}]`;
3887
- if (!isObject(entry)) {
3888
- problems.push(`${at} must be an object`);
3889
- return [];
3890
- }
3891
- for (const key of Object.keys(entry)) if (!VARIABLE_FIELDS.includes(key)) problems.push(`${at}.${key} is not a field of a variable`);
3892
- const text = (key) => typeof entry[key] === "string" ? entry[key].trim() : "";
3893
- const number = (key) => {
3894
- if (entry[key] === void 0 || entry[key] === null || entry[key] === "") return void 0;
3895
- if (typeof entry[key] !== "number" || !Number.isFinite(entry[key])) {
3896
- problems.push(`${at}.${key} must be a number`);
3897
- return;
3898
- }
3899
- return entry[key];
3900
- };
3901
- const flag = (key) => {
3902
- if (entry[key] === void 0) return void 0;
3903
- if (typeof entry[key] !== "boolean") {
3904
- problems.push(`${at}.${key} must be true or false`);
3905
- return;
3906
- }
3907
- return entry[key];
3908
- };
3909
- const strings = (key) => {
3910
- if (entry[key] === void 0) return [];
3911
- if (!(Array.isArray(entry[key]) && entry[key].every((item) => typeof item === "string"))) {
3912
- problems.push(`${at}.${key} must be a list of text`);
3913
- return [];
3914
- }
3915
- return entry[key].map((item) => item.trim()).filter((item) => item !== "");
3916
- };
3917
- const bands = Array.isArray(entry["bands"]) ? entry["bands"].flatMap((band) => isObject(band) && typeof band["up_to"] === "number" && typeof band["label"] === "string" && band["label"].trim() !== "" ? [{
3918
- up_to: band["up_to"],
3919
- label: band["label"].trim()
3920
- }] : (problems.push(`${at}.bands needs { up_to, label } entries`), [])) : [];
3921
- const rawDefault = entry["default"];
3922
- 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`);
3923
- for (const [key, allowed] of [
3924
- ["kind", VARIABLE_KINDS],
3925
- ["subject", VARIABLE_SUBJECTS],
3926
- ["visibility", VARIABLE_VISIBILITIES]
3927
- ]) if (!allowed.includes(text(key))) problems.push(`${at}.${key} must be one of: ${allowed.join(", ")}`);
3928
- const [min, max] = [number("min"), number("max")];
3929
- const [integer, baseline, always] = [
3930
- flag("integer"),
3931
- flag("baseline"),
3932
- flag("always")
3933
- ];
3934
- const only = strings("only");
3935
- const options = strings("options");
3936
- return [{
3937
- key: text("key"),
3938
- name: text("name"),
3939
- kind: text("kind"),
3940
- subject: text("subject"),
3941
- visibility: text("visibility"),
3942
- ...text("description") === "" ? {} : { description: text("description") },
3943
- ...text("update") === "" ? {} : { update: text("update") },
3944
- ...min === void 0 ? {} : { min },
3945
- ...max === void 0 ? {} : { max },
3946
- ...integer === true ? { integer } : {},
3947
- ...baseline === true ? { baseline } : {},
3948
- ...always === true ? { always } : {},
3949
- ...rawDefault === void 0 || rawDefault === null || rawDefault === "" ? {} : { default: rawDefault },
3950
- ...only.length === 0 ? {} : { only },
3951
- ...options.length === 0 ? {} : { options },
3952
- ...bands.length === 0 ? {} : { bands }
3953
- }];
3954
- });
3955
- if (problems.length > 0) throw new InvalidEditProblems(problems);
3956
- return declarations;
3957
- }
3958
- /**
3959
- * The calendar as the browser sends it.
3960
- * @throws {InvalidEditProblems} naming every field that has the wrong shape; whether the days and ids are acceptable is checked as the file is read.
3961
- */
3962
- function parseCalendarEdit(value) {
3963
- const problems = [];
3964
- if (!isObject(value)) throw new InvalidEditProblems(["the calendar must be { hemisphere, holidays: [...] }"]);
3965
- if (value["hemisphere"] !== "north" && value["hemisphere"] !== "south") problems.push("hemisphere must be \"north\" or \"south\"");
3966
- const list = Array.isArray(value["holidays"]) ? value["holidays"] : void 0;
3967
- if (list === void 0) problems.push("holidays must be a list");
3968
- const holidays = (list ?? []).map((entry, index) => {
3969
- const at = `holidays[${index}]`;
3970
- if (!isObject(entry)) {
3971
- problems.push(`${at} must be an object`);
3972
- return {
3973
- id: "",
3974
- name: "",
3975
- on: []
3976
- };
3977
- }
3978
- for (const key of Object.keys(entry)) if (![
3979
- "id",
3980
- "name",
3981
- "on"
3982
- ].includes(key)) problems.push(`${at}.${key} is not a field of a holiday`);
3983
- for (const key of ["id", "name"]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
3984
- if (!(Array.isArray(entry["on"]) && entry["on"].every((day) => typeof day === "string"))) problems.push(`${at}.on must be a list of days`);
3985
- return {
3986
- id: typeof entry["id"] === "string" ? entry["id"].trim() : "",
3987
- name: typeof entry["name"] === "string" ? entry["name"].trim() : "",
3988
- on: Array.isArray(entry["on"]) ? entry["on"].map((day) => String(day).trim()).filter((day) => day !== "") : []
3989
- };
3990
- });
3991
- if (problems.length > 0) throw new InvalidEditProblems(problems);
3992
- return {
3993
- hemisphere: value["hemisphere"],
3994
- holidays
3995
- };
3996
- }
3997
3839
  // src/host/http/routes/worldFiles.ts
3998
3840
  /** The routes of the API for worldFiles. */
3999
3841
  function worldFilesRoutes({ worldFiles, worldEditor, sessions }) {
@@ -4249,6 +4091,28 @@ function worldFilesRoutes({ worldFiles, worldEditor, sessions }) {
4249
4091
  }
4250
4092
  }
4251
4093
  },
4094
+ "/worlds/commands": {
4095
+ GET: async (_req, res, url) => {
4096
+ try {
4097
+ sendJson(res, 200, await worldFiles.commands(url.searchParams.get("id") ?? ""));
4098
+ } catch (error) {
4099
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
4100
+ throw error;
4101
+ }
4102
+ },
4103
+ PUT: async (req, res, url) => {
4104
+ try {
4105
+ sendJson(res, 200, await worldFiles.editCommands(url.searchParams.get("id") ?? "", parseCommandsEdit(await readJsonBody(req))));
4106
+ } catch (error) {
4107
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
4108
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
4109
+ message: error.message,
4110
+ problems: error.problems
4111
+ });
4112
+ throw error;
4113
+ }
4114
+ }
4115
+ },
4252
4116
  "/worlds/calendar": {
4253
4117
  GET: async (_req, res, url) => {
4254
4118
  try {
@@ -4848,6 +4712,7 @@ async function writeJournal(sessionsDir, id, body, now = () => /* @__PURE__ */ n
4848
4712
  // src/shared/reference.ts
4849
4713
  /** The pages of the reference: what the player may look up about the story, never what only the story knows. */
4850
4714
  const REFERENCE_SECTIONS = [
4715
+ "status",
4851
4716
  "profile",
4852
4717
  "people",
4853
4718
  "places",
@@ -5085,8 +4950,71 @@ function quests(session, options) {
5085
4950
  ...threads.filter((thread) => thread.status === "resolved").reverse()
5086
4951
  ];
5087
4952
  }
4953
+ /**
4954
+ * Every tracked value the player may read, by subject: the world's, their own (private ones too), the place's, those of the people they have met or are with, and of the things they carry
4955
+ * or see lying about, without the feelings every story has (the profile tells those in words). What is hidden, and what is private to someone else, is not read.
4956
+ */
4957
+ function status(session) {
4958
+ const stand = standpoint(session);
4959
+ if (stand === void 0) return [];
4960
+ const values = (kind, id, key, audience) => shownVariables(session, kind, id, key, audience, { all: true }).filter(({ variable }) => variable.builtin !== true).map(({ variable, value }) => ({
4961
+ name: variable.name,
4962
+ value: describeValue(variable, value)
4963
+ }));
4964
+ const groups = [
4965
+ {
4966
+ subject: "world",
4967
+ values: values("world", 0, "world", "others")
4968
+ },
4969
+ {
4970
+ subject: "player",
4971
+ key: keyOf$1(stand.player),
4972
+ name: stand.player.name,
4973
+ values: values("character", stand.player.id, keyOf$1(stand.player), "self")
4974
+ },
4975
+ ...stand.here === void 0 ? [] : [{
4976
+ subject: "place",
4977
+ key: locationKey(stand.here),
4978
+ name: stand.here.name,
4979
+ here: true,
4980
+ values: values("location", stand.here.id, locationKey(stand.here), "others")
4981
+ }],
4982
+ ...people(session).flatMap((person) => {
4983
+ const character = session.characters.list().find((candidate) => keyOf$1(candidate) === person.key);
4984
+ return character === void 0 ? [] : [{
4985
+ subject: "person",
4986
+ key: person.key,
4987
+ name: person.name,
4988
+ here: person.here,
4989
+ values: values("character", character.id, person.key, "others")
4990
+ }];
4991
+ })
4992
+ ];
4993
+ const things = [...session.items.contents({
4994
+ kind: "character",
4995
+ id: stand.player.id
4996
+ }).map((entry) => ({
4997
+ entry,
4998
+ here: false
4999
+ })), ...stand.here === void 0 ? [] : session.items.contents({
5000
+ kind: "location",
5001
+ id: stand.here.id
5002
+ }).map((entry) => ({
5003
+ entry,
5004
+ here: true
5005
+ }))].filter(({ entry }) => !entry.item.hidden);
5006
+ for (const { entry, here } of things) groups.push({
5007
+ subject: "thing",
5008
+ key: itemKey(entry.item),
5009
+ name: entry.item.name,
5010
+ here,
5011
+ values: values("item", entry.item.id, itemKey(entry.item), "others")
5012
+ });
5013
+ return groups.filter((group) => group.values.length > 0);
5014
+ }
5088
5015
  /** One page per section; a new page is a new entry here and in `REFERENCE_SECTIONS`. */
5089
5016
  const PAGES = {
5017
+ status,
5090
5018
  profile,
5091
5019
  people,
5092
5020
  places,
@@ -5681,6 +5609,7 @@ function createApiHandler(deps) {
5681
5609
  ...interfaceRoutes(packs),
5682
5610
  ...presetRoutes(presets),
5683
5611
  ...lorebookRoutes(lorebooks),
5612
+ ...folderRoutes(deps.folders),
5684
5613
  ...promptRoutes(deps.prompts),
5685
5614
  ...syncRoutes(sync)
5686
5615
  };
@@ -5758,7 +5687,8 @@ async function deleteSession(deps, id) {
5758
5687
  const ROOT_LAYOUT = [
5759
5688
  "characters",
5760
5689
  "sessions",
5761
- "worlds"
5690
+ "worlds",
5691
+ "workspace"
5762
5692
  ];
5763
5693
  /**
5764
5694
  * Resolve the configured root to an absolute, normalized path.
@@ -5907,7 +5837,21 @@ const SINGLE = [
5907
5837
  "dsh-agentic-roleplay-core",
5908
5838
  "dsh-roleplay-state"
5909
5839
  ];
5910
- /** The bundle layers the profile has selected, in order; none when the profile cannot be read. */
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
+ */
5911
5855
  function selectedBundles(profileDir) {
5912
5856
  if (profileDir === void 0) return [];
5913
5857
  try {
@@ -5927,157 +5871,6 @@ function redundantLayers(bundles) {
5927
5871
  function redundantLayersMessage(layers) {
5928
5872
  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`;
5929
5873
  }
5930
- // src/host/worlds/daily-life.ts
5931
- /** The day each character lives, and the places its windows may name. */
5932
- async function readRoutines(world) {
5933
- const [{ characters }, { locations }] = await Promise.all([loadCharacters(world.directory), loadLocations(world.directory)]);
5934
- return {
5935
- characters: characters.map((character) => ({
5936
- key: character.id,
5937
- name: character.name,
5938
- routine: character.routine ?? []
5939
- })),
5940
- places: locations.map((place) => ({
5941
- key: place.id,
5942
- name: place.name,
5943
- features: place.features.map((feature) => ({
5944
- key: feature.key,
5945
- name: feature.name
5946
- }))
5947
- }))
5948
- };
5949
- }
5950
- /**
5951
- * 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.
5952
- * @throws {InvalidEditProblems} when the character does not exist or a window is not acceptable; nothing is written.
5953
- */
5954
- async function editRoutine(world, key, windows) {
5955
- const folder = await entityFolder(world.directory, CHARACTERS_DIR, CHARACTER_FILE_NAME, key, parseCharacterFile);
5956
- if (folder === void 0) throw new InvalidEditProblems([`there is no character "${key}"`]);
5957
- const file = join(world.directory, CHARACTERS_DIR, folder, CHARACTER_FILE_NAME);
5958
- const text = (await readFile(file, "utf8")).replace(/^/, "");
5959
- const document = JSON.parse(text);
5960
- if (windows.length === 0) delete document["routine"];
5961
- else document["routine"] = windows;
5962
- const next = JSON.stringify(document, null, /^([ \t]+)"/m.exec(text)?.[1] ?? " ") + (text.endsWith("\n") ? "\n" : "");
5963
- const parsed = parseCharacterFile(next, folder);
5964
- if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
5965
- const { locations } = await loadLocations(world.directory);
5966
- const { calendar } = await loadCalendar(world.directory);
5967
- const places = routineProblems([parsed.value], locations, calendar);
5968
- if (places.length > 0) throw new InvalidEditProblems(places);
5969
- await replaceFile(file, next);
5970
- return await readRoutines(world);
5971
- }
5972
- /** The variables the world declares, as the file writes them. */
5973
- async function readVariables(world) {
5974
- try {
5975
- const parsed = JSON.parse((await readFile(join(world.directory, VARIABLES_FILE_NAME), "utf8")).replace(/^/, ""));
5976
- return Array.isArray(parsed) ? parsed : [];
5977
- } catch (error) {
5978
- if (error.code === "ENOENT") return [];
5979
- throw error;
5980
- }
5981
- }
5982
- /**
5983
- * 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
5984
- * character, item, place or the world still gives a value to cannot be removed, and a value must still fit its declaration.
5985
- * @throws {InvalidEditProblems} naming each problem; nothing is written.
5986
- */
5987
- async function editVariables(world, declarations) {
5988
- const text = `${JSON.stringify(declarations, null, 2)}\n`;
5989
- const parsed = parseVariablesFile(text);
5990
- if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
5991
- const [{ characters }, { locations }] = await Promise.all([loadCharacters(world.directory), loadLocations(world.directory)]);
5992
- const { items } = await loadItems(world.directory, {
5993
- characters: characters.map((character) => character.id),
5994
- locations
5995
- });
5996
- const worldFile = parseWorldFile(await readFile(join(world.directory, WORLD_FILE_NAME), "utf8"));
5997
- const problems = variableProblems({
5998
- defs: parsed.value,
5999
- characters,
6000
- items,
6001
- locations,
6002
- values: worldFile.ok ? worldFile.value.variables : void 0
6003
- });
6004
- if (problems.length > 0) throw new InvalidEditProblems(problems);
6005
- if (declarations.length === 0) await rm(join(world.directory, VARIABLES_FILE_NAME), { force: true });
6006
- else await replaceFileOrCreate(join(world.directory, VARIABLES_FILE_NAME), text);
6007
- return await readVariables(world);
6008
- }
6009
- async function replaceFileOrCreate(file, text) {
6010
- try {
6011
- await replaceFile(file, text);
6012
- } catch (error) {
6013
- if (error.code !== "ENOENT") throw error;
6014
- await writeFile(file, text, { flag: "wx" });
6015
- }
6016
- }
6017
- /** The calendar of the world as `calendar.json` writes it; a world without one has the northern seasons and no holidays. */
6018
- async function readCalendarDocument(world) {
6019
- const { calendar } = await loadCalendar(world.directory);
6020
- return {
6021
- hemisphere: calendar.hemisphere,
6022
- holidays: calendar.holidays.map((holiday) => ({
6023
- id: holiday.id,
6024
- name: holiday.name,
6025
- on: [...holiday.on]
6026
- }))
6027
- };
6028
- }
6029
- /**
6030
- * 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.
6031
- * A calendar with no holidays and the northern seasons is no file at all.
6032
- * @throws {InvalidEditProblems} naming each problem; nothing is written.
6033
- */
6034
- async function editCalendar(world, calendar) {
6035
- const text = `${JSON.stringify(calendar, null, 2)}\n`;
6036
- const parsed = parseCalendarFile(text);
6037
- if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
6038
- const [{ characters }, { locations }] = await Promise.all([loadCharacters(world.directory), loadLocations(world.directory)]);
6039
- const problems = routineProblems(characters, locations, parsed.value);
6040
- const triggers = await readFile(join(world.directory, TRIGGERS_FILE_NAME), "utf8").catch((error) => {
6041
- if (error.code === "ENOENT") return "";
6042
- throw error;
6043
- });
6044
- const named = new Set(calendar.holidays.map((holiday) => holiday.id));
6045
- 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`);
6046
- if (problems.length > 0) throw new InvalidEditProblems(problems);
6047
- if (calendar.holidays.length === 0 && calendar.hemisphere === "north") await rm(join(world.directory, CALENDAR_FILE_NAME), { force: true });
6048
- else await replaceFileOrCreate(join(world.directory, CALENDAR_FILE_NAME), text);
6049
- return await readCalendarDocument(world);
6050
- }
6051
- /** The checks of a world as its `dice.json` has them; none without the file. */
6052
- async function readDiceDocument(world) {
6053
- const { checks } = await loadDice(world.directory);
6054
- return { checks };
6055
- }
6056
- /**
6057
- * 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
6058
- * declares for characters. No checks is no file at all.
6059
- * @throws {InvalidEditProblems} naming each problem; nothing is written.
6060
- */
6061
- async function editDice(world, dice) {
6062
- const written = dice.checks.map(({ reading, compare, ...check }) => ({
6063
- ...check,
6064
- ...reading === void 0 || reading === "total" ? {} : { reading },
6065
- ...compare === void 0 || compare === "absolute" ? {} : { compare }
6066
- }));
6067
- const text = `${JSON.stringify({ checks: written }, null, 2)}\n`;
6068
- const parsed = parseDiceFile(text);
6069
- if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
6070
- const declared = await loadVariables(world.directory);
6071
- const problems = parsed.value.flatMap((check) => {
6072
- if (check.modifier === void 0) return [];
6073
- const variable = declared.defs.find((def) => def.key === check.modifier);
6074
- 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)`] : [];
6075
- });
6076
- if (problems.length > 0) throw new InvalidEditProblems(problems);
6077
- if (dice.checks.length === 0) await rm(join(world.directory, DICE_FILE_NAME), { force: true });
6078
- else await replaceFileOrCreate(join(world.directory, DICE_FILE_NAME), text);
6079
- return await readDiceDocument(world);
6080
- }
6081
5874
  // src/host/worlds/lore-entries.ts
6082
5875
  const MAX_TITLE = 200;
6083
5876
  /**
@@ -7092,6 +6885,18 @@ async function startSession(deps, request) {
7092
6885
  mode: answers.clockMode
7093
6886
  }
7094
6887
  };
6888
+ const givenAutonomy = (request.settings?.autonomy)?.enabled;
6889
+ if (world.autonomy === true && givenAutonomy === void 0) settings = {
6890
+ ...settings,
6891
+ autonomy: {
6892
+ ...settings.autonomy,
6893
+ enabled: true
6894
+ },
6895
+ ...givenClock === void 0 && answers.clockMode === void 0 ? { clock: {
6896
+ ...settings.clock,
6897
+ mode: "real"
6898
+ } } : {}
6899
+ };
7095
6900
  const timeZone = settings.clock.timeZone !== "" ? settings.clock.timeZone : settings.clock.mode === "real" ? systemTimeZone() : world.clock?.timeZone ?? "UTC";
7096
6901
  const tools = Object.fromEntries([.../* @__PURE__ */ new Set([
7097
6902
  ...Object.keys(world.tools ?? {}),
@@ -7872,6 +7677,7 @@ async function loadWorld(folder, dir, file, problems) {
7872
7677
  ...world.startQuestions === void 0 ? {} : { startQuestions: world.startQuestions },
7873
7678
  ...world.rules === void 0 ? {} : { rules: world.rules },
7874
7679
  ...world.tools === void 0 ? {} : { tools: world.tools },
7680
+ ...world.autonomy === void 0 ? {} : { autonomy: world.autonomy },
7875
7681
  ...world.narrationVoice === void 0 ? {} : { narrationVoice: world.narrationVoice },
7876
7682
  ...world.sampling === void 0 ? {} : { sampling: world.sampling },
7877
7683
  ...world.preset === void 0 ? {} : { preset: world.preset },
@@ -8076,7 +7882,11 @@ async function installWorld(catalog, archive, maxBytes, options) {
8076
7882
  await mkdir(catalog.directory, { recursive: true });
8077
7883
  if (replacing !== void 0) {
8078
7884
  placed = basename(replacing.directory);
8079
- backup = join(".trash", "worlds", `${placed}-${stamp()}`);
7885
+ backup = [
7886
+ ".trash",
7887
+ "worlds",
7888
+ `${placed}-${stamp()}`
7889
+ ].join("/");
8080
7890
  await mkdir(join(root, dirname(backup)), { recursive: true });
8081
7891
  await rename(replacing.directory, join(root, backup));
8082
7892
  } else placed = freeFolder(catalog.directory, folder);
@@ -9914,6 +9724,7 @@ const Config = z.object({
9914
9724
  }).default({ ...DEFAULT_OFFLOAD }).volatile(),
9915
9725
  catalogueMaxBytes: z.number().min(1024).default(268435456).volatile(),
9916
9726
  catalogueTrashDays: z.number().min(0).default(30).volatile(),
9727
+ autonomyTickSeconds: z.number().min(0).max(3600).default(30).volatile(),
9917
9728
  importMaxUploadBytes: z.number().min(1024).default(104857600).volatile(),
9918
9729
  importConcurrency: z.number().min(1).max(16).default(4).volatile(),
9919
9730
  importReasoning: z.string().default("").volatile(),
@@ -9933,7 +9744,7 @@ const name = "@dsh-agentic-roleplay/core";
9933
9744
  /** Sessions are kept by the state plugin, which the bundle installs with this one. */
9934
9745
  const inject = ["roleplayState"];
9935
9746
  function apply(ctx, config) {
9936
- const layers = () => redundantLayers(selectedBundles(ctx.get("profileContext")?.dir));
9747
+ const layers = () => redundantLayers(selectedBundles(profileDirectory()));
9937
9748
  const repeated = layers();
9938
9749
  if (repeated.length > 0) ctx.logger.error(redundantLayersMessage(repeated));
9939
9750
  ctx.inject(["aiProviders"], (scope) => {
@@ -9978,6 +9789,38 @@ function apply(ctx, config) {
9978
9789
  const languages = new AuthoringLanguages(ctx, () => join(root.path, "worlds"));
9979
9790
  const authoringTools = new AuthoringTools(ctx, () => config.authoringTools.get());
9980
9791
  const agent = new AgentSessions(agentServicesOf(ctx), () => root.path);
9792
+ const autonomy = new AutonomyTicker({
9793
+ sessions: () => listSessions({
9794
+ state: ctx.roleplayState,
9795
+ sessionsDir: () => join(root.path, "sessions")
9796
+ }).sessions.map((session) => ({
9797
+ id: session.id,
9798
+ name: session.name,
9799
+ archived: session.archivedAt !== void 0
9800
+ })),
9801
+ settings: (id) => liveSettings(sessionFolder(join(root.path, "sessions"), id)),
9802
+ ensure: async (id, name) => await agent.ensure(id, name),
9803
+ tick: async (chat, signal) => await orchestration.autonomy(chat, signal),
9804
+ problem: (message) => {
9805
+ ctx.logger.warn(`roleplay: ${message}`);
9806
+ }
9807
+ });
9808
+ ctx.effect(() => {
9809
+ let timer;
9810
+ const controller = new AbortController();
9811
+ const later = () => {
9812
+ const seconds = config.autonomyTickSeconds.get();
9813
+ timer = setTimeout(() => {
9814
+ (seconds === 0 ? Promise.resolve(0) : autonomy.run(controller.signal)).finally(later);
9815
+ }, Math.max(5, seconds === 0 ? 60 : seconds) * 1e3);
9816
+ timer.unref();
9817
+ };
9818
+ later();
9819
+ return () => {
9820
+ controller.abort();
9821
+ if (timer !== void 0) clearTimeout(timer);
9822
+ };
9823
+ }, "roleplay: stories that go on while the player is away");
9981
9824
  const authoring = new AuthoringSessions(agentServicesOf(ctx), () => root.path, prompts, languages);
9982
9825
  const presetAuthoring = new PresetAuthoringSessions(agentServicesOf(ctx), () => root.path, prompts, languages);
9983
9826
  const lorebookAuthoring = new LorebookAuthoringSessions(agentServicesOf(ctx), () => root.path, prompts, languages);
@@ -10013,6 +9856,14 @@ function apply(ctx, config) {
10013
9856
  };
10014
9857
  const staging = new ImportStaging();
10015
9858
  const purgeChat = purgeOf(ctx, config.sessionStorePath);
9859
+ const chatStatus = (chatSessionId) => {
9860
+ const live = ctx.get("agents")?.get(SessionId(chatSessionId));
9861
+ return {
9862
+ chatSessionId,
9863
+ turns: roleplayImport.turnsOf(chatSessionId),
9864
+ running: live !== void 0 && live.status !== "idle"
9865
+ };
9866
+ };
10016
9867
  const deps = {
10017
9868
  worlds,
10018
9869
  state: ctx.roleplayState,
@@ -10157,6 +10008,14 @@ function apply(ctx, config) {
10157
10008
  catalogue,
10158
10009
  presets: presetLibrary,
10159
10010
  lorebooks: lorebookLibrary,
10011
+ folders: new StoryFoldersService({
10012
+ root: () => root.path,
10013
+ sessionFolder: (id) => {
10014
+ const sessions = join(root.path, "sessions");
10015
+ if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);
10016
+ return sessionFolder(sessions, id);
10017
+ }
10018
+ }),
10160
10019
  prompts: new PromptManager(prompts),
10161
10020
  packs: new InterfaceService({
10162
10021
  open: (id) => ctx.roleplayState.openSession(deps.sessionsDir(), id),
@@ -10180,6 +10039,24 @@ function apply(ctx, config) {
10180
10039
  if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
10181
10040
  return { chatSessionId: await authoring.ensure(world.summary.id, world.summary.name, title, language) };
10182
10041
  },
10042
+ sayToAuthor: async (worldId, text, language) => {
10043
+ const world = await worlds.find(worldId);
10044
+ if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
10045
+ const chatSessionId = await authoring.ensure(world.summary.id, world.summary.name, void 0, language);
10046
+ await authoring.send(chatSessionId, text);
10047
+ return { chatSessionId };
10048
+ },
10049
+ authoringStatus: async (worldId) => {
10050
+ const world = await worlds.find(worldId);
10051
+ if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
10052
+ return chatStatus(authoringChatSessionId(world.summary.id));
10053
+ },
10054
+ chatStatus,
10055
+ forgetAuthoring: 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
+ await purgeChat(authoringChatSessionId(world.summary.id));
10059
+ },
10183
10060
  translation: {
10184
10061
  language: (id) => worldLanguage(worlds, id),
10185
10062
  start: (id, to, title, language) => startTranslation({
@@ -10285,6 +10162,8 @@ function apply(ctx, config) {
10285
10162
  editRoutine: async (worldId, key, windows) => await editRoutine(await editableWorld(worlds, worldId, root.path), key, windows),
10286
10163
  dice: async (worldId) => await readDiceDocument(await editableWorld(worlds, worldId, root.path)),
10287
10164
  editDice: async (worldId, dice) => await editDice(await editableWorld(worlds, worldId, root.path), dice),
10165
+ commands: async (worldId) => await readCommandsDocument(await editableWorld(worlds, worldId, root.path)),
10166
+ editCommands: async (worldId, commands) => await editCommands(await editableWorld(worlds, worldId, root.path), commands),
10288
10167
  calendar: async (worldId) => await readCalendarDocument(await editableWorld(worlds, worldId, root.path)),
10289
10168
  editCalendar: async (worldId, calendar) => await editCalendar(await editableWorld(worlds, worldId, root.path), calendar),
10290
10169
  variables: async (worldId) => await readVariables(await editableWorld(worlds, worldId, root.path)),