@dsh-agentic-roleplay/core 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { A as languageOf, C as errorMessage, E as PROMPTS_FOLDER, H as INTENT_HORIZONS, M as promptProblem, N as shippedLanguages, P as shippedPromptsDirectory, R as InvalidWorldError, S as readDocument, T as formatIssue, U as INTENT_STATUSES, W as INTENT_TYPES, _ as API_PREFIX, b as parsePlotsFile, j as listFiles, v as PLOTS_FILE_NAME, w as Reader, x as plotReferenceProblems, y as loadPlots } from "./packs-ByP1J-zj.js";
1
+ import { A as languageOf, C as errorMessage, E as PROMPTS_FOLDER, G as INTENT_TYPES, M as promptProblem, N as shippedLanguages, P as shippedPromptsDirectory, R as InvalidWorldError, S as readDocument, T as formatIssue, U as INTENT_HORIZONS, W as INTENT_STATUSES, _ as API_PREFIX, b as parsePlotsFile, j as listFiles, v as PLOTS_FILE_NAME, w as Reader, x as plotReferenceProblems, y as loadPlots } from "./packs-alJTiDM2.js";
2
2
  import { n as VARIABLE_SUBJECTS, r as VARIABLE_VISIBILITIES, t as VARIABLE_KINDS } from "./src-CWTNeL6Y.js";
3
3
  import { C as norm, S as mapLimit, T as uniqueKey, a as uploadReferenceImage, h as MEDIA_TYPES, o as addToLibrary, p as referenceImagePath, s as imageExtensionOf, t as generateReferenceImage, w as slug, y as writeImageFileMetadata } from "./generator-HPifO3Kk.js";
4
4
  import { basename, dirname, join } from "node:path";
@@ -5069,6 +5069,71 @@ function authoredWorldOf(chatSessionId) {
5069
5069
  }
5070
5070
  }
5071
5071
  //#endregion
5072
+ //#region src/host/triggers/parts.ts
5073
+ /** What the files of a world say it has, for checking what a trigger names. @throws {InvalidEditProblems} when those files have problems of their own: they are fixed first. */
5074
+ async function loadWorldParts(directory) {
5075
+ const { characters, problems: characterProblems } = await loadCharacters(directory);
5076
+ const { locations, problems: locationProblems } = await loadLocations(directory);
5077
+ const { items, slots, problems: itemProblems } = await loadItems(directory, {
5078
+ characters: characters.map((character) => character.id),
5079
+ locations
5080
+ });
5081
+ const { defs, problems: variableProblems } = await loadVariables(directory);
5082
+ const problems = [
5083
+ ...characterProblems,
5084
+ ...locationProblems,
5085
+ ...itemProblems,
5086
+ ...variableProblems
5087
+ ];
5088
+ if (problems.length > 0) throw new InvalidEditProblems([`the world's other files have problems that come first: ${problems.map((problem) => `${problem.path}: ${problem.message}`).join("; ")}`]);
5089
+ return {
5090
+ characters,
5091
+ locations,
5092
+ items,
5093
+ slots,
5094
+ variables: defs
5095
+ };
5096
+ }
5097
+ //#endregion
5098
+ //#region src/host/triggers/check.ts
5099
+ /**
5100
+ * What each trigger names that the world does not have (a character, place, item or variable in its condition, its cues or the words of a
5101
+ * cue), found as a session start finds it: against a scratch story made from the world's files. Triggers that wait for each other count
5102
+ * as there. @returns the problems by trigger key; a trigger with none is not in it.
5103
+ */
5104
+ function triggerProblemsOf(parts, definitions) {
5105
+ const found = /* @__PURE__ */ new Map();
5106
+ if (definitions.length === 0) return found;
5107
+ const scratch = createSessionStore(":memory:", {
5108
+ id: "scratch",
5109
+ name: "scratch",
5110
+ world: {
5111
+ id: "scratch",
5112
+ name: "scratch"
5113
+ }
5114
+ }, { vectors: false });
5115
+ try {
5116
+ const session = scratch;
5117
+ populateLocations(session, parts.locations);
5118
+ populateCharacters(session, parts.characters, parts.characters.find((character) => character.role === "playable")?.id ?? "");
5119
+ populateItems(session, parts.items, parts.slots, parts.locations);
5120
+ populateVariables(session, parts.variables, {
5121
+ characters: parts.characters,
5122
+ items: parts.items,
5123
+ locations: parts.locations,
5124
+ values: void 0
5125
+ });
5126
+ const keys = definitions.map((definition) => definition.key);
5127
+ for (const definition of definitions) {
5128
+ const problems = triggerReferenceProblems(scratch, definition, keys).map((problem) => problem.slice(definition.key.length + 2));
5129
+ if (problems.length > 0) found.set(definition.key, problems);
5130
+ }
5131
+ } finally {
5132
+ scratch.close();
5133
+ }
5134
+ return found;
5135
+ }
5136
+ //#endregion
5072
5137
  //#region src/host/worlds/world-editor.ts
5073
5138
  function stateOf(world, definition, names) {
5074
5139
  const { start } = definition;
@@ -5115,6 +5180,34 @@ function stateOf(world, definition, names) {
5115
5180
  }))
5116
5181
  };
5117
5182
  }
