@dsh-agentic-roleplay/core 0.10.0 → 0.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +1 -1
  2. package/icon.svg +13 -0
  3. package/lib/{authoring-tools-B4mEdKp_.js → authoring-tools-C9cmcUbD.js} +1820 -1243
  4. package/lib/authoring.js +18 -7
  5. package/lib/{child-Dtv76jNx.js → child-C9nPIy9j.js} +40 -5
  6. package/lib/client.js +4668 -2249
  7. package/lib/client.js.map +1 -1
  8. package/lib/compaction.js +2 -2
  9. package/lib/doctor.js +3 -3
  10. package/lib/{gallery-BZJleAeH.js → gallery-CtG-bDzz.js} +2 -2
  11. package/lib/{generator-Cg6CQc5S.js → generator-nLoPM5MF.js} +2 -2
  12. package/lib/helper.js +8 -1
  13. package/lib/{hooks-DTjHWTfx.js → hooks-BpLN_hhT.js} +282 -211
  14. package/lib/images.js +4 -4
  15. package/lib/index.js +1399 -146
  16. package/lib/{library-GIlrkOim.js → library-CH-ahlm0.js} +2 -2
  17. package/lib/{lorebook-author-tools-BCFFJSle.js → lorebook-author-tools-Cg7QQemi.js} +6 -6
  18. package/lib/lorebook-authoring.js +4 -4
  19. package/lib/{narration-BVzew4-K.js → narration-B0hConSw.js} +5 -2
  20. package/lib/orchestration.js +108 -21
  21. package/lib/{pack-jail-hsNQNTOf.js → pack-jail-D5j5mIq6.js} +16 -12
  22. package/lib/{packs-UpK_cvI4.js → packs-Cc05FrId.js} +2 -2
  23. package/lib/{presenter-agent-DZOgBOR9.js → presenter-agent-UKbKYXMO.js} +6 -6
  24. package/lib/{preset-Cyoj1ZWa.js → preset-Be4lz6vB.js} +4 -4
  25. package/lib/{preset-author-tools-RSta6pHK.js → preset-author-tools-C3s0iSfv.js} +6 -6
  26. package/lib/preset-authoring.js +5 -5
  27. package/lib/{presets-CvpsW_10.js → presets-Cl9sU3Qs.js} +152 -14
  28. package/lib/{reflection-0qTvw2It.js → reflection-I9z-PvFK.js} +135 -93
  29. package/lib/{text-CbGQhK1-.js → text-CzqhC8sT.js} +11 -1
  30. package/lib/{turn-guard-BzNeGNnc.js → turn-guard-B9pGCeir.js} +3 -3
  31. package/package.json +4 -2
  32. package/prompts/en/checks/decide-opening.md +7 -1
  33. package/prompts/en/checks/decide-stated.md +1 -0
  34. package/prompts/en/roleplay/record-keeper.md +2 -1
  35. package/prompts/zh/checks/decide-opening.md +7 -1
  36. package/prompts/zh/checks/decide-stated.md +1 -0
  37. package/prompts/zh/roleplay/record-keeper.md +2 -1
