@dsh-agentic-roleplay/core 0.12.6 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/lib/{authoring-tools-BpkpGMSO.js → authoring-tools-CKV1UnN7.js} +1133 -139
  2. package/lib/authoring.js +340 -54
  3. package/lib/client.js +1675 -729
  4. package/lib/client.js.map +1 -1
  5. package/lib/compaction.js +2 -2
  6. package/lib/doctor.js +2 -2
  7. package/lib/{library-CnWOHwQl.js → gallery-CT5uj50b.js} +212 -7
  8. package/lib/{hooks-P_--KSFl.js → hooks-CnxV2uEh.js} +46 -17
  9. package/lib/images.js +3 -4
  10. package/lib/index.js +409 -26
  11. package/lib/{presenter-agent-BTpJxmGi.js → interpreter-Cz5qsuXk.js} +155 -64
  12. package/lib/{lorebook-author-tools-CWZ6WRN-.js → lorebook-author-tools-p3Nfpuxh.js} +6 -6
  13. package/lib/lorebook-authoring.js +5 -5
  14. package/lib/{narration-DAHmte8p.js → narration-CUZIXzab.js} +8 -2
  15. package/lib/orchestration.js +64 -19
  16. package/lib/{pack-jail-DSTyLhMc.js → pack-jail-KyZen_gy.js} +19 -13
  17. package/lib/{packs-D9_N8kDF.js → packs-DU171pDX.js} +2 -2
  18. package/lib/presenter-agent-CwDg0WE8.js +59 -0
  19. package/lib/{preset-B69AXtip.js → preset-BO8iWQ-n.js} +3 -3
  20. package/lib/{preset-author-tools-BJtt7D0J.js → preset-author-tools-C83shASm.js} +6 -6
  21. package/lib/preset-authoring.js +5 -5
  22. package/lib/{reflection-2uzE3U-v.js → reflection-CXS87Di3.js} +8 -7
  23. package/lib/{serial-DnVqMDe5.js → serial-xcAG57p_.js} +199 -43
  24. package/lib/{text-B-HsLdb-.js → text-KnqhN_Zv.js} +4 -1
  25. package/lib/{turn-guard-D4YHE00t.js → turn-guard-CfsGepCg.js} +2 -2
  26. package/package.json +3 -2
  27. package/prompts/en/import/finish-ok.md +2 -0
  28. package/prompts/en/import/next-stage-go.md +1 -0
  29. package/prompts/en/import/next-stage-paused.md +1 -0
  30. package/prompts/en/import/next-survey-paused.md +1 -0
  31. package/prompts/en/import/notice-staged.md +5 -0
  32. package/prompts/en/import/pause-stages.md +1 -0
  33. package/prompts/en/import/pause-survey.md +1 -0
  34. package/prompts/en/roleplay/image-worth.md +5 -0
  35. package/prompts/en/world/procedure.md +3 -0
  36. package/prompts/zh/import/finish-ok.md +2 -0
  37. package/prompts/zh/import/next-stage-go.md +1 -0
  38. package/prompts/zh/import/next-stage-paused.md +1 -0
  39. package/prompts/zh/import/next-survey-paused.md +1 -0
  40. package/prompts/zh/import/notice-staged.md +5 -0
  41. package/prompts/zh/import/pause-stages.md +1 -0
  42. package/prompts/zh/import/pause-survey.md +1 -0
  43. package/prompts/zh/roleplay/image-worth.md +5 -0
  44. package/prompts/zh/world/procedure.md +3 -0
  45. package/lib/gallery-D0h0X7Jy.js +0 -190
  46. package/lib/generator-CAJkevKl.js +0 -150