5183
+ /** The triggers of the world's file as the editor shows them, with what each names that the world does not have; or why the file cannot be shown. */
5184
+ function triggersOf(parts, scripted) {
5185
+ if (scripted.problems.length > 0) return {
5186
+ triggers: [],
5187
+ triggersProblem: scripted.problems.map((problem) => problem.message).join("; ")
5188
+ };
5189
+ const view = (problems) => scripted.triggers.map((definition) => ({
5190
+ key: definition.key,
5191
+ name: definition.name,
5192
+ when: definition.condition,
5193
+ effects: definition.effects,
5194
+ repeat: definition.repeat,
5195
+ priority: definition.priority,
5196
+ ...definition.cooldownSeconds === void 0 ? {} : { cooldownSeconds: definition.cooldownSeconds },
5197
+ ...definition.chance === void 0 ? {} : { chance: definition.chance },
5198
+ ...definition.expires === void 0 ? {} : { expires: definition.expires },
5199
+ announced: definition.announce !== void 0,
5200
+ problems: problems.get(definition.key) ?? []
5201
+ }));
5202
+ try {
5203
+ return { triggers: view(triggerProblemsOf(parts, scripted.triggers)) };
5204
+ } catch (error) {
5205
+ return {
5206
+ triggers: view(/* @__PURE__ */ new Map()),
5207
+ triggersProblem: `what the triggers name could not be checked, because the rest of the world has a problem: ${error instanceof Error ? error.message : String(error)}`
5208
+ };
5209
+ }
5210
+ }
5118
5211
  /** The characters of a world as they start, and the places they can start in. */
5119
5212
  async function readWorldEditor(world) {
5120
5213
  const [{ characters }, { locations }, { factions }, { lore }, { plots }] = await Promise.all([
@@ -5124,10 +5217,18 @@ async function readWorldEditor(world) {
5124
5217
  loadLore(world.directory),
5125
5218
  loadPlots(world.directory)
5126
5219
  ]);
5127
- const { items } = await loadItems(world.directory, {
5220
+ const { items, slots } = await loadItems(world.directory, {
5128
5221
  characters: characters.map((character) => character.id),
5129
5222
  locations
5130
5223
  });
5224
+ const scripted = await loadTriggers(world.directory);
5225
+ const { triggers, triggersProblem } = triggersOf({
5226
+ characters,
5227
+ locations,
5228
+ items,
5229
+ slots,
5230
+ variables: (await loadVariables(world.directory)).defs
5231
+ }, scripted);
5131
5232
  const names = new Map(locations.map((location) => [location.id, location.name]));
5132
5233
  const characterNames = new Map(characters.map((character) => [character.id, character.name]));
5133
5234
  const itemNames = new Map(items.map((item) => [item.id, item.name]));
@@ -5296,6 +5397,8 @@ async function readWorldEditor(world) {
5296
5397
  })),
5297
5398
  sources: entry.sources
5298
5399
  })),
5400
+ triggers,
5401
+ ...triggersProblem === void 0 ? {} : { triggersProblem },
5299
5402
  plots: plots.map((definition) => ({ definition })),
5300
5403
  relations
5301
5404
  };
@@ -5923,6 +6026,6 @@ async function deleteAuthoredEntity(world, kind, key) {
5923
6026
  return destination;
5924
6027
  }
5925
6028
  //#endregion
5926
- export { variableProblems as $, populateCharacters as A, routineProblems as B, endReview as C, markReady as D, isReviewing as E, populateLocations as F, subfolders as G, loadItems as H, populateLore as I, listWorldPrompts as J, PROSE_PROMPTS as K, populateRoutines as L, populateFactions as M, populateItems as N, survey as O, populateKnowledge as P, parseVariablesFile as Q, populateTriggers as R, build as S, importPhase as T, CHARACTERS_DIR as U, loadLocations as V, loadCharacters as W, writeWorldPrompt as X, readWorldPrompt as Y, VARIABLES_FILE_NAME as Z, replaceFile$1 as _, parseImportCommand as _t, replaceAuthoredEntity as a, parseChoices as at, authoredWorldOf as b, editWorldLore as c, parseWorldInfoEdit as ct, editWorldPlots as d, parseFactionEdit as dt, CHARACTER_FILE_NAME as et, editWorldRelation as f, parseLoreEdit as ft, readWorldEditor as g, IMPORT_COMMAND as gt, generateWorldCharacterPortrait as h, parseThingEdit as ht, readAuthoredEntityDocument as i, ImportStore as it, populateClock as j, loadValidatedWorld as k, editWorldNarrationVoice as l, InvalidEditProblems as lt, entityFolder as m, parseRelationEdit as mt, createAuthoredEntity as n, IMPORT_FOLDER as nt, editWorldCharacter as o, WORLD_FILE_NAME as ot, editWorldThing as p, parsePlaceEdit as pt, deleteWorldPrompt as q, deleteAuthoredEntity as r, ImportNotFoundError as rt, editWorldFaction as s, parseWorldFile as st, AUTHORED_ENTITY_KINDS as t, parseCharacterFile as tt, editWorldPlace as u, parseCharacterEdit as ut, uploadWorldCharacterPortrait as v, finish as w, authoringChatSessionId as x, worldCharacterPortraitFile as y, populateVariables as z };
6029
+ export { writeWorldPrompt as $, survey as A, populateTriggers as B, authoringChatSessionId as C, importPhase as D, finish as E, populateItems as F, loadItems as G, routineProblems as H, populateKnowledge as I, subfolders as J, CHARACTERS_DIR as K, populateLocations as L, populateCharacters as M, populateClock as N, isReviewing as O, populateFactions as P, readWorldPrompt as Q, populateLore as R, authoredWorldOf as S, endReview as T, TRIGGERS_FILE_NAME as U, populateVariables as V, loadLocations as W, deleteWorldPrompt as X, PROSE_PROMPTS as Y, listWorldPrompts as Z, replaceFile$1 as _, parseRelationEdit as _t, replaceAuthoredEntity as a, IMPORT_FOLDER as at, triggerProblemsOf as b, parseImportCommand as bt, editWorldLore as c, parseChoices as ct, editWorldPlots as d, parseWorldInfoEdit as dt, VARIABLES_FILE_NAME as et, editWorldRelation as f, InvalidEditProblems as ft, readWorldEditor as g, parsePlaceEdit as gt, generateWorldCharacterPortrait as h, parseLoreEdit as ht, readAuthoredEntityDocument as i, parseCharacterFile as it, loadValidatedWorld as j, markReady as k, editWorldNarrationVoice as l, WORLD_FILE_NAME as lt, entityFolder as m, parseFactionEdit as mt, createAuthoredEntity as n, variableProblems as nt, editWorldCharacter as o, ImportNotFoundError as ot, editWorldThing as p, parseCharacterEdit as pt, loadCharacters as q, deleteAuthoredEntity as r, CHARACTER_FILE_NAME as rt, editWorldFaction as s, ImportStore as st, AUTHORED_ENTITY_KINDS as t, parseVariablesFile as tt, editWorldPlace as u, parseWorldFile as ut, uploadWorldCharacterPortrait as v, parseThingEdit as vt, build as w, loadWorldParts as x, worldCharacterPortraitFile as y, IMPORT_COMMAND as yt, populateRoutines as z };
5927
6030
 