package/lib/index.js CHANGED
@@ -1,35 +1,114 @@
1
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 { $ as parseWorldFile, $t as pictureOf, At as routineProblems, B as readOrigin, C as readWorldInfo, Ct as populateItems, Dt as populateRoutines, Et as populateLore, Gt as loadCalendar, H as CatalogueError, Ht as loadDice, I as describeChanges, It as loadLocations, Jt as loadCharacters, Kt as parseCalendarFile, L as hashWorld, Ot as populateTriggers, Q as WORLD_FILE_NAME, Qt as isPng, R as isUnchanged, Rt as loadItems, S as editWorldInfo, St as populateFactions, Tt as populateLocations, Ut as parseDiceFile, V as writeOrigin, Vt as DICE_FILE_NAME, Wt as CALENDAR_FILE_NAME, Xt as knownOutputCeiling, Y as vetUrl, Yt as subfolders, Zt as ImportCardError, _t as knowsCharacter, at as entriesOf, bt as populateClock, c as importPhase, ct as loadLorebook, d as markReady, dt as reserveLorebook, en as readCard, et as parseWorldInfoEdit, f as settleDraft, ft as updateLorebookInfo, ht as loadValidatedWorld, in as authoredWorldOf, it as deleteLorebookEntry, jt as TRIGGERS_FILE_NAME, kt as populateVariables, lt as lorebookDirectory, mt as checkWorld, nn as DICE_READINGS, nt as createLorebook, ot as isLorebookName, p as structureImport, pt as writeLorebookEntry, q as guardedLookup, qt as CHARACTERS_DIR, rn as DICE_RESULTS, rt as deleteLorebook, st as listLorebooks, t as AuthoringTools, tn as DICE_COMPARISONS, tt as addLorebookEntries, u as keepDraft, vt as populateCalendar, w as loadWorldParts, wt as populateKnowledge, xt as populateDice, yt as populateCharacters, z as localChanges } from "./authoring-tools-B4mEdKp_.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-BCFFJSle.js";
4
- import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-RSta6pHK.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-BVzew4-K.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-hsNQNTOf.js";
7
- import { d as sharedSamplingOf, i as childSamplingOf, u as parseSampling } from "./child-Dtv76jNx.js";
8
- import { $ as PromptLibrary, C as notesOfSession, H as parsePlotsFile, M as PLOTS_METADATA_KEY, N as plotProgressOf, P as populatePlots, S as addToNote, T as observeAsPlayer, U as plotReferenceProblems, W as COMMANDS_KEY, X as errorMessage, Y as formatIssue, _ as readRunDetail, at as shippedLanguages, ct as AgentUnavailableError, dt as ReflectionRefusedError, et as copyWorldPrompts, ft as SessionArchivedError, g as readActivity, h as readDecisionStats, i as externalTools, k as zoneOf, lt as InvalidStartError, m as readUsage, mt as WorldNotFoundError, nt as languageOf, pt as SessionNotFoundError, q as readDocument, ut as InvalidWorldError, v as readTraces, w as readNotes, x as readWithdrawn } from "./hooks-DTjHWTfx.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-CvpsW_10.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-Cyoj1ZWa.js";
12
- import { C as slug, T as uniqueKey, d as sceneImagePath, s as inheritImages, t as addToLibrary, u as referenceImagePath } from "./library-GIlrkOim.js";
2
+ import { $t as subfolders, At as populateLore, Bt as loadLocations, Ct as populateCharacters, Dt as populateItems, E as loadWorldParts, Et as populateFactions, F as localChanges, Ft as TRIGGERS_FILE_NAME, G as vetUrl, Gt as DICE_FILE_NAME, Ht as loadItems, I as readOrigin, Jt as CALENDAR_FILE_NAME, Kt as loadDice, L as writeOrigin, M as describeChanges, Mt as populateTriggers, N as hashWorld, Nt as populateVariables, Ot as populateKnowledge, P as isUnchanged, Pt as routineProblems, Qt as loadCharacters, R as CatalogueError, St as populateCalendar, T as readWorldInfo, Tt as populateDice, U as guardedLookup, Xt as parseCalendarFile, Yt as loadCalendar, Zt as CHARACTERS_DIR, _ as runChecks, _t as writeLorebookEntry, an as readCard, at as addLorebookEntries, c as importPhase, cn as DICE_RESULTS, ct as deleteLorebookEntry, d as markReady, dt as listLorebooks, en as knownOutputCeiling, et as WORLD_FILE_NAME, f as settleDraft, ft as loadLorebook, gt as updateLorebookInfo, ht as reserveLorebook, in as pictureOf, it as questionView, jt as populateRoutines, kt as populateLocations, ln as authoredWorldOf, lt as entriesOf, nn as cardFormat, nt as parseWorldInfoEdit, on as DICE_COMPARISONS, ot as createLorebook, p as structureImport, pt as lorebookDirectory, qt as parseDiceFile, rn as isPng, rt as combineAnswers, sn as DICE_READINGS, st as deleteLorebook, t as AuthoringTools, tn as ImportCardError, tt as parseWorldFile, u as keepDraft, ut as isLorebookName, vt as checkWorld, w as editWorldInfo, wt as populateClock, xt as knowsCharacter, yt as loadValidatedWorld } from "./authoring-tools-C9cmcUbD.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-Cg7QQemi.js";
4
+ import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-C3s0iSfv.js";
5
+ import { $ as listFiles, B as COMMANDS_KEY, C as readNotes, D as PLOTS_METADATA_KEY, F as readUsage, G as formatIssue, J as PROMPTS_FOLDER, K as errorMessage, O as plotProgressOf, Q as languageOf, R as parsePlotsFile, S as notesOfSession, U as readDocument, X as copyWorldPrompts, Y as PromptLibrary, _ as readTraces, at as InvalidStartError, b as readWithdrawn, ct as SessionArchivedError, et as promptProblem, g as readRunDetail, h as readActivity, i as externalTools, it as AgentUnavailableError, k as populatePlots, lt as SessionNotFoundError, m as readDecisionStats, mt as zoneOf, ot as InvalidWorldError, q as LANGUAGE_FOLDER, st as ReflectionRefusedError, tt as shippedLanguages, ut as WorldNotFoundError, w as observeAsPlayer, x as addToNote, z as plotReferenceProblems } from "./hooks-BpLN_hhT.js";
6
+ import { a as liveSettings, c as writeSettings, d as parseSettings, i as InvalidSettingsError, l as DEFAULT_SETTINGS, o as readSettings, p as WORLD_RULES_KEY, s as useChildReasoning, u as SETTINGS_SPEC } from "./narration-B0hConSw.js";
7
+ 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-D5j5mIq6.js";
8
+ import { d as parseSampling, f as sharedSamplingOf, i as childSamplingOf, m as RECOVERY_SHRINK, p as RECOVERY_FLOOR, s as isUnfinishedCall, x as totalTokens } from "./child-C9nPIy9j.js";
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-Cl9sU3Qs.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-I9z-PvFK.js";
12
+ import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-Be4lz6vB.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-0qTvw2It.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-UpK_cvI4.js";
16
- import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-Cg6CQc5S.js";
17
- import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-BZJleAeH.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-Cc05FrId.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 { SESSION_DATABASE_FILE, addLocalDays, createSessionStore, describeInstant, describeValue, holidaysOn, isSessionId, itemKey, lintWorld, locationKey, openSessionStore, parseInstant, readCalendar, seasonOf, sessionDatabase, sessionFolder, shownVariables, systemTimeZone } from "@dsh-agentic-roleplay/state";
20
+ import { copyFileSync, cpSync, createReadStream, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
20
21
  import { createHash, randomBytes, randomUUID } from "node:crypto";
21
22
  import { copyFile, cp, lstat, mkdir, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
22
23
  import { Session, SessionId } from "@deepseek-ai/dsh-session";
23
- import { inflateRawSync } from "node:zlib";
24
+ import { crc32, deflateRawSync, inflateRawSync } from "node:zlib";
24
25
  import { fileURLToPath } from "node:url";
25
26
  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";
27
27
  import { request } from "node:http";
28
28
  import { request as request$1 } from "node:https";
29
29
  import { homedir } from "node:os";
30
30
  import { pipeline } from "node:stream/promises";
31
31
  import { spawn } from "node:child_process";
32
32
  import z from "@deepseek-ai/schemastery";
33
+ // src/host/prompts/manage.ts
34
+ /** A prompt the person asked for does not exist or cannot be written; the message says why. */
35
+ var PromptEditError = class extends Error {};
36
+ const normal = (text) => text.replace(/\r\n/g, "\n").trimEnd();
37
+ const VARIABLE = /\$\{([A-Za-z]+)\}/g;
38
+ const variablesOf = (text) => [...new Set([...text.matchAll(VARIABLE)].map((match) => match[1]))];
39
+ const ID$1 = /^[a-z0-9-]+(\/[a-z0-9-]+)*$/;
40
+ /**
41
+ * The prompts of the roleplay root, for the person to look at and edit: what each file says, whether it differs from the shipped text, the shipped text itself
42
+ * to compare with, and replacing a file by it. Nothing is replaced by itself and no record is kept of what was shipped when, so a different file may be an edit or a
43
+ * shipped text that moved on: the person decides.
44
+ */
45
+ var PromptManager = class {
46
+ library;
47
+ now;
48
+ constructor(library, now = () => /* @__PURE__ */ new Date()) {
49
+ this.library = library;
50
+ this.now = now;
51
+ }
52
+ list() {
53
+ return this.library.languages.flatMap((language) => listFiles(join(this.library.shipped, language)).map((id) => this.entry(id, language))).sort((a, b) => a.id.localeCompare(b.id) || a.language.localeCompare(b.language));
54
+ }
55
+ /** @throws {PromptEditError} for a prompt the package does not ship. */
56
+ read(id, language) {
57
+ const shipped = this.shipped(id, language);
58
+ const current = this.current(id, language) ?? shipped;
59
+ return {
60
+ id,
61
+ language,
62
+ state: normal(current) === normal(shipped) ? "default" : "different",
63
+ current,
64
+ shipped,
65
+ variables: variablesOf(shipped)
66
+ };
67
+ }
68
+ /** Saves a text as the prompt, keeping the file it replaces in the trash when that was not the shipped text. @throws {PromptEditError} when the text cannot be the prompt or the folder is syncing. */
69
+ async write(id, language, text) {
70
+ this.shipped(id, language);
71
+ if (this.library.frozen()) throw new PromptEditError("the prompts are being synced: try again when that is done");
72
+ const problem = text.includes("{{") ? "holds \"{{\", which DSH reads as a variable of its own" : promptProblem(language, id, text, this.library.shipped);
73
+ if (problem !== void 0) throw new PromptEditError(`prompt ${id} (${language}) ${problem}`);
74
+ const target = this.file(id, language);
75
+ const body = text.endsWith("\n") ? text : `${text}\n`;
76
+ const before = this.current(id, language);
77
+ if (before !== void 0 && normal(before) !== normal(body) && normal(before) !== normal(this.shipped(id, language))) this.keep(id, language, target);
78
+ await atomicWrite(target, body, { createDirectory: true });
79
+ return this.entry(id, language);
80
+ }
81
+ /** Puts the shipped text in the file. The file it replaces goes to the trash unless it already was the shipped text. */
82
+ async reset(id, language) {
83
+ return await this.write(id, language, this.shipped(id, language));
84
+ }
85
+ entry(id, language) {
86
+ const { state } = this.read(id, language);
87
+ return {
88
+ id,
89
+ language,
90
+ state
91
+ };
92
+ }
93
+ shipped(id, language) {
94
+ const file = ID$1.test(id) ? join(this.library.shipped, language, `${id}.md`) : void 0;
95
+ if (file === void 0 || !LANGUAGE_FOLDER.test(language) || !existsSync(file)) throw new PromptEditError(`there is no shipped prompt "${id}" in "${language}"`);
96
+ return readFileSync(file, "utf8");
97
+ }
98
+ file(id, language) {
99
+ return join(this.library.directory, language, `${id}.md`);
100
+ }
101
+ current(id, language) {
102
+ const file = this.file(id, language);
103
+ return existsSync(file) ? readFileSync(file, "utf8") : void 0;
104
+ }
105
+ keep(id, language, file) {
106
+ const stamp = this.now().toISOString().replace(/[:.]/g, "-");
107
+ const target = join(dirname(this.library.directory), ".trash", PROMPTS_FOLDER, stamp, language, `${id}.md`);
108
+ mkdirSync(dirname(target), { recursive: true });
109
+ copyFileSync(file, target);
110
+ }
111
+ };
33
112
  // src/host/worlds/authoring-language.ts
34
113
  /**
35
114
  * The language the person was using when they last worked on a world with the authoring assistant. The assistant's instructions
@@ -137,9 +216,17 @@ function folderNameOf(name) {
137
216
  return folder === "" ? "imported world" : folder;
138
217
  }
139
218
  /** 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.")}`;
219
+ function importMessage(language, card) {
220
+ const request = translator(languageOf$1(language))("Import this card into this newly created world.");
221
+ return `${IMPORT_COMMAND} ${IMPORT_FOLDER}/card.json ${card === void 0 ? request : `${request} ${sourceSummary(card, language)}`}`;
222
+ }
223
+ /** The card kept in a world's import folder, when it can be read; the message then carries a summary of it. */
224
+ async function cardOf(directory) {
225
+ try {
226
+ return (await readImportFolder(join(directory, IMPORT_FOLDER))).card;
227
+ } catch {
228
+ return;
229
+ }
143
230
  }
144
231
  /**
145
232
  * 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 +241,7 @@ async function resumeImport(deps, worldId, language) {
154
241
  const chatSessionId = await deps.authoring.ensure(record.summary.id, record.summary.name, authoringTitle(record.summary.name, language), language);
155
242
  let failure;
156
243
  try {
157
- await deps.authoring.send(chatSessionId, importMessage(language));
244
+ await deps.authoring.send(chatSessionId, importMessage(language, await cardOf(record.directory)));
158
245
  } catch (error) {
159
246
  failure = error instanceof Error ? error.message : String(error);
160
247
  }
@@ -195,11 +282,11 @@ async function createImportedWorld(deps, id, choices) {
195
282
  * @throws {InvalidEditProblems} when the choices cannot be used. @throws {ImportNotFoundError} when the upload is gone.
196
283
  */
197
284
  async function startImport(deps, id, choices, language) {
198
- const { world } = await createImportedWorld(deps, id, choices);
285
+ const { world, directory } = await createImportedWorld(deps, id, choices);
199
286
  const chatSessionId = await deps.authoring.ensure(world.id, world.name, authoringTitle(world.name, language), language);
200
287
  let failure;
201
288
  try {
202
- await deps.authoring.send(chatSessionId, importMessage(language));
289
+ await deps.authoring.send(chatSessionId, importMessage(language, await cardOf(directory)));
203
290
  } catch (error) {
204
291
  failure = error instanceof Error ? error.message : String(error);
205
292
  }
@@ -272,6 +359,399 @@ async function actOnDraft(deps, worldId, action, language) {
272
359
  keptIn: relative(deps.root(), destination)
273
360
  };
274
361
  }
362
+ // src/host/sessions/statistics.ts
363
+ const CJK = /[ -鿿가-힯]/gu;
364
+ /** How long a text is: its words, and each character of a script that is written without spaces. */
365
+ function lengthOf(text) {
366
+ return (text.match(CJK)?.length ?? 0) + (text.replace(CJK, " ").match(/[\p{L}\p{N}]+/gu)?.length ?? 0);
367
+ }
368
+ /** Voices of the delivered turns on the way the story went: who spoke how often and how much, and what the narration came to. */
369
+ function speakingOf(timeline) {
370
+ const voices = /* @__PURE__ */ new Map();
371
+ const narration = {
372
+ passages: 0,
373
+ length: 0
374
+ };
375
+ for (const node of pathTo(timeline, timeline.head)) for (const segment of node.output?.segments ?? []) {
376
+ if (segment.type === "narration") {
377
+ narration.passages += 1;
378
+ narration.length += lengthOf(segment.text);
379
+ continue;
380
+ }
381
+ const voice = voices.get(segment.character) ?? {
382
+ name: segment.name,
383
+ lines: 0,
384
+ length: 0
385
+ };
386
+ voice.lines += 1;
387
+ voice.length += lengthOf(segment.text);
388
+ voices.set(segment.character, voice);
389
+ }
390
+ return {
391
+ speaking: [...voices.values()].sort((a, b) => b.length - a.length),
392
+ narration
393
+ };
394
+ }
395
+ /** How the story branched: turns played again from one state, and turns that were played and are not on the way the story went. */
396
+ function branchesOf(timeline) {
397
+ const onPath = new Set(pathTo(timeline, timeline.head).map((node) => node.id));
398
+ const parents = /* @__PURE__ */ new Map();
399
+ for (const node of timeline.nodes) parents.set(node.parent, (parents.get(node.parent) ?? 0) + 1);
400
+ return {
401
+ branchPoints: [...parents.values()].filter((count) => count > 1).length,
402
+ setAside: timeline.nodes.filter((node) => !onPath.has(node.id)).length
403
+ };
404
+ }
405
+ /**
406
+ * 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.
407
+ * @throws {SessionNotFoundError} when the id names no session.
408
+ */
409
+ function statisticsOfSession(deps, id) {
410
+ const directory = deps.sessionsDir();
411
+ if (!isSessionId(id) || !existsSync(sessionDatabase(directory, id))) throw new SessionNotFoundError(`no session "${id}"`);
412
+ const story = deps.state.openSession(directory, id);
413
+ const metadata = story.metadata.get();
414
+ const timeline = readTimeline(sessionFolder(directory, id));
415
+ const usage = readUsage(story);
416
+ const first = story.clock.log()[0];
417
+ const now = story.clock.get()?.now;
418
+ const places = story.events.list().map((event) => event.locationId).filter((place) => place !== void 0);
419
+ const threads = story.threads.list();
420
+ const relationships = story.relationships.list();
421
+ return {
422
+ turns: pathTo(timeline, timeline.head).length,
423
+ realTime: {
424
+ createdAt: metadata.createdAt,
425
+ ...metadata.lastPlayedAt === void 0 ? {} : { lastPlayedAt: metadata.lastPlayedAt },
426
+ waitedMs: usage.reduce((sum, entry) => sum + (entry.masterMs ?? 0), 0)
427
+ },
428
+ storyTime: {
429
+ ...first === void 0 ? {} : { start: new Date(first.to).toISOString() },
430
+ ...now === void 0 ? {} : { now: new Date(now).toISOString() },
431
+ ...first === void 0 || now === void 0 ? {} : { elapsedSeconds: Math.max(0, Math.round((now - first.to) / 1e3)) }
432
+ },
433
+ scenes: places.filter((place, index) => index === 0 || place !== places[index - 1]).length,
434
+ ...speakingOf(timeline),
435
+ threads: {
436
+ open: threads.filter((thread) => thread.status === "open").length,
437
+ resolved: threads.filter((thread) => thread.status !== "open").length
438
+ },
439
+ relationships: {
440
+ total: relationships.length,
441
+ changed: relationships.filter((relation) => relation.updatedTurn > 0).length
442
+ },
443
+ branches: branchesOf(timeline),
444
+ usage: {
445
+ runs: usage.reduce((sum, entry) => sum + entry.runs, 0),
446
+ masterTokens: usage.reduce((sum, entry) => sum + totalTokens(entry.master), 0),
447
+ helperTokens: usage.reduce((sum, entry) => sum + totalTokens(entry.helpers), 0)
448
+ }
449
+ };
450
+ }
451
+ // src/host/timeline/compare.ts
452
+ /** The differences between two lists of rows that share a key: a row only one side has, and a row whose summary differs. */
453
+ function differences(area, a, b, key, subject, summary) {
454
+ const before = new Map(a.map((row) => [key(row), row]));
455
+ const after = new Map(b.map((row) => [key(row), row]));
456
+ const changes = [];
457
+ for (const [id, row] of before) {
458
+ const other = after.get(id);
459
+ if (other === void 0) changes.push({
460
+ area,
461
+ subject: subject(row),
462
+ a: summary(row)
463
+ });
464
+ else if (summary(other) !== summary(row)) changes.push({
465
+ area,
466
+ subject: subject(row),
467
+ a: summary(row),
468
+ b: summary(other)
469
+ });
470
+ }
471
+ for (const [id, row] of after) if (!before.has(id)) changes.push({
472
+ area,
473
+ subject: subject(row),
474
+ b: summary(row)
475
+ });
476
+ return changes;
477
+ }
478
+ const place = (row) => row.location === null ? "nowhere" : `${row.location}${row.position === "" ? "" : ` (${row.position})`}`;
479
+ const number = (value) => String(Math.round(value * 100) / 100);
480
+ /** Compares two states of a story: positions, activity, things, tracked values, open threads, relationships, commitments and the story's time. */
481
+ function compareStates(first, second) {
482
+ const changes = [];
483
+ if (first.now !== second.now) changes.push({
484
+ area: "time",
485
+ subject: "story time",
486
+ ...first.now === void 0 ? {} : { a: first.now },
487
+ ...second.now === void 0 ? {} : { b: second.now }
488
+ });
489
+ if (first.turns !== second.turns) changes.push({
490
+ area: "turns",
491
+ subject: "turns played",
492
+ a: String(first.turns),
493
+ b: String(second.turns)
494
+ });
495
+ const a = first.view;
496
+ const b = second.view;
497
+ 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));
498
+ return {
499
+ a: first.label,
500
+ b: second.label,
501
+ changes
502
+ };
503
+ }
504
+ // src/host/playtest/playtest.ts
505
+ /** The test player's words when the story offered no suggestion to take. */
506
+ const FALLBACK_MOVES = {
507
+ en: [
508
+ "I look around and take stock of where I am.",
509
+ "I speak to the nearest person.",
510
+ "I go somewhere else."
511
+ ],
512
+ zh: [
513
+ "我环顾四周,看看自己身处何地。",
514
+ "我和离我最近的人说话。",
515
+ "我去别的地方看看。"
516
+ ]
517
+ };
518
+ const movesIn = (language) => language?.toLowerCase().startsWith("zh") === true ? FALLBACK_MOVES.zh : FALLBACK_MOVES.en;
519
+ const POLL_MS = 1e3;
520
+ const SUGGESTION_WAIT_MS = 9e4;
521
+ /** A turn that takes this many times the median is named as slow. */
522
+ const SLOW_FACTOR = 3;
523
+ /** The most refused calls a report lists. */
524
+ const MAX_REFUSED = 12;
525
+ /** The most missing look-ups a report lists. */
526
+ const MAX_MISSING = 20;
527
+ function refusals(traces) {
528
+ return traces.flatMap((trace) => (trace.calls ?? []).filter((call) => call.failed).map((call) => ({
529
+ turn: trace.turn,
530
+ tool: call.tool,
531
+ note: call.note
532
+ }))).slice(0, MAX_REFUSED);
533
+ }
534
+ function lacks(traces) {
535
+ const seen = /* @__PURE__ */ new Set();
536
+ return traces.flatMap((trace) => (trace.missing ?? []).map((entry) => ({
537
+ turn: trace.turn,
538
+ ...entry
539
+ }))).filter((entry) => {
540
+ const key = `${entry.character}\n${entry.tool}\n${entry.about.toLowerCase()}`;
541
+ if (seen.has(key)) return false;
542
+ seen.add(key);
543
+ return true;
544
+ }).slice(0, MAX_MISSING);
545
+ }
546
+ const sideOf$1 = (label, story) => ({
547
+ label,
548
+ turns: story.metadata.get().turns,
549
+ now: ((now) => now === void 0 ? void 0 : new Date(now).toISOString())(story.clock.get()?.now),
550
+ view: story.records()
551
+ });
552
+ const median = (values) => {
553
+ const sorted = [...values].sort((a, b) => a - b);
554
+ return sorted.length === 0 ? 0 : sorted[Math.floor(sorted.length / 2)];
555
+ };
556
+ /**
557
+ * 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,
558
+ * 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.
559
+ */
560
+ var Playtests = class {
561
+ deps;
562
+ runs = /* @__PURE__ */ new Map();
563
+ constructor(deps) {
564
+ this.deps = deps;
565
+ }
566
+ status(world) {
567
+ return this.runs.get(world)?.status;
568
+ }
569
+ /**
570
+ * @throws {InvalidEditProblems} when the request cannot be used or a test play of this world is running.
571
+ */
572
+ start(request) {
573
+ if (!Number.isInteger(request.turns) || request.turns < 1 || request.turns > 10) throw new InvalidEditProblems([`turns must be a whole number from 1 to 10`]);
574
+ if (this.runs.get(request.worldId)?.status.state === "running") throw new InvalidEditProblems(["a test play of this world is running: stop it first"]);
575
+ 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"]);
576
+ const status = {
577
+ state: "running",
578
+ world: request.worldId,
579
+ turns: request.turns,
580
+ played: 0,
581
+ step: "starting the story",
582
+ startedAt: new Date(this.deps.now()).toISOString()
583
+ };
584
+ const abort = new AbortController();
585
+ const run = {
586
+ status,
587
+ abort,
588
+ done: Promise.resolve()
589
+ };
590
+ run.done = this.play(request, run).catch((error) => {
591
+ status.state = abort.signal.aborted ? "stopped" : "failed";
592
+ status.error = error instanceof Error ? error.message : String(error);
593
+ });
594
+ this.runs.set(request.worldId, run);
595
+ return status;
596
+ }
597
+ /** Has the test play end after the turn it is in; the story is removed. */
598
+ async stop(world) {
599
+ const run = this.runs.get(world);
600
+ if (run === void 0 || run.status.state !== "running") return;
601
+ run.abort.abort();
602
+ await run.done;
603
+ }
604
+ /** Resolves when the test play of a world is over (for tests and shutdown). */
605
+ async finished(world) {
606
+ await this.runs.get(world)?.done;
607
+ }
608
+ async dispose() {
609
+ await Promise.all([...this.runs].filter(([, run]) => run.status.state === "running").map(([world]) => this.stop(world)));
610
+ }
611
+ async play(request, run) {
612
+ const { deps } = this;
613
+ const { status, abort } = run;
614
+ const began = deps.now();
615
+ const player = request.playerCharacterId ?? await deps.firstPlayer(request.worldId);
616
+ if (player === void 0) throw new InvalidEditProblems(["the world has no character a player can play"]);
617
+ const started = await deps.start({
618
+ worldId: request.worldId,
619
+ name: `Playtest ${new Date(began).toISOString().slice(0, 16).replace("T", " ")}`,
620
+ playerCharacterId: player,
621
+ ...request.opening === void 0 ? {} : { opening: request.opening },
622
+ ...request.startingTime === void 0 ? {} : { startingTime: request.startingTime },
623
+ settings: {
624
+ ...request.language === void 0 ? {} : { prompts: { language: request.language } },
625
+ images: { mode: "off" },
626
+ suggestions: { count: 3 }
627
+ }
628
+ });
629
+ const session = started.id;
630
+ const problems = [];
631
+ const turns = [];
632
+ try {
633
+ const story = deps.story(session);
634
+ const first = sideOf$1("the start", story);
635
+ const visited = /* @__PURE__ */ new Set();
636
+ const placeOf = () => story.records().characters.find((character) => character.controlled_by === "the player")?.location ?? "";
637
+ if (placeOf() !== "") visited.add(placeOf());
638
+ for (let turn = 1; turn <= request.turns && !abort.signal.aborted; turn += 1) {
639
+ status.step = `turn ${turn} of ${request.turns}: choosing the player's move`;
640
+ const move = await this.moveFor(session, turn, problems, abort.signal, request.language);
641
+ if (abort.signal.aborted) break;
642
+ status.step = `turn ${turn} of ${request.turns}: playing`;
643
+ const sentAt = deps.now();
644
+ await deps.send(session, move);
645
+ if (!await this.waitForTurn(session, started.chatSessionId, turn, abort.signal)) {
646
+ problems.push(abort.signal.aborted ? `turn ${turn} was stopped` : `turn ${turn} did not finish within ${Math.round(deps.turnTimeoutMs() / 6e4)} minutes`);
647
+ break;
648
+ }
649
+ const place = placeOf();
650
+ if (place !== "") visited.add(place);
651
+ turns.push({
652
+ turn,
653
+ player: move,
654
+ seconds: Math.round((deps.now() - sentAt) / 1e3),
655
+ place
656
+ });
657
+ status.played = turn;
658
+ }
659
+ status.step = "looking at what happened";
660
+ const last = sideOf$1("the end", story);
661
+ const typical = median(turns.map((turn) => turn.seconds));
662
+ 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`);
663
+ const places = story.locations.list().map((place) => ({
664
+ key: place.sourceId ?? String(place.id),
665
+ name: place.name
666
+ }));
667
+ const triggers = story.triggers.list().filter((trigger) => trigger.origin === "world");
668
+ status.report = {
669
+ world: started.worldName,
670
+ asked: request.turns,
671
+ played: turns.length,
672
+ seconds: Math.round((deps.now() - began) / 1e3),
673
+ turns,
674
+ places: {
675
+ visited: places.filter((place) => visited.has(place.key)).map((place) => place.name),
676
+ unvisited: places.filter((place) => !visited.has(place.key)).map((place) => place.name)
677
+ },
678
+ triggers: {
679
+ fired: triggers.filter((trigger) => trigger.fireCount > 0).map((trigger) => trigger.name),
680
+ waiting: triggers.filter((trigger) => trigger.status === "dormant" && trigger.fireCount === 0).map((trigger) => trigger.name)
681
+ },
682
+ changes: compareStates(first, last).changes,
683
+ findings: await deps.check(request.worldId),
684
+ refused: refusals(deps.trace(session)),
685
+ missing: lacks(deps.trace(session)),
686
+ problems
687
+ };
688
+ status.state = abort.signal.aborted ? "stopped" : "done";
689
+ status.step = "";
690
+ } finally {
691
+ await deps.halt(started.chatSessionId).catch(() => void 0);
692
+ await deps.remove(session).catch((error) => {
693
+ status.error = `the test story could not be removed (${error instanceof Error ? error.message : String(error)}): delete the session "${started.name}" yourself`;
694
+ });
695
+ }
696
+ }
697
+ /** What the test player says: one of the story's own suggestions, in turn, or a plain move when none came. */
698
+ async moveFor(session, turn, problems, signal, language) {
699
+ const moves = movesIn(language);
700
+ if (turn === 1) return moves[0];
701
+ const until = this.deps.now() + SUGGESTION_WAIT_MS;
702
+ while (this.deps.now() < until && !signal.aborted) {
703
+ const lines = this.deps.notes(session).find((note) => note.kind === "suggestions")?.lines ?? [];
704
+ if (lines.length > 0) return lines[(turn - 2) % lines.length];
705
+ await this.deps.sleep(POLL_MS);
706
+ }
707
+ if (!signal.aborted) problems.push(`no suggestion came before turn ${turn}, so the test player took a plain move`);
708
+ return moves[(turn - 1) % moves.length];
709
+ }
710
+ async waitForTurn(session, chat, turn, signal) {
711
+ const until = this.deps.now() + this.deps.turnTimeoutMs();
712
+ while (this.deps.now() < until && !signal.aborted) {
713
+ const view = this.deps.timeline(session);
714
+ const last = view.path.at(-1);
715
+ if (view.path.length >= turn && last?.output !== void 0 && !this.deps.playing(chat)) return true;
716
+ await this.deps.sleep(POLL_MS);
717
+ }
718
+ return false;
719
+ }
720
+ };
721
+ // src/host/sessions/compare-session.ts
722
+ var UnknownStateError = class extends Error {};
723
+ const sideOf = (label, store) => ({
724
+ label,
725
+ turns: store.metadata.get().turns,
726
+ now: ((now) => now === void 0 ? void 0 : new Date(now).toISOString())(store.clock.get()?.now),
727
+ view: store.records()
728
+ });
729
+ /**
730
+ * 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
731
+ * whose state was not kept (older than the setting allows, unless named as a checkpoint) cannot be compared.
732
+ * @throws {SessionNotFoundError} when the id names no session. @throws {UnknownStateError} when a side names no turn, or one whose state is not kept.
733
+ */
734
+ function compareSession(deps, id, first, second) {
735
+ const directory = deps.sessionsDir();
736
+ if (!isSessionId(id) || !existsSync(sessionDatabase(directory, id))) throw new SessionNotFoundError(`no session "${id}"`);
737
+ const timeline = readTimeline(sessionFolder(directory, id));
738
+ const kept = new Set(deps.state.snapshots(directory, id));
739
+ const label = (at) => {
740
+ if (at === "head") return "now";
741
+ if (at === "start") return "the start";
742
+ const node = timeline.nodes.find((candidate) => candidate.id === at);
743
+ if (node === void 0) throw new UnknownStateError(`there is no turn "${at}"`);
744
+ return node.label === void 0 ? `turn ${node.turn}` : `“${node.label}” (turn ${node.turn})`;
745
+ };
746
+ const side = (at) => {
747
+ const name = label(at);
748
+ if (at === "head") return sideOf(name, deps.state.openSession(directory, id));
749
+ const snapshot = at === "start" ? START_SNAPSHOT : snapshotOf(at);
750
+ if (!kept.has(snapshot)) throw new UnknownStateError(`the state after ${name} is not kept: name the turn as a checkpoint to keep it`);
751
+ return deps.state.readSnapshot(directory, id, snapshot, (store) => sideOf(name, store));
752
+ };
753
+ return compareStates(side(first), side(second));
754
+ }
275
755
  // src/host/translate/service.ts
276
756
  async function recordOf(worlds, id) {
277
757
  const record = await worlds.find(id);
@@ -823,6 +1303,35 @@ var DoctorSessions = class {
823
1303
  });
824
1304
  }
825
1305
  };
1306
+ // src/host/orchestration/recovery.ts
1307
+ /**
1308
+ * Runs the game master's step again when the model's tool call could not be read, instead of ending the turn with nothing. The first try is the same request
1309
+ * (a model is not the same twice), later ones leave a smaller output, so a call that runs on is cut sooner. Past the last the failure stands.
1310
+ */
1311
+ var MasterRecovery = class {
1312
+ used = /* @__PURE__ */ new Map();
1313
+ /** Whether the step is to be run again; counts it. */
1314
+ retry(chat, turn, failure) {
1315
+ if (!isUnfinishedCall(new Error(failure.message))) return false;
1316
+ const seen = this.used.get(chat);
1317
+ const count = seen?.turn === turn ? seen.count : 0;
1318
+ if (count >= 3) return false;
1319
+ this.used.set(chat, {
1320
+ turn,
1321
+ count: count + 1
1322
+ });
1323
+ return true;
1324
+ }
1325
+ /** The output cap of the chat's next request: as set until a step was run again, then shrinking with each recovery. */
1326
+ budget(chat, cap) {
1327
+ const count = this.used.get(chat)?.count ?? 0;
1328
+ return count < 2 ? cap : Math.max(Math.min(cap, RECOVERY_FLOOR), Math.floor(cap * RECOVERY_SHRINK ** (count - 1)));
1329
+ }
1330
+ /** A turn that ended starts the next from the full cap. */
1331
+ clear(chat) {
1332
+ this.used.delete(chat);
1333
+ }
1334
+ };
826
1335
  // src/host/orchestration/service.ts
827
1336
  /**
828
1337
  * The extension points of a roleplay turn. Another plugin changes how the turn
@@ -830,6 +1339,8 @@ var DoctorSessions = class {
830
1339
  */
831
1340
  var RoleplayOrchestration = class extends Service {
832
1341
  current = defaultBoundaries();
1342
+ /** The game master's steps that were run again after a call that could not be read, and the output they were left. */
1343
+ recovery = new MasterRecovery();
833
1344
  /** Resolves once the records of a chat's recorded rounds are written (or have failed): the writing goes on behind the story, so what needs them waits here. */
834
1345
  settle = () => Promise.resolve();
835
1346
  /** Resolves once the chat's story is free: a turn waits here while the story is being synced. */
@@ -1439,6 +1950,50 @@ function lorebookRoutes(api) {
1439
1950
  } }
1440
1951
  };
1441
1952
  }
1953
+ // src/host/prompts/routes.ts
1954
+ function promptRoutes(api) {
1955
+ const fail = (res, error) => {
1956
+ if (error instanceof PromptEditError) return sendError(res, 422, error.message);
1957
+ throw error;
1958
+ };
1959
+ const target = (url) => ({
1960
+ id: url.searchParams.get("id") ?? "",
1961
+ language: url.searchParams.get("language") ?? ""
1962
+ });
1963
+ return {
1964
+ "/prompts": { GET: async (_req, res) => {
1965
+ sendJson(res, 200, api.list());
1966
+ } },
1967
+ "/prompts/item": {
1968
+ GET: async (_req, res, url) => {
1969
+ try {
1970
+ const { id, language } = target(url);
1971
+ sendJson(res, 200, api.read(id, language));
1972
+ } catch (error) {
1973
+ fail(res, error);
1974
+ }
1975
+ },
1976
+ PUT: async (req, res, url) => {
1977
+ const { text } = await readJsonBody(req);
1978
+ if (typeof text !== "string") return sendError(res, 400, "\"text\" must be text");
1979
+ try {
1980
+ const { id, language } = target(url);
1981
+ sendJson(res, 200, await api.write(id, language, text));
1982
+ } catch (error) {
1983
+ fail(res, error);
1984
+ }
1985
+ }
1986
+ },
1987
+ "/prompts/item/reset": { POST: async (_req, res, url) => {
1988
+ try {
1989
+ const { id, language } = target(url);
1990
+ sendJson(res, 200, await api.reset(id, language));
1991
+ } catch (error) {
1992
+ fail(res, error);
1993
+ }
1994
+ } }
1995
+ };
1996
+ }
1442
1997
  // src/shared/catalogue.ts
1443
1998
  /** What a credential reference is: letters, digits and `_`, not starting with a digit (DSH's grammar). */
1444
1999
  const CREDENTIAL_REF = /^[A-Za-z_][A-Za-z0-9_]*$/;
@@ -2427,7 +2982,7 @@ function languageField(value) {
2427
2982
  }
2428
2983
  // src/host/http/routes/worlds.ts
2429
2984
  /** The routes of the API for worlds. */
2430
- function worldsRoutes({ worlds, createWorld, starter, authorWorld, translation, worldCharacters, avatars }) {
2985
+ function worldsRoutes({ worlds, createWorld, starter, authorWorld, translation, worldCharacters, avatars, playtest }) {
2431
2986
  return {
2432
2987
  "/worlds": {
2433
2988
  GET: async (_req, res) => {
@@ -2507,6 +3062,39 @@ function worldsRoutes({ worlds, createWorld, starter, authorWorld, translation,
2507
3062
  throw error;
2508
3063
  }
2509
3064
  } },
3065
+ "/worlds/playtest": {
3066
+ GET: (_req, res, url) => {
3067
+ sendJson(res, 200, playtest.status(url.searchParams.get("id") ?? "") ?? { state: "idle" });
3068
+ return Promise.resolve();
3069
+ },
3070
+ POST: async (req, res, url) => {
3071
+ const body = await readJsonBody(req);
3072
+ if (typeof body.turns !== "number") return sendError(res, 400, "turns must be a number");
3073
+ if (body.playerCharacterId !== void 0 && typeof body.playerCharacterId !== "string") return sendError(res, 400, "playerCharacterId must be text");
3074
+ if (body.opening !== void 0 && typeof body.opening !== "number") return sendError(res, 400, "opening must be a number");
3075
+ if (body.startingTime !== void 0 && typeof body.startingTime !== "string") return sendError(res, 400, "startingTime must be text");
3076
+ try {
3077
+ sendJson(res, 202, playtest.start({
3078
+ worldId: url.searchParams.get("id") ?? "",
3079
+ turns: body.turns,
3080
+ ...body.playerCharacterId === void 0 ? {} : { playerCharacterId: body.playerCharacterId },
3081
+ ...body.opening === void 0 ? {} : { opening: body.opening },
3082
+ ...body.startingTime === void 0 || body.startingTime.trim() === "" ? {} : { startingTime: body.startingTime.trim() },
3083
+ ...languageField(body.language) === void 0 ? {} : { language: languageField(body.language) }
3084
+ }));
3085
+ } catch (error) {
3086
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
3087
+ message: error.message,
3088
+ problems: error.problems
3089
+ });
3090
+ throw error;
3091
+ }
3092
+ },
3093
+ DELETE: async (_req, res, url) => {
3094
+ await playtest.stop(url.searchParams.get("id") ?? "");
3095
+ sendJson(res, 200, playtest.status(url.searchParams.get("id") ?? "") ?? { state: "idle" });
3096
+ }
3097
+ },
2510
3098
  "/avatars": {
2511
3099
  POST: async (req, res) => {
2512
3100
  const body = await readJsonBody(req);
@@ -2642,6 +3230,15 @@ function catalogueRoutes({ catalogue }) {
2642
3230
  return catalogueFailure(res, error);
2643
3231
  }
2644
3232
  } },
3233
+ "/catalogue/link": { POST: async (req, res) => {
3234
+ const { url } = await readJsonBody(req);
3235
+ if (typeof url !== "string") return sendError(res, 400, "url must be text");
3236
+ try {
3237
+ sendJson(res, 200, { link: await catalogue.link(url) ?? null });
3238
+ } catch (error) {
3239
+ return catalogueFailure(res, error);
3240
+ }
3241
+ } },
2645
3242
  "/catalogue/install": { POST: async (req, res) => {
2646
3243
  const body = await readJsonBody(req);
2647
3244
  if (typeof body.url !== "string") return sendError(res, 400, "url must be text");
@@ -2763,6 +3360,15 @@ function importsRoutes({ importer }) {
2763
3360
  return importFailure(res, error);
2764
3361
  }
2765
3362
  } },
3363
+ "/worlds/import/card/url": { POST: async (req, res) => {
3364
+ const { url } = await readJsonBody(req);
3365
+ if (typeof url !== "string") return sendError(res, 400, "url must be text");
3366
+ try {
3367
+ sendJson(res, 200, await importer.fromAddress(url));
3368
+ } catch (error) {
3369
+ return error instanceof CatalogueError ? catalogueFailure(res, error) : importFailure(res, error);
3370
+ }
3371
+ } },
2766
3372
  "/worlds/import/update": {
2767
3373
  GET: async (_req, res, url) => {
2768
3374
  try {
@@ -3692,6 +4298,319 @@ function worldFilesRoutes({ worldFiles, worldEditor, sessions }) {
3692
4298
  ]))
3693
4299
  };
3694
4300
  }
4301
+ // src/host/catalogue/zip.ts
4302
+ const END_SIGNATURE$1 = 101010256;
4303
+ const CENTRAL_SIGNATURE$1 = 33639248;
4304
+ const LOCAL_SIGNATURE$1 = 67324752;
4305
+ const MAX_FILES = 5e3;
4306
+ const SYMBOLIC_LINK = 40960;
4307
+ const TYPE_MASK = 61440;
4308
+ const invalid = (message) => new CatalogueError(message, "invalid");
4309
+ /** An archive path that stays inside the folder it is unpacked to, or the reason it does not. */
4310
+ function archivePathProblem(name) {
4311
+ if (name.includes("\\") || name.includes("\0")) return "has a backslash or a NUL character";
4312
+ if (name.startsWith("/") || /^[A-Za-z]:/.test(name)) return "is absolute";
4313
+ const parts = name.split("/");
4314
+ if (parts.some((part) => part === "..")) return "climbs out of the folder";
4315
+ if (parts.some((part, index) => part === "." || part === "" && index !== parts.length - 1)) return "is ambiguous";
4316
+ }
4317
+ /**
4318
+ * Reads the files of a ZIP archive, refusing anything that could write outside the target or exhaust the machine: unsafe or repeated paths
4319
+ * (also by case), links, encryption, ZIP64, methods other than stored and deflate, too many files, and a total size past the limit
4320
+ * (checked from the sizes the archive declares and again from what inflating really produced).
4321
+ * @throws {CatalogueError} (`invalid`) when the archive is not acceptable.
4322
+ */
4323
+ function readZip(archive, limits) {
4324
+ let end = -1;
4325
+ for (let at = archive.length - 22; at >= Math.max(0, archive.length - 22 - 65535); at -= 1) if (archive.readUInt32LE(at) === END_SIGNATURE$1) {
4326
+ end = at;
4327
+ break;
4328
+ }
4329
+ if (end < 0) throw invalid("the file is not a ZIP archive");
4330
+ const count = archive.readUInt16LE(end + 10);
4331
+ const directorySize = archive.readUInt32LE(end + 12);
4332
+ let at = archive.readUInt32LE(end + 16);
4333
+ if (count === 65535 || directorySize === 4294967295 || at === 4294967295) throw invalid("ZIP64 archives are not supported");
4334
+ if (count > MAX_FILES) throw invalid(`the archive holds more than ${MAX_FILES} files`);
4335
+ const files = /* @__PURE__ */ new Map();
4336
+ const folded = /* @__PURE__ */ new Set();
4337
+ let declared = 0;
4338
+ let produced = 0;
4339
+ for (let index = 0; index < count; index += 1) {
4340
+ if (at + 46 > archive.length || archive.readUInt32LE(at) !== CENTRAL_SIGNATURE$1) throw invalid("the archive directory is damaged");
4341
+ const flags = archive.readUInt16LE(at + 8);
4342
+ const method = archive.readUInt16LE(at + 10);
4343
+ const compressed = archive.readUInt32LE(at + 20);
4344
+ const size = archive.readUInt32LE(at + 24);
4345
+ const nameLength = archive.readUInt16LE(at + 28);
4346
+ const extraLength = archive.readUInt16LE(at + 30);
4347
+ const commentLength = archive.readUInt16LE(at + 32);
4348
+ const attributes = archive.readUInt32LE(at + 38);
4349
+ const local = archive.readUInt32LE(at + 42);
4350
+ if (at + 46 + nameLength > archive.length) throw invalid("the archive directory is damaged");
4351
+ const name = archive.toString("utf8", at + 46, at + 46 + nameLength);
4352
+ at += 46 + nameLength + extraLength + commentLength;
4353
+ const problem = archivePathProblem(name);
4354
+ if (problem !== void 0) throw invalid(`the archive path "${name}" ${problem}`);
4355
+ if (name.endsWith("/")) continue;
4356
+ if ((attributes >>> 16 & TYPE_MASK) === SYMBOLIC_LINK) throw invalid(`the archive holds a link: ${name}`);
4357
+ if ((flags & 1) !== 0) throw invalid("encrypted archives are not supported");
4358
+ if (method !== 0 && method !== 8) throw invalid(`the archive entry ${name} uses an unsupported compression method`);
4359
+ if (compressed === 4294967295 || size === 4294967295) throw invalid("ZIP64 archives are not supported");
4360
+ const key = name.toLowerCase();
4361
+ if (files.has(name) || folded.has(key)) throw invalid(`the archive repeats a path (or differs only by case): ${name}`);
4362
+ declared += size;
4363
+ if (declared > limits.maxBytes) throw invalid(`the archive unpacks to more than ${limits.maxBytes} bytes`);
4364
+ if (local + 30 > archive.length || archive.readUInt32LE(local) !== LOCAL_SIGNATURE$1) throw invalid(`the archive entry ${name} is damaged`);
4365
+ const start = local + 30 + archive.readUInt16LE(local + 26) + archive.readUInt16LE(local + 28);
4366
+ if (start + compressed > archive.length) throw invalid(`the archive entry ${name} is cut short`);
4367
+ const raw = archive.subarray(start, start + compressed);
4368
+ let content;
4369
+ try {
4370
+ content = method === 0 ? Buffer.from(raw) : inflateRawSync(raw, { maxOutputLength: Math.max(size, 1) });
4371
+ } catch {
4372
+ throw invalid(`the archive entry ${name} cannot be unpacked`);
4373
+ }
4374
+ if (content.length !== size) throw invalid(`the archive entry ${name} does not match its declared size`);
4375
+ produced += content.length;
4376
+ if (produced > limits.maxBytes) throw invalid(`the archive unpacks to more than ${limits.maxBytes} bytes`);
4377
+ files.set(name, content);
4378
+ folded.add(key);
4379
+ }
4380
+ return files;
4381
+ }
4382
+ // src/host/catalogue/zip-write.ts
4383
+ const LOCAL_SIGNATURE = 67324752;
4384
+ const CENTRAL_SIGNATURE = 33639248;
4385
+ const END_SIGNATURE = 101010256;
4386
+ const UTF8_NAMES = 2048;
4387
+ const VERSION = 20;
4388
+ /** Midnight, 1 January 1980: the earliest time a ZIP entry can carry, so an archive of the same files is the same bytes. */
4389
+ const DOS_DATE = 33;
4390
+ /**
4391
+ * 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
4392
+ * folder of unbounded size.
4393
+ * @throws {RangeError} when a file or the archive passes what a ZIP without ZIP64 can hold.
4394
+ */
4395
+ function writeZip(files) {
4396
+ const parts = [];
4397
+ const directory = [];
4398
+ let offset = 0;
4399
+ if (files.size >= 65535) throw new RangeError("too many files for a ZIP archive");
4400
+ for (const [name, content] of files) {
4401
+ const encoded = Buffer.from(name, "utf8");
4402
+ const packed = deflateRawSync(content);
4403
+ const useDeflate = packed.length < content.length;
4404
+ const data = useDeflate ? packed : content;
4405
+ if (content.length >= 4294967295 || offset >= 4294967295) throw new RangeError("the archive is too large");
4406
+ const checksum = crc32(content);
4407
+ const local = Buffer.alloc(30);
4408
+ local.writeUInt32LE(LOCAL_SIGNATURE, 0);
4409
+ local.writeUInt16LE(VERSION, 4);
4410
+ local.writeUInt16LE(UTF8_NAMES, 6);
4411
+ local.writeUInt16LE(useDeflate ? 8 : 0, 8);
4412
+ local.writeUInt16LE(0, 10);
4413
+ local.writeUInt16LE(DOS_DATE, 12);
4414
+ local.writeUInt32LE(checksum, 14);
4415
+ local.writeUInt32LE(data.length, 18);
4416
+ local.writeUInt32LE(content.length, 22);
4417
+ local.writeUInt16LE(encoded.length, 26);
4418
+ parts.push(local, encoded, data);
4419
+ const central = Buffer.alloc(46);
4420
+ central.writeUInt32LE(CENTRAL_SIGNATURE, 0);
4421
+ central.writeUInt16LE(VERSION, 4);
4422
+ central.writeUInt16LE(VERSION, 6);
4423
+ central.writeUInt16LE(UTF8_NAMES, 8);
4424
+ central.writeUInt16LE(useDeflate ? 8 : 0, 10);
4425
+ central.writeUInt16LE(0, 12);
4426
+ central.writeUInt16LE(DOS_DATE, 14);
4427
+ central.writeUInt32LE(checksum, 16);
4428
+ central.writeUInt32LE(data.length, 20);
4429
+ central.writeUInt32LE(content.length, 24);
4430
+ central.writeUInt16LE(encoded.length, 28);
4431
+ central.writeUInt32LE(offset, 42);
4432
+ directory.push(central, encoded);
4433
+ offset += local.length + encoded.length + data.length;
4434
+ }
4435
+ const size = directory.reduce((sum, part) => sum + part.length, 0);
4436
+ const end = Buffer.alloc(22);
4437
+ end.writeUInt32LE(END_SIGNATURE, 0);
4438
+ end.writeUInt16LE(files.size, 8);
4439
+ end.writeUInt16LE(files.size, 10);
4440
+ end.writeUInt32LE(size, 12);
4441
+ end.writeUInt32LE(offset, 16);
4442
+ return Buffer.concat([
4443
+ ...parts,
4444
+ ...directory,
4445
+ end
4446
+ ]);
4447
+ }
4448
+ // src/host/sessions/session-archive.ts
4449
+ const ARCHIVE_FORMAT = "dsh-agentic-roleplay/session-archive";
4450
+ const MANIFEST = "manifest.json";
4451
+ const SESSION_PREFIX = "session/";
4452
+ const WORLD_PREFIX = "world/";
4453
+ const TEMPORARY_SNAPSHOT = "archive-export";
4454
+ /** 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. */
4455
+ const LEFT_OUT = /* @__PURE__ */ new Set([
4456
+ SESSION_DATABASE_FILE,
4457
+ "status.json",
4458
+ ".trash",
4459
+ ".sync"
4460
+ ]);
4461
+ const LEFT_OUT_SUFFIX = [
4462
+ ".writing",
4463
+ ".restoring",
4464
+ "-journal",
4465
+ "-wal",
4466
+ "-shm"
4467
+ ];
4468
+ var InvalidArchiveError = class extends Error {};
4469
+ /** Every file of a folder as `prefix` + its path, except those left out and links. */
4470
+ function collect(directory, prefix, files, skip = () => false) {
4471
+ const walk = (at) => {
4472
+ for (const entry of readdirSync(at, { withFileTypes: true })) {
4473
+ const path = join(at, entry.name);
4474
+ const inside = relative(directory, path).split("\\").join("/");
4475
+ if (skip(inside) || entry.isSymbolicLink()) continue;
4476
+ if (entry.isDirectory()) walk(path);
4477
+ else if (entry.isFile() && lstatSync(path).isFile()) files.set(`${prefix}${inside}`, readFileSync(path));
4478
+ }
4479
+ };
4480
+ walk(directory);
4481
+ }
4482
+ /**
4483
+ * 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,
4484
+ * 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.
4485
+ * @throws {SessionNotFoundError} when the id names no session. @throws {RangeError} when the archive is too large for a ZIP.
4486
+ */
4487
+ function exportSession(deps, id) {
4488
+ const directory = deps.sessionsDir();
4489
+ if (!isSessionId(id) || !existsSync(sessionDatabase(directory, id))) throw new SessionNotFoundError(`no session "${id}"`);
4490
+ const folder = sessionFolder(directory, id);
4491
+ const metadata = deps.state.openSession(directory, id).metadata.get();
4492
+ const files = /* @__PURE__ */ new Map();
4493
+ deps.state.snapshot(directory, id, TEMPORARY_SNAPSHOT);
4494
+ const copy = join(folder, "snapshots", `${TEMPORARY_SNAPSHOT}.sqlite`);
4495
+ try {
4496
+ files.set(`${SESSION_PREFIX}${SESSION_DATABASE_FILE}`, readFileSync(copy));
4497
+ } finally {
4498
+ deps.state.removeSnapshot(directory, id, TEMPORARY_SNAPSHOT);
4499
+ }
4500
+ collect(folder, SESSION_PREFIX, files, (path) => LEFT_OUT.has(path.split("/")[0]) || LEFT_OUT_SUFFIX.some((suffix) => path.endsWith(suffix)));
4501
+ const source = metadata.world.source;
4502
+ const worldFolder = source !== void 0 && source.startsWith("worlds/") ? join(deps.worldsDir(), source.slice(7)) : void 0;
4503
+ const worldHere = worldFolder !== void 0 && existsSync(join(worldFolder, "world.json"));
4504
+ if (worldHere) collect(worldFolder, WORLD_PREFIX, files, (path) => path.split("/")[0] === ".trash");
4505
+ const manifest = {
4506
+ format: ARCHIVE_FORMAT,
4507
+ version: 1,
4508
+ exportedAt: (deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString(),
4509
+ session: {
4510
+ id,
4511
+ name: metadata.name,
4512
+ turns: metadata.turns
4513
+ },
4514
+ world: {
4515
+ id: metadata.world.id,
4516
+ name: metadata.world.name,
4517
+ included: worldHere
4518
+ }
4519
+ };
4520
+ files.set(MANIFEST, Buffer.from(JSON.stringify(manifest, null, 2)));
4521
+ return {
4522
+ file: `${folderName(metadata.name) || "story"}.dsh-story.zip`,
4523
+ bytes: writeZip(files)
4524
+ };
4525
+ }
4526
+ function manifestOf(files) {
4527
+ const raw = files.get(MANIFEST);
4528
+ if (raw === void 0) throw new InvalidArchiveError("this is not a story archive: it has no manifest.json");
4529
+ let value;
4530
+ try {
4531
+ value = JSON.parse(raw.toString("utf8"));
4532
+ } catch {
4533
+ throw new InvalidArchiveError("the manifest of this archive is not valid JSON");
4534
+ }
4535
+ if (value.format !== "dsh-agentic-roleplay/session-archive") throw new InvalidArchiveError("this is not a story archive of this program");
4536
+ if (value.version !== 1) throw new InvalidArchiveError(`this archive is version ${String(value.version)}; this program reads version 1`);
4537
+ 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");
4538
+ return value;
4539
+ }
4540
+ function write(root, files, prefix) {
4541
+ for (const [name, content] of files) {
4542
+ if (!name.startsWith(prefix)) continue;
4543
+ const target = join(root, name.slice(prefix.length));
4544
+ mkdirSync(dirname(target), { recursive: true });
4545
+ writeFileSync(target, content);
4546
+ }
4547
+ }
4548
+ /**
4549
+ * 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
4550
+ * carries is added to the worlds when the person has none with that id. The chat is made when the session is first opened.
4551
+ * @throws {InvalidArchiveError} when the file is not an archive this program can read. Nothing is left behind when it fails.
4552
+ */
4553
+ async function importSession(deps, bytes) {
4554
+ let files;
4555
+ try {
4556
+ files = readZip(bytes, { maxBytes: deps.maxBytes() });
4557
+ } catch (error) {
4558
+ throw new InvalidArchiveError(error instanceof Error ? error.message : String(error));
4559
+ }
4560
+ const manifest = manifestOf(files);
4561
+ if (!files.has(`${SESSION_PREFIX}${SESSION_DATABASE_FILE}`)) throw new InvalidArchiveError("the archive holds no story database");
4562
+ const id = randomUUID();
4563
+ const directory = deps.sessionsDir();
4564
+ const folder = sessionFolder(directory, id);
4565
+ const name = `${manifest.session.name} (restored)`.slice(0, 200);
4566
+ const added = [];
4567
+ try {
4568
+ mkdirSync(folder, { recursive: true });
4569
+ write(folder, files, SESSION_PREFIX);
4570
+ const existingWorld = await deps.worldDirectory(manifest.world.id);
4571
+ let worldDirectory = existingWorld;
4572
+ if (manifest.world.included && existingWorld === void 0 && [...files.keys()].some((key) => key.startsWith(WORLD_PREFIX))) {
4573
+ worldDirectory = freeFolder$1(deps.worldsDir(), folderName(manifest.world.name) || "world");
4574
+ added.push(worldDirectory);
4575
+ write(worldDirectory, files, WORLD_PREFIX);
4576
+ }
4577
+ const store = openSessionStore(sessionDatabase(directory, id));
4578
+ try {
4579
+ const was = store.metadata.get();
4580
+ store.metadata.rebrand(id, name, was.createdAt);
4581
+ store.metadata.setWorld({
4582
+ ...was.world,
4583
+ ...worldDirectory === void 0 ? {} : { source: `worlds/${basename(worldDirectory)}` }
4584
+ });
4585
+ } finally {
4586
+ store.close();
4587
+ }
4588
+ } catch (error) {
4589
+ rmSync(folder, {
4590
+ recursive: true,
4591
+ force: true
4592
+ });
4593
+ for (const target of added) rmSync(target, {
4594
+ recursive: true,
4595
+ force: true
4596
+ });
4597
+ throw error;
4598
+ }
4599
+ return {
4600
+ id,
4601
+ name,
4602
+ worldAdded: added.length > 0
4603
+ };
4604
+ }
4605
+ /** 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. */
4606
+ const folderName = (name) => name.normalize("NFKC").replace(/[^\p{L}\p{N}\p{M}]+/gu, "-").replace(/^-+|-+$/gu, "").slice(0, 60);
4607
+ /** A folder name under `parent` that is free: the name itself, or with -2, -3... */
4608
+ function freeFolder$1(parent, name) {
4609
+ for (let attempt = 1;; attempt += 1) {
4610
+ const candidate = join(parent, attempt === 1 ? name : `${name}-${attempt}`);
4611
+ if (!existsSync(candidate)) return candidate;
4612
+ }
4613
+ }
3695
4614
  // src/shared/journal.ts
3696
4615
  /** The most a journal may hold. */
3697
4616
  const MAX_JOURNAL = 2e4;
@@ -3740,7 +4659,8 @@ const REFERENCE_SECTIONS = [
3740
4659
  "profile",
3741
4660
  "people",
3742
4661
  "places",
3743
- "things"
4662
+ "things",
4663
+ "quests"
3744
4664
  ];
3745
4665
  const isReferenceSection = (value) => REFERENCE_SECTIONS.includes(value);
3746
4666
  // src/host/reference/profile.ts
@@ -3932,12 +4852,54 @@ function things(session) {
3932
4852
  }));
3933
4853
  return [...carried, ...around];
3934
4854
  }
4855
+ /**
4856
+ * What the player's character has been told of or taken on: the story's threads that are marked as known to them (the others are the story's
4857
+ * own notes and are never shown) and the promises and appointments they are part of, soonest first.
4858
+ */
4859
+ function quests(session, options) {
4860
+ const stand = standpoint(session);
4861
+ if (stand === void 0) return [];
4862
+ const zone = options.zone ?? "UTC";
4863
+ const language = options.language ?? "en";
4864
+ const nameOf = (id) => session.characters.get(id)?.name;
4865
+ const commitments = session.engagements.list({
4866
+ status: "pending",
4867
+ participant: stand.player.id
4868
+ }).map((engagement) => {
4869
+ const place = engagement.locationId === void 0 ? void 0 : session.locations.get(engagement.locationId)?.name;
4870
+ const others = engagement.participants.filter((id) => id !== stand.player.id).flatMap((id) => nameOf(id) ?? []);
4871
+ return {
4872
+ kind: "commitment",
4873
+ text: engagement.title,
4874
+ status: "open",
4875
+ when: describeInstant(engagement.at, zone, language),
4876
+ ...engagement.until === void 0 ? {} : { until: describeInstant(engagement.until, zone, language) },
4877
+ ...place === void 0 ? {} : { place },
4878
+ ...others.length === 0 ? {} : { with: others },
4879
+ ...engagement.note === "" ? {} : { note: engagement.note },
4880
+ turn: engagement.createdTurn
4881
+ };
4882
+ });
4883
+ const threads = session.threads.list().filter((thread) => thread.playerKnows).map((thread) => ({
4884
+ kind: "story",
4885
+ text: thread.text,
4886
+ status: thread.status,
4887
+ turn: thread.openedTurn,
4888
+ ...thread.resolvedTurn === void 0 ? {} : { resolvedTurn: thread.resolvedTurn }
4889
+ }));
4890
+ return [
4891
+ ...commitments,
4892
+ ...threads.filter((thread) => thread.status === "open"),
4893
+ ...threads.filter((thread) => thread.status === "resolved").reverse()
4894
+ ];
4895
+ }
3935
4896
  /** One page per section; a new page is a new entry here and in `REFERENCE_SECTIONS`. */
3936
4897
  const PAGES = {
3937
4898
  profile,
3938
4899
  people,
3939
4900
  places,
3940
- things
4901
+ things,
4902
+ quests
3941
4903
  };
3942
4904
  function referencePage(session, section, options = {}) {
3943
4905
  if (!isReferenceSection(section)) throw new UnknownSectionError(`no reference section "${section}"`);
@@ -3949,7 +4911,10 @@ function referencePage(session, section, options = {}) {
3949
4911
  /** @throws {SessionNotFoundError} when the id names no session. */
3950
4912
  function referenceOfSession(deps, id, section, options = {}) {
3951
4913
  if (!isSessionId(id) || !existsSync(sessionDatabase(deps.sessionsDir(), id))) throw new SessionNotFoundError(`no session "${id}"`);
3952
- return referencePage(deps.open(id), section, options);
4914
+ return referencePage(deps.open(id), section, {
4915
+ ...deps.timing?.(id),
4916
+ ...options
4917
+ });
3953
4918
  }
3954
4919
  // src/shared/recall-preview.ts
3955
4920
  /** The longest situation accepted. */
@@ -3963,7 +4928,7 @@ function sessionsRoutes({ sessions, externalTools, redundantLayers }) {
3963
4928
  sendJson(res, 200, sessions.list());
3964
4929
  },
3965
4930
  POST: async (req, res) => {
3966
- const { worldId, playerCharacterId, playerAvatar, avatars: brought, name, settings, opening, startingTime, preset, lorebooks } = await readJsonBody(req);
4931
+ const { worldId, playerCharacterId, playerAvatar, avatars: brought, name, settings, opening, startingTime, preset, lorebooks, answers } = await readJsonBody(req);
3967
4932
  if (typeof worldId !== "string" || worldId.trim() === "") return sendError(res, 400, "\"worldId\" is required");
3968
4933
  if (playerCharacterId === void 0 && playerAvatar === void 0) return sendError(res, 400, "\"playerCharacterId\" or \"playerAvatar\" is required");
3969
4934
  if (playerCharacterId !== void 0 && (typeof playerCharacterId !== "string" || playerCharacterId.trim() === "")) return sendError(res, 400, "\"playerCharacterId\" must be text");
@@ -3972,10 +4937,12 @@ function sessionsRoutes({ sessions, externalTools, redundantLayers }) {
3972
4937
  if (name !== void 0 && typeof name !== "string") return sendError(res, 400, "\"name\" must be a string");
3973
4938
  if (opening !== void 0 && (typeof opening !== "number" || !Number.isInteger(opening))) return sendError(res, 400, "\"opening\" must be a whole number");
3974
4939
  if (startingTime !== void 0 && typeof startingTime !== "string") return sendError(res, 400, "\"startingTime\" must be text");
4940
+ if (answers !== void 0 && (typeof answers !== "object" || answers === null || Array.isArray(answers) || !Object.values(answers).every((entry) => typeof entry === "string"))) return sendError(res, 400, "\"answers\" must map question ids to answer ids");
3975
4941
  if (preset !== void 0 && typeof preset !== "string") return sendError(res, 400, "\"preset\" must be text");
3976
4942
  if (lorebooks !== void 0 && (!Array.isArray(lorebooks) || !lorebooks.every((entry) => typeof entry === "string"))) return sendError(res, 400, "\"lorebooks\" must be a list of lorebook names");
3977
4943
  try {
3978
4944
  sendJson(res, 201, await sessions.start({
4945
+ ...answers === void 0 ? {} : { answers },
3979
4946
  ...preset === void 0 || preset === "" ? {} : { preset },
3980
4947
  ...lorebooks === void 0 ? {} : { lorebooks },
3981
4948
  ...opening === void 0 ? {} : { opening },
@@ -4042,6 +5009,77 @@ function sessionsRoutes({ sessions, externalTools, redundantLayers }) {
4042
5009
  throw error;
4043
5010
  }
4044
5011
  } },
5012
+ "/sessions/timeline/checkpoint": { POST: async (req, res, url) => {
5013
+ const { label, note } = await readJsonBody(req);
5014
+ if (typeof label !== "string") return sendError(res, 400, "\"label\" is required (empty takes the name off)");
5015
+ if (note !== void 0 && typeof note !== "string") return sendError(res, 400, "\"note\" must be text");
5016
+ try {
5017
+ await sessions.markCheckpoint(url.searchParams.get("id") ?? "", url.searchParams.get("turn") ?? "", label, note);
5018
+ } catch (error) {
5019
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
5020
+ if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
5021
+ if (error instanceof TimelineError) return sendError(res, 409, error.message);
5022
+ throw error;
5023
+ }
5024
+ res.statusCode = 204;
5025
+ res.end();
5026
+ } },
5027
+ "/sessions/statistics": { GET: async (_req, res, url) => {
5028
+ try {
5029
+ sendJson(res, 200, sessions.statistics(url.searchParams.get("id") ?? ""));
5030
+ } catch (error) {
5031
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
5032
+ throw error;
5033
+ }
5034
+ } },
5035
+ "/sessions/compare": { GET: async (_req, res, url) => {
5036
+ try {
5037
+ sendJson(res, 200, sessions.compare(url.searchParams.get("id") ?? "", url.searchParams.get("a") ?? "head", url.searchParams.get("b") ?? "head"));
5038
+ } catch (error) {
5039
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
5040
+ if (error instanceof UnknownStateError) return sendError(res, 409, error.message);
5041
+ throw error;
5042
+ }
5043
+ } },
5044
+ "/sessions/export": { GET: async (_req, res, url) => {
5045
+ const id = url.searchParams.get("id") ?? "";
5046
+ const format = url.searchParams.get("format") ?? "markdown";
5047
+ if (format !== "markdown" && format !== "json" && format !== "archive") return sendError(res, 400, "\"format\" is markdown, json or archive");
5048
+ const scope = url.searchParams.get("scope") ?? "path";
5049
+ if (scope !== "path" && scope !== "all") return sendError(res, 400, "\"scope\" is path or all");
5050
+ try {
5051
+ const file = format === "archive" ? {
5052
+ ...sessions.exportArchive(id),
5053
+ mediaType: "application/zip"
5054
+ } : (() => {
5055
+ const out = sessions.transcript(id, format, scope, url.searchParams.get("annotated") === "1");
5056
+ return {
5057
+ file: out.file,
5058
+ mediaType: out.mediaType,
5059
+ bytes: Buffer.from(out.text, "utf8")
5060
+ };
5061
+ })();
5062
+ res.statusCode = 200;
5063
+ res.setHeader("content-type", file.mediaType);
5064
+ res.setHeader("content-length", file.bytes.length);
5065
+ res.setHeader("content-disposition", `attachment; filename*=UTF-8''${encodeURIComponent(file.file)}`);
5066
+ res.setHeader("x-content-type-options", "nosniff");
5067
+ res.end(file.bytes);
5068
+ } catch (error) {
5069
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
5070
+ if (error instanceof TimelineError) return sendError(res, 409, error.message);
5071
+ if (error instanceof RangeError) return sendError(res, 413, error.message);
5072
+ throw error;
5073
+ }
5074
+ } },
5075
+ "/sessions/import": { POST: async (req, res) => {
5076
+ try {
5077
+ sendJson(res, 200, await sessions.importArchive(await readBinaryBody(req, sessions.maxArchiveBytes)));
5078
+ } catch (error) {
5079
+ if (error instanceof InvalidArchiveError) return sendError(res, 422, error.message);
5080
+ throw error;
5081
+ }
5082
+ } },
4045
5083
  "/sessions/decisions": { GET: async (_req, res, url) => {
4046
5084
  try {
4047
5085
  sendJson(res, 200, sessions.decisions(url.searchParams.get("id") ?? ""));
@@ -4451,6 +5489,7 @@ function createApiHandler(deps) {
4451
5489
  ...interfaceRoutes(packs),
4452
5490
  ...presetRoutes(presets),
4453
5491
  ...lorebookRoutes(lorebooks),
5492
+ ...promptRoutes(deps.prompts),
4454
5493
  ...syncRoutes(sync)
4455
5494
  };
4456
5495
  return async (req, res) => {
@@ -5816,10 +6855,17 @@ async function startSession(deps, request) {
5816
6855
  const world = await deps.worlds.find(request.worldId);
5817
6856
  if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${request.worldId}"`);
5818
6857
  const { characters: authored, factions, locations, items, slots, authoredLore, declared, scripted, authoredPlots, calendar, checks, commands } = await loadValidatedWorld(world);
5819
- if (request.opening !== void 0 && (!Number.isInteger(request.opening) || request.opening < 0 || request.opening >= (world.alternateOpenings?.length ?? 0))) throw new InvalidStartError(`the world has no alternate opening ${String(request.opening)}`);
5820
- const opening = request.opening === void 0 ? openingOf(world, authored) : [{
6858
+ const answered = combineAnswers(world.startQuestions ?? [], request.answers ?? {});
6859
+ if (answered.problems.length > 0) throw new InvalidStartError(answered.problems.join("; "));
6860
+ const answers = answered.effect;
6861
+ const unknownPlot = Object.keys(answers.plots ?? {}).find((id) => !authoredPlots.plots.some((plot) => plot.id === id));
6862
+ if (unknownPlot !== void 0) throw new InvalidStartError(`an answer names the plot "${unknownPlot}", which the world does not have`);
6863
+ const openingIndex = request.opening ?? answers.opening;
6864
+ const startingTimeAsked = request.startingTime?.trim() || answers.startingTime;
6865
+ if (openingIndex !== void 0 && (!Number.isInteger(openingIndex) || openingIndex < 0 || openingIndex >= (world.alternateOpenings?.length ?? 0))) throw new InvalidStartError(`the world has no alternate opening ${String(openingIndex)}`);
6866
+ const opening = openingIndex === void 0 ? openingOf(world, authored) : [{
5821
6867
  type: "narration",
5822
- text: world.alternateOpenings[request.opening].text
6868
+ text: world.alternateOpenings[openingIndex].text
5823
6869
  }];
5824
6870
  const keys = [...new Set(request.avatars ?? [])];
5825
6871
  if (keys.length > 0 && deps.avatars === void 0) throw new InvalidStartError("player avatars are not available");
@@ -5836,7 +6882,7 @@ async function startSession(deps, request) {
5836
6882
  message: `"${entry.character}" is not a playable character of this world`
5837
6883
  }]);
5838
6884
  if (openingProblems.length > 0) throw new InvalidWorldError(`the alternate openings of "${world.summary.name}" have ${openingProblems.length} problem(s)`, openingProblems);
5839
- const forCharacter = request.opening === void 0 ? void 0 : world.alternateOpenings[request.opening].character;
6885
+ const forCharacter = openingIndex === void 0 ? void 0 : world.alternateOpenings[openingIndex].character;
5840
6886
  if (forCharacter !== void 0 && forCharacter !== player.id) throw new InvalidStartError(`this opening is for ${authored.find((character) => character.id === forCharacter)?.name ?? forCharacter}, not for ${player.name}`);
5841
6887
  const name = request.name?.trim() || world.summary.name;
5842
6888
  if (name.length > 200) throw new InvalidStartError(`the name must be at most 200 characters`);
@@ -5846,9 +6892,22 @@ async function startSession(deps, request) {
5846
6892
  if (!parsed.ok) throw new InvalidStartError(`the settings are not acceptable: ${parsed.problems.join("; ")}`);
5847
6893
  settings = parsed.value;
5848
6894
  }
6895
+ const givenClock = (request.settings?.clock)?.mode;
6896
+ if (answers.clockMode !== void 0 && givenClock === void 0) settings = {
6897
+ ...settings,
6898
+ clock: {
6899
+ ...settings.clock,
6900
+ mode: answers.clockMode
6901
+ }
6902
+ };
5849
6903
  const timeZone = settings.clock.timeZone !== "" ? settings.clock.timeZone : settings.clock.mode === "real" ? systemTimeZone() : world.clock?.timeZone ?? "UTC";
5850
- const tools = Object.fromEntries([.../* @__PURE__ */ new Set([...Object.keys(world.tools ?? {}), ...Object.keys(settings.tools)])].map((agent) => [agent, {
6904
+ const tools = Object.fromEntries([.../* @__PURE__ */ new Set([
6905
+ ...Object.keys(world.tools ?? {}),
6906
+ ...Object.keys(answers.tools ?? {}),
6907
+ ...Object.keys(settings.tools)
6908
+ ])].map((agent) => [agent, {
5851
6909
  ...world.tools?.[agent],
6910
+ ...answers.tools?.[agent],
5852
6911
  ...settings.tools[agent]
5853
6912
  }]));
5854
6913
  settings = {
@@ -5889,14 +6948,16 @@ async function startSession(deps, request) {
5889
6948
  }
5890
6949
  };
5891
6950
  let startsAt = world.clock?.startingTime;
5892
- if (request.startingTime !== void 0 && request.startingTime.trim() !== "") {
6951
+ if (startingTimeAsked !== void 0 && startingTimeAsked.trim() !== "") {
5893
6952
  if (settings.clock.mode === "real") throw new InvalidStartError("the story's time follows the wall clock, so it has no starting time to choose");
5894
6953
  try {
5895
- startsAt = parseInstant(request.startingTime.trim(), timeZone);
6954
+ startsAt = parseInstant(startingTimeAsked.trim(), timeZone);
5896
6955
  } catch (error) {
5897
6956
  throw new InvalidStartError(`the starting time is not acceptable: ${error instanceof Error ? error.message : String(error)}`);
5898
6957
  }
5899
6958
  }
6959
+ const storyRules = [...world.rules ?? [], ...answers.rules ?? []];
6960
+ if (storyRules.length > 30) throw new InvalidStartError(`the world's rules and the answers' rules come to ${storyRules.length}, and a story holds at most 30`);
5900
6961
  const sessionsDir = deps.sessionsDir();
5901
6962
  const session = deps.state.createSession(sessionsDir, {
5902
6963
  name,
@@ -5928,10 +6989,13 @@ async function startSession(deps, request) {
5928
6989
  values: world.variables
5929
6990
  });
5930
6991
  populateTriggers(session, scripted.triggers);
5931
- populatePlots(session.metadata, authoredPlots.plots);
6992
+ populatePlots(session.metadata, authoredPlots.plots.map((plot) => answers.plots?.[plot.id] === void 0 ? plot : {
6993
+ ...plot,
6994
+ start: answers.plots[plot.id]
6995
+ }));
5932
6996
  populateClock(session, settings.clock, startsAt === void 0 ? void 0 : { startingTime: startsAt }, (deps.now ?? Date.now)());
5933
6997
  if (commands.length > 0) session.metadata.setValue(COMMANDS_KEY, commands.map((command) => ({ ...command })));
5934
- if (world.rules !== void 0) session.metadata.setValue(WORLD_RULES_KEY, world.rules);
6998
+ if (storyRules.length > 0) session.metadata.setValue(WORLD_RULES_KEY, storyRules);
5935
6999
  if (world.narrationVoice !== void 0) session.metadata.setValue("roleplay.tts.narrationVoice", world.narrationVoice);
5936
7000
  });
5937
7001
  await inheritImages(world.directory, sessionFolder(sessionsDir, id), []);
@@ -6077,6 +7141,97 @@ async function restoreSession(deps, id) {
6077
7141
  await deps.agent.restore(id);
6078
7142
  writeStatus(folder, {});
6079
7143
  }
7144
+ // src/shared/transcript.ts
7145
+ const segmentLine = (segment) => segment.type === "utterance" ? `**${segment.name}:** “${segment.text}”` : segment.text;
7146
+ function outputLines(output, annotated) {
7147
+ if (output === void 0) return ["*(nothing was delivered)*"];
7148
+ const lines = output.segments.map(segmentLine);
7149
+ if (!annotated) return lines;
7150
+ const ruling = output.ooc;
7151
+ if (ruling !== void 0) lines.push(`> ${ruling.question === true ? "Answered out of character" : ruling.legal ? "Ruled legal" : "Ruled illegal and refused"}: ${ruling.note}`);
7152
+ for (const roll of output.rolls ?? []) lines.push(`> Roll (${roll.by}): ${roll.text}`);
7153
+ return lines;
7154
+ }
7155
+ function turnBlock(node, options, extra) {
7156
+ return [
7157
+ ...options.annotated || options.scope === "all" ? [`### Turn ${node.turn}${node.label === void 0 ? "" : ` — checkpoint “${node.label}”`}${extra}`, ...node.note === void 0 ? [] : [`> Note: ${node.note}`]] : [],
7158
+ `*${node.player.trim()}*`,
7159
+ ...outputLines(node.output, options.annotated)
7160
+ ].join("\n\n");
7161
+ }
7162
+ /** 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. */
7163
+ function transcriptMarkdown(timeline, options) {
7164
+ const parts = [`# ${options.title}`];
7165
+ if (options.opening !== void 0) parts.push(options.opening.map(segmentLine).join("\n\n"));
7166
+ const onPath = new Set(pathTo(timeline, timeline.head).map((node) => node.id));
7167
+ if (options.scope === "path") {
7168
+ for (const node of pathTo(timeline, timeline.head)) parts.push(turnBlock(node, options, ""));
7169
+ return `${parts.join("\n\n")}\n`;
7170
+ }
7171
+ const walk = (parent) => {
7172
+ const siblings = childrenOf(timeline, parent).sort((a, b) => Number(onPath.has(b.id)) - Number(onPath.has(a.id)));
7173
+ siblings.forEach((node, index) => {
7174
+ const taken = onPath.has(node.id);
7175
+ 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)");
7176
+ parts.push(block);
7177
+ walk(node.id);
7178
+ });
7179
+ };
7180
+ walk(null);
7181
+ return `${parts.join("\n\n")}\n`;
7182
+ }
7183
+ /** The same story as data: every turn with its parent, so a branch can be rebuilt by a reader. */
7184
+ function transcriptJson(timeline, options) {
7185
+ const keep = options.scope === "path" ? pathTo(timeline, timeline.head) : timeline.nodes;
7186
+ return {
7187
+ version: 1,
7188
+ title: options.title,
7189
+ ...options.opening === void 0 ? {} : { opening: options.opening },
7190
+ head: timeline.head,
7191
+ turns: keep.map((node) => ({
7192
+ id: node.id,
7193
+ parent: node.parent,
7194
+ turn: node.turn,
7195
+ createdAt: node.createdAt,
7196
+ player: node.player,
7197
+ ...node.output === void 0 ? {} : { output: options.annotated ? node.output : { segments: node.output.segments } },
7198
+ ...options.annotated && node.label !== void 0 ? { checkpoint: {
7199
+ label: node.label,
7200
+ ...node.note === void 0 ? {} : { note: node.note }
7201
+ } } : {}
7202
+ }))
7203
+ };
7204
+ }
7205
+ // src/host/sessions/transcript-session.ts
7206
+ /**
7207
+ * 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,
7208
+ * rulings, rolls and checkpoints.
7209
+ * @throws {SessionNotFoundError} when the id names no session.
7210
+ */
7211
+ function transcriptOfSession(deps, id, format, options) {
7212
+ const directory = deps.sessionsDir();
7213
+ if (!isSessionId(id) || !existsSync(sessionDatabase(directory, id))) throw new SessionNotFoundError(`no session "${id}"`);
7214
+ const folder = sessionFolder(directory, id);
7215
+ const name = deps.state.openSession(directory, id).metadata.get().name;
7216
+ const opening = readOpening(folder);
7217
+ const all = {
7218
+ title: name,
7219
+ ...opening === void 0 ? {} : { opening },
7220
+ ...options
7221
+ };
7222
+ const timeline = readTimeline(folder);
7223
+ const base = folderName(name) || "story";
7224
+ if (format === "json") return {
7225
+ file: `${base}.json`,
7226
+ mediaType: "application/json; charset=utf-8",
7227
+ text: `${JSON.stringify(transcriptJson(timeline, all), null, 2)}\n`
7228
+ };
7229
+ return {
7230
+ file: `${base}.md`,
7231
+ mediaType: "text/markdown; charset=utf-8",
7232
+ text: transcriptMarkdown(timeline, all)
7233
+ };
7234
+ }
6080
7235
  // src/host/sessions/chat-settings.ts
6081
7236
  function folderOf(deps, id) {
6082
7237
  const directory = deps.sessionsDir();
@@ -6357,6 +7512,7 @@ async function worldCharacters(worlds, worldId) {
6357
7512
  })),
6358
7513
  startingTime: world.clock?.startingTime === void 0 ? "" : localInstant(world.clock.startingTime, world.clock.timeZone ?? "UTC"),
6359
7514
  timeZone: world.clock?.timeZone ?? "",
7515
+ ...world.startQuestions === void 0 ? {} : { questions: world.startQuestions.map(questionView) },
6360
7516
  ...world.preset === void 0 ? {} : { preset: world.preset },
6361
7517
  ...world.lorebooks === void 0 ? {} : { lorebooks: world.lorebooks },
6362
7518
  problems
@@ -6521,6 +7677,7 @@ async function loadWorld(folder, dir, file, problems) {
6521
7677
  ...world.clock === void 0 ? {} : { clock: world.clock },
6522
7678
  ...world.variables === void 0 ? {} : { variables: world.variables },
6523
7679
  ...world.alternateOpenings === void 0 ? {} : { alternateOpenings: world.alternateOpenings },
7680
+ ...world.startQuestions === void 0 ? {} : { startQuestions: world.startQuestions },
6524
7681
  ...world.rules === void 0 ? {} : { rules: world.rules },
6525
7682
  ...world.tools === void 0 ? {} : { tools: world.tools },
6526
7683
  ...world.narrationVoice === void 0 ? {} : { narrationVoice: world.narrationVoice },
@@ -6652,87 +7809,6 @@ var WorldCatalog = class extends Service {
6652
7809
  return run;
6653
7810
  }
6654
7811
  };
6655
- // src/host/catalogue/zip.ts
6656
- const END_SIGNATURE = 101010256;
6657
- const CENTRAL_SIGNATURE = 33639248;
6658
- const LOCAL_SIGNATURE = 67324752;
6659
- const MAX_FILES = 5e3;
6660
- const SYMBOLIC_LINK = 40960;
6661
- const TYPE_MASK = 61440;
6662
- const invalid = (message) => new CatalogueError(message, "invalid");
6663
- /** An archive path that stays inside the folder it is unpacked to, or the reason it does not. */
6664
- function archivePathProblem(name) {
6665
- if (name.includes("\\") || name.includes("\0")) return "has a backslash or a NUL character";
6666
- if (name.startsWith("/") || /^[A-Za-z]:/.test(name)) return "is absolute";
6667
- const parts = name.split("/");
6668
- if (parts.some((part) => part === "..")) return "climbs out of the folder";
6669
- if (parts.some((part, index) => part === "." || part === "" && index !== parts.length - 1)) return "is ambiguous";
6670
- }
6671
- /**
6672
- * Reads the files of a ZIP archive, refusing anything that could write outside the target or exhaust the machine: unsafe or repeated paths
6673
- * (also by case), links, encryption, ZIP64, methods other than stored and deflate, too many files, and a total size past the limit
6674
- * (checked from the sizes the archive declares and again from what inflating really produced).
6675
- * @throws {CatalogueError} (`invalid`) when the archive is not acceptable.
6676
- */
6677
- function readZip(archive, limits) {
6678
- let end = -1;
6679
- for (let at = archive.length - 22; at >= Math.max(0, archive.length - 22 - 65535); at -= 1) if (archive.readUInt32LE(at) === END_SIGNATURE) {
6680
- end = at;
6681
- break;
6682
- }
6683
- if (end < 0) throw invalid("the file is not a ZIP archive");
6684
- const count = archive.readUInt16LE(end + 10);
6685
- const directorySize = archive.readUInt32LE(end + 12);
6686
- let at = archive.readUInt32LE(end + 16);
6687
- if (count === 65535 || directorySize === 4294967295 || at === 4294967295) throw invalid("ZIP64 archives are not supported");
6688
- if (count > MAX_FILES) throw invalid(`the archive holds more than ${MAX_FILES} files`);
6689
- const files = /* @__PURE__ */ new Map();
6690
- const folded = /* @__PURE__ */ new Set();
6691
- let declared = 0;
6692
- let produced = 0;
6693
- for (let index = 0; index < count; index += 1) {
6694
- if (at + 46 > archive.length || archive.readUInt32LE(at) !== CENTRAL_SIGNATURE) throw invalid("the archive directory is damaged");
6695
- const flags = archive.readUInt16LE(at + 8);
6696
- const method = archive.readUInt16LE(at + 10);
6697
- const compressed = archive.readUInt32LE(at + 20);
6698
- const size = archive.readUInt32LE(at + 24);
6699
- const nameLength = archive.readUInt16LE(at + 28);
6700
- const extraLength = archive.readUInt16LE(at + 30);
6701
- const commentLength = archive.readUInt16LE(at + 32);
6702
- const attributes = archive.readUInt32LE(at + 38);
6703
- const local = archive.readUInt32LE(at + 42);
6704
- if (at + 46 + nameLength > archive.length) throw invalid("the archive directory is damaged");
6705
- const name = archive.toString("utf8", at + 46, at + 46 + nameLength);
6706
- at += 46 + nameLength + extraLength + commentLength;
6707
- const problem = archivePathProblem(name);
6708
- if (problem !== void 0) throw invalid(`the archive path "${name}" ${problem}`);
6709
- if (name.endsWith("/")) continue;
6710
- if ((attributes >>> 16 & TYPE_MASK) === SYMBOLIC_LINK) throw invalid(`the archive holds a link: ${name}`);
6711
- if ((flags & 1) !== 0) throw invalid("encrypted archives are not supported");
6712
- if (method !== 0 && method !== 8) throw invalid(`the archive entry ${name} uses an unsupported compression method`);
6713
- if (compressed === 4294967295 || size === 4294967295) throw invalid("ZIP64 archives are not supported");
6714
- const key = name.toLowerCase();
6715
- if (files.has(name) || folded.has(key)) throw invalid(`the archive repeats a path (or differs only by case): ${name}`);
6716
- declared += size;
6717
- if (declared > limits.maxBytes) throw invalid(`the archive unpacks to more than ${limits.maxBytes} bytes`);
6718
- if (local + 30 > archive.length || archive.readUInt32LE(local) !== LOCAL_SIGNATURE) throw invalid(`the archive entry ${name} is damaged`);
6719
- const start = local + 30 + archive.readUInt16LE(local + 26) + archive.readUInt16LE(local + 28);
6720
- if (start + compressed > archive.length) throw invalid(`the archive entry ${name} is cut short`);
6721
- const raw = archive.subarray(start, start + compressed);
6722
- let content;
6723
- try {
6724
- content = method === 0 ? Buffer.from(raw) : inflateRawSync(raw, { maxOutputLength: Math.max(size, 1) });
6725
- } catch {
6726
- throw invalid(`the archive entry ${name} cannot be unpacked`);
6727
- }
6728
- if (content.length !== size) throw invalid(`the archive entry ${name} does not match its declared size`);
6729
- produced += content.length;
6730
- if (produced > limits.maxBytes) throw invalid(`the archive unpacks to more than ${limits.maxBytes} bytes`);
6731
- files.set(name, content);
6732
- folded.add(key);
6733
- }
6734
- return files;
6735
- }
6736
7812
  // src/host/catalogue/install.ts
6737
7813
  const FOLDER_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
6738
7814
  const MAX_FOLDER_COPIES = 99;
@@ -6902,7 +7978,7 @@ const TIMEOUT_MS = 6e4;
6902
7978
  const MAX_REDIRECTS = 5;
6903
7979
  const nodeTransport = (url, ask) => new Promise((resolveReply, reject) => {
6904
7980
  const request$2 = (url.protocol === "https:" ? request$1 : request)(url, {
6905
- method: "GET",
7981
+ method: ask.method ?? "GET",
6906
7982
  signal: ask.signal,
6907
7983
  timeout: TIMEOUT_MS,
6908
7984
  agent: false,
@@ -6986,7 +8062,8 @@ async function fetchAddress(address, options) {
6986
8062
  },
6987
8063
  guarded: source === void 0,
6988
8064
  maxBytes: options.maxBytes,
6989
- signal
8065
+ signal,
8066
+ ...options.method === void 0 ? {} : { method: options.method }
6990
8067
  });
6991
8068
  } catch (error) {
6992
8069
  if (error instanceof CatalogueError) throw error;
@@ -7018,6 +8095,24 @@ const VISIBILITY = [
7018
8095
  "private"
7019
8096
  ];
7020
8097
  const CHECKED_AT_ONCE = 4;
8098
+ const PAGE = /^\/(characters|presets|lorebooks|agentic-worlds)\/([A-Za-z0-9_-]{1,100})\/?$/;
8099
+ const PAGE_KINDS = {
8100
+ characters: "card",
8101
+ presets: "preset",
8102
+ lorebooks: "lorebook",
8103
+ "agentic-worlds": "world"
8104
+ };
8105
+ /** Types a sender may name for a card: JSON or PNG, or nothing a card could not be (servers often send plain text for a JSON file and a generic type for any file). */
8106
+ const CARD_TYPES = /* @__PURE__ */ new Set([
8107
+ "",
8108
+ "application/json",
8109
+ "text/json",
8110
+ "image/png",
8111
+ "application/octet-stream",
8112
+ "binary/octet-stream",
8113
+ "text/plain"
8114
+ ]);
8115
+ const MAX_NAME = 100;
7021
8116
  const unexpected = (what) => new CatalogueError(`the catalogue answered with something unexpected: ${what}`, "upstream");
7022
8117
  const object = (value, what) => {
7023
8118
  if (typeof value !== "object" || value === null || Array.isArray(value)) throw unexpected(what);
@@ -7069,6 +8164,17 @@ function versionOf(value) {
7069
8164
  }
7070
8165
  };
7071
8166
  }
8167
+ /** A file name for a downloaded card: the last part of the address, or "card", with the extension its first bytes call for. */
8168
+ function cardName(url, format) {
8169
+ let last = "";
8170
+ try {
8171
+ last = decodeURIComponent(url.pathname.split("/").filter((part) => part !== "").pop() ?? "");
8172
+ } catch {
8173
+ last = "";
8174
+ }
8175
+ const base = Array.from(last.replace(/[\u0000-\u001f\u007f/\\]/g, "")).slice(0, MAX_NAME).join("") || "card";
8176
+ return format === void 0 || base.toLowerCase().endsWith(`.${format}`) ? base : `${base}.${format}`;
8177
+ }
7072
8178
  /** Browsing the worlds a catalogue holds and installing one; the catalogue's API key goes with every request that belongs to its site. */
7073
8179
  var Catalogue = class {
7074
8180
  deps;
@@ -7188,6 +8294,62 @@ var Catalogue = class {
7188
8294
  result.updates.sort((a, b) => a.worldName.localeCompare(b.worldName));
7189
8295
  return result;
7190
8296
  }
8297
+ /**
8298
+ * The resource a web page address of a configured catalogue's site names (its `/characters/<id>`, `/presets/<id>`, `/lorebooks/<id>` or
8299
+ * `/agentic-worlds/<id>` page), or nothing when the address is not such a page.
8300
+ * @throws {CatalogueError} when the address is not a web address, or the page names a resource of another kind or one that does not exist.
8301
+ */
8302
+ async link(address) {
8303
+ return await this.pageOf(this.parse(address));
8304
+ }
8305
+ async pageOf(url) {
8306
+ const source = this.deps.sources.match(url);
8307
+ const named = source === void 0 ? null : PAGE.exec(url.pathname);
8308
+ if (source === void 0 || named === null) return void 0;
8309
+ const kind = PAGE_KINDS[named[1]];
8310
+ const id = named[2];
8311
+ const resource = object(await this.json(source, `/resources/${id}`), "a resource");
8312
+ if (text(resource["resourceType"]) !== TYPES[kind]) throw new CatalogueError(`${url.href} is the page of another kind of resource than the address says`, "invalid");
8313
+ return {
8314
+ source: source.name,
8315
+ id,
8316
+ kind,
8317
+ name: text(object(resource["metadata"], "a resource without metadata")["name"])
8318
+ };
8319
+ }
8320
+ /**
8321
+ * Fetches a character card from an address and hands it over for reading. A catalogue's page for a card is resolved to the card's latest
8322
+ * release. Any address first gets a HEAD request: an answer that names a type other than JSON or PNG is refused before the file is
8323
+ * downloaded, and a server that does not support HEAD (or fails it) is asked for the file anyway. The file is judged by its first bytes by
8324
+ * the card reader, not by the type the server named.
8325
+ * @throws {CatalogueError} when the address cannot be used, cannot be reached or names another type; the reader refuses what is no card.
8326
+ */
8327
+ async fetchCard(address) {
8328
+ let url = this.parse(address);
8329
+ const page = await this.pageOf(url);
8330
+ if (page !== void 0) {
8331
+ if (page.kind !== "card") throw new CatalogueError(`${url.href} is not the page of a character card`, "input");
8332
+ const source = this.deps.sources.get(page.source);
8333
+ url = new URL(this.address(source, `/versions/${(await this.latest(source, page.id)).id}/download`));
8334
+ }
8335
+ const options = {
8336
+ sources: this.deps.sources,
8337
+ maxBytes: this.deps.maxCardBytes(),
8338
+ accept: "application/json, image/png;q=0.9, */*;q=0.1",
8339
+ ...this.deps.transport === void 0 ? {} : { transport: this.deps.transport }
8340
+ };
8341
+ const head = await fetchAddress(url.href, {
8342
+ ...options,
8343
+ method: "HEAD"
8344
+ }).catch(() => void 0);
8345
+ if (head !== void 0 && !CARD_TYPES.has(head.type)) throw new CatalogueError(`${url.href} reports ${head.type}, not a PNG picture or a JSON file`, "invalid");
8346
+ const reply = await fetchAddress(url.href, options);
8347
+ const format = cardFormat(reply.body);
8348
+ return {
8349
+ body: reply.body,
8350
+ name: cardName(url, format)
8351
+ };
8352
+ }
7191
8353
  async cover(name, id) {
7192
8354
  const source = this.deps.sources.get(name);
7193
8355
  const reply = await fetchAddress(this.address(source, `/images/covers/resources/${this.identifier(id)}`), {
@@ -7210,11 +8372,12 @@ var Catalogue = class {
7210
8372
  async install(request) {
7211
8373
  const address = request.url.trim();
7212
8374
  if (address === "") throw new CatalogueError("give the address of a world archive", "input");
7213
- let url;
7214
- try {
7215
- url = new URL(address);
7216
- } catch {
7217
- throw new CatalogueError(`"${address}" is not an address`, "input");
8375
+ let url = this.parse(address);
8376
+ const page = await this.pageOf(url);
8377
+ if (page !== void 0) {
8378
+ if (page.kind !== "world") throw new CatalogueError(`${url.href} is the page of ${page.kind === "card" ? "a character card" : page.kind === "preset" ? "a preset" : "a lorebook"}, not of a world: open it from the catalogue list`, "input");
8379
+ const source = this.deps.sources.get(page.source);
8380
+ url = new URL(this.address(source, `/versions/${(await this.latest(source, page.id)).id}/download`));
7218
8381
  }
7219
8382
  const reply = await fetchAddress(url.href, {
7220
8383
  sources: this.deps.sources,
@@ -7370,6 +8533,23 @@ var Catalogue = class {
7370
8533
  }
7371
8534
  return found;
7372
8535
  }
8536
+ /** The newest published release of a resource. */
8537
+ async latest(source, id) {
8538
+ const listed = await this.json(source, `/versions/resource/${this.identifier(id)}`);
8539
+ if (!Array.isArray(listed)) throw unexpected("the list of versions");
8540
+ const newest = listed.map(versionOf).sort((a, b) => b.number - a.number)[0];
8541
+ if (newest === void 0) throw new CatalogueError("that resource has no release yet", "unknown");
8542
+ return newest.version;
8543
+ }
8544
+ parse(address) {
8545
+ const trimmed = address.trim();
8546
+ if (trimmed === "") throw new CatalogueError("give an address", "input");
8547
+ try {
8548
+ return new URL(trimmed);
8549
+ } catch {
8550
+ throw new CatalogueError(`"${trimmed}" is not an address`, "input");
8551
+ }
8552
+ }
7373
8553
  identifier(id) {
7374
8554
  if (!ID.test(id)) throw new CatalogueError("that is not a catalogue id", "input");
7375
8555
  return id;
@@ -7448,39 +8628,32 @@ var Sources = class {
7448
8628
  root: `${base.origin}${prefix}`,
7449
8629
  origin: base.origin,
7450
8630
  prefix,
7451
- keyRef,
7452
- legacyKey: source.apiKey.trim() === "" ? void 0 : source.apiKey.trim()
8631
+ keyRef
7453
8632
  }
7454
8633
  };
7455
8634
  });
7456
8635
  }
7457
- /** The catalogue's key: the credential store's value for its reference, else the one an earlier version wrote in the configuration. */
8636
+ /** The catalogue's key: the credential store's value for its reference; none when the profile has no store or the store holds none. */
7458
8637
  async key(source) {
7459
8638
  const store = this.store();
7460
- if (store !== void 0) {
7461
- let found;
7462
- try {
7463
- found = await store.resolve(source.keyRef);
7464
- } catch (error) {
7465
- throw new CatalogueError(`could not read the key "${source.keyRef}" of the catalogue "${source.name}": ${error instanceof Error ? error.message : String(error)}`, "invalid");
7466
- }
7467
- if (found !== void 0) return found.value;
8639
+ if (store === void 0) return void 0;
8640
+ try {
8641
+ return (await store.resolve(source.keyRef))?.value;
8642
+ } catch (error) {
8643
+ throw new CatalogueError(`could not read the key "${source.keyRef}" of the catalogue "${source.name}": ${error instanceof Error ? error.message : String(error)}`, "invalid");
7468
8644
  }
7469
- return source.legacyKey;
7470
8645
  }
7471
8646
  async status() {
7472
8647
  const store = this.store();
7473
8648
  return await Promise.all(this.resolved().map(async ({ source, resolved, problem }) => {
7474
8649
  const keyRef = resolved?.keyRef ?? (source.apiKeyRef.trim() === "" ? catalogueKeyRef(source.name) : source.apiKeyRef.trim());
7475
8650
  const stored = resolved === void 0 || store === void 0 ? void 0 : await store.describe(keyRef);
7476
- const legacy = source.apiKey.trim() !== "";
7477
8651
  return {
7478
8652
  name: source.name.trim(),
7479
8653
  baseUrl: source.baseUrl.trim(),
7480
8654
  keyRef,
7481
- hasKey: stored?.configured === true || legacy,
7482
- ...stored?.configured === true && stored.source !== void 0 ? { keySource: stored.source } : legacy ? { keySource: "configuration" } : {},
7483
- ...legacy ? { legacyKey: true } : {},
8655
+ hasKey: stored?.configured === true,
8656
+ ...stored?.configured === true && stored.source !== void 0 ? { keySource: stored.source } : {},
7484
8657
  ...resolved === void 0 ? { problem: problem ?? "cannot be used" } : {}
7485
8658
  };
7486
8659
  }));
@@ -8354,6 +9527,7 @@ async function unitsOf(url, worlds) {
8354
9527
  }
8355
9528
  if (path.startsWith("/presets")) units.push("presets");
8356
9529
  if (path.startsWith("/lorebooks")) units.push("lorebooks");
9530
+ if (path.startsWith("/prompts")) units.push("prompts");
8357
9531
  if (path.startsWith("/avatars") || path.startsWith("/worlds/avatars")) units.push("avatars");
8358
9532
  return units;
8359
9533
  }
@@ -8529,8 +9703,7 @@ const Config = z.object({
8529
9703
  catalogues: z.array(z.object({
8530
9704
  name: z.string().required(),
8531
9705
  baseUrl: z.string().required(),
8532
- apiKeyRef: z.string().default(""),
8533
- apiKey: z.string().default("")
9706
+ apiKeyRef: z.string().default("")
8534
9707
  })).default([]).volatile(),
8535
9708
  authoringTools: z.dict(z.dict(z.boolean())).default({}).volatile(),
8536
9709
  sync: z.object({
@@ -8581,7 +9754,7 @@ function apply(ctx, config) {
8581
9754
  return {
8582
9755
  temperature: sampling.master,
8583
9756
  ...sharedSamplingOf(sampling),
8584
- maxTokens: sampling.masterMaxTokens,
9757
+ maxTokens: orchestration.recovery.budget(id, sampling.masterMaxTokens),
8585
9758
  priority: "foreground"
8586
9759
  };
8587
9760
  }), "roleplay: request controls");
@@ -8642,6 +9815,13 @@ function apply(ctx, config) {
8642
9815
  root: () => root.path,
8643
9816
  avatars: () => avatarsWorld(root.path)
8644
9817
  };
9818
+ const archiveDeps = {
9819
+ state: ctx.roleplayState,
9820
+ sessionsDir: deps.sessionsDir,
9821
+ worldsDir: () => join(root.path, "worlds"),
9822
+ worldDirectory: async (id) => (await worlds.find(id))?.directory,
9823
+ maxBytes: () => config.importMaxUploadBytes.get() * 4
9824
+ };
8645
9825
  const presetLibrary = new Presets({
8646
9826
  root: () => root.path,
8647
9827
  worldDirectory: async (worldId) => (await worlds.find(worldId))?.directory,
@@ -8727,13 +9907,51 @@ function apply(ctx, config) {
8727
9907
  }
8728
9908
  });
8729
9909
  prompts.frozen = () => sync.gate.isLocked("prompts");
9910
+ const playtests = new Playtests({
9911
+ start: (request) => startSession(deps, request),
9912
+ firstPlayer: async (worldId) => (await worldCharacters(worlds, worldId)).characters.find((character) => character.role === "playable")?.id,
9913
+ send: (id, text) => agent.send(id, text),
9914
+ timeline: (id) => timelinesOf(ctx, deps.sessionsDir, id).view(id),
9915
+ playing: (chat) => orchestration.playing(chat),
9916
+ notes: (id) => notesOfSession({
9917
+ sessionsDir: deps.sessionsDir,
9918
+ open: (sessionId) => ctx.roleplayState.openSession(deps.sessionsDir(), sessionId)
9919
+ }, id),
9920
+ story: (id) => ctx.roleplayState.openSession(deps.sessionsDir(), id),
9921
+ trace: (id) => readTraces(ctx.roleplayState.openSession(deps.sessionsDir(), id)),
9922
+ halt: (chat) => orchestration.halt(chat),
9923
+ remove: (id) => deleteSession({
9924
+ state: ctx.roleplayState,
9925
+ sessionsDir: deps.sessionsDir,
9926
+ purgeChat
9927
+ }, id),
9928
+ check: async (worldId) => {
9929
+ const world = await worlds.find(worldId);
9930
+ if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
9931
+ return (await runChecks({ world }, { kits: [
9932
+ "consistency",
9933
+ "quality",
9934
+ "playability"
9935
+ ] })).findings;
9936
+ },
9937
+ now: () => Date.now(),
9938
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
9939
+ turnTimeoutMs: () => 12e5
9940
+ });
9941
+ ctx.effect(() => () => playtests.dispose(), "roleplay: playtests");
8730
9942
  registerApi(ctx, {
9943
+ playtest: {
9944
+ status: (id) => playtests.status(id),
9945
+ start: (request) => playtests.start(request),
9946
+ stop: (id) => playtests.stop(id)
9947
+ },
8731
9948
  sync: sync.api,
8732
9949
  locked: sync.locked,
8733
9950
  anyLocked: () => sync.gate.any,
8734
9951
  catalogue,
8735
9952
  presets: presetLibrary,
8736
9953
  lorebooks: lorebookLibrary,
9954
+ prompts: new PromptManager(prompts),
8737
9955
  packs: new InterfaceService({
8738
9956
  open: (id) => ctx.roleplayState.openSession(deps.sessionsDir(), id),
8739
9957
  root: () => root.path,
@@ -8772,6 +9990,10 @@ function apply(ctx, config) {
8772
9990
  const card = readCard(file, name);
8773
9991
  return await withTargets(await imports.create(card, isPng(file) ? pictureOf(file) : void 0));
8774
9992
  },
9993
+ fromAddress: async (address) => {
9994
+ const { body, name } = await catalogue.fetchCard(address);
9995
+ return await withTargets(await imports.create(readCard(body, name), isPng(body) ? pictureOf(body) : void 0));
9996
+ },
8775
9997
  read: async (id) => await withTargets(await imports.read(id)),
8776
9998
  choose: (id, choices) => imports.choose(id, choices),
8777
9999
  discard: (id) => imports.discard(id),
@@ -9001,6 +10223,30 @@ function apply(ctx, config) {
9001
10223
  writeSettings: (id, value) => writeChatSettings(settingsDeps, id, value),
9002
10224
  timeline: (id) => timelinesOf(ctx, deps.sessionsDir, id).view(id),
9003
10225
  moveTimeline: (id, to) => timelinesOf(ctx, deps.sessionsDir, id).move(chatSessionId(id), to === "start" ? null : to),
10226
+ 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),
10227
+ statistics: (id) => statisticsOfSession({
10228
+ state: ctx.roleplayState,
10229
+ sessionsDir: deps.sessionsDir
10230
+ }, id),
10231
+ compare: (id, a, b) => compareSession({
10232
+ state: ctx.roleplayState,
10233
+ sessionsDir: deps.sessionsDir
10234
+ }, id, a, b),
10235
+ transcript: (id, format, scope, annotated) => transcriptOfSession({
10236
+ state: ctx.roleplayState,
10237
+ sessionsDir: deps.sessionsDir
10238
+ }, id, format, {
10239
+ scope,
10240
+ annotated
10241
+ }),
10242
+ exportArchive: (id) => {
10243
+ if (orchestration.playing(chatSessionId(id))) throw new TimelineError("wait for the current turn to finish before exporting the whole story");
10244
+ return exportSession(archiveDeps, id);
10245
+ },
10246
+ importArchive: (bytes) => importSession(archiveDeps, bytes),
10247
+ get maxArchiveBytes() {
10248
+ return config.importMaxUploadBytes.get();
10249
+ },
9004
10250
  activityRun: (id, run) => {
9005
10251
  const sessions = join(root.path, "sessions");
9006
10252
  if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);
@@ -9041,7 +10287,14 @@ function apply(ctx, config) {
9041
10287
  }, id),
9042
10288
  reference: (id, section, character) => referenceOfSession({
9043
10289
  sessionsDir: deps.sessionsDir,
9044
- open: (sessionId) => ctx.roleplayState.openSession(deps.sessionsDir(), sessionId)
10290
+ open: (sessionId) => ctx.roleplayState.openSession(deps.sessionsDir(), sessionId),
10291
+ timing: (sessionId) => {
10292
+ const settings = liveSettings(sessionFolder(deps.sessionsDir(), sessionId));
10293
+ return {
10294
+ zone: zoneOf(settings.clock),
10295
+ language: settings.prompts.language === "zh" ? "zh" : "en"
10296
+ };
10297
+ }
9045
10298
  }, id, section, character === void 0 ? {} : { character }),
9046
10299
  readJournal: (id) => readJournal(deps.sessionsDir(), id),
9047
10300
  writeJournal: (id, body) => writeJournal(deps.sessionsDir(), id, body),