package/lib/index.js CHANGED
@@ -1,21 +1,20 @@
1
- import { A as chatSessionId, _ as RECOVERY_SHRINK, g as RECOVERY_FLOOR, h as sharedSamplingOf, i as childSamplingOf, j as roleplaySessionOf, m as parseSampling, s as isUnfinishedCall, w as totalTokens } from "./child-Bfj7-Iuo.js";
2
- import { $ as checkWorld, $t as authoringChatSessionId, A as loadWorldParts, B as localChanges, Gt as cardFormat, H as writeOrigin, J as guardedLookup, Jt as readCard, Kt as isPng, L as describeChanges, O as editWorldInfo, Ot as CHARACTERS_DIR, Qt as authoredWorldOf, R as hashWorld, U as CatalogueError, V as readOrigin, Wt as ImportCardError, X as vetUrl, _ as structureImport, _t as loadLocations, a as beginImport, at as populateClock, c as importTextFor, ct as populateItems, d as knownOutputCeiling, dt as populateLore, et as loadValidatedWorld, f as importPhase, ft as populateRoutines, g as settleDraft, h as markReady, i as ImportState, it as populateCharacters, k as readWorldInfo, kt as loadCharacters, lt as populateKnowledge, m as keepDraft, mt as populateVariables, nt as knowsCharacter, ot as populateDice, pt as populateTriggers, qt as pictureOf, rt as populateCalendar, st as populateFactions, t as AuthoringTools, ut as populateLocations, x as runChecks, z as isUnchanged } from "./authoring-tools-BpkpGMSO.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-CWZ6WRN-.js";
4
- import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-BJtt7D0J.js";
5
- import { $ as copyWorldPrompts, A as plotProgressOf, B as parsePlotsFile, C as readNotes, G as readDocument, H as COMMANDS_KEY, J as errorMessage, L as readUsage, Q as PromptLibrary, S as notesOfSession, T as defaultBoundaries, V as plotReferenceProblems, Y as LANGUAGE_FOLDER, Z as PROMPTS_FOLDER, _ as readTraces, b as readWithdrawn, ct as InvalidStartError, dt as SessionArchivedError, ft as SessionNotFoundError, g as readRunDetail, h as readActivity, it as shippedLanguages, j as populatePlots, k as PLOTS_METADATA_KEY, lt as InvalidWorldError, m as readDecisionStats, mt as CommandRefusedError, nt as listFiles, pt as WorldNotFoundError, q as formatIssue, rt as promptProblem, s as externalTools, st as AgentUnavailableError, tt as languageOf, ut as ReflectionRefusedError, w as observeAsPlayer, x as addToNote, yt as zoneOf } from "./hooks-P_--KSFl.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-DAHmte8p.js";
7
- import { B as questionView, Bt as parseThingEdit, Dt as ImportNotFoundError, Et as IMPORT_FOLDER, F as parseWorldInfoEdit, Ft as parseCharacterEdit, G as deletePreset, H as PRESET_FILE, It as parseFactionEdit, J as loadPreset, K as isPresetName, Kt as sourceSummary, Lt as parseLoreEdit, M as WORLD_FILE_NAME, Mt as readImportFolder, N as parseWorldFile, Ot as ImportStore, Pt as InvalidEditProblems, Q as savePresetFromWorld, Rt as parsePlaceEdit, Tt as withPlayer, W as createPresetFromShipped, Y as presetDirectory, Z as reservePreset, _t as updateLorebookInfo, at as writeWorldPrompt, cn as parseCharacterFile, ct as deleteLorebook, dn as LORE_SCOPES, dt as isLorebookName, et as updatePresetInfo, ft as listLorebooks, gt as reserveLorebook, it as readWorldPrompt, jt as parseChoices, ln as guarded, lt as deleteLorebookEntry, mt as lorebookDirectory, nt as deleteWorldPrompt, ot as addLorebookEntries, pt as loadLorebook, q as listPresets, rt as listWorldPrompts, st as createLorebook, un as LORE_KINDS, ut as entriesOf, vt as writeLorebookEntry, wt as partsOf, xt as subfolders, z as combineAnswers, zt as parseRelationEdit } from "./serial-DnVqMDe5.js";
8
- import { $ as languageOfDocuments, A as generateWorldCharacterPortrait, C as editWorldFaction$1, D as editWorldPlots$1, E as editWorldPlace$1, F as uploadWorldCharacterPortrait, G as parseVariablesEdit, I as uploadWorldEntityImage, J as PRESET_FILE$1, K as parseDiceEdit, L as worldCharacterPortraitFile, M as readWorldEditor, N as readWorldTrigger, O as editWorldRelation$1, P as removeWorldTrigger, R as worldEntityImageFile, S as editWorldCharacter$1, T as editWorldNarrationVoice, U as parseCalendarEdit, W as parseRoutineEdit, Y as presetMessage, Z as translateMessage, _ as readCalendarDocument, a as deleteWorldPackFile, at as startUpdate, b as readRoutines, c as createAuthoredEntity, ct as authoringTitle, dt as agentServicesOf, et as readWorldDocuments, f as editCalendar, ft as DOCTOR_OPENING_SOURCE, g as editVariables, h as editRoutine, it as revertUpdate, j as generateWorldEntityImage, k as editWorldThing$1, l as deleteAuthoredEntity, lt as ensureAuthoringChat, m as editDice, mt as appendNarratedTurn, n as packFileProblem, ot as updateStatus, p as editCommands, pt as appendEmptyTurn, q as parseCommandsEdit, st as AuthoringSessions, t as MAX_PACK_TEXT, tt as findTargets, u as readAuthoredEntityDocument, ut as AgentSessions, v as readCommandsDocument, w as editWorldLore$1, x as readVariables, y as readDiceDocument, z as writeWorldTrigger } from "./pack-jail-DSTyLhMc.js";
1
+ import { A as chatSessionId, _ as RECOVERY_SHRINK, g as RECOVERY_FLOOR, h as sharedSamplingOf, i as childSamplingOf, j as roleplaySessionOf, m as parseSampling, r as childSampling, s as isUnfinishedCall, w as totalTokens } from "./child-Bfj7-Iuo.js";
2
+ import { $ as checkWorld, $t as authoredWorldOf, A as loadWorldParts, B as localChanges, Gt as ImportCardError, H as writeOrigin, J as guardedLookup, Jt as pictureOf, Kt as cardFormat, L as describeChanges, O as editWorldInfo, Ot as CHARACTERS_DIR, R as hashWorld, U as CatalogueError, V as readOrigin, X as vetUrl, Yt as readCard, _ as structureImport, _t as loadLocations, a as beginImport, at as populateClock, c as importTextFor, ct as populateItems, d as knownOutputCeiling, dt as populateLore, en as authoringChatSessionId, et as loadValidatedWorld, f as importPhase, ft as populateRoutines, g as settleDraft, h as markReady, i as ImportState, it as populateCharacters, k as readWorldInfo, kt as loadCharacters, lt as populateKnowledge, m as keepDraft, mt as populateVariables, nt as knowsCharacter, ot as populateDice, pt as populateTriggers, qt as isPng, rt as populateCalendar, st as populateFactions, t as AuthoringTools, ut as populateLocations, x as runChecks, z as isUnchanged } from "./authoring-tools-CKV1UnN7.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-p3Nfpuxh.js";
4
+ import { a as presetChatSessionId, n as narrationImportMessage, o as presetOfChat } from "./preset-author-tools-C83shASm.js";
5
+ import { $ as copyWorldPrompts, A as plotProgressOf, B as parsePlotsFile, C as readNotes, G as readDocument, H as COMMANDS_KEY, J as formatIssue, K as errorMessage, L as readUsage, Q as PromptLibrary, S as notesOfSession, T as defaultBoundaries, V as plotReferenceProblems, Y as LANGUAGE_FOLDER, Z as PROMPTS_FOLDER, _ as readTraces, b as readWithdrawn, ct as InvalidStartError, dt as SessionArchivedError, ft as SessionNotFoundError, g as readRunDetail, h as readActivity, it as shippedLanguages, j as populatePlots, k as PLOTS_METADATA_KEY, lt as InvalidWorldError, m as readDecisionStats, mt as CommandRefusedError, nt as listFiles, pt as WorldNotFoundError, rt as promptProblem, s as externalTools, st as AgentUnavailableError, tt as languageOf, ut as ReflectionRefusedError, w as observeAsPlayer, x as addToNote, yt as zoneOf } from "./hooks-CnxV2uEh.js";
6
+ import { a as InvalidSettingsError, c as useChildReasoning, d as SETTINGS_SPEC, f as parseSettings, l as writeSettings, m as WORLD_RULES_KEY, o as liveSettings, s as readSettings, u as DEFAULT_SETTINGS } from "./narration-CUZIXzab.js";
7
+ import { $ as createPresetFromShipped, At as subfolders, Bt as parseChoices, Ct as lorebookDirectory, Dt as writeLorebookEntry, Et as updateLorebookInfo, Ft as IMPORT_FOLDER, Gt as parseFactionEdit, H as parseWorldFile, It as ImportNotFoundError, J as combineAnswers, Jt as parseRelationEdit, Kt as parseLoreEdit, Lt as ImportStore, Nt as partsOf, Pt as withPlayer, St as loadLorebook, Tt as reserveLorebook, Ut as InvalidEditProblems, V as WORLD_FILE_NAME, Vt as readImportFolder, W as parseWorldInfoEdit, Wt as parseCharacterEdit, Y as questionView, Yt as parseThingEdit, Z as PRESET_FILE, _t as deleteLorebook, bn as LORE_KINDS, bt as isLorebookName, dt as deleteWorldPrompt, et as deletePreset, ft as listWorldPrompts, gt as createLorebook, ht as addLorebookEntries, it as presetDirectory, lt as updatePresetInfo, mt as writeWorldPrompt, nn as sourceSummary, nt as listPresets, ot as reservePreset, pt as readWorldPrompt, qt as parsePlaceEdit, rt as loadPreset, st as savePresetFromWorld, tt as isPresetName, vn as parseCharacterFile, vt as deleteLorebookEntry, xn as LORE_SCOPES, xt as listLorebooks, yn as guarded, yt as entriesOf } from "./serial-xcAG57p_.js";
8
+ import { $ as languageOfDocuments, A as generateWorldCharacterPortrait, C as editWorldFaction$1, D as editWorldPlots$1, E as editWorldPlace$1, F as uploadWorldCharacterPortrait, G as parseVariablesEdit, I as uploadWorldEntityImage, J as PRESET_FILE$1, K as parseDiceEdit, L as worldCharacterPortraitFile, M as readWorldEditor, N as readWorldTrigger, O as editWorldRelation$1, P as removeWorldTrigger, R as worldEntityImageFile, S as editWorldCharacter$1, T as editWorldNarrationVoice, U as parseCalendarEdit, W as parseRoutineEdit, Y as presetMessage, Z as translateMessage, _ as readCalendarDocument, a as deleteWorldPackFile, at as startUpdate, b as readRoutines, c as createAuthoredEntity, ct as authoringTitle, dt as agentServicesOf, et as readWorldDocuments, f as editCalendar, ft as DOCTOR_OPENING_SOURCE, g as editVariables, h as editRoutine, it as revertUpdate, j as generateWorldEntityImage, k as editWorldThing$1, l as deleteAuthoredEntity, lt as ensureAuthoringChat, m as editDice, mt as appendNarratedTurn, n as packFileProblem, ot as updateStatus, p as editCommands, pt as appendEmptyTurn, q as parseCommandsEdit, st as AuthoringSessions, t as MAX_PACK_TEXT, tt as findTargets, u as readAuthoredEntityDocument, ut as AgentSessions, v as readCommandsDocument, w as editWorldLore$1, x as readVariables, y as readDiceDocument, z as writeWorldTrigger } from "./pack-jail-KyZen_gy.js";
9
9
  import { i as atomicWriteSync, n as atomicWrite, r as atomicWriteJson } from "./access-5vtPAT3O.js";