5928
- //# sourceMappingURL=documents-Bu5uYRZB.js.map
6031
+ //# sourceMappingURL=documents-7GMc5NnW.js.map
package/lib/images.js CHANGED
@@ -1,4 +1,4 @@
1
1
  import { b as readPngMetadata, d as nextSceneSerial, f as readImageMetadata, i as transientPrompt, l as entityImageDirectory, m as sceneImagePath, n as generateTransientImage, o as addToLibrary, p as referenceImagePath, r as referencePrompt, t as generateReferenceImage, u as inheritImages, x as withPngMetadata } from "./generator-HPifO3Kk.js";
2
2
  import { i as updateImage, r as listGallery } from "./gallery-DUeBMHQX.js";
3
- import { a as tokensOf, i as searchImages, n as interpretImage, o as present, r as imageTools, s as presentedFor, t as runImagePresenter } from "./presenter-agent-G43ODV8I.js";
3
+ import { a as tokensOf, i as searchImages, n as interpretImage, o as present, r as imageTools, s as presentedFor, t as runImagePresenter } from "./presenter-agent-PX1WVaJB.js";
4
4
  export { addToLibrary, entityImageDirectory, generateReferenceImage, generateTransientImage, imageTools, inheritImages, interpretImage, listGallery, nextSceneSerial, present, presentedFor, readImageMetadata, readPngMetadata, referenceImagePath, referencePrompt, runImagePresenter, sceneImagePath, searchImages, tokensOf, transientPrompt, updateImage, withPngMetadata };
