@dsh-agentic-roleplay/core 0.9.1 → 0.10.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 (45) hide show
  1. package/README.md +1 -1
  2. package/lib/{access-CfQWbNZP.js → access-CXtaZNbx.js} +50 -2
  3. package/lib/{authoring-tools-C_l07RYn.js → authoring-tools-C6Hzy8jU.js} +1571 -1301
  4. package/lib/authoring.js +19 -8
  5. package/lib/{child-lYYeOwl2.js → child-C8r8AFpm.js} +150 -14
  6. package/lib/client.js +6295 -3329
  7. package/lib/client.js.map +1 -1
  8. package/lib/compaction.js +3 -3
  9. package/lib/doctor.js +3 -3
  10. package/lib/{gallery-q7niLtWn.js → gallery-CtG-bDzz.js} +5 -9
  11. package/lib/{generator-BpjPrvHe.js → generator-nLoPM5MF.js} +2 -2
  12. package/lib/helper.js +1 -1
  13. package/lib/{hooks-DNaDzMjW.js → hooks-BuQ61nvQ.js} +207 -56
  14. package/lib/images.js +4 -4
  15. package/lib/index.js +1312 -125
  16. package/lib/{library-CIkxhf_R.js → library-CH-ahlm0.js} +7 -14
  17. package/lib/{lorebook-author-tools-BiMDmdFi.js → lorebook-author-tools-B6_Jj8oe.js} +7 -7
  18. package/lib/lorebook-authoring.js +4 -4
  19. package/lib/{narration-CjB_KwwY.js → narration-B0hConSw.js} +11 -53
  20. package/lib/orchestration.js +196 -14
  21. package/lib/{pack-jail-B35Vx3hT.js → pack-jail-OZSgU85i.js} +11 -11
  22. package/lib/{packs-BajKw7S9.js → packs-B88bxt8E.js} +2 -2
  23. package/lib/{presenter-agent-jgtuTwZr.js → presenter-agent-D-WNs626.js} +12 -17
  24. package/lib/{preset-DWgkcPau.js → preset-DNuqvMan.js} +4 -4
  25. package/lib/{preset-author-tools-BhuYIKms.js → preset-author-tools-CDwavcTb.js} +7 -7
  26. package/lib/preset-authoring.js +5 -5
  27. package/lib/{presets-9GzaSELc.js → presets-9_MNxwaw.js} +105 -10
  28. package/lib/{reflection-4L0Plvct.js → reflection-BvM0w1R4.js} +179 -112
  29. package/lib/{text-CbGQhK1-.js → text-CzqhC8sT.js} +11 -1
  30. package/lib/{turn-guard-sCUXmp-5.js → turn-guard-Ygdww1Wt.js} +3 -3
  31. package/package.json +2 -2
  32. package/prompts/en/checks/conflict.md +1 -1
  33. package/prompts/en/checks/decide-conflict.md +1 -1
  34. package/prompts/en/checks/decide-opening.md +1 -1
  35. package/prompts/en/checks/decide-same-value.md +1 -1
  36. package/prompts/en/checks/decide-sheet.md +1 -1
  37. package/prompts/en/checks/decide-stated.md +1 -0
  38. package/prompts/en/checks/fidelity.md +1 -0
  39. package/prompts/zh/checks/conflict.md +1 -1
  40. package/prompts/zh/checks/decide-conflict.md +1 -1
  41. package/prompts/zh/checks/decide-opening.md +1 -1
  42. package/prompts/zh/checks/decide-same-value.md +1 -1
  43. package/prompts/zh/checks/decide-sheet.md +1 -1
  44. package/prompts/zh/checks/decide-stated.md +1 -0
  45. package/prompts/zh/checks/fidelity.md +1 -0
package/lib/index.js CHANGED
@@ -1,29 +1,29 @@
1
- import { a as chatSessionId, i as VARIABLE_VISIBILITIES, n as VARIABLE_KINDS, o as roleplaySessionOf, r as VARIABLE_SUBJECTS } from "./access-CfQWbNZP.js";
2
- import { $ as WORLD_FILE_NAME, $t as pictureOf, At as routineProblems, B as localChanges, C as readWorldInfo, Ct as populateItems, Dt as populateRoutines, Et as populateLore, Gt as loadCalendar, H as writeOrigin, Ht as loadDice, It as loadLocations, J as guardedLookup, Jt as loadCharacters, Kt as parseCalendarFile, L as describeChanges, Ot as populateTriggers, Qt as isPng, R as hashWorld, Rt as loadItems, S as editWorldInfo, St as populateFactions, T as loadWorldParts, Tt as populateLocations, U as CatalogueError, Ut as parseDiceFile, V as readOrigin, Vt as DICE_FILE_NAME, Wt as CALENDAR_FILE_NAME, X as vetUrl, Xt as knownOutputCeiling, Yt as subfolders, Zt as ImportCardError, _t as knowsCharacter, at as deleteLorebookEntry, bt as populateClock, c as importPhase, ct as listLorebooks, d as markReady, en as readCard, et as parseWorldFile, f as settleDraft, ft as reserveLorebook, gt as loadValidatedWorld, ht as checkWorld, in as authoredWorldOf, it as deleteLorebook, jt as TRIGGERS_FILE_NAME, kt as populateVariables, lt as loadLorebook, mt as writeLorebookEntry, nn as DICE_READINGS, nt as addLorebookEntries, ot as entriesOf, p as structureImport, pt as updateLorebookInfo, qt as CHARACTERS_DIR, rn as DICE_RESULTS, rt as createLorebook, st as isLorebookName, t as AuthoringTools, tn as DICE_COMPARISONS, tt as parseWorldInfoEdit, u as keepDraft, ut as lorebookDirectory, vt as populateCalendar, wt as populateKnowledge, xt as populateDice, yt as populateCharacters, z as isUnchanged } from "./authoring-tools-C_l07RYn.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-BiMDmdFi.js";
4
- import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-BhuYIKms.js";
5
- import { a as liveSettings, c as writeSettings, d as DEFAULT_SETTINGS, f as SETTINGS_SPEC, h as WORLD_RULES_KEY, i as InvalidSettingsError, l as atomicWrite, o as readSettings, p as parseSettings, s as useChildReasoning } from "./narration-CjB_KwwY.js";
6
- import { $ as DOCTOR_OPENING_SOURCE, A as worldEntityImageFile, B as languageOfDocuments, C as readWorldEditor, D as uploadWorldCharacterPortrait, E as replaceFile, F as PRESET_FILE, G as revertUpdate, H as findTargets, I as presetMessage, J as AuthoringSessions, K as startUpdate, O as uploadWorldEntityImage, Q as agentServicesOf, R as translateMessage, S as generateWorldEntityImage, T as removeWorldTrigger, V as readWorldDocuments, X as ensureAuthoringChat, Y as authoringTitle, Z as AgentSessions, _ as editWorldPlots$1, a as deleteWorldPackFile, b as entityFolder, c as createAuthoredEntity, et as appendEmptyTurn, f as editWorldCharacter$1, g as editWorldPlace$1, h as editWorldNarrationVoice, j as writeWorldTrigger, k as worldCharacterPortraitFile, l as deleteAuthoredEntity, m as editWorldLore$1, n as packFileProblem, p as editWorldFaction$1, q as updateStatus, t as MAX_PACK_TEXT, tt as appendNarratedTurn, u as readAuthoredEntityDocument, v as editWorldRelation$1, w as readWorldTrigger, x as generateWorldCharacterPortrait, y as editWorldThing$1 } from "./pack-jail-B35Vx3hT.js";
7
- import { d as sharedSamplingOf, i as childSamplingOf, u as parseSampling } from "./child-lYYeOwl2.js";
8
- import { $ as copyWorldPrompts, C as readNotes, H as plotReferenceProblems, J as formatIssue, K as readDocument, M as plotProgressOf, N as populatePlots, O as zoneOf, Q as PromptLibrary, S as notesOfSession, U as COMMANDS_KEY, V as parsePlotsFile, Y as errorMessage, _ as readRunDetail, b as readWithdrawn, ct as InvalidStartError, dt as SessionArchivedError, ft as SessionNotFoundError, g as readActivity, h as readDecisionStats, i as externalTools, it as shippedLanguages, j as PLOTS_METADATA_KEY, lt as InvalidWorldError, m as readUsage, pt as WorldNotFoundError, st as AgentUnavailableError, tt as languageOf, ut as ReflectionRefusedError, w as observeAsPlayer, x as addToNote } from "./hooks-DNaDzMjW.js";
9
- import { $ as ImportNotFoundError, At as parseLoreEdit, Ct as CHARACTER_FILE_NAME, Dt as InvalidEditProblems, Ft as LORE_SCOPES, G as listWorldPrompts, K as readWorldPrompt, Mt as parseRelationEdit, Nt as parseThingEdit, Ot as parseCharacterEdit, Pt as LORE_KINDS, Q as IMPORT_FOLDER, W as deleteWorldPrompt, X as partsOf, Z as withPlayer, a as isPresetName, c as presetDirectory, d as savePresetFromWorld, dt as parseVariablesFile, et as ImportStore, ft as variableProblems, i as deletePreset, jt as parsePlaceEdit, kt as parseFactionEdit, lt as VARIABLES_FILE_NAME, o as listPresets, ot as IMPORT_COMMAND, p as updatePresetInfo, q as writeWorldPrompt, r as createPresetFromShipped, rt as parseChoices, s as loadPreset, t as PRESET_FILE$1, u as reservePreset, ut as loadVariables, wt as parseCharacterFile } from "./presets-9GzaSELc.js";
10
- import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-CbGQhK1-.js";
11
- import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-DWgkcPau.js";
12
- import { C as slug, T as uniqueKey, d as sceneImagePath, s as inheritImages, t as addToLibrary, u as referenceImagePath } from "./library-CIkxhf_R.js";
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-CXtaZNbx.js";
2
+ import { $t as ImportCardError, At as populateTriggers, Bt as loadItems, Ct as populateDice, Dt as populateLocations, E as loadWorldParts, Et as populateKnowledge, F as localChanges, G as vetUrl, Gt as parseDiceFile, I as readOrigin, Jt as parseCalendarFile, Kt as CALENDAR_FILE_NAME, L as writeOrigin, M as describeChanges, Mt as routineProblems, N as hashWorld, Nt as TRIGGERS_FILE_NAME, Ot as populateLore, P as isUnchanged, Qt as knownOutputCeiling, R as CatalogueError, Rt as loadLocations, St as populateClock, T as readWorldInfo, Tt as populateItems, U as guardedLookup, Ut as DICE_FILE_NAME, Wt as loadDice, Xt as loadCharacters, Yt as CHARACTERS_DIR, Zt as subfolders, _ as runChecks, _t as loadValidatedWorld, an as DICE_RESULTS, at as deleteLorebook, bt as populateCalendar, c as importPhase, ct as isLorebookName, d as markReady, dt as lorebookDirectory, en as isPng, et as WORLD_FILE_NAME, f as settleDraft, gt as checkWorld, ht as writeLorebookEntry, in as DICE_READINGS, it as createLorebook, jt as populateVariables, kt as populateRoutines, lt as listLorebooks, mt as updateLorebookInfo, nn as readCard, nt as parseWorldInfoEdit, on as authoredWorldOf, ot as deleteLorebookEntry, p as structureImport, pt as reserveLorebook, qt as loadCalendar, rn as DICE_COMPARISONS, rt as addLorebookEntries, st as entriesOf, t as AuthoringTools, tn as pictureOf, tt as parseWorldFile, u as keepDraft, ut as loadLorebook, w as editWorldInfo, wt as populateFactions, xt as populateCharacters, yt as knowsCharacter } from "./authoring-tools-C6Hzy8jU.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-B6_Jj8oe.js";
4
+ import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-CDwavcTb.js";
5
+ 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-B0hConSw.js";
6
+ import { $ as DOCTOR_OPENING_SOURCE, A as worldEntityImageFile, B as languageOfDocuments, C as readWorldEditor, D as uploadWorldCharacterPortrait, E as replaceFile, F as PRESET_FILE, G as revertUpdate, H as findTargets, I as presetMessage, J as AuthoringSessions, K as startUpdate, O as uploadWorldEntityImage, Q as agentServicesOf, R as translateMessage, S as generateWorldEntityImage, T as removeWorldTrigger, V as readWorldDocuments, X as ensureAuthoringChat, Y as authoringTitle, Z as AgentSessions, _ as editWorldPlots$1, a as deleteWorldPackFile, b as entityFolder, c as createAuthoredEntity, et as appendEmptyTurn, f as editWorldCharacter$1, g as editWorldPlace$1, h as editWorldNarrationVoice, j as writeWorldTrigger, k as worldCharacterPortraitFile, l as deleteAuthoredEntity, m as editWorldLore$1, n as packFileProblem, p as editWorldFaction$1, q as updateStatus, t as MAX_PACK_TEXT, tt as appendNarratedTurn, u as readAuthoredEntityDocument, v as editWorldRelation$1, w as readWorldTrigger, x as generateWorldCharacterPortrait, y as editWorldThing$1 } from "./pack-jail-OZSgU85i.js";
7
+ import { d as sharedSamplingOf, i as childSamplingOf, u as parseSampling, v as totalTokens } from "./child-C8r8AFpm.js";
8
+ import { $ as PromptLibrary, C as readNotes, H as parsePlotsFile, M as plotProgressOf, N as populatePlots, O as zoneOf, S as notesOfSession, U as plotReferenceProblems, W as COMMANDS_KEY, X as errorMessage, Y as formatIssue, _ as readTraces, at as shippedLanguages, b as readWithdrawn, ct as AgentUnavailableError, dt as ReflectionRefusedError, et as copyWorldPrompts, ft as SessionArchivedError, g as readRunDetail, h as readActivity, i as externalTools, j as PLOTS_METADATA_KEY, lt as InvalidStartError, m as readDecisionStats, mt as WorldNotFoundError, nt as languageOf, pt as SessionNotFoundError, q as readDocument, ut as InvalidWorldError, w as observeAsPlayer, x as addToNote, z as readUsage } from "./hooks-BuQ61nvQ.js";
9
+ 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 LORE_KINDS, Mt as parseFactionEdit, Nt as parseLoreEdit, Pt as parsePlaceEdit, Q as withPlayer, Rt as LORE_SCOPES, 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$1, tt as ImportStore, u as reservePreset } from "./presets-9_MNxwaw.js";
10
+ import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-CzqhC8sT.js";
11
+ import { _ as START_SNAPSHOT, b as snapshotOf, c as copyPreset, d as switchPreset, f as defaultBoundaries, g as writeTimeline, h as readTimeline, i as reflectionStatus, l as presetStatus, o as TimelineError, u as recordPreset, v as childrenOf, y as pathTo } from "./reflection-BvM0w1R4.js";
12
+ import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-DNuqvMan.js";
13
+ import { C as slug, T as uniqueKey, d as sceneImagePath, s as inheritImages, t as addToLibrary, u as referenceImagePath } from "./library-CH-ahlm0.js";
13
14
  import { t as doctorChatSessionId } from "./doctor-chat-hL1a61hp.js";