10
- import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-B-HsLdb-.js";
11
- import { _ as pathTo, c as BranchError, d as recordPreset, f as switchPreset, g as childrenOf, h as START_SNAPSHOT, i as reflectionStatus, l as copyPreset, m as writeTimeline, o as TimelineError, p as readTimeline, u as presetStatus, v as snapshotOf } from "./reflection-2uzE3U-v.js";
12
- import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-B69AXtip.js";
13
- import { C as slug, T as uniqueKey, d as sceneImagePath, s as inheritImages, t as addToLibrary, u as referenceImagePath } from "./library-CnWOHwQl.js";
10
+ import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-KnqhN_Zv.js";
11
+ import { _ as pathTo, c as BranchError, d as recordPreset, f as switchPreset, g as childrenOf, h as START_SNAPSHOT, i as reflectionStatus, l as copyPreset, m as writeTimeline, o as TimelineError, p as readTimeline, u as presetStatus, v as snapshotOf } from "./reflection-CXS87Di3.js";
12
+ import { n as readPreset, r as selectPrompts, t as previewPreset } from "./preset-BO8iWQ-n.js";
13
+ import { D as uniqueKey, T as slug, a as updateImage, d as inheritImages, h as sceneImagePath, i as listGallery, m as referenceImagePath, o as addToLibrary, r as galleryFile } from "./gallery-CT5uj50b.js";
14
14
  import { o as FOLDER_ACCESS, r as InvalidFoldersError, t as StoryFoldersService } from "./service-mRKwpWjX.js";
15
15
  import { t as doctorChatSessionId } from "./doctor-chat-hL1a61hp.js";