package/lib/index.js CHANGED
@@ -1,13 +1,13 @@
1
- import { n as roleplaySessionOf, t as chatSessionId } from "./chat-AKrVcWIC.js";
2
- import { $ as variableProblems, A as populateCharacters, B as routineProblems, D as markReady, F as populateLocations, G as subfolders, H as loadItems, I as populateLore, J as listWorldPrompts, L as populateRoutines, M as populateFactions, N as populateItems, P as populateKnowledge, Q as parseVariablesFile, R as populateTriggers, U as CHARACTERS_DIR, V as loadLocations, W as loadCharacters, X as writeWorldPrompt, Y as readWorldPrompt, Z as VARIABLES_FILE_NAME, _ as replaceFile$1, at as parseChoices, c as editWorldLore$1, ct as parseWorldInfoEdit, d as editWorldPlots$1, dt as parseFactionEdit, et as CHARACTER_FILE_NAME, f as editWorldRelation$1, ft as parseLoreEdit, g as readWorldEditor, gt as IMPORT_COMMAND, h as generateWorldCharacterPortrait, ht as parseThingEdit, i as readAuthoredEntityDocument, it as ImportStore, j as populateClock, k as loadValidatedWorld, l as editWorldNarrationVoice, lt as InvalidEditProblems, m as entityFolder, mt as parseRelationEdit, n as createAuthoredEntity, nt as IMPORT_FOLDER, o as editWorldCharacter$1, ot as WORLD_FILE_NAME, p as editWorldThing$1, pt as parsePlaceEdit, q as deleteWorldPrompt, r as deleteAuthoredEntity, rt as ImportNotFoundError, s as editWorldFaction$1, st as parseWorldFile, tt as parseCharacterFile, u as editWorldPlace$1, ut as parseCharacterEdit, v as uploadWorldCharacterPortrait, x as authoringChatSessionId, y as worldCharacterPortraitFile, z as populateVariables } from "./documents-Bu5uYRZB.js";
3
- import { A as languageOf, B as SessionNotFoundError, C as errorMessage, D as PromptLibrary, I as AgentUnavailableError, L as InvalidStartError, O as copyWorldPrompts, R as InvalidWorldError, S as readDocument$1, T as formatIssue, V as WorldNotFoundError, _ as API_PREFIX, a as packIds, b as parsePlotsFile, c as describePack, f as readPack, m as PACK_LIMITS, n as anyTab, o as syncWorldPacks, r as copyWorldPacks, s as worldPackStates, t as activePack, u as packFile, x as plotReferenceProblems, z as SessionArchivedError } from "./packs-ByP1J-zj.js";
4
- import { a as liveSettings, c as writeSettings, d as parseSettings, f as WORLD_RULES_KEY, i as InvalidSettingsError, l as DEFAULT_SETTINGS, n as encodeOutput, o as readSettings, s as useChildReasoning, u as SETTINGS_SPEC } from "./narration-BRyHU0H2.js";
1
+ import { n as chatSessionId, r as roleplaySessionOf } from "./access-EbNdZFbk.js";
2
+ import { $ as writeWorldPrompt, B as populateTriggers, C as authoringChatSessionId, F as populateItems, G as loadItems, H as routineProblems, I as populateKnowledge, J as subfolders, K as CHARACTERS_DIR, L as populateLocations, M as populateCharacters, N as populateClock, P as populateFactions, Q as readWorldPrompt, R as populateLore, V as populateVariables, W as loadLocations, X as deleteWorldPrompt, Z as listWorldPrompts, _ as replaceFile$1, _t as parseRelationEdit, at as IMPORT_FOLDER, c as editWorldLore$1, ct as parseChoices, d as editWorldPlots$1, dt as parseWorldInfoEdit, et as VARIABLES_FILE_NAME, f as editWorldRelation$1, ft as InvalidEditProblems, g as readWorldEditor, gt as parsePlaceEdit, h as generateWorldCharacterPortrait, ht as parseLoreEdit, i as readAuthoredEntityDocument, it as parseCharacterFile, j as loadValidatedWorld, k as markReady, l as editWorldNarrationVoice, lt as WORLD_FILE_NAME, m as entityFolder, mt as parseFactionEdit, n as createAuthoredEntity, nt as variableProblems, o as editWorldCharacter$1, ot as ImportNotFoundError, p as editWorldThing$1, pt as parseCharacterEdit, q as loadCharacters, r as deleteAuthoredEntity, rt as CHARACTER_FILE_NAME, s as editWorldFaction$1, st as ImportStore, tt as parseVariablesFile, u as editWorldPlace$1, ut as parseWorldFile, v as uploadWorldCharacterPortrait, vt as parseThingEdit, x as loadWorldParts, y as worldCharacterPortraitFile, yt as IMPORT_COMMAND, z as populateRoutines } from "./documents-7GMc5NnW.js";
3
+ import { A as languageOf, B as SessionArchivedError, C as errorMessage, D as PromptLibrary, H as WorldNotFoundError, I as AgentUnavailableError, L as InvalidStartError, O as copyWorldPrompts, R as InvalidWorldError, S as readDocument$1, T as formatIssue, V as SessionNotFoundError, _ as API_PREFIX, a as packIds, b as parsePlotsFile, c as describePack, f as readPack, l as isPackId, m as PACK_LIMITS, n as anyTab, o as syncWorldPacks, r as copyWorldPacks, s as worldPackStates, t as activePack, u as packFile, x as plotReferenceProblems, z as ReflectionRefusedError } from "./packs-alJTiDM2.js";
4
+ import { A as readTimeline, C as notesOfSession, E as observeAsPlayer, M as defaultBoundaries, O as TimelineError, T as readNotes, V as zoneOf, a as readActivity, d as reflectionStatus, j as pathTo, n as readWithdrawn, o as readRunDetail, p as PLOTS_METADATA_KEY, v as plotProgressOf, x as addToNote, y as populatePlots } from "./deliver--uMhC6oO.js";
5
+ import { a as liveSettings, c as writeSettings, d as parseSettings, f as WORLD_RULES_KEY, i as InvalidSettingsError, l as DEFAULT_SETTINGS, n as encodeOutput, o as readSettings, s as useChildReasoning, u as SETTINGS_SPEC } from "./narration-CKZTk5UE.js";
5
6
  import { n as VARIABLE_SUBJECTS, r as VARIABLE_VISIBILITIES, t as VARIABLE_KINDS } from "./src-CWTNeL6Y.js";
6
7
  import { O as childSamplingOf, T as uniqueKey, a as uploadReferenceImage, m as sceneImagePath, o as addToLibrary, p as referenceImagePath, t as generateReferenceImage, u as inheritImages, w as slug } from "./generator-HPifO3Kk.js";
7
- import { C as defaultBoundaries, M as zoneOf, S as pathTo, d as plotProgressOf, f as populatePlots, g as notesOfSession, i as readRunDetail, m as addToNote, o as PLOTS_METADATA_KEY, r as readActivity, v as readNotes, x as readTimeline, y as TimelineError } from "./activity-t7OBgHlc.js";
8
8
  import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-DUeBMHQX.js";
9
9
  import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve } from "node:path";