14
- import { c as readTimeline, d as copyPreset, f as presetStatus, h as defaultBoundaries, i as reflectionStatus, l as writeTimeline, m as switchPreset, o as TimelineError, p as recordPreset, u as pathTo } from "./reflection-4L0Plvct.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-BajKw7S9.js";
16
- import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-BpjPrvHe.js";
17
- import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-q7niLtWn.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-B88bxt8E.js";
16
+ import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-nLoPM5MF.js";
17
+ import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-CtG-bDzz.js";
18
18
  import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
19
- import { cpSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
19
+ import { cpSync, createReadStream, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
20
20
  import { createHash, randomBytes, randomUUID } from "node:crypto";
21
21
  import { copyFile, cp, lstat, mkdir, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
22
22
  import { Session, SessionId } from "@deepseek-ai/dsh-session";
23
- import { inflateRawSync } from "node:zlib";
23
+ import { crc32, deflateRawSync, inflateRawSync } from "node:zlib";
24
24
  import { fileURLToPath } from "node:url";
25
25
  import { Service } from "@deepseek-ai/cordis";
26
- import { addLocalDays, createSessionStore, describeInstant, describeValue, holidaysOn, isSessionId, itemKey, lintWorld, locationKey, parseInstant, readCalendar, seasonOf, sessionDatabase, sessionFolder, shownVariables, systemTimeZone } from "@dsh-agentic-roleplay/state";
26
+ 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";
27
27
  import { request } from "node:http";
28
28
  import { request as request$1 } from "node:https";
29
29
  import { homedir } from "node:os";
@@ -137,9 +137,17 @@ function folderNameOf(name) {
137
137
  return folder === "" ? "imported world" : folder;
138
138
  }
139
139
  /** The command that starts the import, for a card kept in the world's import folder. */
140
- function importMessage(language) {
141
- const tr = translator(languageOf$1(language));
142
- return `${IMPORT_COMMAND} ${IMPORT_FOLDER}/card.json ${tr("Import this card into this newly created world.")}`;
140
+ function importMessage(language, card) {
141
+ const request = translator(languageOf$1(language))("Import this card into this newly created world.");
142
+ return `${IMPORT_COMMAND} ${IMPORT_FOLDER}/card.json ${card === void 0 ? request : `${request} ${sourceSummary(card, language)}`}`;
143
+ }
144
+ /** The card kept in a world's import folder, when it can be read; the message then carries a summary of it. */
145
+ async function cardOf(directory) {
146
+ try {
147
+ return (await readImportFolder(join(directory, IMPORT_FOLDER))).card;
148
+ } catch {
149
+ return;
150
+ }
143
151
  }
144
152
  /**
145
153
  * Has the chat of a world whose import stopped before it was done carry on from the step it reached (the import hooks tell the chat which step that is). An import is lost
@@ -154,7 +162,7 @@ async function resumeImport(deps, worldId, language) {
154
162
  const chatSessionId = await deps.authoring.ensure(record.summary.id, record.summary.name, authoringTitle(record.summary.name, language), language);
155
163
  let failure;
156
164
  try {
157
- await deps.authoring.send(chatSessionId, importMessage(language));
165
+ await deps.authoring.send(chatSessionId, importMessage(language, await cardOf(record.directory)));
158
166
  } catch (error) {
159
167
  failure = error instanceof Error ? error.message : String(error);
160
168
  }
@@ -195,11 +203,11 @@ async function createImportedWorld(deps, id, choices) {
195
203
  * @throws {InvalidEditProblems} when the choices cannot be used. @throws {ImportNotFoundError} when the upload is gone.
196
204
  */
197
205
  async function startImport(deps, id, choices, language) {
198
- const { world } = await createImportedWorld(deps, id, choices);
206
+ const { world, directory } = await createImportedWorld(deps, id, choices);
199
207
  const chatSessionId = await deps.authoring.ensure(world.id, world.name, authoringTitle(world.name, language), language);
200
208
  let failure;
201
209
  try {
202
- await deps.authoring.send(chatSessionId, importMessage(language));
210
+ await deps.authoring.send(chatSessionId, importMessage(language, await cardOf(directory)));
203
211
  } catch (error) {
204
212
  failure = error instanceof Error ? error.message : String(error);
205
213
  }
@@ -272,6 +280,364 @@ async function actOnDraft(deps, worldId, action, language) {
272
280
  keptIn: relative(deps.root(), destination)
273
281
  };
274
282
  }
283
+ // src/host/sessions/statistics.ts
284
+ const CJK = /[ -鿿가-힯]/gu;
285
+ /** How long a text is: its words, and each character of a script that is written without spaces. */
286
+ function lengthOf(text) {
287
+ return (text.match(CJK)?.length ?? 0) + (text.replace(CJK, " ").match(/[\p{L}\p{N}]+/gu)?.length ?? 0);
288
+ }
289
+ /** Voices of the delivered turns on the way the story went: who spoke how often and how much, and what the narration came to. */
290
+ function speakingOf(timeline) {
291
+ const voices = /* @__PURE__ */ new Map();
292
+ const narration = {
293
+ passages: 0,
294
+ length: 0
295
+ };
296
+ for (const node of pathTo(timeline, timeline.head)) for (const segment of node.output?.segments ?? []) {
297
+ if (segment.type === "narration") {
298
+ narration.passages += 1;
299
+ narration.length += lengthOf(segment.text);
300
+ continue;
301
+ }
302
+ const voice = voices.get(segment.character) ?? {
303
+ name: segment.name,
304
+ lines: 0,
305
+ length: 0
306
+ };
307
+ voice.lines += 1;
308
+ voice.length += lengthOf(segment.text);
309
+ voices.set(segment.character, voice);
310
+ }
311
+ return {
312
+ speaking: [...voices.values()].sort((a, b) => b.length - a.length),
313
+ narration
314
+ };
315
+ }
316
+ /** How the story branched: turns played again from one state, and turns that were played and are not on the way the story went. */
317
+ function branchesOf(timeline) {
318
+ const onPath = new Set(pathTo(timeline, timeline.head).map((node) => node.id));
319
+ const parents = /* @__PURE__ */ new Map();
320
+ for (const node of timeline.nodes) parents.set(node.parent, (parents.get(node.parent) ?? 0) + 1);
321
+ return {
322
+ branchPoints: [...parents.values()].filter((count) => count > 1).length,
323
+ setAside: timeline.nodes.filter((node) => !onPath.has(node.id)).length
324
+ };
325
+ }
326
+ /**
327
+ * The shape of a played story: its length in turns, real and story time, scenes, who spoke how much, open threads, relationships that changed, branches, and what the models used.
328
+ * @throws {SessionNotFoundError} when the id names no session.
329
+ */
330
+ function statisticsOfSession(deps, id) {
331
+ const directory = deps.sessionsDir();
332
+ if (!isSessionId(id) || !existsSync(sessionDatabase(directory, id))) throw new SessionNotFoundError(`no session "${id}"`);
333
+ const story = deps.state.openSession(directory, id);
334
+ const metadata = story.metadata.get();
335
+ const timeline = readTimeline(sessionFolder(directory, id));
336
+ const usage = readUsage(story);
337
+ const first = story.clock.log()[0];
338
+ const now = story.clock.get()?.now;
339
+ const places = story.events.list().map((event) => event.locationId).filter((place) => place !== void 0);
340
+ const threads = story.threads.list();
341
+ const relationships = story.relationships.list();
342
+ return {
343
+ turns: pathTo(timeline, timeline.head).length,
344
+ realTime: {
345
+ createdAt: metadata.createdAt,
346
+ ...metadata.lastPlayedAt === void 0 ? {} : { lastPlayedAt: metadata.lastPlayedAt },
347
+ waitedMs: usage.reduce((sum, entry) => sum + (entry.masterMs ?? 0), 0)
348
+ },
349
+ storyTime: {
350
+ ...first === void 0 ? {} : { start: new Date(first.to).toISOString() },
351
+ ...now === void 0 ? {} : { now: new Date(now).toISOString() },
352
+ ...first === void 0 || now === void 0 ? {} : { elapsedSeconds: Math.max(0, Math.round((now - first.to) / 1e3)) }
353
+ },
354
+ scenes: places.filter((place, index) => index === 0 || place !== places[index - 1]).length,
355
+ ...speakingOf(timeline),
356
+ threads: {
357
+ open: threads.filter((thread) => thread.status === "open").length,
358
+ resolved: threads.filter((thread) => thread.status !== "open").length
359
+ },
360
+ relationships: {
361
+ total: relationships.length,
362
+ changed: relationships.filter((relation) => relation.updatedTurn > 0).length
363
+ },
364
+ branches: branchesOf(timeline),
365
+ usage: {
366
+ runs: usage.reduce((sum, entry) => sum + entry.runs, 0),
367
+ masterTokens: usage.reduce((sum, entry) => sum + totalTokens(entry.master), 0),
368
+ helperTokens: usage.reduce((sum, entry) => sum + totalTokens(entry.helpers), 0)
369
+ }
370
+ };
371
+ }
372
+ // src/host/timeline/compare.ts
373
+ /** The differences between two lists of rows that share a key: a row only one side has, and a row whose summary differs. */
374
+ function differences(area, a, b, key, subject, summary) {
375
+ const before = new Map(a.map((row) => [key(row), row]));
376
+ const after = new Map(b.map((row) => [key(row), row]));
377
+ const changes = [];
378
+ for (const [id, row] of before) {
379
+ const other = after.get(id);
380
+ if (other === void 0) changes.push({
381
+ area,
382
+ subject: subject(row),
383
+ a: summary(row)
384
+ });
385
+ else if (summary(other) !== summary(row)) changes.push({
386
+ area,
387
+ subject: subject(row),
388
+ a: summary(row),
389
+ b: summary(other)
390
+ });
391
+ }
392
+ for (const [id, row] of after) if (!before.has(id)) changes.push({
393
+ area,
394
+ subject: subject(row),
395
+ b: summary(row)
396
+ });
397
+ return changes;
398
+ }
399
+ const place = (row) => row.location === null ? "nowhere" : `${row.location}${row.position === "" ? "" : ` (${row.position})`}`;
400
+ const number = (value) => String(Math.round(value * 100) / 100);
401
+ /** Compares two states of a story: positions, activity, things, tracked values, open threads, relationships, commitments and the story's time. */
402
+ function compareStates(first, second) {
403
+ const changes = [];
404
+ if (first.now !== second.now) changes.push({
405
+ area: "time",
406
+ subject: "story time",
407
+ ...first.now === void 0 ? {} : { a: first.now },
408
+ ...second.now === void 0 ? {} : { b: second.now }
409
+ });
410
+ if (first.turns !== second.turns) changes.push({
411
+ area: "turns",
412
+ subject: "turns played",
413
+ a: String(first.turns),
414
+ b: String(second.turns)
415
+ });
416
+ const a = first.view;
417
+ const b = second.view;
418
+ changes.push(...differences("position", a.characters, b.characters, (row) => row.character, (row) => row.name, place), ...differences("activity", a.characters, b.characters, (row) => row.character, (row) => row.name, (row) => row.activity), ...differences("item", a.items, b.items, (row) => row.key, (row) => row.name, (row) => `${row.holder}${row.quantity === 1 ? "" : `, ${row.quantity}`}${row.state === null ? "" : `, ${row.state}`}`), ...differences("variable", a.variables, b.variables, (row) => `${row.variable}|${row.subject}`, (row) => `${row.variable} of ${row.about || row.subject}`, (row) => String(row.value)), ...differences("thread", a.open_threads, b.open_threads, (row) => row.text, () => "open thread", (row) => row.text), ...differences("relationship", a.relationships, b.relationships, (row) => `${row.from}>${row.to}`, (row) => `${row.from} to ${row.to}`, (row) => `${row.label} (trust ${number(row.trust)}, affinity ${number(row.affinity)}, tension ${number(row.tension)})`), ...differences("engagement", a.engagements, b.engagements, (row) => `${row.title}|${row.at}`, (row) => row.title, (row) => row.at));
419
+ return {
420
+ a: first.label,
421
+ b: second.label,
422
+ changes
423
+ };
424
+ }
425
+ // src/host/playtest/playtest.ts
426
+ /** The test player's words when the story offered no suggestion to take. */
427
+ const FALLBACK_MOVES = [
428
+ "I look around and take stock of where I am.",
429
+ "I speak to the nearest person.",
430
+ "I go somewhere else."
431
+ ];
432
+ const POLL_MS = 1e3;
433
+ const SUGGESTION_WAIT_MS = 9e4;
434
+ /** A turn that takes this many times the median is named as slow. */
435
+ const SLOW_FACTOR = 3;
436
+ const sideOf$1 = (label, story) => ({
437
+ label,
438
+ turns: story.metadata.get().turns,
439
+ now: ((now) => now === void 0 ? void 0 : new Date(now).toISOString())(story.clock.get()?.now),
440
+ view: story.records()
441
+ });
442
+ const median = (values) => {
443
+ const sorted = [...values].sort((a, b) => a - b);
444
+ return sorted.length === 0 ? 0 : sorted[Math.floor(sorted.length / 2)];
445
+ };
446
+ /**
447
+ * A bounded test play of a world: a story is started from it like any other, a few turns are played in which the test player takes what the story itself suggests,
448
+ * and the report says where it went, what it set off, how long each turn took and what the world's own checks find. The story is removed afterwards, and the world is only read.
449
+ */
450
+ var Playtests = class {
451
+ deps;
452
+ runs = /* @__PURE__ */ new Map();
453
+ constructor(deps) {
454
+ this.deps = deps;
455
+ }
456
+ status(world) {
457
+ return this.runs.get(world)?.status;
458
+ }
459
+ /**
460
+ * @throws {InvalidEditProblems} when the request cannot be used or a test play of this world is running.
461
+ */
462
+ start(request) {
463
+ if (!Number.isInteger(request.turns) || request.turns < 1 || request.turns > 10) throw new InvalidEditProblems([`turns must be a whole number from 1 to 10`]);
464
+ if (this.runs.get(request.worldId)?.status.state === "running") throw new InvalidEditProblems(["a test play of this world is running: stop it first"]);
465
+ if ([...this.runs.values()].some((run) => run.status.state === "running")) throw new InvalidEditProblems(["another test play is running: models are used for one at a time"]);
466
+ const status = {
467
+ state: "running",
468
+ world: request.worldId,
469
+ turns: request.turns,
470
+ played: 0,
471
+ step: "starting the story",
472
+ startedAt: new Date(this.deps.now()).toISOString()
473
+ };
474
+ const abort = new AbortController();
475
+ const run = {
476
+ status,
477
+ abort,
478
+ done: Promise.resolve()
479
+ };
480
+ run.done = this.play(request, run).catch((error) => {
481
+ status.state = abort.signal.aborted ? "stopped" : "failed";
482
+ status.error = error instanceof Error ? error.message : String(error);
483
+ });
484
+ this.runs.set(request.worldId, run);
485
+ return status;
486
+ }
487
+ /** Has the test play end after the turn it is in; the story is removed. */
488
+ async stop(world) {
489
+ const run = this.runs.get(world);
490
+ if (run === void 0 || run.status.state !== "running") return;
491
+ run.abort.abort();
492
+ await run.done;
493
+ }
494
+ /** Resolves when the test play of a world is over (for tests and shutdown). */
495
+ async finished(world) {
496
+ await this.runs.get(world)?.done;
497
+ }
498
+ async dispose() {
499
+ await Promise.all([...this.runs].filter(([, run]) => run.status.state === "running").map(([world]) => this.stop(world)));
500
+ }
501
+ async play(request, run) {
502
+ const { deps } = this;
503
+ const { status, abort } = run;
504
+ const began = deps.now();
505
+ const player = request.playerCharacterId ?? await deps.firstPlayer(request.worldId);
506
+ if (player === void 0) throw new InvalidEditProblems(["the world has no character a player can play"]);
507
+ const started = await deps.start({
508
+ worldId: request.worldId,
509
+ name: `Playtest ${new Date(began).toISOString().slice(0, 16).replace("T", " ")}`,
510
+ playerCharacterId: player,
511
+ ...request.opening === void 0 ? {} : { opening: request.opening },
512
+ settings: {
513
+ ...request.language === void 0 ? {} : { prompts: { language: request.language } },
514
+ images: { mode: "off" },
515
+ suggestions: { count: 3 }
516
+ }
517
+ });
518
+ const session = started.id;
519
+ const problems = [];
520
+ const turns = [];
521
+ try {
522
+ const story = deps.story(session);
523
+ const first = sideOf$1("the start", story);
524
+ const visited = /* @__PURE__ */ new Set();
525
+ const placeOf = () => story.records().characters.find((character) => character.controlled_by === "the player")?.location ?? "";
526
+ if (placeOf() !== "") visited.add(placeOf());
527
+ for (let turn = 1; turn <= request.turns && !abort.signal.aborted; turn += 1) {
528
+ status.step = `turn ${turn} of ${request.turns}: choosing the player's move`;
529
+ const move = await this.moveFor(session, turn, problems, abort.signal);
530
+ if (abort.signal.aborted) break;
531
+ status.step = `turn ${turn} of ${request.turns}: playing`;
532
+ const sentAt = deps.now();
533
+ await deps.send(session, move);
534
+ if (!await this.waitForTurn(session, started.chatSessionId, turn, abort.signal)) {
535
+ problems.push(abort.signal.aborted ? `turn ${turn} was stopped` : `turn ${turn} did not finish within ${Math.round(deps.turnTimeoutMs() / 6e4)} minutes`);
536
+ break;
537
+ }
538
+ const place = placeOf();
539
+ if (place !== "") visited.add(place);
540
+ turns.push({
541
+ turn,
542
+ player: move,
543
+ seconds: Math.round((deps.now() - sentAt) / 1e3),
544
+ place
545
+ });
546
+ status.played = turn;
547
+ }
548
+ status.step = "looking at what happened";
549
+ const last = sideOf$1("the end", story);
550
+ const typical = median(turns.map((turn) => turn.seconds));
551
+ for (const turn of turns) if (turns.length >= 3 && typical > 0 && turn.seconds > typical * SLOW_FACTOR) problems.push(`turn ${turn.turn} took ${turn.seconds} s, ${Math.round(turn.seconds / typical)} times the usual ${typical} s`);
552
+ const places = story.locations.list().map((place) => ({
553
+ key: place.sourceId ?? String(place.id),
554
+ name: place.name
555
+ }));
556
+ const triggers = story.triggers.list().filter((trigger) => trigger.origin === "world");
557
+ status.report = {
558
+ world: started.worldName,
559
+ asked: request.turns,
560
+ played: turns.length,
561
+ seconds: Math.round((deps.now() - began) / 1e3),
562
+ turns,
563
+ places: {
564
+ visited: places.filter((place) => visited.has(place.key)).map((place) => place.name),
565
+ unvisited: places.filter((place) => !visited.has(place.key)).map((place) => place.name)
566
+ },
567
+ triggers: {
568
+ fired: triggers.filter((trigger) => trigger.fireCount > 0).map((trigger) => trigger.name),
569
+ waiting: triggers.filter((trigger) => trigger.status === "dormant" && trigger.fireCount === 0).map((trigger) => trigger.name)
570
+ },
571
+ changes: compareStates(first, last).changes,
572
+ findings: await deps.check(request.worldId),
573
+ problems
574
+ };
575
+ status.state = abort.signal.aborted ? "stopped" : "done";
576
+ status.step = "";
577
+ } finally {
578
+ await deps.halt(started.chatSessionId).catch(() => void 0);
579
+ await deps.remove(session).catch((error) => {
580
+ status.error = `the test story could not be removed (${error instanceof Error ? error.message : String(error)}): delete the session "${started.name}" yourself`;
581
+ });
582
+ }
583
+ }
584
+ /** What the test player says: one of the story's own suggestions, in turn, or a plain move when none came. */
585
+ async moveFor(session, turn, problems, signal) {
586
+ if (turn === 1) return FALLBACK_MOVES[0];
587
+ const until = this.deps.now() + SUGGESTION_WAIT_MS;
588
+ while (this.deps.now() < until && !signal.aborted) {
589
+ const lines = this.deps.notes(session).find((note) => note.kind === "suggestions")?.lines ?? [];
590
+ if (lines.length > 0) return lines[(turn - 2) % lines.length];
591
+ await this.deps.sleep(POLL_MS);
592
+ }
593
+ if (!signal.aborted) problems.push(`no suggestion came before turn ${turn}, so the test player took a plain move`);
594
+ return FALLBACK_MOVES[(turn - 1) % FALLBACK_MOVES.length];
595
+ }
596
+ async waitForTurn(session, chat, turn, signal) {
597
+ const until = this.deps.now() + this.deps.turnTimeoutMs();
598
+ while (this.deps.now() < until && !signal.aborted) {
599
+ const view = this.deps.timeline(session);
600
+ const last = view.path.at(-1);
601
+ if (view.path.length >= turn && last?.output !== void 0 && !this.deps.playing(chat)) return true;
602
+ await this.deps.sleep(POLL_MS);
603
+ }
604
+ return false;
605
+ }
606
+ };
607
+ // src/host/sessions/compare-session.ts
608
+ var UnknownStateError = class extends Error {};
609
+ const sideOf = (label, store) => ({
610
+ label,
611
+ turns: store.metadata.get().turns,
612
+ now: ((now) => now === void 0 ? void 0 : new Date(now).toISOString())(store.clock.get()?.now),
613
+ view: store.records()
614
+ });
615
+ /**
616
+ * What differs between two states of a story: `head` (as it is now), `start` (before the first turn) or a turn of the timeline, whose kept state is read. Turns
617
+ * whose state was not kept (older than the setting allows, unless named as a checkpoint) cannot be compared.
618
+ * @throws {SessionNotFoundError} when the id names no session. @throws {UnknownStateError} when a side names no turn, or one whose state is not kept.
619
+ */
620
+ function compareSession(deps, id, first, second) {
621
+ const directory = deps.sessionsDir();
622
+ if (!isSessionId(id) || !existsSync(sessionDatabase(directory, id))) throw new SessionNotFoundError(`no session "${id}"`);
623
+ const timeline = readTimeline(sessionFolder(directory, id));
624
+ const kept = new Set(deps.state.snapshots(directory, id));
625
+ const label = (at) => {
626
+ if (at === "head") return "now";
627
+ if (at === "start") return "the start";
628
+ const node = timeline.nodes.find((candidate) => candidate.id === at);
629
+ if (node === void 0) throw new UnknownStateError(`there is no turn "${at}"`);
630
+ return node.label === void 0 ? `turn ${node.turn}` : `“${node.label}” (turn ${node.turn})`;
631
+ };
632
+ const side = (at) => {
633
+ const name = label(at);
634
+ if (at === "head") return sideOf(name, deps.state.openSession(directory, id));
635
+ const snapshot = at === "start" ? START_SNAPSHOT : snapshotOf(at);
636
+ if (!kept.has(snapshot)) throw new UnknownStateError(`the state after ${name} is not kept: name the turn as a checkpoint to keep it`);
637
+ return deps.state.readSnapshot(directory, id, snapshot, (store) => sideOf(name, store));
638
+ };
639
+ return compareStates(side(first), side(second));
640
+ }
275
641
  // src/host/translate/service.ts
276
642
  async function recordOf(worlds, id) {
277
643
  const record = await worlds.find(id);
@@ -570,7 +936,7 @@ async function lorebookLore(root, names, chosen, knows, taken) {
570
936
  function lorebooksOf(session) {
571
937
  return session.metadata.getValue("roleplay.lorebooks") ?? [];
572
938
  }
573
- const keyOf$3 = (entry) => entry.sourceId ?? String(entry.id);
939
+ const keyOf$4 = (entry) => entry.sourceId ?? String(entry.id);
574
940
  /**
575
941
  * Copies a library lorebook into a story that is already being played. The characters that know an entry learn it at the story's current turn.
576
942
  * @throws {Error} when the story already has the book or the book cannot be used.
@@ -603,12 +969,12 @@ function removeLorebook(session, name) {
603
969
  const ids = new Set(leaving.map((entry) => entry.id));
604
970
  const citing = all.filter((entry) => !ids.has(entry.id) && (entry.related.some((id) => ids.has(id)) || entry.subjects.some((subject) => subject.kind === "lore" && ids.has(subject.id)))).map((entry) => entry.title);
605
971
  if (citing.length > 0) throw new Error(`other lore refers to entries of this lorebook: ${citing.join(", ")}`);
606
- const remaining = all.filter((entry) => !ids.has(entry.id)).map(keyOf$3);
972
+ const remaining = all.filter((entry) => !ids.has(entry.id)).map(keyOf$4);
607
973
  const plots = plotReferenceProblems(plotProgressOf(session.metadata).map((progress) => progress.plot), [
608
- ...session.characters.list().map(keyOf$3),
609
- ...session.factions.list().map(keyOf$3),
610
- ...session.locations.list().map(keyOf$3),
611
- ...session.items.list().map(keyOf$3),
974
+ ...session.characters.list().map(keyOf$4),
975
+ ...session.factions.list().map(keyOf$4),
976
+ ...session.locations.list().map(keyOf$4),
977
+ ...session.items.list().map(keyOf$4),
612
978
  ...remaining
613
979
  ]);
614
980
  if (plots.length > 0) throw new Error(`a plot refers to entries of this lorebook: ${plots.join("; ")}`);
@@ -840,6 +1206,8 @@ var RoleplayOrchestration = class extends Service {
840
1206
  halt = () => Promise.resolve();
841
1207
  /** Starts a reflection of a chat's characters on what they have taken in, in the background; there while the orchestration is. */
842
1208
  reflect = () => Promise.reject(/* @__PURE__ */ new Error("the orchestration is not running"));
1209
+ /** What a moment would bring back for the chat's characters, without playing it or changing the story; there while the orchestration is. */
1210
+ recallPreview = () => Promise.reject(/* @__PURE__ */ new Error("the orchestration is not running"));
843
1211
  /** Whether a turn of the chat is being played; there while the orchestration is. */
844
1212
  playing = () => false;
845
1213
  /** Whether a reflection of the chat is running; there while the orchestration is. */
@@ -1650,7 +2018,7 @@ function withBridge(html) {
1650
2018
  return `${script}${html}`;
1651
2019
  }
1652
2020
  // src/host/interface/player-view.ts
1653
- const keyOf$2 = (character) => character.sourceId ?? String(character.id);
2021
+ const keyOf$3 = (character) => character.sourceId ?? String(character.id);
1654
2022
  /** What a variable shows, in one line of data. */
1655
2023
  function shown(subject, entries) {
1656
2024
  return entries.map(({ variable, value }) => ({
@@ -1697,12 +2065,12 @@ function playerViewOf(session, options) {
1697
2065
  if (player === void 0) return finish(view, session);
1698
2066
  const playerState = session.characterStates.get(player.id);
1699
2067
  view.player = {
1700
- key: keyOf$2(player),
2068
+ key: keyOf$3(player),
1701
2069
  name: player.name,
1702
2070
  summary: player.summary,
1703
2071
  publicState: playerState?.publicState ?? ""
1704
2072
  };
1705
- view.variables.push(...shown(player.name, shownVariables(session, "character", player.id, keyOf$2(player), "others")));
2073
+ view.variables.push(...shown(player.name, shownVariables(session, "character", player.id, keyOf$3(player), "others")));
1706
2074
  const placement = session.placements.get("character", player.id);
1707
2075
  const here = placement === void 0 ? void 0 : session.locations.get(placement.locationId);
1708
2076
  const known = new Set(session.knowledge.list(player.id, "location").map((entry) => entry.subjectId));
@@ -1733,7 +2101,7 @@ function playerViewOf(session, options) {
1733
2101
  here: session.placements.at(here.id, "character").flatMap((other) => {
1734
2102
  const character = other.entityId === player.id ? void 0 : session.characters.get(other.entityId);
1735
2103
  return character === void 0 ? [] : [{
1736
- key: keyOf$2(character),
2104
+ key: keyOf$3(character),
1737
2105
  name: character.name,
1738
2106
  publicState: session.characterStates.get(character.id)?.publicState ?? ""
1739
2107
  }];
@@ -1741,7 +2109,7 @@ function playerViewOf(session, options) {
1741
2109
  };
1742
2110
  view.variables.push(...shown(here.name, shownVariables(session, "location", here.id, locationKey(here), "others")));
1743
2111
  for (const other of view.place.here) {
1744
- const character = session.characters.list().find((candidate) => keyOf$2(candidate) === other.key);
2112
+ const character = session.characters.list().find((candidate) => keyOf$3(candidate) === other.key);
1745
2113
  if (character !== void 0) view.variables.push(...shown(character.name, shownVariables(session, "character", character.id, other.key, "others")));
1746
2114
  }
1747
2115
  for (const entry of session.items.contents({
@@ -1847,13 +2215,13 @@ async function previewViewOf(world, wall) {
1847
2215
  }
1848
2216
  }
1849
2217
  // src/host/interface/storage.ts
1850
- const keyOf$1 = (pack) => `roleplay.interface.${pack}`;
2218
+ const keyOf$2 = (pack) => `roleplay.interface.${pack}`;
1851
2219
  function checkedKey(key) {
1852
2220
  if (key === "" || key.length > 100) throw new RangeError("a key is 1 to 100 characters");
1853
2221
  return key;
1854
2222
  }
1855
2223
  function read(session, pack) {
1856
- const stored = session.metadata.getValue(keyOf$1(pack));
2224
+ const stored = session.metadata.getValue(keyOf$2(pack));
1857
2225
  return typeof stored === "object" && stored !== null && !Array.isArray(stored) ? stored : {};
1858
2226
  }
1859
2227
  /** What a pack keeps in a session: small JSON values by name. */
@@ -1880,12 +2248,12 @@ var PackStorage = class {
1880
2248
  throw new RangeError("a stored value must be JSON");
1881
2249
  }
1882
2250
  if (Buffer.byteLength(json) > PACK_LIMITS.storageBytes) throw new RangeError(`a pack keeps at most ${PACK_LIMITS.storageBytes / 1024} KB in a story`);
1883
- this.session.metadata.setValue(keyOf$1(this.pack), next);
2251
+ this.session.metadata.setValue(keyOf$2(this.pack), next);
1884
2252
  }
1885
2253
  remove(key) {
1886
2254
  checkedKey(key);
1887
2255
  const { [key]: _removed, ...rest } = read(this.session, this.pack);
1888
- this.session.metadata.setValue(keyOf$1(this.pack), rest);
2256
+ this.session.metadata.setValue(keyOf$2(this.pack), rest);
1889
2257
  }
1890
2258
  };
1891
2259
  // src/host/interface/service.ts
@@ -2425,7 +2793,7 @@ function languageField(value) {
2425
2793
  }
2426
2794
  // src/host/http/routes/worlds.ts
2427
2795
  /** The routes of the API for worlds. */
2428
- function worldsRoutes({ worlds, createWorld, starter, authorWorld, translation, worldCharacters, avatars }) {
2796
+ function worldsRoutes({ worlds, createWorld, starter, authorWorld, translation, worldCharacters, avatars, playtest }) {
2429
2797
  return {
2430
2798
  "/worlds": {
2431
2799
  GET: async (_req, res) => {
@@ -2505,6 +2873,37 @@ function worldsRoutes({ worlds, createWorld, starter, authorWorld, translation,
2505
2873
  throw error;
2506
2874
  }
2507
2875
  } },
2876
+ "/worlds/playtest": {
2877
+ GET: (_req, res, url) => {
2878
+ sendJson(res, 200, playtest.status(url.searchParams.get("id") ?? "") ?? { state: "idle" });
2879
+ return Promise.resolve();
2880
+ },
2881
+ POST: async (req, res, url) => {
2882
+ const body = await readJsonBody(req);
2883
+ if (typeof body.turns !== "number") return sendError(res, 400, "turns must be a number");
2884
+ if (body.playerCharacterId !== void 0 && typeof body.playerCharacterId !== "string") return sendError(res, 400, "playerCharacterId must be text");
2885
+ if (body.opening !== void 0 && typeof body.opening !== "number") return sendError(res, 400, "opening must be a number");
2886
+ try {
2887
+ sendJson(res, 202, playtest.start({
2888
+ worldId: url.searchParams.get("id") ?? "",
2889
+ turns: body.turns,
2890
+ ...body.playerCharacterId === void 0 ? {} : { playerCharacterId: body.playerCharacterId },
2891
+ ...body.opening === void 0 ? {} : { opening: body.opening },
2892
+ ...languageField(body.language) === void 0 ? {} : { language: languageField(body.language) }
2893
+ }));
2894
+ } catch (error) {
2895
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2896
+ message: error.message,
2897
+ problems: error.problems
2898
+ });
2899
+ throw error;
2900
+ }
2901
+ },
2902
+ DELETE: async (_req, res, url) => {
2903
+ await playtest.stop(url.searchParams.get("id") ?? "");
2904
+ sendJson(res, 200, playtest.status(url.searchParams.get("id") ?? "") ?? { state: "idle" });
2905
+ }
2906
+ },
2508
2907
  "/avatars": {
2509
2908
  POST: async (req, res) => {
2510
2909
  const body = await readJsonBody(req);
@@ -3690,6 +4089,581 @@ function worldFilesRoutes({ worldFiles, worldEditor, sessions }) {
3690
4089
  ]))
3691
4090
  };
3692
4091
  }
4092
+ // src/host/catalogue/zip.ts
4093
+ const END_SIGNATURE$1 = 101010256;
4094
+ const CENTRAL_SIGNATURE$1 = 33639248;
4095
+ const LOCAL_SIGNATURE$1 = 67324752;
4096
+ const MAX_FILES = 5e3;
4097
+ const SYMBOLIC_LINK = 40960;
4098
+ const TYPE_MASK = 61440;
4099
+ const invalid = (message) => new CatalogueError(message, "invalid");
4100
+ /** An archive path that stays inside the folder it is unpacked to, or the reason it does not. */
4101
+ function archivePathProblem(name) {
4102
+ if (name.includes("\\") || name.includes("\0")) return "has a backslash or a NUL character";
4103
+ if (name.startsWith("/") || /^[A-Za-z]:/.test(name)) return "is absolute";
4104
+ const parts = name.split("/");
4105
+ if (parts.some((part) => part === "..")) return "climbs out of the folder";
4106
+ if (parts.some((part, index) => part === "." || part === "" && index !== parts.length - 1)) return "is ambiguous";
4107
+ }
4108
+ /**
4109
+ * Reads the files of a ZIP archive, refusing anything that could write outside the target or exhaust the machine: unsafe or repeated paths
4110
+ * (also by case), links, encryption, ZIP64, methods other than stored and deflate, too many files, and a total size past the limit
4111
+ * (checked from the sizes the archive declares and again from what inflating really produced).
4112
+ * @throws {CatalogueError} (`invalid`) when the archive is not acceptable.
4113
+ */
4114
+ function readZip(archive, limits) {
4115
+ let end = -1;
4116
+ for (let at = archive.length - 22; at >= Math.max(0, archive.length - 22 - 65535); at -= 1) if (archive.readUInt32LE(at) === END_SIGNATURE$1) {
4117
+ end = at;
4118
+ break;
4119
+ }
4120
+ if (end < 0) throw invalid("the file is not a ZIP archive");
4121
+ const count = archive.readUInt16LE(end + 10);
4122
+ const directorySize = archive.readUInt32LE(end + 12);
4123
+ let at = archive.readUInt32LE(end + 16);
4124
+ if (count === 65535 || directorySize === 4294967295 || at === 4294967295) throw invalid("ZIP64 archives are not supported");
4125
+ if (count > MAX_FILES) throw invalid(`the archive holds more than ${MAX_FILES} files`);
4126
+ const files = /* @__PURE__ */ new Map();
4127
+ const folded = /* @__PURE__ */ new Set();
4128
+ let declared = 0;
4129
+ let produced = 0;
4130
+ for (let index = 0; index < count; index += 1) {
4131
+ if (at + 46 > archive.length || archive.readUInt32LE(at) !== CENTRAL_SIGNATURE$1) throw invalid("the archive directory is damaged");
4132
+ const flags = archive.readUInt16LE(at + 8);
4133
+ const method = archive.readUInt16LE(at + 10);
4134
+ const compressed = archive.readUInt32LE(at + 20);
4135
+ const size = archive.readUInt32LE(at + 24);
4136
+ const nameLength = archive.readUInt16LE(at + 28);
4137
+ const extraLength = archive.readUInt16LE(at + 30);
4138
+ const commentLength = archive.readUInt16LE(at + 32);
4139
+ const attributes = archive.readUInt32LE(at + 38);
4140
+ const local = archive.readUInt32LE(at + 42);
4141
+ if (at + 46 + nameLength > archive.length) throw invalid("the archive directory is damaged");
4142
+ const name = archive.toString("utf8", at + 46, at + 46 + nameLength);
4143
+ at += 46 + nameLength + extraLength + commentLength;
4144
+ const problem = archivePathProblem(name);
4145
+ if (problem !== void 0) throw invalid(`the archive path "${name}" ${problem}`);
4146
+ if (name.endsWith("/")) continue;
4147
+ if ((attributes >>> 16 & TYPE_MASK) === SYMBOLIC_LINK) throw invalid(`the archive holds a link: ${name}`);
4148
+ if ((flags & 1) !== 0) throw invalid("encrypted archives are not supported");
4149
+ if (method !== 0 && method !== 8) throw invalid(`the archive entry ${name} uses an unsupported compression method`);
4150
+ if (compressed === 4294967295 || size === 4294967295) throw invalid("ZIP64 archives are not supported");
4151
+ const key = name.toLowerCase();
4152
+ if (files.has(name) || folded.has(key)) throw invalid(`the archive repeats a path (or differs only by case): ${name}`);
4153
+ declared += size;
4154
+ if (declared > limits.maxBytes) throw invalid(`the archive unpacks to more than ${limits.maxBytes} bytes`);
4155
+ if (local + 30 > archive.length || archive.readUInt32LE(local) !== LOCAL_SIGNATURE$1) throw invalid(`the archive entry ${name} is damaged`);
4156
+ const start = local + 30 + archive.readUInt16LE(local + 26) + archive.readUInt16LE(local + 28);
4157
+ if (start + compressed > archive.length) throw invalid(`the archive entry ${name} is cut short`);
4158
+ const raw = archive.subarray(start, start + compressed);
4159
+ let content;
4160
+ try {
4161
+ content = method === 0 ? Buffer.from(raw) : inflateRawSync(raw, { maxOutputLength: Math.max(size, 1) });
4162
+ } catch {
4163
+ throw invalid(`the archive entry ${name} cannot be unpacked`);
4164
+ }
4165
+ if (content.length !== size) throw invalid(`the archive entry ${name} does not match its declared size`);
4166
+ produced += content.length;
4167
+ if (produced > limits.maxBytes) throw invalid(`the archive unpacks to more than ${limits.maxBytes} bytes`);
4168
+ files.set(name, content);
4169
+ folded.add(key);
4170
+ }
4171
+ return files;
4172
+ }
4173
+ // src/host/catalogue/zip-write.ts
4174
+ const LOCAL_SIGNATURE = 67324752;
4175
+ const CENTRAL_SIGNATURE = 33639248;
4176
+ const END_SIGNATURE = 101010256;
4177
+ const UTF8_NAMES = 2048;
4178
+ const VERSION = 20;
4179
+ /** Midnight, 1 January 1980: the earliest time a ZIP entry can carry, so an archive of the same files is the same bytes. */
4180
+ const DOS_DATE = 33;
4181
+ /**
4182
+ * A ZIP archive of the given files, deflated, with names in UTF-8 and a fixed time. It is built in memory, so it suits what a person keeps (a story), not a
4183
+ * folder of unbounded size.
4184
+ * @throws {RangeError} when a file or the archive passes what a ZIP without ZIP64 can hold.
4185
+ */
4186
+ function writeZip(files) {
4187
+ const parts = [];
4188
+ const directory = [];
4189
+ let offset = 0;
4190
+ if (files.size >= 65535) throw new RangeError("too many files for a ZIP archive");
4191
+ for (const [name, content] of files) {
4192
+ const encoded = Buffer.from(name, "utf8");
4193
+ const packed = deflateRawSync(content);
4194
+ const useDeflate = packed.length < content.length;
4195
+ const data = useDeflate ? packed : content;
4196
+ if (content.length >= 4294967295 || offset >= 4294967295) throw new RangeError("the archive is too large");
4197
+ const checksum = crc32(content);
4198
+ const local = Buffer.alloc(30);
4199
+ local.writeUInt32LE(LOCAL_SIGNATURE, 0);
4200
+ local.writeUInt16LE(VERSION, 4);
4201
+ local.writeUInt16LE(UTF8_NAMES, 6);
4202
+ local.writeUInt16LE(useDeflate ? 8 : 0, 8);
4203
+ local.writeUInt16LE(0, 10);
4204
+ local.writeUInt16LE(DOS_DATE, 12);
4205
+ local.writeUInt32LE(checksum, 14);
4206
+ local.writeUInt32LE(data.length, 18);
4207
+ local.writeUInt32LE(content.length, 22);
4208
+ local.writeUInt16LE(encoded.length, 26);
4209
+ parts.push(local, encoded, data);
4210
+ const central = Buffer.alloc(46);
4211
+ central.writeUInt32LE(CENTRAL_SIGNATURE, 0);
4212
+ central.writeUInt16LE(VERSION, 4);
4213
+ central.writeUInt16LE(VERSION, 6);
4214
+ central.writeUInt16LE(UTF8_NAMES, 8);
4215
+ central.writeUInt16LE(useDeflate ? 8 : 0, 10);
4216
+ central.writeUInt16LE(0, 12);
4217
+ central.writeUInt16LE(DOS_DATE, 14);
4218
+ central.writeUInt32LE(checksum, 16);
4219
+ central.writeUInt32LE(data.length, 20);
4220
+ central.writeUInt32LE(content.length, 24);
4221
+ central.writeUInt16LE(encoded.length, 28);
4222
+ central.writeUInt32LE(offset, 42);
4223
+ directory.push(central, encoded);
4224
+ offset += local.length + encoded.length + data.length;
4225
+ }
4226
+ const size = directory.reduce((sum, part) => sum + part.length, 0);
4227
+ const end = Buffer.alloc(22);
4228
+ end.writeUInt32LE(END_SIGNATURE, 0);
4229
+ end.writeUInt16LE(files.size, 8);
4230
+ end.writeUInt16LE(files.size, 10);
4231
+ end.writeUInt32LE(size, 12);
4232
+ end.writeUInt32LE(offset, 16);
4233
+ return Buffer.concat([
4234
+ ...parts,
4235
+ ...directory,
4236
+ end
4237
+ ]);
4238
+ }
4239
+ // src/host/sessions/session-archive.ts
4240
+ const ARCHIVE_FORMAT = "dsh-agentic-roleplay/session-archive";
4241
+ const MANIFEST = "manifest.json";
4242
+ const SESSION_PREFIX = "session/";
4243
+ const WORLD_PREFIX = "world/";
4244
+ const TEMPORARY_SNAPSHOT = "archive-export";
4245
+ /** What an archive does not carry: the database is taken fresh, and the rest is working state of this device or of an earlier archive. */
4246
+ const LEFT_OUT = /* @__PURE__ */ new Set([
4247
+ SESSION_DATABASE_FILE,
4248
+ "status.json",
4249
+ ".trash",
4250
+ ".sync"
4251
+ ]);
4252
+ const LEFT_OUT_SUFFIX = [
4253
+ ".writing",
4254
+ ".restoring",
4255
+ "-journal",
4256
+ "-wal",
4257
+ "-shm"
4258
+ ];
4259
+ var InvalidArchiveError = class extends Error {};
4260
+ /** Every file of a folder as `prefix` + its path, except those left out and links. */
4261
+ function collect(directory, prefix, files, skip = () => false) {
4262
+ const walk = (at) => {
4263
+ for (const entry of readdirSync(at, { withFileTypes: true })) {
4264
+ const path = join(at, entry.name);
4265
+ const inside = relative(directory, path).split("\\").join("/");
4266
+ if (skip(inside) || entry.isSymbolicLink()) continue;
4267
+ if (entry.isDirectory()) walk(path);
4268
+ else if (entry.isFile() && lstatSync(path).isFile()) files.set(`${prefix}${inside}`, readFileSync(path));
4269
+ }
4270
+ };
4271
+ walk(directory);
4272
+ }
4273
+ /**
4274
+ * A session as one ZIP: the story's database as it is now, every other file of its folder (the timeline with every turn that was played, the settings,
4275
+ * the pictures, the kept states and the prompts it was given) and a copy of the world it was started from, so it can be put back on another machine.
4276
+ * @throws {SessionNotFoundError} when the id names no session. @throws {RangeError} when the archive is too large for a ZIP.
4277
+ */
4278
+ function exportSession(deps, id) {
4279
+ const directory = deps.sessionsDir();
4280
+ if (!isSessionId(id) || !existsSync(sessionDatabase(directory, id))) throw new SessionNotFoundError(`no session "${id}"`);
4281
+ const folder = sessionFolder(directory, id);
4282
+ const metadata = deps.state.openSession(directory, id).metadata.get();
4283
+ const files = /* @__PURE__ */ new Map();
4284
+ deps.state.snapshot(directory, id, TEMPORARY_SNAPSHOT);
4285
+ const copy = join(folder, "snapshots", `${TEMPORARY_SNAPSHOT}.sqlite`);
4286
+ try {
4287
+ files.set(`${SESSION_PREFIX}${SESSION_DATABASE_FILE}`, readFileSync(copy));
4288
+ } finally {
4289
+ deps.state.removeSnapshot(directory, id, TEMPORARY_SNAPSHOT);
4290
+ }
4291
+ collect(folder, SESSION_PREFIX, files, (path) => LEFT_OUT.has(path.split("/")[0]) || LEFT_OUT_SUFFIX.some((suffix) => path.endsWith(suffix)));
4292
+ const source = metadata.world.source;
4293
+ const worldFolder = source !== void 0 && source.startsWith("worlds/") ? join(deps.worldsDir(), source.slice(7)) : void 0;
4294
+ const worldHere = worldFolder !== void 0 && existsSync(join(worldFolder, "world.json"));
4295
+ if (worldHere) collect(worldFolder, WORLD_PREFIX, files, (path) => path.split("/")[0] === ".trash");
4296
+ const manifest = {
4297
+ format: ARCHIVE_FORMAT,
4298
+ version: 1,
4299
+ exportedAt: (deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString(),
4300
+ session: {
4301
+ id,
4302
+ name: metadata.name,
4303
+ turns: metadata.turns
4304
+ },
4305
+ world: {
4306
+ id: metadata.world.id,
4307
+ name: metadata.world.name,
4308
+ included: worldHere
4309
+ }
4310
+ };
4311
+ files.set(MANIFEST, Buffer.from(JSON.stringify(manifest, null, 2)));
4312
+ return {
4313
+ file: `${folderName(metadata.name) || "story"}.dsh-story.zip`,
4314
+ bytes: writeZip(files)
4315
+ };
4316
+ }
4317
+ function manifestOf(files) {
4318
+ const raw = files.get(MANIFEST);
4319
+ if (raw === void 0) throw new InvalidArchiveError("this is not a story archive: it has no manifest.json");
4320
+ let value;
4321
+ try {
4322
+ value = JSON.parse(raw.toString("utf8"));
4323
+ } catch {
4324
+ throw new InvalidArchiveError("the manifest of this archive is not valid JSON");
4325
+ }
4326
+ if (value.format !== "dsh-agentic-roleplay/session-archive") throw new InvalidArchiveError("this is not a story archive of this program");
4327
+ if (value.version !== 1) throw new InvalidArchiveError(`this archive is version ${String(value.version)}; this program reads version 1`);
4328
+ if (typeof value.session?.name !== "string" || value.session.name.trim() === "" || typeof value.world?.id !== "string" || value.world.id.trim() === "" || typeof value.world.name !== "string" || typeof value.world.included !== "boolean") throw new InvalidArchiveError("the manifest of this archive is incomplete");
4329
+ return value;
4330
+ }
4331
+ function write(root, files, prefix) {
4332
+ for (const [name, content] of files) {
4333
+ if (!name.startsWith(prefix)) continue;
4334
+ const target = join(root, name.slice(prefix.length));
4335
+ mkdirSync(dirname(target), { recursive: true });
4336
+ writeFileSync(target, content);
4337
+ }
4338
+ }
4339
+ /**
4340
+ * Puts an archived story back as a new session with an identity of its own (the original may still exist), named like it with " (restored)". The world it
4341
+ * carries is added to the worlds when the person has none with that id. The chat is made when the session is first opened.
4342
+ * @throws {InvalidArchiveError} when the file is not an archive this program can read. Nothing is left behind when it fails.
4343
+ */
4344
+ async function importSession(deps, bytes) {
4345
+ let files;
4346
+ try {
4347
+ files = readZip(bytes, { maxBytes: deps.maxBytes() });
4348
+ } catch (error) {
4349
+ throw new InvalidArchiveError(error instanceof Error ? error.message : String(error));
4350
+ }
4351
+ const manifest = manifestOf(files);
4352
+ if (!files.has(`${SESSION_PREFIX}${SESSION_DATABASE_FILE}`)) throw new InvalidArchiveError("the archive holds no story database");
4353
+ const id = randomUUID();
4354
+ const directory = deps.sessionsDir();
4355
+ const folder = sessionFolder(directory, id);
4356
+ const name = `${manifest.session.name} (restored)`.slice(0, 200);
4357
+ const added = [];
4358
+ try {
4359
+ mkdirSync(folder, { recursive: true });
4360
+ write(folder, files, SESSION_PREFIX);
4361
+ const existingWorld = await deps.worldDirectory(manifest.world.id);
4362
+ let worldDirectory = existingWorld;
4363
+ if (manifest.world.included && existingWorld === void 0 && [...files.keys()].some((key) => key.startsWith(WORLD_PREFIX))) {
4364
+ worldDirectory = freeFolder$1(deps.worldsDir(), folderName(manifest.world.name) || "world");
4365
+ added.push(worldDirectory);
4366
+ write(worldDirectory, files, WORLD_PREFIX);
4367
+ }
4368
+ const store = openSessionStore(sessionDatabase(directory, id));
4369
+ try {
4370
+ const was = store.metadata.get();
4371
+ store.metadata.rebrand(id, name, was.createdAt);
4372
+ store.metadata.setWorld({
4373
+ ...was.world,
4374
+ ...worldDirectory === void 0 ? {} : { source: `worlds/${basename(worldDirectory)}` }
4375
+ });
4376
+ } finally {
4377
+ store.close();
4378
+ }
4379
+ } catch (error) {
4380
+ rmSync(folder, {
4381
+ recursive: true,
4382
+ force: true
4383
+ });
4384
+ for (const target of added) rmSync(target, {
4385
+ recursive: true,
4386
+ force: true
4387
+ });
4388
+ throw error;
4389
+ }
4390
+ return {
4391
+ id,
4392
+ name,
4393
+ worldAdded: added.length > 0
4394
+ };
4395
+ }
4396
+ /** A name that is safe as a file or folder name on any system: letters, digits and marks of any script, with single hyphens between the rest. */
4397
+ const folderName = (name) => name.normalize("NFKC").replace(/[^\p{L}\p{N}\p{M}]+/gu, "-").replace(/^-+|-+$/gu, "").slice(0, 60);
4398
+ /** A folder name under `parent` that is free: the name itself, or with -2, -3... */
4399
+ function freeFolder$1(parent, name) {
4400
+ for (let attempt = 1;; attempt += 1) {
4401
+ const candidate = join(parent, attempt === 1 ? name : `${name}-${attempt}`);
4402
+ if (!existsSync(candidate)) return candidate;
4403
+ }
4404
+ }
4405
+ // src/shared/journal.ts
4406
+ /** The most a journal may hold. */
4407
+ const MAX_JOURNAL = 2e4;
4408
+ // src/host/reference/journal.ts
4409
+ const JOURNAL_FILE = "journal.json";
4410
+ var InvalidJournalError = class extends Error {};
4411
+ function folderOf$2(sessionsDir, id) {
4412
+ if (!isSessionId(id) || !existsSync(sessionDatabase(sessionsDir, id))) throw new SessionNotFoundError(`no session "${id}"`);
4413
+ return sessionFolder(sessionsDir, id);
4414
+ }
4415
+ /**
4416
+ * The player's notes. They sit beside the database, so taking the story back does not touch them and a branch starts with a copy.
4417
+ * @throws {SessionNotFoundError} when the id names no session.
4418
+ */
4419
+ async function readJournal(sessionsDir, id) {
4420
+ const file = join(folderOf$2(sessionsDir, id), JOURNAL_FILE);
4421
+ let value;
4422
+ try {
4423
+ value = JSON.parse(await readFile(file, "utf8"));
4424
+ } catch (error) {
4425
+ if (error.code === "ENOENT") return { text: "" };
4426
+ throw error;
4427
+ }
4428
+ const { text, updatedAt } = value ?? {};
4429
+ return {
4430
+ text: typeof text === "string" ? text : "",
4431
+ ...typeof updatedAt === "string" ? { updatedAt } : {}
4432
+ };
4433
+ }
4434
+ /** @throws {InvalidJournalError} for text that is not a string or is over `MAX_JOURNAL`. */
4435
+ async function writeJournal(sessionsDir, id, body, now = () => /* @__PURE__ */ new Date()) {
4436
+ const folder = folderOf$2(sessionsDir, id);
4437
+ const text = body?.text;
4438
+ if (typeof text !== "string") throw new InvalidJournalError("the journal needs a text");
4439
+ if (text.length > 2e4) throw new InvalidJournalError(`the journal may hold at most ${MAX_JOURNAL} characters`);
4440
+ const journal = {
4441
+ text,
4442
+ updatedAt: now().toISOString()
4443
+ };
4444
+ await atomicWriteJson(join(folder, JOURNAL_FILE), journal);
4445
+ return journal;
4446
+ }
4447
+ // src/shared/reference.ts
4448
+ /** The pages of the reference: what the player may look up about the story, never what only the story knows. */
4449
+ const REFERENCE_SECTIONS = [
4450
+ "profile",
4451
+ "people",
4452
+ "places",
4453
+ "things"
4454
+ ];
4455
+ const isReferenceSection = (value) => REFERENCE_SECTIONS.includes(value);
4456
+ // src/host/reference/profile.ts
4457
+ const keyOf$1 = (character) => character.sourceId ?? String(character.id);
4458
+ const BLOCKS = [
4459
+ {
4460
+ audiences: ["self", "observer"],
4461
+ build: (session, character, audience) => {
4462
+ const state = session.characterStates.get(character.id);
4463
+ return {
4464
+ aliases: character.aliases,
4465
+ ...character.age === void 0 || character.age === null ? {} : { age: character.age },
4466
+ ...character.gender === void 0 || character.gender === null ? {} : { gender: character.gender },
4467
+ ...character.pronouns === void 0 || character.pronouns === null ? {} : { pronouns: character.pronouns },
4468
+ appearance: character.appearance,
4469
+ publicState: state?.publicState ?? "",
4470
+ values: shownVariables(session, "character", character.id, keyOf$1(character), audience === "self" ? "self" : "others").map(({ variable, value }) => ({
4471
+ name: variable.name,
4472
+ value: describeValue(variable, value)
4473
+ }))
4474
+ };
4475
+ }
4476
+ },
4477
+ {
4478
+ audiences: ["self"],
4479
+ build: (session, character) => {
4480
+ const state = session.characterStates.get(character.id);
4481
+ const groups = session.factionMemberships.ofCharacter(character.id, "active").flatMap((membership) => {
4482
+ const faction = session.factions.get(membership.factionId);
4483
+ return faction === void 0 ? [] : [{
4484
+ name: faction.name,
4485
+ role: membership.role
4486
+ }];
4487
+ });
4488
+ return {
4489
+ summary: character.summary,
4490
+ personality: character.personality,
4491
+ background: character.background,
4492
+ speech: character.speech,
4493
+ innerState: state?.innerState ?? "",
4494
+ activity: state?.activity ?? "",
4495
+ groups,
4496
+ goals: session.intents.list(character.id, { status: "active" }).map((intent) => ({
4497
+ name: intent.name,
4498
+ description: intent.description,
4499
+ status: intent.status,
4500
+ plan: intent.plan,
4501
+ ...intent.deadline === void 0 ? {} : { deadline: intent.deadline }
4502
+ }))
4503
+ };
4504
+ }
4505
+ },
4506
+ {
4507
+ audiences: ["self"],
4508
+ build: (session, character) => {
4509
+ const recollections = session.events.perceivedBy(character.id).sort((a, b) => b.event.turn - a.event.turn || b.event.round - a.event.round);
4510
+ const beliefs = session.memories.list(character.id).sort((a, b) => b.turn - a.turn);
4511
+ return {
4512
+ recollections: recollections.slice(0, 100).map(({ perception, event }) => ({
4513
+ text: perception.content,
4514
+ gist: perception.gist,
4515
+ mode: perception.mode,
4516
+ turn: event.turn
4517
+ })),
4518
+ beliefs: beliefs.slice(0, 100).map((memory) => ({
4519
+ text: memory.text,
4520
+ kind: memory.kind,
4521
+ confidence: memory.confidence,
4522
+ turn: memory.turn
4523
+ })),
4524
+ totals: {
4525
+ recollections: recollections.length,
4526
+ beliefs: beliefs.length
4527
+ }
4528
+ };
4529
+ }
4530
+ }
4531
+ ];
4532
+ /** A character as the audience may see them: only the blocks that audience is allowed. */
4533
+ function profileOf(session, character, audience) {
4534
+ const profile = {
4535
+ key: keyOf$1(character),
4536
+ name: character.name,
4537
+ audience,
4538
+ aliases: [],
4539
+ appearance: "",
4540
+ publicState: "",
4541
+ values: []
4542
+ };
4543
+ for (const block of BLOCKS) if (block.audiences.includes(audience)) Object.assign(profile, block.build(session, character, audience));
4544
+ return profile;
4545
+ }
4546
+ // src/host/reference/reference.ts
4547
+ var UnknownSectionError = class extends Error {};
4548
+ /** Where the player's character is and what it has met or learned of: the only ground a page may read from. */
4549
+ function standpoint(session) {
4550
+ const player = session.characters.list().find((character) => character.control === "player");
4551
+ if (player === void 0) return void 0;
4552
+ const placement = session.placements.get("character", player.id);
4553
+ return {
4554
+ player,
4555
+ here: placement === void 0 ? void 0 : session.locations.get(placement.locationId)
4556
+ };
4557
+ }
4558
+ /**
4559
+ * The player's character in full, or another character the player has met or is with, as an observer sees them.
4560
+ * Anyone the player's character has not met is not shown.
4561
+ */
4562
+ function profile(session, options) {
4563
+ const stand = standpoint(session);
4564
+ if (stand === void 0) return [];
4565
+ if (options.character === void 0 || options.character === keyOf$1(stand.player)) return [profileOf(session, stand.player, "self")];
4566
+ const other = people(session).some((person) => person.key === options.character) ? session.characters.list().find((character) => keyOf$1(character) === options.character) : void 0;
4567
+ return other === void 0 ? [] : [profileOf(session, other, "observer")];
4568
+ }
4569
+ function people(session) {
4570
+ const stand = standpoint(session);
4571
+ if (stand === void 0) return [];
4572
+ const present = new Set(stand.here === void 0 ? [] : session.placements.at(stand.here.id, "character").map((entry) => entry.entityId));
4573
+ const met = new Map(session.relationships.from(stand.player.id).map((relation) => [relation.toId, relation]));
4574
+ return session.characters.list().flatMap((character) => {
4575
+ if (character.id === stand.player.id || !present.has(character.id) && !met.has(character.id)) return [];
4576
+ const relation = met.get(character.id);
4577
+ return [{
4578
+ key: keyOf$1(character),
4579
+ name: character.name,
4580
+ publicState: session.characterStates.get(character.id)?.publicState ?? "",
4581
+ here: present.has(character.id),
4582
+ ...relation === void 0 ? {} : {
4583
+ label: relation.label,
4584
+ summary: relation.summary
4585
+ }
4586
+ }];
4587
+ }).sort((a, b) => Number(b.here) - Number(a.here) || a.name.localeCompare(b.name));
4588
+ }
4589
+ function places(session) {
4590
+ const stand = standpoint(session);
4591
+ if (stand === void 0) return [];
4592
+ const known = new Set(session.knowledge.list(stand.player.id, "location").map((entry) => entry.subjectId));
4593
+ if (stand.here !== void 0) known.add(stand.here.id);
4594
+ const knownExits = new Set(session.knowledge.list(stand.player.id, "exit").map((entry) => entry.subjectId));
4595
+ const exits = session.locations.allExits();
4596
+ const placeOf = (id) => known.has(id) ? session.locations.get(id) : void 0;
4597
+ const nameOf = (id) => placeOf(id)?.name;
4598
+ return [...known].flatMap((id) => {
4599
+ const place = session.locations.get(id);
4600
+ if (place === void 0) return [];
4601
+ const here = place.id === stand.here?.id;
4602
+ const parent = place.parentId === void 0 ? void 0 : nameOf(place.parentId);
4603
+ return [{
4604
+ key: locationKey(place),
4605
+ name: place.name,
4606
+ here,
4607
+ ...parent === void 0 ? {} : { parent },
4608
+ ...here ? { description: place.description } : {},
4609
+ features: here ? place.features.map((feature) => feature.name) : [],
4610
+ ways: exits.filter((exit) => exit.fromId === place.id && (here || knownExits.has(exit.id))).flatMap((exit) => {
4611
+ const to = placeOf(exit.toId);
4612
+ return to === void 0 ? [] : [{
4613
+ to: to.name,
4614
+ toKey: locationKey(to),
4615
+ open: exit.state === "open"
4616
+ }];
4617
+ })
4618
+ }];
4619
+ }).sort((a, b) => Number(b.here) - Number(a.here) || a.name.localeCompare(b.name));
4620
+ }
4621
+ function things(session) {
4622
+ const stand = standpoint(session);
4623
+ if (stand === void 0) return [];
4624
+ const carried = session.items.contents({
4625
+ kind: "character",
4626
+ id: stand.player.id
4627
+ }).filter((entry) => !entry.item.hidden).map((entry) => {
4628
+ const holder = entry.holding.holder;
4629
+ return {
4630
+ name: entry.item.name,
4631
+ quantity: entry.item.quantity,
4632
+ where: holder.kind === "character" && holder.mode === "worn" ? "worn" : "carried"
4633
+ };
4634
+ });
4635
+ const around = stand.here === void 0 ? [] : session.items.contents({
4636
+ kind: "location",
4637
+ id: stand.here.id
4638
+ }).filter((entry) => !entry.item.hidden).map((entry) => ({
4639
+ name: entry.item.name,
4640
+ quantity: entry.item.quantity,
4641
+ where: "here"
4642
+ }));
4643
+ return [...carried, ...around];
4644
+ }
4645
+ /** One page per section; a new page is a new entry here and in `REFERENCE_SECTIONS`. */
4646
+ const PAGES = {
4647
+ profile,
4648
+ people,
4649
+ places,
4650
+ things
4651
+ };
4652
+ function referencePage(session, section, options = {}) {
4653
+ if (!isReferenceSection(section)) throw new UnknownSectionError(`no reference section "${section}"`);
4654
+ return {
4655
+ section,
4656
+ entries: PAGES[section](session, options)
4657
+ };
4658
+ }
4659
+ /** @throws {SessionNotFoundError} when the id names no session. */
4660
+ function referenceOfSession(deps, id, section, options = {}) {
4661
+ if (!isSessionId(id) || !existsSync(sessionDatabase(deps.sessionsDir(), id))) throw new SessionNotFoundError(`no session "${id}"`);
4662
+ return referencePage(deps.open(id), section, options);
4663
+ }
4664
+ // src/shared/recall-preview.ts
4665
+ /** The longest situation accepted. */
4666
+ const MAX_SITUATION = 4e3;
3693
4667
  // src/host/http/routes/sessions.ts
3694
4668
  /** The routes of the API for sessions. */
3695
4669
  function sessionsRoutes({ sessions, externalTools, redundantLayers }) {
@@ -3778,6 +4752,77 @@ function sessionsRoutes({ sessions, externalTools, redundantLayers }) {
3778
4752
  throw error;
3779
4753
  }
3780
4754
  } },
4755
+ "/sessions/timeline/checkpoint": { POST: async (req, res, url) => {
4756
+ const { label, note } = await readJsonBody(req);
4757
+ if (typeof label !== "string") return sendError(res, 400, "\"label\" is required (empty takes the name off)");
4758
+ if (note !== void 0 && typeof note !== "string") return sendError(res, 400, "\"note\" must be text");
4759
+ try {
4760
+ await sessions.markCheckpoint(url.searchParams.get("id") ?? "", url.searchParams.get("turn") ?? "", label, note);
4761
+ } catch (error) {
4762
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
4763
+ if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
4764
+ if (error instanceof TimelineError) return sendError(res, 409, error.message);
4765
+ throw error;
4766
+ }
4767
+ res.statusCode = 204;
4768
+ res.end();
4769
+ } },
4770
+ "/sessions/statistics": { GET: async (_req, res, url) => {
4771
+ try {
4772
+ sendJson(res, 200, sessions.statistics(url.searchParams.get("id") ?? ""));
4773
+ } catch (error) {
4774
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
4775
+ throw error;
4776
+ }
4777
+ } },
4778
+ "/sessions/compare": { GET: async (_req, res, url) => {
4779
+ try {
4780
+ sendJson(res, 200, sessions.compare(url.searchParams.get("id") ?? "", url.searchParams.get("a") ?? "head", url.searchParams.get("b") ?? "head"));
4781
+ } catch (error) {
4782
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
4783
+ if (error instanceof UnknownStateError) return sendError(res, 409, error.message);
4784
+ throw error;
4785
+ }
4786
+ } },
4787
+ "/sessions/export": { GET: async (_req, res, url) => {
4788
+ const id = url.searchParams.get("id") ?? "";
4789
+ const format = url.searchParams.get("format") ?? "markdown";
4790
+ if (format !== "markdown" && format !== "json" && format !== "archive") return sendError(res, 400, "\"format\" is markdown, json or archive");
4791
+ const scope = url.searchParams.get("scope") ?? "path";
4792
+ if (scope !== "path" && scope !== "all") return sendError(res, 400, "\"scope\" is path or all");
4793
+ try {
4794
+ const file = format === "archive" ? {
4795
+ ...sessions.exportArchive(id),
4796
+ mediaType: "application/zip"
4797
+ } : (() => {
4798
+ const out = sessions.transcript(id, format, scope, url.searchParams.get("annotated") === "1");
4799
+ return {
4800
+ file: out.file,
4801
+ mediaType: out.mediaType,
4802
+ bytes: Buffer.from(out.text, "utf8")
4803
+ };
4804
+ })();
4805
+ res.statusCode = 200;
4806
+ res.setHeader("content-type", file.mediaType);
4807
+ res.setHeader("content-length", file.bytes.length);
4808
+ res.setHeader("content-disposition", `attachment; filename*=UTF-8''${encodeURIComponent(file.file)}`);
4809
+ res.setHeader("x-content-type-options", "nosniff");
4810
+ res.end(file.bytes);
4811
+ } catch (error) {
4812
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
4813
+ if (error instanceof TimelineError) return sendError(res, 409, error.message);
4814
+ if (error instanceof RangeError) return sendError(res, 413, error.message);
4815
+ throw error;
4816
+ }
4817
+ } },
4818
+ "/sessions/import": { POST: async (req, res) => {
4819
+ try {
4820
+ sendJson(res, 200, await sessions.importArchive(await readBinaryBody(req, sessions.maxArchiveBytes)));
4821
+ } catch (error) {
4822
+ if (error instanceof InvalidArchiveError) return sendError(res, 422, error.message);
4823
+ throw error;
4824
+ }
4825
+ } },
3781
4826
  "/sessions/decisions": { GET: async (_req, res, url) => {
3782
4827
  try {
3783
4828
  sendJson(res, 200, sessions.decisions(url.searchParams.get("id") ?? ""));
@@ -3794,6 +4839,35 @@ function sessionsRoutes({ sessions, externalTools, redundantLayers }) {
3794
4839
  throw error;
3795
4840
  }
3796
4841
  } },
4842
+ "/sessions/reference": { GET: async (_req, res, url) => {
4843
+ try {
4844
+ sendJson(res, 200, sessions.reference(url.searchParams.get("id") ?? "", url.searchParams.get("section") ?? "", url.searchParams.get("character") ?? void 0));
4845
+ } catch (error) {
4846
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
4847
+ if (error instanceof UnknownSectionError) return sendError(res, 400, error.message);
4848
+ throw error;
4849
+ }
4850
+ } },
4851
+ "/sessions/journal": {
4852
+ GET: async (_req, res, url) => {
4853
+ try {
4854
+ sendJson(res, 200, await sessions.readJournal(url.searchParams.get("id") ?? ""));
4855
+ } catch (error) {
4856
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
4857
+ throw error;
4858
+ }
4859
+ },
4860
+ PUT: async (req, res, url) => {
4861
+ const body = await readJsonBody(req);
4862
+ try {
4863
+ sendJson(res, 200, await sessions.writeJournal(url.searchParams.get("id") ?? "", body));
4864
+ } catch (error) {
4865
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
4866
+ if (error instanceof InvalidJournalError) return sendError(res, 422, error.message);
4867
+ throw error;
4868
+ }
4869
+ }
4870
+ },
3797
4871
  "/sessions/images": {
3798
4872
  GET: async (_req, res, url) => {
3799
4873
  try {
@@ -3943,6 +5017,30 @@ function sessionsRoutes({ sessions, externalTools, redundantLayers }) {
3943
5017
  res.statusCode = 202;
3944
5018
  res.end();
3945
5019
  } },
5020
+ "/sessions/recall": { POST: async (req, res, url) => {
5021
+ const body = await readJsonBody(req);
5022
+ if (typeof body.situation !== "string" || body.situation.trim() === "") return sendError(res, 400, "a situation is needed");
5023
+ if (body.situation.length > 4e3) return sendError(res, 413, `the situation is longer than ${MAX_SITUATION} characters`);
5024
+ if (body.character !== void 0 && typeof body.character !== "string") return sendError(res, 400, "character must be a key");
5025
+ const abort = new AbortController();
5026
+ req.on("aborted", () => {
5027
+ abort.abort();
5028
+ });
5029
+ res.on("close", () => {
5030
+ if (!res.writableEnded) abort.abort();
5031
+ });
5032
+ try {
5033
+ sendJson(res, 200, await sessions.recallPreview(url.searchParams.get("id") ?? "", {
5034
+ situation: body.situation,
5035
+ ...body.character === void 0 ? {} : { character: body.character }
5036
+ }, abort.signal));
5037
+ } catch (error) {
5038
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
5039
+ if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
5040
+ if (error instanceof Error && /^no character /.test(error.message)) return sendError(res, 422, error.message);
5041
+ throw error;
5042
+ }
5043
+ } },
3946
5044
  "/sessions/vectors/reset": { POST: async (_req, res, url) => {
3947
5045
  try {
3948
5046
  sessions.resetVectors(url.searchParams.get("id") ?? "");
@@ -5760,6 +6858,97 @@ async function restoreSession(deps, id) {
5760
6858
  await deps.agent.restore(id);
5761
6859
  writeStatus(folder, {});
5762
6860
  }
6861
+ // src/shared/transcript.ts
6862
+ const segmentLine = (segment) => segment.type === "utterance" ? `**${segment.name}:** “${segment.text}”` : segment.text;
6863
+ function outputLines(output, annotated) {
6864
+ if (output === void 0) return ["*(nothing was delivered)*"];
6865
+ const lines = output.segments.map(segmentLine);
6866
+ if (!annotated) return lines;
6867
+ const ruling = output.ooc;
6868
+ if (ruling !== void 0) lines.push(`> ${ruling.question === true ? "Answered out of character" : ruling.legal ? "Ruled legal" : "Ruled illegal and refused"}: ${ruling.note}`);
6869
+ for (const roll of output.rolls ?? []) lines.push(`> Roll (${roll.by}): ${roll.text}`);
6870
+ return lines;
6871
+ }
6872
+ function turnBlock(node, options, extra) {
6873
+ return [
6874
+ ...options.annotated || options.scope === "all" ? [`### Turn ${node.turn}${node.label === void 0 ? "" : ` — checkpoint “${node.label}”`}${extra}`, ...node.note === void 0 ? [] : [`> Note: ${node.note}`]] : [],
6875
+ `*${node.player.trim()}*`,
6876
+ ...outputLines(node.output, options.annotated)
6877
+ ].join("\n\n");
6878
+ }
6879
+ /** The story as Markdown: the opening, then each turn as the player's words in italics followed by what was told. With every turn (`all`) each one has a heading, so the alternatives can be told apart. */
6880
+ function transcriptMarkdown(timeline, options) {
6881
+ const parts = [`# ${options.title}`];
6882
+ if (options.opening !== void 0) parts.push(options.opening.map(segmentLine).join("\n\n"));
6883
+ const onPath = new Set(pathTo(timeline, timeline.head).map((node) => node.id));
6884
+ if (options.scope === "path") {
6885
+ for (const node of pathTo(timeline, timeline.head)) parts.push(turnBlock(node, options, ""));
6886
+ return `${parts.join("\n\n")}\n`;
6887
+ }
6888
+ const walk = (parent) => {
6889
+ const siblings = childrenOf(timeline, parent).sort((a, b) => Number(onPath.has(b.id)) - Number(onPath.has(a.id)));
6890
+ siblings.forEach((node, index) => {
6891
+ const taken = onPath.has(node.id);
6892
+ const block = turnBlock(node, options, siblings.length > 1 ? ` — alternative ${index + 1} of ${siblings.length}${taken ? " (the story went this way)" : " (set aside)"}` : taken ? "" : " (set aside)");
6893
+ parts.push(block);
6894
+ walk(node.id);
6895
+ });
6896
+ };
6897
+ walk(null);
6898
+ return `${parts.join("\n\n")}\n`;
6899
+ }
6900
+ /** The same story as data: every turn with its parent, so a branch can be rebuilt by a reader. */
6901
+ function transcriptJson(timeline, options) {
6902
+ const keep = options.scope === "path" ? pathTo(timeline, timeline.head) : timeline.nodes;
6903
+ return {
6904
+ version: 1,
6905
+ title: options.title,
6906
+ ...options.opening === void 0 ? {} : { opening: options.opening },
6907
+ head: timeline.head,
6908
+ turns: keep.map((node) => ({
6909
+ id: node.id,
6910
+ parent: node.parent,
6911
+ turn: node.turn,
6912
+ createdAt: node.createdAt,
6913
+ player: node.player,
6914
+ ...node.output === void 0 ? {} : { output: options.annotated ? node.output : { segments: node.output.segments } },
6915
+ ...options.annotated && node.label !== void 0 ? { checkpoint: {
6916
+ label: node.label,
6917
+ ...node.note === void 0 ? {} : { note: node.note }
6918
+ } } : {}
6919
+ }))
6920
+ };
6921
+ }
6922
+ // src/host/sessions/transcript-session.ts
6923
+ /**
6924
+ * The played story as a file for the person: the turns on the way the story went, or every turn including those set aside; plain, or with headings,
6925
+ * rulings, rolls and checkpoints.
6926
+ * @throws {SessionNotFoundError} when the id names no session.
6927
+ */
6928
+ function transcriptOfSession(deps, id, format, options) {
6929
+ const directory = deps.sessionsDir();
6930
+ if (!isSessionId(id) || !existsSync(sessionDatabase(directory, id))) throw new SessionNotFoundError(`no session "${id}"`);
6931
+ const folder = sessionFolder(directory, id);
6932
+ const name = deps.state.openSession(directory, id).metadata.get().name;
6933
+ const opening = readOpening(folder);
6934
+ const all = {
6935
+ title: name,
6936
+ ...opening === void 0 ? {} : { opening },
6937
+ ...options
6938
+ };
6939
+ const timeline = readTimeline(folder);
6940
+ const base = folderName(name) || "story";
6941
+ if (format === "json") return {
6942
+ file: `${base}.json`,
6943
+ mediaType: "application/json; charset=utf-8",
6944
+ text: `${JSON.stringify(transcriptJson(timeline, all), null, 2)}\n`
6945
+ };
6946
+ return {
6947
+ file: `${base}.md`,
6948
+ mediaType: "text/markdown; charset=utf-8",
6949
+ text: transcriptMarkdown(timeline, all)
6950
+ };
6951
+ }
5763
6952
  // src/host/sessions/chat-settings.ts
5764
6953
  function folderOf(deps, id) {
5765
6954
  const directory = deps.sessionsDir();
@@ -5794,6 +6983,7 @@ function payloadOf(deps, id, settings) {
5794
6983
  pendingConsolidation: deps.pendingConsolidation(id),
5795
6984
  activity: deps.activity(id),
5796
6985
  usage: deps.usage(id),
6986
+ trace: deps.trace(id),
5797
6987
  interventions: deps.interventions(id),
5798
6988
  vectors: deps.vectors(id),
5799
6989
  reflection: deps.reflection(id),
@@ -6334,87 +7524,6 @@ var WorldCatalog = class extends Service {
6334
7524
  return run;
6335
7525
  }
6336
7526
  };
6337
- // src/host/catalogue/zip.ts
6338
- const END_SIGNATURE = 101010256;
6339
- const CENTRAL_SIGNATURE = 33639248;
6340
- const LOCAL_SIGNATURE = 67324752;
6341
- const MAX_FILES = 5e3;
6342
- const SYMBOLIC_LINK = 40960;
6343
- const TYPE_MASK = 61440;
6344
- const invalid = (message) => new CatalogueError(message, "invalid");
6345
- /** An archive path that stays inside the folder it is unpacked to, or the reason it does not. */
6346
- function archivePathProblem(name) {
6347
- if (name.includes("\\") || name.includes("\0")) return "has a backslash or a NUL character";
6348
- if (name.startsWith("/") || /^[A-Za-z]:/.test(name)) return "is absolute";
6349
- const parts = name.split("/");
6350
- if (parts.some((part) => part === "..")) return "climbs out of the folder";
6351
- if (parts.some((part, index) => part === "." || part === "" && index !== parts.length - 1)) return "is ambiguous";
6352
- }
6353
- /**
6354
- * Reads the files of a ZIP archive, refusing anything that could write outside the target or exhaust the machine: unsafe or repeated paths
6355
- * (also by case), links, encryption, ZIP64, methods other than stored and deflate, too many files, and a total size past the limit
6356
- * (checked from the sizes the archive declares and again from what inflating really produced).
6357
- * @throws {CatalogueError} (`invalid`) when the archive is not acceptable.
6358
- */
6359
- function readZip(archive, limits) {
6360
- let end = -1;
6361
- for (let at = archive.length - 22; at >= Math.max(0, archive.length - 22 - 65535); at -= 1) if (archive.readUInt32LE(at) === END_SIGNATURE) {
6362
- end = at;
6363
- break;
6364
- }
6365
- if (end < 0) throw invalid("the file is not a ZIP archive");
6366
- const count = archive.readUInt16LE(end + 10);
6367
- const directorySize = archive.readUInt32LE(end + 12);
6368
- let at = archive.readUInt32LE(end + 16);
6369
- if (count === 65535 || directorySize === 4294967295 || at === 4294967295) throw invalid("ZIP64 archives are not supported");
6370
- if (count > MAX_FILES) throw invalid(`the archive holds more than ${MAX_FILES} files`);
6371
- const files = /* @__PURE__ */ new Map();
6372
- const folded = /* @__PURE__ */ new Set();
6373
- let declared = 0;
6374
- let produced = 0;
6375
- for (let index = 0; index < count; index += 1) {
6376
- if (at + 46 > archive.length || archive.readUInt32LE(at) !== CENTRAL_SIGNATURE) throw invalid("the archive directory is damaged");
6377
- const flags = archive.readUInt16LE(at + 8);
6378
- const method = archive.readUInt16LE(at + 10);
6379
- const compressed = archive.readUInt32LE(at + 20);
6380
- const size = archive.readUInt32LE(at + 24);
6381
- const nameLength = archive.readUInt16LE(at + 28);
6382
- const extraLength = archive.readUInt16LE(at + 30);
6383
- const commentLength = archive.readUInt16LE(at + 32);
6384
- const attributes = archive.readUInt32LE(at + 38);
6385
- const local = archive.readUInt32LE(at + 42);
6386
- if (at + 46 + nameLength > archive.length) throw invalid("the archive directory is damaged");
6387
- const name = archive.toString("utf8", at + 46, at + 46 + nameLength);
6388
- at += 46 + nameLength + extraLength + commentLength;
6389
- const problem = archivePathProblem(name);
6390
- if (problem !== void 0) throw invalid(`the archive path "${name}" ${problem}`);
6391
- if (name.endsWith("/")) continue;
6392
- if ((attributes >>> 16 & TYPE_MASK) === SYMBOLIC_LINK) throw invalid(`the archive holds a link: ${name}`);
6393
- if ((flags & 1) !== 0) throw invalid("encrypted archives are not supported");
6394
- if (method !== 0 && method !== 8) throw invalid(`the archive entry ${name} uses an unsupported compression method`);
6395
- if (compressed === 4294967295 || size === 4294967295) throw invalid("ZIP64 archives are not supported");
6396
- const key = name.toLowerCase();
6397
- if (files.has(name) || folded.has(key)) throw invalid(`the archive repeats a path (or differs only by case): ${name}`);
6398
- declared += size;
6399
- if (declared > limits.maxBytes) throw invalid(`the archive unpacks to more than ${limits.maxBytes} bytes`);
6400
- if (local + 30 > archive.length || archive.readUInt32LE(local) !== LOCAL_SIGNATURE) throw invalid(`the archive entry ${name} is damaged`);
6401
- const start = local + 30 + archive.readUInt16LE(local + 26) + archive.readUInt16LE(local + 28);
6402
- if (start + compressed > archive.length) throw invalid(`the archive entry ${name} is cut short`);
6403
- const raw = archive.subarray(start, start + compressed);
6404
- let content;
6405
- try {
6406
- content = method === 0 ? Buffer.from(raw) : inflateRawSync(raw, { maxOutputLength: Math.max(size, 1) });
6407
- } catch {
6408
- throw invalid(`the archive entry ${name} cannot be unpacked`);
6409
- }
6410
- if (content.length !== size) throw invalid(`the archive entry ${name} does not match its declared size`);
6411
- produced += content.length;
6412
- if (produced > limits.maxBytes) throw invalid(`the archive unpacks to more than ${limits.maxBytes} bytes`);
6413
- files.set(name, content);
6414
- folded.add(key);
6415
- }
6416
- return files;
6417
- }
6418
7527
  // src/host/catalogue/install.ts
6419
7528
  const FOLDER_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
6420
7529
  const MAX_FOLDER_COPIES = 99;
@@ -7349,9 +8458,7 @@ function readStore(root) {
7349
8458
  function writeStore(root, store) {
7350
8459
  const folder = syncFolder(root);
7351
8460
  mkdirSync(folder, { recursive: true });
7352
- const temporary = join(folder, `state.json.${process.pid}.tmp`);
7353
- writeFileSync(temporary, `${JSON.stringify(store, null, 2)}\n`);
7354
- renameSync(temporary, join(folder, "state.json"));
8461
+ atomicWriteSync(join(folder, "state.json"), `${JSON.stringify(store, null, 2)}\n`);
7355
8462
  }
7356
8463
  // src/host/sync/units.ts
7357
8464
  /** Folders of the root that are one unit each, whatever they hold. */
@@ -8313,6 +9420,7 @@ function apply(ctx, config) {
8313
9420
  reflection: (id) => reflectionStatus(ctx.roleplayState.openSession(join(root.path, "sessions"), id), orchestration.reflecting(chatSessionId(id))),
8314
9421
  activity: (id) => readActivity(ctx.roleplayState.openSession(join(root.path, "sessions"), id)),
8315
9422
  usage: (id) => readUsage(ctx.roleplayState.openSession(join(root.path, "sessions"), id)),
9423
+ trace: (id) => readTraces(ctx.roleplayState.openSession(join(root.path, "sessions"), id)),
8316
9424
  interventions: (id) => readInterventions(ctx.roleplayState.openSession(join(root.path, "sessions"), id))
8317
9425
  };
8318
9426
  const staging = new ImportStaging();
@@ -8325,6 +9433,13 @@ function apply(ctx, config) {
8325
9433
  root: () => root.path,
8326
9434
  avatars: () => avatarsWorld(root.path)
8327
9435
  };
9436
+ const archiveDeps = {
9437
+ state: ctx.roleplayState,
9438
+ sessionsDir: deps.sessionsDir,
9439
+ worldsDir: () => join(root.path, "worlds"),
9440
+ worldDirectory: async (id) => (await worlds.find(id))?.directory,
9441
+ maxBytes: () => config.importMaxUploadBytes.get() * 4
9442
+ };
8328
9443
  const presetLibrary = new Presets({
8329
9444
  root: () => root.path,
8330
9445
  worldDirectory: async (worldId) => (await worlds.find(worldId))?.directory,
@@ -8410,7 +9525,43 @@ function apply(ctx, config) {
8410
9525
  }
8411
9526
  });
8412
9527
  prompts.frozen = () => sync.gate.isLocked("prompts");
9528
+ const playtests = new Playtests({
9529
+ start: (request) => startSession(deps, request),
9530
+ firstPlayer: async (worldId) => (await worldCharacters(worlds, worldId)).characters.find((character) => character.role === "playable")?.id,
9531
+ send: (id, text) => agent.send(id, text),
9532
+ timeline: (id) => timelinesOf(ctx, deps.sessionsDir, id).view(id),
9533
+ playing: (chat) => orchestration.playing(chat),
9534
+ notes: (id) => notesOfSession({
9535
+ sessionsDir: deps.sessionsDir,
9536
+ open: (sessionId) => ctx.roleplayState.openSession(deps.sessionsDir(), sessionId)
9537
+ }, id),
9538
+ story: (id) => ctx.roleplayState.openSession(deps.sessionsDir(), id),
9539
+ halt: (chat) => orchestration.halt(chat),
9540
+ remove: (id) => deleteSession({
9541
+ state: ctx.roleplayState,
9542
+ sessionsDir: deps.sessionsDir,
9543
+ purgeChat
9544
+ }, id),
9545
+ check: async (worldId) => {
9546
+ const world = await worlds.find(worldId);
9547
+ if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
9548
+ return (await runChecks({ world }, { kits: [
9549
+ "consistency",
9550
+ "quality",
9551
+ "playability"
9552
+ ] })).findings;
9553
+ },
9554
+ now: () => Date.now(),
9555
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
9556
+ turnTimeoutMs: () => 12e5
9557
+ });
9558
+ ctx.effect(() => () => playtests.dispose(), "roleplay: playtests");
8413
9559
  registerApi(ctx, {
9560
+ playtest: {
9561
+ status: (id) => playtests.status(id),
9562
+ start: (request) => playtests.start(request),
9563
+ stop: (id) => playtests.stop(id)
9564
+ },
8414
9565
  sync: sync.api,
8415
9566
  locked: sync.locked,
8416
9567
  anyLocked: () => sync.gate.any,
@@ -8684,6 +9835,30 @@ function apply(ctx, config) {
8684
9835
  writeSettings: (id, value) => writeChatSettings(settingsDeps, id, value),
8685
9836
  timeline: (id) => timelinesOf(ctx, deps.sessionsDir, id).view(id),
8686
9837
  moveTimeline: (id, to) => timelinesOf(ctx, deps.sessionsDir, id).move(chatSessionId(id), to === "start" ? null : to),
9838
+ markCheckpoint: (id, turn, label, note) => label.trim() === "" ? timelinesOf(ctx, deps.sessionsDir, id).unmark(chatSessionId(id), turn) : timelinesOf(ctx, deps.sessionsDir, id).mark(chatSessionId(id), turn, label, note),
9839
+ statistics: (id) => statisticsOfSession({
9840
+ state: ctx.roleplayState,
9841
+ sessionsDir: deps.sessionsDir
9842
+ }, id),
9843
+ compare: (id, a, b) => compareSession({
9844
+ state: ctx.roleplayState,
9845
+ sessionsDir: deps.sessionsDir
9846
+ }, id, a, b),
9847
+ transcript: (id, format, scope, annotated) => transcriptOfSession({
9848
+ state: ctx.roleplayState,
9849
+ sessionsDir: deps.sessionsDir
9850
+ }, id, format, {
9851
+ scope,
9852
+ annotated
9853
+ }),
9854
+ exportArchive: (id) => {
9855
+ if (orchestration.playing(chatSessionId(id))) throw new TimelineError("wait for the current turn to finish before exporting the whole story");
9856
+ return exportSession(archiveDeps, id);
9857
+ },
9858
+ importArchive: (bytes) => importSession(archiveDeps, bytes),
9859
+ get maxArchiveBytes() {
9860
+ return config.importMaxUploadBytes.get();
9861
+ },
8687
9862
  activityRun: (id, run) => {
8688
9863
  const sessions = join(root.path, "sessions");
8689
9864
  if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);
@@ -8703,6 +9878,12 @@ function apply(ctx, config) {
8703
9878
  await agent.ensure(id, ctx.roleplayState.openSession(sessions, id).metadata.get().name);
8704
9879
  await ctx.roleplayOrchestration.reflect(chatSessionId(id));
8705
9880
  },
9881
+ recallPreview: async (id, request, signal) => {
9882
+ const sessions = join(root.path, "sessions");
9883
+ if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);
9884
+ await agent.ensure(id, ctx.roleplayState.openSession(sessions, id).metadata.get().name);
9885
+ return ctx.roleplayOrchestration.recallPreview(chatSessionId(id), request, signal);
9886
+ },
8706
9887
  resetVectors: (id) => {
8707
9888
  const sessions = join(root.path, "sessions");
8708
9889
  if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);
@@ -8716,6 +9897,12 @@ function apply(ctx, config) {
8716
9897
  sessionsDir: deps.sessionsDir,
8717
9898
  open: (sessionId) => ctx.roleplayState.openSession(deps.sessionsDir(), sessionId)
8718
9899
  }, id),
9900
+ reference: (id, section, character) => referenceOfSession({
9901
+ sessionsDir: deps.sessionsDir,
9902
+ open: (sessionId) => ctx.roleplayState.openSession(deps.sessionsDir(), sessionId)
9903
+ }, id, section, character === void 0 ? {} : { character }),
9904
+ readJournal: (id) => readJournal(deps.sessionsDir(), id),
9905
+ writeJournal: (id, body) => writeJournal(deps.sessionsDir(), id, body),
8719
9906
  imageStatus: (id, node) => imagesOf(ctx, deps.sessionsDir, id).status(id, node),
8720
9907
  generateImage: (id, node) => imagesOf(ctx, deps.sessionsDir, id).generate(id, node),
8721
9908
  imageFile: async (id, node, serial) => {