16
- import { _ as API_PREFIX, a as packIds, c as describePack, d as packPath, f as readPack, l as isPackId, m as PACK_LIMITS, n as anyTab, o as syncWorldPacks, r as copyWorldPacks, s as worldPackStates, t as activePack, u as packFile } from "./packs-D9_N8kDF.js";
17
- import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-CAJkevKl.js";
18
- import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-D0h0X7Jy.js";
16
+ import { _ as API_PREFIX, a as packIds, c as describePack, d as packPath, f as readPack, l as isPackId, m as PACK_LIMITS, n as anyTab, o as syncWorldPacks, r as copyWorldPacks, s as worldPackStates, t as activePack, u as packFile } from "./packs-DU171pDX.js";
17
+ import { l as generateReferenceImage, n as interpretImage, p as uploadReferenceImage } from "./interpreter-Cz5qsuXk.js";
19
18
  import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
20
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";
21
20
  import { copyFileSync, cpSync, createReadStream, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
@@ -225,7 +224,7 @@ var PromptEditError = class extends Error {};
225
224
  const normal = (text) => text.replace(/\r\n/g, "\n").trimEnd();
226
225
  const VARIABLE = /\$\{([A-Za-z]+)\}/g;
227
226
  const variablesOf = (text) => [...new Set([...text.matchAll(VARIABLE)].map((match) => match[1]))];
228
- const ID$1 = /^[a-z0-9-]+(\/[a-z0-9-]+)*$/;
227
+ const ID$2 = /^[a-z0-9-]+(\/[a-z0-9-]+)*$/;
229
228
  /**
230
229
  * 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
231
230
  * 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
@@ -280,7 +279,7 @@ var PromptManager = class {
280
279
  };
281
280
  }
282
281
  shipped(id, language) {
283
- const file = ID$1.test(id) ? join(this.library.shipped, language, `${id}.md`) : void 0;
282
+ const file = ID$2.test(id) ? join(this.library.shipped, language, `${id}.md`) : void 0;
284
283
  if (file === void 0 || !LANGUAGE_FOLDER.test(language) || !existsSync(file)) throw new PromptEditError(`there is no shipped prompt "${id}" in "${language}"`);
285
284
  return readFileSync(file, "utf8");
286
285
  }
@@ -330,6 +329,280 @@ var AuthoringLanguages = class extends Service {
330
329
  return join(this.worldsDirectory(), ".authoring", `${encodeURIComponent(worldId)}.json`);
331
330
  }
332
331
  };
332
+ // src/host/worlds/checkpoints.ts
333
+ const CHECKPOINTS_FOLDER = ".checkpoints";
334
+ const FILES = "files";
335
+ const INFO = "checkpoint.json";
336
+ const RESTORED = "restored.json";
337
+ const ID$1 = /^\d{8}T\d{9}Z-[0-9a-f]{4}$/;
338
+ /** Not versioned: the pictures. Every dot entry at the top (the import's records, the checks, the trash, the checkpoints) is left out too. */
339
+ const LEFT_OUT$1 = /* @__PURE__ */ new Set(["images", "media"]);
340
+ /** A world larger than this (text and packs, not pictures) is not copied: a checkpoint is a safety net for authored text, not a backup of a library. */
341
+ const CHECKPOINT_MAX_BYTES = 67108864;
342
+ /** The longest file the agent may read back from a checkpoint in one call. */
343
+ const CHECKPOINT_READ_CHARS = 2e4;
344
+ var CheckpointError = class extends Error {};
345
+ var CheckpointNotFoundError = class extends CheckpointError {};
346
+ const checkpointsOf = (world) => join(world, CHECKPOINTS_FOLDER);
347
+ const folderOf$3 = (world, id) => join(checkpointsOf(world), id);
348
+ function validId(id) {
349
+ if (!ID$1.test(id)) throw new CheckpointNotFoundError(`there is no checkpoint "${id}"`);
350
+ return id;
351
+ }
352
+ const stamp$1 = () => (/* @__PURE__ */ new Date()).toISOString().replace(/[-:.]/g, "");
353
+ const leftOut = (top) => top.startsWith(".") || LEFT_OUT$1.has(top);
354
+ /** The world's files that a checkpoint keeps, by path with the hash of their content. Links are skipped. */
355
+ async function scan(world, dir = "", top = true) {
356
+ const manifest = {};
357
+ let bytes = 0;
358
+ for (const entry of await readdir(join(world, dir), { withFileTypes: true })) {
359
+ if (top && leftOut(entry.name)) continue;
360
+ const path = dir === "" ? entry.name : `${dir}/${entry.name}`;
361
+ if (entry.isDirectory()) {
362
+ const inner = await scan(world, path, false);
363
+ Object.assign(manifest, inner.manifest);
364
+ bytes += inner.bytes;
365
+ } else if (entry.isFile()) {
366
+ const data = await readFile(join(world, path));
367
+ manifest[path] = createHash("sha256").update(data).digest("hex");
368
+ bytes += data.length;
369
+ }
370
+ }
371
+ return {
372
+ manifest,
373
+ bytes
374
+ };
375
+ }
376
+ const same = (a, b) => {
377
+ const keys = Object.keys(a);
378
+ return keys.length === Object.keys(b).length && keys.every((key) => a[key] === b[key]);
379
+ };
380
+ async function readStored(world, id) {
381
+ try {
382
+ return JSON.parse(await readFile(join(folderOf$3(world, validId(id)), INFO), "utf8"));
383
+ } catch (error) {
384
+ if (error.code === "ENOENT") throw new CheckpointNotFoundError(`there is no checkpoint "${id}"`);
385
+ throw error;
386
+ }
387
+ }
388
+ const infoOf = ({ manifest: _manifest, ...info }) => info;
389
+ /** The checkpoints of a world, newest first. A folder that was cut short (no record) is not one. */
390
+ async function listCheckpoints(world) {
391
+ let names;
392
+ try {
393
+ names = await readdir(checkpointsOf(world));
394
+ } catch (error) {
395
+ if (error.code === "ENOENT") return [];
396
+ throw error;
397
+ }
398
+ const found = [];
399
+ for (const name of names.filter((each) => ID$1.test(each))) try {
400
+ found.push(infoOf(await readStored(world, name)));
401
+ } catch (error) {
402
+ if (!(error instanceof CheckpointNotFoundError)) throw error;
403
+ }
404
+ return found.sort((a, b) => a.id < b.id ? 1 : -1);
405
+ }
406
+ /**
407
+ * Copies the world's files into `<world>/.checkpoints/<id>/`. A world that is the same as its newest checkpoint is not copied again, except on request. Older checkpoints beyond `keep` are removed.
408
+ * @returns the checkpoint, and whether it was made now.
409
+ */
410
+ async function makeCheckpoint(world, request) {
411
+ const { manifest, bytes } = await scan(world);
412
+ if (bytes > 67108864) throw new CheckpointError(`the world's files are ${Math.round(bytes / 1024 / 1024)} MB, more than the ${CHECKPOINT_MAX_BYTES / 1024 / 1024} MB a checkpoint keeps`);
413
+ const latest = (await listCheckpoints(world))[0];
414
+ if (latest !== void 0 && request.reason !== "manual" && same((await readStored(world, latest.id)).manifest, manifest)) return {
415
+ checkpoint: latest,
416
+ made: false
417
+ };
418
+ const id = `${stamp$1()}-${randomBytes(2).toString("hex")}`;
419
+ const target = folderOf$3(world, id);
420
+ try {
421
+ for (const path of Object.keys(manifest)) {
422
+ const to = join(target, FILES, path);
423
+ await mkdir(dirname(to), { recursive: true });
424
+ await copyFile(join(world, path), to);
425
+ }
426
+ const info = {
427
+ id,
428
+ at: (/* @__PURE__ */ new Date()).toISOString(),
429
+ label: request.label.slice(0, 200),
430
+ reason: request.reason,
431
+ ...request.chat === void 0 ? {} : { chat: request.chat },
432
+ ...request.turn === void 0 ? {} : { turn: request.turn },
433
+ files: Object.keys(manifest).length,
434
+ bytes,
435
+ manifest
436
+ };
437
+ await mkdir(target, { recursive: true });
438
+ await atomicWriteJson(join(target, INFO), info);
439
+ await prune(world, request.keep);
440
+ return {
441
+ checkpoint: infoOf(info),
442
+ made: true
443
+ };
444
+ } catch (error) {
445
+ await rm(target, {
446
+ recursive: true,
447
+ force: true
448
+ });
449
+ throw error;
450
+ }
451
+ }
452
+ async function prune(world, keep) {
453
+ const all = await listCheckpoints(world);
454
+ for (const old of all.slice(Math.max(1, keep))) await rm(folderOf$3(world, old.id), {
455
+ recursive: true,
456
+ force: true
457
+ });
458
+ }
459
+ /** What differs between the world as it is and a checkpoint. */
460
+ async function diffCheckpoint(world, id) {
461
+ const stored = await readStored(world, id);
462
+ const { manifest } = await scan(world);
463
+ return {
464
+ changed: Object.keys(manifest).filter((path) => stored.manifest[path] !== void 0 && stored.manifest[path] !== manifest[path]).sort((a, b) => a.localeCompare(b)),
465
+ added: Object.keys(manifest).filter((path) => stored.manifest[path] === void 0).sort((a, b) => a.localeCompare(b)),
466
+ removed: Object.keys(stored.manifest).filter((path) => manifest[path] === void 0).sort((a, b) => a.localeCompare(b))
467
+ };
468
+ }
469
+ /** One file as the checkpoint has it. The path is one the checkpoint holds, never a way out of it. */
470
+ async function readCheckpointFile(world, id, path) {
471
+ const stored = await readStored(world, id);
472
+ const clean = normalize(path).split(sep).join("/");
473
+ if (clean.startsWith("..") || clean.startsWith("/") || stored.manifest[clean] === void 0) throw new CheckpointNotFoundError(`checkpoint ${id} has no file "${path}"`);
474
+ const text = await readFile(join(folderOf$3(world, id), FILES, clean), "utf8");
475
+ return {
476
+ path: clean,
477
+ text: text.slice(0, CHECKPOINT_READ_CHARS),
478
+ of: text.length,
479
+ truncated: text.length > CHECKPOINT_READ_CHARS
480
+ };
481
+ }
482
+ /** Puts the world's files back as a checkpoint has them. What is there now is first kept as a checkpoint of its own and moved to the trash, so a restore can be undone. */
483
+ async function restoreCheckpoint(world, id, keep) {
484
+ const stored = await readStored(world, id);
485
+ for (const path of Object.keys(stored.manifest)) await stat(join(folderOf$3(world, id), FILES, path)).catch(() => {
486
+ throw new CheckpointError(`checkpoint ${id} is incomplete: ${path} is missing`);
487
+ });
488
+ const before = (await makeCheckpoint(world, {
489
+ label: `Before restoring “${stored.label}”`,
490
+ reason: "before-restore",
491
+ keep: keep + 1
492
+ })).checkpoint;
493
+ const trash = join(world, ".trash", `restore-${stamp$1()}`);
494
+ const moved = [];
495
+ const placed = [];
496
+ try {
497
+ await mkdir(trash, { recursive: true });
498
+ for (const entry of await readdir(world)) {
499
+ if (leftOut(entry)) continue;
500
+ await rename(join(world, entry), join(trash, entry));
501
+ moved.push(entry);
502
+ }
503
+ for (const path of Object.keys(stored.manifest)) {
504
+ const to = join(world, path);
505
+ await mkdir(dirname(to), { recursive: true });
506
+ await copyFile(join(folderOf$3(world, id), FILES, path), to);
507
+ placed.push(path.split("/")[0]);
508
+ }
509
+ await atomicWriteJson(join(checkpointsOf(world), RESTORED), {
510
+ at: (/* @__PURE__ */ new Date()).toISOString(),
511
+ checkpoint: id,
512
+ label: stored.label
513
+ });
514
+ await prune(world, keep);
515
+ } catch (error) {
516
+ for (const top of new Set(placed)) await rm(join(world, top), {
517
+ recursive: true,
518
+ force: true
519
+ });
520
+ for (const entry of moved) await rename(join(trash, entry), join(world, entry)).catch(() => void 0);
521
+ throw error;
522
+ }
523
+ return {
524
+ restored: infoOf(stored),
525
+ before
526
+ };
527
+ }
528
+ /** When and to what the world was last restored by the person, so that an authoring chat can be told. */
529
+ async function lastRestore(world) {
530
+ try {
531
+ return JSON.parse(await readFile(join(checkpointsOf(world), RESTORED), "utf8"));
532
+ } catch (error) {
533
+ if (error.code === "ENOENT") return void 0;
534
+ throw error;
535
+ }
536
+ }
537
+ // src/host/worlds/checkpoint-service.ts
538
+ /** A restore was asked for while the world's authoring assistant is working on it. */
539
+ var CheckpointBusyError = class extends CheckpointError {};
540
+ /** The checkpoints of the worlds, by world id: made at the first edit of an authoring turn or on request, read back, compared and restored. */
541
+ var WorldCheckpoints = class extends Service {
542
+ kept;
543
+ problem;
544
+ taken = /* @__PURE__ */ new Map();
545
+ told = /* @__PURE__ */ new Map();
546
+ constructor(ctx, kept, problem) {
547
+ super(ctx, "roleplayCheckpoints");
548
+ this.kept = kept;
549
+ this.problem = problem;
550
+ }
551
+ async directory(worldId) {
552
+ const record = await this.ctx.roleplayWorlds.find(worldId);
553
+ if (record === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
554
+ return record.directory;
555
+ }
556
+ async list(worldId) {
557
+ return await listCheckpoints(await this.directory(worldId));
558
+ }
559
+ async make(worldId, label) {
560
+ return (await makeCheckpoint(await this.directory(worldId), {
561
+ label: label.trim() === "" ? "Checkpoint" : label.trim(),
562
+ reason: "manual",
563
+ keep: this.kept()
564
+ })).checkpoint;
565
+ }
566
+ async diff(worldId, id) {
567
+ return await diffCheckpoint(await this.directory(worldId), id);
568
+ }
569
+ async read(worldId, id, path) {
570
+ return await readCheckpointFile(await this.directory(worldId), id, path);
571
+ }
572
+ /** Puts a world back as a checkpoint has it; refused while its authoring assistant is in the middle of a turn. */
573
+ async restore(worldId, id, running) {
574
+ if (running) throw new CheckpointBusyError("the authoring assistant is working on this world: wait for it to finish, then restore");
575
+ const outcome = await restoreCheckpoint(await this.directory(worldId), id, this.kept());
576
+ await this.ctx.roleplayWorlds.list({ refresh: true });
577
+ return outcome;
578
+ }
579
+ /** The first edit of an authoring chat's turn: the world as it is, before the turn changes it. A checkpoint that cannot be made never stops the edit. */
580
+ async beforeEdit(chat, turn, tool) {
581
+ const worldId = authoredWorldOf(chat);
582
+ if (worldId === void 0 || this.taken.get(chat) === turn) return;
583
+ this.taken.set(chat, turn);
584
+ try {
585
+ await makeCheckpoint(await this.directory(worldId), {
586
+ label: `Before the edits of turn ${turn} (${tool})`,
587
+ reason: "turn",
588
+ chat,
589
+ turn,
590
+ keep: this.kept()
591
+ });
592
+ } catch (error) {
593
+ this.problem(`could not make a checkpoint of world ${worldId}: ${error instanceof Error ? error.message : String(error)}`);
594
+ }
595
+ }
596
+ /** What a chat has not been told yet about the person restoring its world. */
597
+ async unannouncedRestore(chat) {
598
+ const worldId = authoredWorldOf(chat);
599
+ if (worldId === void 0) return void 0;
600
+ const restored = await lastRestore(await this.directory(worldId));
601
+ if (restored === void 0 || this.told.get(chat) === restored.at) return void 0;
602
+ this.told.set(chat, restored.at);
603
+ return restored;
604
+ }
605
+ };
333
606
  // src/host/worlds/draft.ts
334
607
  /** Whether the world is an import that was written but would not start yet: its import state (kept in the world's `.import` folder) says it is being repaired. */
335
608
  async function isDraftWorld(directory) {
@@ -573,6 +846,7 @@ function speakingOf$1(timeline) {
573
846
  length: 0
574
847
  };
575
848
  for (const node of pathTo(timeline, timeline.head)) for (const segment of node.output?.segments ?? []) {
849
+ if (segment.type === "image") continue;
576
850
  if (segment.type === "narration") {
577
851
  narration.passages += 1;
578
852
  narration.length += lengthOf(segment.text);
@@ -2930,14 +3204,14 @@ var InterfaceService = class {
2930
3204
  return pathTo(timeline, timeline.head).filter((node) => node.output !== void 0).map((node, index) => ({
2931
3205
  turn: index + 1,
2932
3206
  player: node.player,
2933
- segments: (node.output?.segments ?? []).map((segment) => segment.type === "utterance" ? {
3207
+ segments: (node.output?.segments ?? []).flatMap((segment) => segment.type === "image" ? [] : [segment.type === "utterance" ? {
2934
3208
  type: "utterance",
2935
3209
  name: segment.name,
2936
3210
  text: segment.text
2937
3211
  } : {
2938
3212
  type: "narration",
2939
3213
  text: segment.text
2940
- }),
3214
+ }]),
2941
3215
  ...node.output?.ooc === void 0 ? {} : { note: node.output.ooc.note }
2942
3216
  })).slice(-Math.min(Math.max(1, limit), PACK_LIMITS.history.max));
2943
3217
  }
@@ -3277,8 +3551,15 @@ function languageField(value) {
3277
3551
  }
3278
3552
  }
3279
3553
  // src/host/http/routes/worlds.ts
3554
+ /** Answers a failed checkpoint request with the status that says what was wrong. */
3555
+ function checkpointFailure(res, error) {
3556
+ if (error instanceof WorldNotFoundError || error instanceof CheckpointNotFoundError) return sendError(res, 404, error.message);
3557
+ if (error instanceof CheckpointBusyError) return sendError(res, 409, error.message);
3558
+ if (error instanceof CheckpointError) return sendError(res, 422, error.message);
3559
+ throw error;
3560
+ }
3280
3561
  /** The routes of the API for worlds. */
3281
- function worldsRoutes({ worlds, createWorld, starter, authorWorld, sayToAuthor, authoringStatus, chatStatus, forgetAuthoring, translation, worldCharacters, avatars, playtest }) {
3562
+ function worldsRoutes({ worlds, createWorld, starter, authorWorld, sayToAuthor, authoringStatus, chatStatus, checkpoints, forgetAuthoring, translation, worldCharacters, avatars, playtest }) {
3282
3563
  return {
3283
3564
  "/worlds": {
3284
3565
  GET: async (_req, res) => {
@@ -3366,6 +3647,41 @@ function worldsRoutes({ worlds, createWorld, starter, authorWorld, sayToAuthor,
3366
3647
  throw error;
3367
3648
  }
3368
3649
  } },
3650
+ "/worlds/checkpoints": {
3651
+ GET: async (_req, res, url) => {
3652
+ try {
3653
+ sendJson(res, 200, { checkpoints: await checkpoints.list(url.searchParams.get("id") ?? "") });
3654
+ } catch (error) {
3655
+ return checkpointFailure(res, error);
3656
+ }
3657
+ },
3658
+ POST: async (req, res, url) => {
3659
+ const body = await readJsonBody(req);
3660
+ if (body.label !== void 0 && typeof body.label !== "string") return sendError(res, 400, "label must be text");
3661
+ try {
3662
+ sendJson(res, 201, await checkpoints.make(url.searchParams.get("id") ?? "", body.label ?? ""));
3663
+ } catch (error) {
3664
+ return checkpointFailure(res, error);
3665
+ }
3666
+ }
3667
+ },
3668
+ "/worlds/checkpoints/diff": { GET: async (_req, res, url) => {
3669
+ try {
3670
+ sendJson(res, 200, await checkpoints.diff(url.searchParams.get("id") ?? "", url.searchParams.get("checkpoint") ?? ""));
3671
+ } catch (error) {
3672
+ return checkpointFailure(res, error);
3673
+ }
3674
+ } },
3675
+ "/worlds/checkpoints/restore": { POST: async (req, res, url) => {
3676
+ const body = await readJsonBody(req);
3677
+ if (typeof body.checkpoint !== "string") return sendError(res, 400, "checkpoint must be text");
3678
+ const id = url.searchParams.get("id") ?? "";
3679
+ try {
3680
+ sendJson(res, 200, await checkpoints.restore(id, body.checkpoint, (await authoringStatus(id)).running));
3681
+ } catch (error) {
3682
+ return checkpointFailure(res, error);
3683
+ }
3684
+ } },
3369
3685
  "/worlds/language": { GET: async (_req, res, url) => {
3370
3686
  try {
3371
3687
  const id = url.searchParams.get("id") ?? "";
@@ -4243,6 +4559,13 @@ function worldFilesRoutes({ worldFiles, worldEditor, sessions }) {
4243
4559
  }
4244
4560
  }
4245
4561
  },
4562
+ "/worlds/gallery/describe": { POST: async (_req, res, url) => {
4563
+ try {
4564
+ sendJson(res, 200, await worldFiles.describeImage(url.searchParams.get("id") ?? "", url.searchParams.get("path") ?? ""));
4565
+ } catch (error) {
4566
+ return sendError(res, error instanceof WorldNotFoundError ? 404 : 409, error instanceof Error ? error.message : String(error));
4567
+ }
4568
+ } },
4246
4569
  "/worlds/gallery/upload": { POST: async (req, res, url) => {
4247
4570
  const name = decodeURIComponent(String(req.headers["x-file-name"] ?? url.searchParams.get("name") ?? "image"));
4248
4571
  try {
@@ -6801,6 +7124,25 @@ async function addAvatarsToWorld(avatars, world, keys, locations) {
6801
7124
  }
6802
7125
  return brought.map((entry) => entry.id);
6803
7126
  }
7127
+ // src/host/images/world-describe.ts
7128
+ /** Describes one picture of a world's library with a model that reads images, and writes the answer into the picture's file. */
7129
+ async function describeWorldImage(deps, path) {
7130
+ if (deps.attachments === void 0) throw new Error("this DSH profile has no attachment service, so a picture cannot be shown to a model");
7131
+ if (deps.parent === void 0) throw new Error("the world's authoring chat is not running: open it with Author with AI once, then describe the picture again");
7132
+ const settings = DEFAULT_SETTINGS;
7133
+ return await interpretImage({
7134
+ parent: deps.parent,
7135
+ signal: new AbortController().signal,
7136
+ attachments: deps.attachments,
7137
+ subjects: deps.subjects,
7138
+ sessionFolder: deps.directory,
7139
+ path,
7140
+ language: deps.language,
7141
+ model: settings.images.interpreterModel,
7142
+ captioner: settings.images.captioner,
7143
+ sampling: childSampling(settings, "records")
7144
+ });
7145
+ }
6804
7146
  // src/host/agent/history.ts
6805
7147
  /** The unknown seq of a turn that is not in the log. */
6806
7148
  const NOT_IN_LOG = -1;
@@ -7111,6 +7453,13 @@ function speakingOf(world, parts, characters, where) {
7111
7453
  const problems = [];
7112
7454
  const segments = parts.map((segment) => {
7113
7455
  if (segment.type === "narration") return segment;
7456
+ if (segment.type === "image") {
7457
+ if (!existsSync(join(world.directory, "images", segment.path))) problems.push({
7458
+ path: join(world.directory, WORLD_FILE_NAME),
7459
+ message: `${where}: the picture "${segment.path}" is not in the world's images`
7460
+ });
7461
+ return segment;
7462
+ }
7114
7463
  const speaker = characters.find((character) => character.id === segment.character);
7115
7464
  if (speaker === void 0) problems.push({
7116
7465
  path: join(world.directory, WORLD_FILE_NAME),
@@ -7200,7 +7549,7 @@ async function restoreSession(deps, id) {
7200
7549
  writeStatus(folder, {});
7201
7550
  }
7202
7551
  // src/shared/transcript.ts
7203
- const segmentLine = (segment) => segment.type === "utterance" ? `**${segment.name}:** “${segment.text}”` : segment.text;
7552
+ const segmentLine = (segment) => segment.type === "image" ? `*(picture: ${segment.path})*` : segment.type === "utterance" ? `**${segment.name}:** “${segment.text}”` : segment.text;
7204
7553
  function outputLines(output, annotated) {
7205
7554
  if (output === void 0) return ["*(nothing was delivered)*"];
7206
7555
  const lines = output.segments.map(segmentLine);
@@ -9786,6 +10135,7 @@ const Config = z.object({
9786
10135
  }).default({ ...DEFAULT_OFFLOAD }).volatile(),
9787
10136
  catalogueMaxBytes: z.number().min(1024).default(268435456).volatile(),
9788
10137
  catalogueTrashDays: z.number().min(0).default(30).volatile(),
10138
+ worldCheckpointsKept: z.number().min(1).max(500).default(30).volatile(),
9789
10139
  autonomyTickSeconds: z.number().min(0).max(3600).default(30).volatile(),
9790
10140
  importMaxUploadBytes: z.number().min(1024).default(104857600).volatile(),
9791
10141
  importConcurrency: z.number().min(1).max(16).default(4).volatile(),
@@ -9850,6 +10200,9 @@ function apply(ctx, config) {
9850
10200
  installFirstPartyPacks(root.path);
9851
10201
  const languages = new AuthoringLanguages(ctx, () => join(root.path, "worlds"));
9852
10202
  const authoringTools = new AuthoringTools(ctx, () => config.authoringTools.get());
10203
+ const checkpoints = new WorldCheckpoints(ctx, () => config.worldCheckpointsKept.get(), (message) => {
10204
+ ctx.logger.warn(message);
10205
+ });
9853
10206
  const agent = new AgentSessions(agentServicesOf(ctx), () => root.path);
9854
10207
  const autonomy = new AutonomyTicker({
9855
10208
  sessions: () => listSessions({
@@ -10026,10 +10379,14 @@ function apply(ctx, config) {
10026
10379
  purgeChat
10027
10380
  }, id),
10028
10381
  rebuild: async (id) => {
10029
- if (await agent.has(id)) await openSession({
10030
- ...deps,
10031
- replaceChat: (chat, title, events) => agent.replace(chat, title, events, purgeChat)
10032
- }, id, { rebuild: true });
10382
+ try {
10383
+ await openSession({
10384
+ ...deps,
10385
+ replaceChat: (chat, title, events) => agent.replace(chat, title, events, purgeChat)
10386
+ }, id, { rebuild: true });
10387
+ } catch (error) {
10388
+ if (!(error instanceof SessionArchivedError)) throw error;
10389
+ }
10033
10390
  }
10034
10391
  });
10035
10392
  prompts.frozen = () => sync.gate.isLocked("prompts");
@@ -10123,6 +10480,7 @@ function apply(ctx, config) {
10123
10480
  return chatStatus(authoringChatSessionId(world.summary.id));
10124
10481
  },
10125
10482
  chatStatus,
10483
+ checkpoints,
10126
10484
  forgetAuthoring: async (worldId) => {
10127
10485
  const world = await worlds.find(worldId);
10128
10486
  if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
@@ -10258,7 +10616,32 @@ function apply(ctx, config) {
10258
10616
  }),
10259
10617
  galleryFile: async (worldId, path) => await galleryFile((await editableWorld(worlds, worldId, root.path)).directory, path),
10260
10618
  uploadImage: async (worldId, name, bytes) => await addToLibrary((await editableWorld(worlds, worldId, root.path)).directory, bytes, name),
10261
- updateImage: async (worldId, path, update) => await updateImage((await editableWorld(worlds, worldId, root.path)).directory, path, update)
10619
+ updateImage: async (worldId, path, update) => await updateImage((await editableWorld(worlds, worldId, root.path)).directory, path, update),
10620
+ describeImage: async (worldId, path) => {
10621
+ const world = await editableWorld(worlds, worldId, root.path);
10622
+ const state = await readWorldEditor(world);
10623
+ const chat = await authoring.ensure(world.id, (await worlds.find(world.id))?.summary.name ?? world.id);
10624
+ return await describeWorldImage({
10625
+ directory: world.directory,
10626
+ parent: ctx.get("agents")?.get(SessionId(chat)),
10627
+ attachments: ctx.get("attachments"),
10628
+ language: languages.get(world.id),
10629
+ subjects: [
10630
+ ...state.characters.map((entry) => ({
10631
+ kind: "character",
10632
+ name: entry.name
10633
+ })),
10634
+ ...state.places.map((entry) => ({
10635
+ kind: "location",
10636
+ name: entry.name
10637
+ })),
10638
+ ...state.things.map((entry) => ({
10639
+ kind: "item",
10640
+ name: entry.name
10641
+ }))
10642
+ ]
10643
+ }, path);
10644
+ }
10262
10645
  },
10263
10646
  worldEditor: {
10264
10647
  read: async (worldId) => await readWorldEditor(await editableWorld(worlds, worldId, root.path)),