10
- import { createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
10
+ import { cpSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
11
11
  import { createHash, randomBytes, randomUUID } from "node:crypto";
12
12
  import { Session, SessionId } from "@deepseek-ai/dsh-session";
13
13
  import { ToolCallId, createMessage, createSystemMessage, createToolResultMessage } from "@deepseek-ai/dsh-llm";
@@ -16,7 +16,7 @@ import { inflateSync } from "node:zlib";
16
16
  import { fileURLToPath } from "node:url";
17
17
  import { Service } from "@deepseek-ai/cordis";
18
18
  import { chmod, copyFile, cp, lstat, mkdir, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
19
- import { describeInstant, describeValue, isSessionId, itemKey, lintWorld, locationKey, parseInstant, sessionDatabase, sessionFolder, shownVariables, systemTimeZone } from "@dsh-agentic-roleplay/state";
19
+ import { createSessionStore, describeInstant, describeValue, isSessionId, itemKey, lintWorld, locationKey, parseInstant, sessionDatabase, sessionFolder, shownVariables, systemTimeZone } from "@dsh-agentic-roleplay/state";
20
20
  import { pipeline } from "node:stream/promises";
21
21
  import { homedir } from "node:os";
22
22
  import z from "@deepseek-ai/schemastery";
@@ -680,6 +680,10 @@ var RoleplayOrchestration = class extends Service {
680
680
  settle = () => Promise.resolve();
681
681
  /** Stops everything a chat has in flight in the background and waits for it; there while the orchestration is. */
682
682
  halt = () => Promise.resolve();
683
+ /** Starts a reflection of a chat's characters on what they have taken in, in the background; there while the orchestration is. */
684
+ reflect = () => Promise.reject(/* @__PURE__ */ new Error("the orchestration is not running"));
685
+ /** Whether a reflection of the chat is running; there while the orchestration is. */
686
+ reflecting = () => false;
683
687
  /** What the story's turns are and taking the story back to one; there while the orchestration is. */
684
688
  timelines;
685
689
  /** Background scene illustration jobs; there while the orchestration is mounted. */
@@ -1027,6 +1031,7 @@ const BRIDGE_SCRIPT = `(function () {
1027
1031
  var root = document.documentElement;
1028
1032
  root.setAttribute('data-rp-scheme', data.scheme);
1029
1033
  root.style.colorScheme = data.scheme;
1034
+ if (data.language) root.setAttribute('lang', data.language);
1030
1035
  Object.keys(data.tokens).forEach(function (name) { root.style.setProperty(name, data.tokens[name]); });
1031
1036
  }
1032
1037
  function remove(list, listener) { var index = list.indexOf(listener); if (index >= 0) list.splice(index, 1); }
@@ -1234,6 +1239,59 @@ function finish(view, session) {
1234
1239
  };
1235
1240
  }
1236
1241
  //#endregion
1242
+ //#region src/host/interface/preview.ts
1243
+ /** What a story shows for suggestions when a pack is looked at before any story exists. */
1244
+ const SAMPLE_SUGGESTIONS = [
1245
+ "Look around.",
1246
+ "Ask someone here what they know.",
1247
+ "Try the nearest door."
1248
+ ];
1249
+ /**
1250
+ * What a story of this world would show a pack at its start, from the world's files: a story made in memory, the player taking the first
1251
+ * playable character, who then looks around as they do at the start of a turn. Nothing is stored.
1252
+ * @throws {InvalidEditProblems} when the rest of the world has problems of its own.
1253
+ */
1254
+ async function previewViewOf(world, wall) {
1255
+ const parts = await loadWorldParts(world.directory);
1256
+ const player = parts.characters.find((character) => character.role === "playable") ?? parts.characters[0];
1257
+ const scratch = createSessionStore(":memory:", {
1258
+ id: "preview",
1259
+ name: world.summary.name,
1260
+ world: {
1261
+ id: world.summary.id,
1262
+ name: world.summary.name
1263
+ }
1264
+ }, { vectors: false });
1265
+ try {
1266
+ const session = scratch;
1267
+ populateLocations(session, parts.locations);
1268
+ populateCharacters(session, parts.characters, player?.id ?? "");
1269
+ populateItems(session, parts.items, parts.slots, parts.locations);
1270
+ populateKnowledge(session, parts.characters);
1271
+ populateVariables(session, parts.variables, {
1272
+ characters: parts.characters,
1273
+ items: parts.items,
1274
+ locations: parts.locations,
1275
+ values: world.variables
1276
+ });
1277
+ populateClock(session, DEFAULT_SETTINGS.clock, world.clock, wall);
1278
+ observeAsPlayer(session, 1);
1279
+ const view = playerViewOf(session, {
1280
+ zone: world.clock?.timeZone ?? "UTC",
1281
+ wall
1282
+ });
1283
+ const { revision: _, ...rest } = view;
1284
+ return {
1285
+ ...rest,
1286
+ api: 1,
1287
+ suggestions: SAMPLE_SUGGESTIONS,
1288
+ revision: `preview-${view.revision}`
1289
+ };
1290
+ } finally {
1291
+ scratch.close();
1292
+ }
1293
+ }
1294
+ //#endregion
1237
1295
  //#region src/host/interface/storage.ts
1238
1296
  const keyOf$1 = (pack) => `roleplay.interface.${pack}`;
1239
1297
  function checkedKey(key) {
@@ -1286,12 +1344,16 @@ var InvalidPacksError = class extends Error {
1286
1344
  this.problems = problems;
1287
1345
  }
1288
1346
  };
1347
+ /** What stands for a pack looked at in the editor where a session id would be; the key after it is the frame's. */
1348
+ const PREVIEW = "preview:";
1289
1349
  const addressFor = (session) => (path) => `roleplay-api/sessions/interface/pack/${session}/${path.split("/").map(encodeURIComponent).join("/")}`;
1290
1350
  /** What the interface packs of the stories show and do, for the browser. */
1291
1351
  var InterfaceService = class {
1292
1352
  deps;
1293
1353
  keys = /* @__PURE__ */ new Map();
1294
1354
  keyOf = /* @__PURE__ */ new Map();
1355
+ /** The pack folders being previewed, by frame key. */
1356
+ previews = /* @__PURE__ */ new Map();
1295
1357
  constructor(deps) {
1296
1358
  this.deps = deps;
1297
1359
  }
@@ -1311,6 +1373,73 @@ var InterfaceService = class {
1311
1373
  sessions() {
1312
1374
  return join(this.deps.root(), "sessions");
1313
1375
  }
1376
+ async worldOf(worldId) {
1377
+ const world = await this.deps.world(worldId);
1378
+ if (world === void 0) throw new WorldNotFoundError(`there is no world "${worldId}"`);
1379
+ return world;
1380
+ }
1381
+ /** The packs of a world, each with what it holds and what is wrong with it. @throws {WorldNotFoundError} */
1382
+ async worldPacks(worldId) {
1383
+ const { directory } = await this.worldOf(worldId);
1384
+ return packIds(directory).map((id) => {
1385
+ const { pack, problems } = readPack(join(directory, "ui", id), id, (file) => file);
1386
+ if (pack === void 0) return {
1387
+ id,
1388
+ name: id,
1389
+ version: "",
1390
+ description: "",
1391
+ actions: [],
1392
+ surfaces: {},
1393
+ tokens: 0,
1394
+ files: [],
1395
+ problems
1396
+ };
1397
+ const { manifest } = pack;
1398
+ return {
1399
+ id,
1400
+ name: manifest.name,
1401
+ version: manifest.version,
1402
+ description: manifest.description,
1403
+ actions: manifest.actions,
1404
+ surfaces: manifest.surfaces,
1405
+ ...manifest.skin === void 0 ? {} : { skin: manifest.skin },
1406
+ tokens: Object.keys(manifest.theme).length,
1407
+ files: [...pack.files].map(([path, file]) => ({
1408
+ path,
1409
+ size: file.size
1410
+ })),
1411
+ problems
1412
+ };
1413
+ });
1414
+ }
1415
+ /**
1416
+ * A pack of a world as a story of that world would start with it: its surfaces load their own files, and are given the view the story would show.
1417
+ * @throws {WorldNotFoundError} when the world, or the pack in it, is not there.
1418
+ * @throws {InvalidPacksError} when the pack has problems.
1419
+ * @throws {InvalidEditProblems} when the rest of the world has problems of its own.
1420
+ */
1421
+ async preview(worldId, packId) {
1422
+ const world = await this.worldOf(worldId);
1423
+ const folder = join(world.directory, "ui", packId);
1424
+ if (!isPackId(packId) || !existsSync(folder)) throw new WorldNotFoundError(`the world carries no pack "${packId}"`);
1425
+ const name = `${worldId}\n${packId}`;
1426
+ const key = this.keyOf.get(`${PREVIEW}${name}`) ?? randomBytes(24).toString("base64url");
1427
+ const { pack, problems } = readPack(folder, packId, addressFor(`${PREVIEW}${key}`));
1428
+ if (pack === void 0) throw new InvalidPacksError(`the pack "${packId}" has ${problems.length} problem(s)`, problems.map((problem) => ({
1429
+ path: problem.file,
1430
+ message: problem.message
1431
+ })));
1432
+ this.keyOf.set(`${PREVIEW}${name}`, key);
1433
+ this.keys.set(key, `${PREVIEW}${key}`);
1434
+ this.previews.set(key, {
1435
+ folder,
1436
+ pack: packId
1437
+ });
1438
+ return {
1439
+ pack: describePack(pack, key),
1440
+ view: await previewViewOf(world, (this.deps.wall ?? Date.now)())
1441
+ };
1442
+ }
1314
1443
  session(id) {
1315
1444
  if (!isSessionId(id) || !existsSync(sessionDatabase(this.sessions(), id))) throw new SessionNotFoundError(`no session "${id}"`);
1316
1445
  return {
@@ -1412,7 +1541,7 @@ var InterfaceService = class {
1412
1541
  }
1413
1542
  /** A file of the session's pack; a page of it comes with the bridge. @returns nothing when the pack has no such file. */
1414
1543
  file(id, path) {
1415
- const { pack } = this.active(id);
1544
+ const pack = id.startsWith(PREVIEW) ? this.previewed(id) : this.active(id).pack;
1416
1545
  const found = pack === void 0 ? void 0 : packFile(pack, path);
1417
1546
  if (found === void 0) return void 0;
1418
1547
  return found.mediaType.startsWith("text/html") ? {
@@ -1424,6 +1553,11 @@ var InterfaceService = class {
1424
1553
  ...found
1425
1554
  };
1426
1555
  }
1556
+ /** The pack of a preview, read afresh. */
1557
+ previewed(id) {
1558
+ const shown = this.previews.get(id.slice(8));
1559
+ return shown === void 0 ? void 0 : readPack(shown.folder, shown.pack, addressFor(id)).pack;
1560
+ }
1427
1561
  /** What the pack keeps in the session. @throws {RangeError} when a value does not fit. */
1428
1562
  storage(id, request) {
1429
1563
  const { session } = this.session(id);
@@ -1522,6 +1656,28 @@ function interfaceRoutes(api) {
1522
1656
  notFound(res, error);
1523
1657
  }
1524
1658
  } },
1659
+ "/worlds/interface": { GET: async (_req, res, url) => {
1660
+ try {
1661
+ sendJson(res, 200, await api.worldPacks(url.searchParams.get("id") ?? ""));
1662
+ } catch (error) {
1663
+ notFound(res, error);
1664
+ }
1665
+ } },
1666
+ "/worlds/interface/preview": { GET: async (_req, res, url) => {
1667
+ try {
1668
+ sendJson(res, 200, await api.preview(url.searchParams.get("id") ?? "", url.searchParams.get("pack") ?? ""));
1669
+ } catch (error) {
1670
+ if (error instanceof InvalidPacksError) return sendJson(res, 422, {
1671
+ message: error.message,
1672
+ problems: error.problems.map((problem) => `${problem.path === "" ? "" : `${problem.path}: `}${problem.message}`)
1673
+ });
1674
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
1675
+ message: error.message,
1676
+ problems: error.problems
1677
+ });
1678
+ notFound(res, error);
1679
+ }
1680
+ } },
1525
1681
  "/interface/availability": { GET: async (_req, res) => {
1526
1682
  sendJson(res, 200, api.availability());
1527
1683
  } }
@@ -2409,6 +2565,17 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, worldChar
2409
2565
  throw error;
2410
2566
  }
2411
2567
  } },
2568
+ "/sessions/reflect": { POST: async (_req, res, url) => {
2569
+ try {
2570
+ await sessions.reflect(url.searchParams.get("id") ?? "");
2571
+ } catch (error) {
2572
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
2573
+ if (error instanceof ReflectionRefusedError) return sendError(res, 409, error.message);
2574
+ throw error;
2575
+ }
2576
+ res.statusCode = 202;
2577
+ res.end();
2578
+ } },
2412
2579
  "/sessions/vectors/reset": { POST: async (_req, res, url) => {
2413
2580
  try {
2414
2581
  sessions.resetVectors(url.searchParams.get("id") ?? "");
@@ -3063,6 +3230,22 @@ function worldOf(session, sessionsDir) {
3063
3230
  definition: plot,
3064
3231
  progress
3065
3232
  }));
3233
+ const triggers = session.triggers.list().map((trigger) => ({
3234
+ key: trigger.key,
3235
+ name: trigger.name,
3236
+ when: trigger.condition,
3237
+ effects: trigger.effects,
3238
+ repeat: trigger.repeat,
3239
+ priority: trigger.priority,
3240
+ ...trigger.cooldownSeconds === void 0 ? {} : { cooldownSeconds: trigger.cooldownSeconds },
3241
+ ...trigger.chance === void 0 ? {} : { chance: trigger.chance },
3242
+ ...trigger.expires === void 0 ? {} : { expires: trigger.expires },
3243
+ announced: trigger.announce !== void 0,
3244
+ status: trigger.status,
3245
+ fireCount: trigger.fireCount,
3246
+ origin: trigger.origin,
3247
+ problems: trigger.problem === void 0 ? [] : [trigger.problem]
3248
+ }));
3066
3249
  return {
3067
3250
  ...typeof narrationVoice === "string" ? { narrationVoice } : {},
3068
3251
  characters,
@@ -3070,6 +3253,7 @@ function worldOf(session, sessionsDir) {
3070
3253
  things,
3071
3254
  factions,
3072
3255
  lore,
3256
+ triggers,
3073
3257
  plots,
3074
3258
  relations
3075
3259
  };
@@ -3896,10 +4080,39 @@ function payloadOf(deps, id, settings) {
3896
4080
  activity: deps.activity(id),
3897
4081
  interventions: deps.interventions(id),
3898
4082
  vectors: deps.vectors(id),
4083
+ reflection: deps.reflection(id),
3899
4084
  ...clockMode === void 0 ? {} : { clockMode }
3900
4085
  };
3901
4086
  }
3902
4087
  //#endregion
4088
+ //#region src/host/interface/first-party.ts
4089
+ /** The folder of the packs shipped with the package. */
4090
+ const FIRST_PARTY_FOLDER = "packs";
4091
+ /** Found from this module, so that it works from source and from the build. */
4092
+ function firstPartyDirectory(from = dirname(fileURLToPath(import.meta.url))) {
4093
+ for (let directory = from;; directory = dirname(directory)) {
4094
+ const candidate = join(directory, FIRST_PARTY_FOLDER);
4095
+ if (existsSync(join(directory, "package.json")) && existsSync(candidate)) return candidate;
4096
+ if (dirname(directory) === directory) throw new Error("the interface packs shipped with the package were not found");
4097
+ }
4098
+ }
4099
+ /**
4100
+ * Puts the packs that ship with the package into the roleplay root's own `ui` folder, where any story can use one by naming it. A pack
4101
+ * that is there is never overwritten, so it can be edited; one that was deleted comes back.
4102
+ * @returns the packs that were put there.
4103
+ */
4104
+ function installFirstPartyPacks(root, shipped = firstPartyDirectory()) {
4105
+ const installed = [];
4106
+ for (const entry of readdirSync(shipped, { withFileTypes: true })) {
4107
+ if (!entry.isDirectory() || !isPackId(entry.name)) continue;
4108
+ const target = join(root, "ui", entry.name);
4109
+ if (existsSync(target)) continue;
4110
+ cpSync(join(shipped, entry.name), target, { recursive: true });
4111
+ installed.push(entry.name);
4112
+ }
4113
+ return installed;
4114
+ }
4115
+ //#endregion
3903
4116
  //#region src/host/sessions/vectors.ts
3904
4117
  /** How many waiting texts are counted before saying "that many": the number is for reassurance, not accounting. */
3905
4118
  const MAX_COUNTED = 1e4;
@@ -3926,14 +4139,19 @@ function resetVectors(session) {
3926
4139
  //#region src/host/sessions/interventions.ts
3927
4140
  /** What the story's triggers delivered lately and what became of each, oldest first. */
3928
4141
  function readInterventions(session) {
3929
- return session.triggers.notes().slice(-30).map((note) => ({
3930
- turn: note.turn,
3931
- kind: note.kind,
3932
- text: note.text,
3933
- trigger: session.triggers.get(note.triggerId)?.key ?? "",
3934
- characters: note.characterIds.flatMap((id) => session.characters.get(id)?.name ?? []),
3935
- status: note.status === "pending" ? "waiting" : note.status === "done" ? "taken" : "lapsed"
3936
- }));
4142
+ const withdrawn = readWithdrawn(session);
4143
+ return session.triggers.notes().slice(-30).map((note) => {
4144
+ const reason = note.status === "lapsed" ? withdrawn[note.id] : void 0;
4145
+ return {
4146
+ turn: note.turn,
4147
+ kind: note.kind,
4148
+ text: note.text,
4149
+ trigger: session.triggers.get(note.triggerId)?.key ?? "",
4150
+ characters: note.characterIds.flatMap((id) => session.characters.get(id)?.name ?? []),
4151
+ status: note.status === "pending" ? "waiting" : note.status === "done" ? "taken" : reason === void 0 ? "lapsed" : "withdrawn",
4152
+ ...reason === void 0 ? {} : { reason }
4153
+ };
4154
+ });
3937
4155
  }
3938
4156
  //#endregion
3939
4157
  //#region src/host/sessions/open-session.ts
@@ -4428,6 +4646,7 @@ function apply(ctx, config) {
4428
4646
  const worlds = new WorldCatalog(ctx, root);
4429
4647
  const prompts = new PromptLibrary(ctx, root);
4430
4648
  prompts.bootstrap();
4649
+ installFirstPartyPacks(root.path);
4431
4650
  const languages = new AuthoringLanguages(ctx, () => join(root.path, "worlds"));
4432
4651
  const agent = new AgentSessions(agentServicesOf(ctx), () => root.path);
4433
4652
  const authoring = new AuthoringSessions(agentServicesOf(ctx), () => root.path, prompts, languages);
@@ -4445,6 +4664,7 @@ function apply(ctx, config) {
4445
4664
  clockMode: (id) => ctx.roleplayState.openSession(join(root.path, "sessions"), id).clock.get()?.mode,
4446
4665
  pendingConsolidation: (id) => ctx.roleplayState.openSession(join(root.path, "sessions"), id).consolidation.pending().length,
4447
4666
  vectors: (id) => vectorStatus(ctx.roleplayState.openSession(join(root.path, "sessions"), id)),
4667
+ reflection: (id) => reflectionStatus(ctx.roleplayState.openSession(join(root.path, "sessions"), id), ctx.roleplayOrchestration.reflecting(chatSessionId(id))),
4448
4668
  activity: (id) => readActivity(ctx.roleplayState.openSession(join(root.path, "sessions"), id)),
4449
4669
  interventions: (id) => readInterventions(ctx.roleplayState.openSession(join(root.path, "sessions"), id))
4450
4670
  };
@@ -4460,7 +4680,8 @@ function apply(ctx, config) {
4460
4680
  packs: new InterfaceService({
4461
4681
  open: (id) => ctx.roleplayState.openSession(deps.sessionsDir(), id),
4462
4682
  root: () => root.path,
4463
- worldDirectory: async (worldId) => (await worlds.find(worldId))?.directory
4683
+ worldDirectory: async (worldId) => (await worlds.find(worldId))?.directory,
4684
+ world: (worldId) => worlds.find(worldId)
4464
4685
  }),
4465
4686
  speech: {
4466
4687
  voices: async () => await voicesOf(textToSpeechOf(ctx)),
@@ -4634,6 +4855,11 @@ function apply(ctx, config) {
4634
4855
  if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);
4635
4856
  return readRunDetail(sessionFolder(sessions, id), run);
4636
4857
  },
4858
+ reflect: async (id) => {
4859
+ const sessions = join(root.path, "sessions");
4860
+ if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);
4861
+ await ctx.roleplayOrchestration.reflect(chatSessionId(id));
4862
+ },
4637
4863
  resetVectors: (id) => {
4638
4864
  const sessions = join(root.path, "sessions");
4639
4865
  if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);
@@ -104,6 +104,15 @@ const SETTINGS_SPEC = {
104
104
  perTurn: integer(0, 3, 1),
105
105
  everyDays: integer(1, 365, 3)
106
106
  },
107
+ reflection: {
108
+ auto: flag(true),
109
+ everyTurns: integer(0, 500, 20),
110
+ onSceneChange: flag(true),
111
+ sceneDays: integer(0, 365, 1),
112
+ minTurns: integer(1, 100, 5),
113
+ perRun: integer(1, 6, 3),
114
+ minNew: integer(1, 50, 4)
115
+ },
107
116
  models: {
108
117
  characters: text(200, ""),
109
118
  background: text(200, ""),
@@ -355,4 +364,4 @@ function decodeOutput(text) {
355
364
  //#endregion
356
365
  export { liveSettings as a, writeSettings as c, parseSettings as d, WORLD_RULES_KEY as f, InvalidSettingsError as i, DEFAULT_SETTINGS as l, encodeOutput as n, readSettings as o, rulesOf as p, encodePreview as r, useChildReasoning as s, decodeOutput as t, SETTINGS_SPEC as u };
357
366
 
358
- //# sourceMappingURL=narration-BRyHU0H2.js.map
367
+ //# sourceMappingURL=narration-CKZTk5UE.js.map