@dsh-agentic-roleplay/core 0.9.0 → 0.10.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 (47) hide show
  1. package/lib/{access-CfQWbNZP.js → access-CXtaZNbx.js} +50 -2
  2. package/lib/{authoring-tools-CdHlvx32.js → authoring-tools-B4mEdKp_.js} +1349 -604
  3. package/lib/authoring.js +23 -19
  4. package/lib/{child-lYYeOwl2.js → child-Dtv76jNx.js} +116 -11
  5. package/lib/client.js +2810 -795
  6. package/lib/client.js.map +1 -1
  7. package/lib/compaction.js +3 -3
  8. package/lib/doctor.js +3 -3
  9. package/lib/{gallery-BKh7eu80.js → gallery-BZJleAeH.js} +5 -9
  10. package/lib/{generator-DdZ1-sgv.js → generator-Cg6CQc5S.js} +2 -2
  11. package/lib/helper.js +1 -1
  12. package/lib/{hooks-CcQj_dJo.js → hooks-DTjHWTfx.js} +168 -28
  13. package/lib/images.js +4 -4
  14. package/lib/index.js +362 -33
  15. package/lib/{library-QFL6Z_Nr.js → library-GIlrkOim.js} +9 -14
  16. package/lib/{lorebook-author-tools-DWBnYo1E.js → lorebook-author-tools-BCFFJSle.js} +6 -6
  17. package/lib/lorebook-authoring.js +4 -4
  18. package/lib/{narration-CjB_KwwY.js → narration-BVzew4-K.js} +7 -52
  19. package/lib/orchestration.js +155 -10
  20. package/lib/{pack-jail-BMy6NcCY.js → pack-jail-hsNQNTOf.js} +25 -15
  21. package/lib/{packs-BREPSfHy.js → packs-UpK_cvI4.js} +2 -2
  22. package/lib/{presenter-agent-B49-_iUm.js → presenter-agent-DZOgBOR9.js} +12 -17
  23. package/lib/{preset-BqgY1Tz4.js → preset-Cyoj1ZWa.js} +4 -4
  24. package/lib/{preset-author-tools-BB_Dcv2o.js → preset-author-tools-RSta6pHK.js} +6 -6
  25. package/lib/preset-authoring.js +5 -5
  26. package/lib/{presets-Bwnrx7p0.js → presets-CvpsW_10.js} +17 -9
  27. package/lib/{reflection-CUWG-6Qg.js → reflection-0qTvw2It.js} +53 -26
  28. package/lib/{turn-guard-Bb8Ew-1z.js → turn-guard-BzNeGNnc.js} +3 -3
  29. package/package.json +2 -2
  30. package/prompts/en/checks/conflict.md +1 -0
  31. package/prompts/en/checks/decide-conflict.md +1 -0
  32. package/prompts/en/checks/decide-covered.md +1 -0
  33. package/prompts/en/checks/decide-opening.md +1 -0
  34. package/prompts/en/checks/decide-same-thing.md +1 -0
  35. package/prompts/en/checks/decide-same-value.md +1 -0
  36. package/prompts/en/checks/decide-sheet.md +1 -1
  37. package/prompts/en/checks/fidelity.md +1 -0
  38. package/prompts/en/checks/notice.md +2 -2
  39. package/prompts/zh/checks/conflict.md +1 -0
  40. package/prompts/zh/checks/decide-conflict.md +1 -0
  41. package/prompts/zh/checks/decide-covered.md +1 -0
  42. package/prompts/zh/checks/decide-opening.md +1 -0
  43. package/prompts/zh/checks/decide-same-thing.md +1 -0
  44. package/prompts/zh/checks/decide-same-value.md +1 -0
  45. package/prompts/zh/checks/decide-sheet.md +1 -1
  46. package/prompts/zh/checks/fidelity.md +1 -0
  47. package/prompts/zh/checks/notice.md +2 -2
@@ -1,8 +1,6 @@
1
- import "./access-CfQWbNZP.js";
2
- import { basename, dirname, join } from "node:path";
3
- import { chmodSync, existsSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
4
- import { randomUUID } from "node:crypto";
5
- import { chmod, mkdir, rename, rm, stat, writeFile } from "node:fs/promises";
1
+ import { i as atomicWriteSync } from "./access-CXtaZNbx.js";
2
+ import { join } from "node:path";
3
+ import { existsSync, readFileSync, statSync } from "node:fs";
6
4
  // ../dsh-roleplay-model/src/clock.ts
7
5
  /**
8
6
  * How the story's time passes: `simulated` moves only when the story does (the game master says how
@@ -319,50 +317,6 @@ function parseSettings(value) {
319
317
  value: parsed
320
318
  };
321
319
  }
322
- // src/host/atomic-write.ts
323
- /**
324
- * Replaces a file in one step: the data goes to a temporary file in the same folder and is renamed over the file, so an interruption leaves the old file or the new one,
325
- * never half of either. Every writer of a file someone else may read at the same time goes through here.
326
- */
327
- async function atomicWrite(file, data, options = {}) {
328
- if (options.createDirectory === true) await mkdir(dirname(file), { recursive: true });
329
- const temporary = join(dirname(file), `.${basename(file)}.${process.pid}.${randomUUID()}.tmp`);
330
- try {
331
- const mode = options.mode ?? await stat(file).then((value) => value.mode & 511, (error) => {
332
- if (error.code === "ENOENT") return 420;
333
- throw error;
334
- });
335
- await writeFile(temporary, data, { mode });
336
- await chmod(temporary, mode);
337
- await rename(temporary, file);
338
- } catch (error) {
339
- await rm(temporary, { force: true });
340
- throw error;
341
- }
342
- }
343
- /** A JSON file written the same way, with the indentation given (none by default) and a final newline when it is indented. */
344
- async function atomicWriteJson(file, value, options = {}) {
345
- const { indent, ...rest } = options;
346
- await atomicWrite(file, indent === void 0 ? JSON.stringify(value) : `${JSON.stringify(value, null, indent)}\n`, rest);
347
- }
348
- /** The synchronous form, for the few writers that cannot wait (the chat settings, read at every step). */
349
- function atomicWriteSync(file, data) {
350
- const temporary = join(dirname(file), `.${basename(file)}.${process.pid}.${randomUUID()}.tmp`);
351
- try {
352
- let mode = 420;
353
- try {
354
- mode = statSync(file).mode & 511;
355
- } catch (error) {
356
- if (error.code !== "ENOENT") throw error;
357
- }
358
- writeFileSync(temporary, data, { mode });
359
- chmodSync(temporary, mode);
360
- renameSync(temporary, file);
361
- } catch (error) {
362
- rmSync(temporary, { force: true });
363
- throw error;
364
- }
365
- }
366
320
  // src/host/sessions/settings.ts
367
321
  const SETTINGS_FILE = "settings.json";
368
322
  const known = /* @__PURE__ */ new Map();
@@ -406,7 +360,8 @@ function readSettings(folder) {
406
360
  function writeSettings(folder, value) {
407
361
  const parsed = parseSettings(value);
408
362
  if (!parsed.ok) throw new InvalidSettingsError(parsed.problems);
409
- atomicWriteSync(join(folder, SETTINGS_FILE), `${JSON.stringify(parsed.value, null, 2)}\n`);
363
+ const file = join(folder, SETTINGS_FILE);
364
+ atomicWriteSync(file, `${JSON.stringify(parsed.value, null, 2)}\n`);
410
365
  known.delete(folder);
411
366
  return parsed.value;
412
367
  }
@@ -494,6 +449,6 @@ function decodeOutput(text) {
494
449
  return;
495
450
  }
496
451
  }
497
- export { DECISION_SITES as _, liveSettings as a, writeSettings as c, DEFAULT_SETTINGS as d, SETTINGS_SPEC as f, rulesOf as g, WORLD_RULES_KEY as h, InvalidSettingsError as i, atomicWrite as l, parseSwitchboard as m, encodeOutput as n, readSettings as o, parseSettings as p, encodePreview as r, useChildReasoning as s, decodeOutput as t, atomicWriteJson as u, GATE_SITES as v, emptyStats as y };
452
+ export { emptyStats as _, liveSettings as a, writeSettings as c, parseSettings as d, parseSwitchboard as f, GATE_SITES as g, DECISION_SITES as h, InvalidSettingsError as i, DEFAULT_SETTINGS as l, rulesOf as m, encodeOutput as n, readSettings as o, WORLD_RULES_KEY as p, encodePreview as r, useChildReasoning as s, decodeOutput as t, SETTINGS_SPEC as u };
498
453
 
499
- //# sourceMappingURL=narration-CjB_KwwY.js.map
454
+ //# sourceMappingURL=narration-BVzew4-K.js.map
@@ -1,14 +1,14 @@
1
- import { a as chatSessionId, o as roleplaySessionOf, t as promptFor } from "./access-CfQWbNZP.js";
2
- import { D as describeWhen, G as commandsOf, O as zoneOf, R as wrongLanguage, T as ClockError, U as COMMANDS_KEY, W as commandFlagKey, c as record, f as MAX_OOC_ANSWER, k as RESULTS, l as characterRunner, mt as AUTHORING_NEEDS, n as installHooks, o as PREVIEW_TOOL, ot as shippedText, p as storesOf, r as externalGiven, s as createTools$1, u as toolEnabled, ut as ReflectionRefusedError, v as readVerdicts, y as writeVerdicts } from "./hooks-CcQj_dJo.js";
3
- import { a as childTrace, c as runChild, h as currentTurn, n as childModel, r as childSampling, v as estimateAnswer, y as tokensOf } from "./child-lYYeOwl2.js";
4
- import { _ as referent, a as whereabouts, g as sameWords, n as memoryReflector, r as recordFailure, s as Timelines, t as dueReflection } from "./reflection-CUWG-6Qg.js";
5
- import { B as noAt, H as yesAt, I as announceProblem, L as askYesNo, Rt as INTENT_STATUSES, V as routeVerdicts, m as STANDING_PROMPT, z as modeFor } from "./presets-Bwnrx7p0.js";
1
+ import { c as chatSessionId, l as roleplaySessionOf, t as promptFor } from "./access-CXtaZNbx.js";
2
+ import { A as RESULTS, E as ClockError, G as commandFlagKey, K as commandsOf, O as describeWhen, W as COMMANDS_KEY, b as writeVerdicts, c as record, dt as ReflectionRefusedError, f as MAX_OOC_ANSWER, ht as AUTHORING_NEEDS, k as zoneOf, l as characterRunner, n as installHooks, o as PREVIEW_TOOL, p as storesOf, r as externalGiven, s as createTools$1, st as shippedText, u as toolEnabled, y as readVerdicts, z as wrongLanguage } from "./hooks-DTjHWTfx.js";
3
+ import { S as tokensOf, a as childTrace, c as runChild, n as childModel, r as childSampling, v as currentTurn, x as estimateAnswer } from "./child-Dtv76jNx.js";
4
+ import { _ as referent, a as whereabouts, g as sameWords, n as memoryReflector, r as recordFailure, s as Timelines, t as dueReflection } from "./reflection-0qTvw2It.js";
5
+ import { B as noAt, H as yesAt, I as announceProblem, L as askYesNo, Rt as INTENT_STATUSES, V as routeVerdicts, m as STANDING_PROMPT, z as modeFor } from "./presets-CvpsW_10.js";
6
6
  import { i as translator, r as languageOf } from "./text-CbGQhK1-.js";
7
- import { a as liveSettings, n as encodeOutput, v as GATE_SITES } from "./narration-CjB_KwwY.js";
8
- import { S as slug, t as addToLibrary, w as uniqueKey } from "./library-QFL6Z_Nr.js";
9
- import { _ as API_PREFIX } from "./packs-BREPSfHy.js";
10
- import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-BKh7eu80.js";
11
- import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-B49-_iUm.js";
7
+ import { a as liveSettings, g as GATE_SITES, n as encodeOutput } from "./narration-BVzew4-K.js";
8
+ import { C as slug, T as uniqueKey, t as addToLibrary } from "./library-GIlrkOim.js";
9
+ import { _ as API_PREFIX } from "./packs-UpK_cvI4.js";
10
+ import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-BZJleAeH.js";
11
+ import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-DZOgBOR9.js";
12
12
  import { join } from "node:path";
13
13
  import { existsSync } from "node:fs";
14
14
  import { readdir } from "node:fs/promises";
@@ -1777,6 +1777,89 @@ var AfterTurnJobs = class {
1777
1777
  }));
1778
1778
  }
1779
1779
  };
1780
+ // src/host/diagnostics/access.ts
1781
+ const MAX_NAMES = 12;
1782
+ const unknown = (all, known, name) => all.map(name).filter((entry) => !known.has(entry));
1783
+ /**
1784
+ * What a character was given for an activation, counted by kind, and what the story holds that it was not given: the people, places, things, ways, groups and background it has
1785
+ * no knowledge of, hidden things where it stands, and the events it took no part in. A missing edge means not knowing, so each count is what the world has less what the character knows.
1786
+ * The names behind the counts are what the character must not know, and are kept only when asked for.
1787
+ */
1788
+ function accessOf(story, request, withNames) {
1789
+ const { member, knowledge, memories = [], relationships = [], carrying = [], cues = [], affiliations = [] } = request;
1790
+ const known = knowledge ?? {
1791
+ characters: [],
1792
+ factions: [],
1793
+ locations: [],
1794
+ items: [],
1795
+ routes: [],
1796
+ lore: []
1797
+ };
1798
+ const here = /* @__PURE__ */ new Set([
1799
+ member.key,
1800
+ member.character.name,
1801
+ ...(request.place?.here ?? request.cast).map((entry) => entry.character.name)
1802
+ ]);
1803
+ const people = unknown(story.characters.list(), /* @__PURE__ */ new Set([...known.characters, ...here]), (character) => character.name);
1804
+ const places = unknown(story.locations.list(), new Set(known.locations), (place) => place.name);
1805
+ const seenThings = /* @__PURE__ */ new Set([
1806
+ ...known.items,
1807
+ ...carrying.map((item) => item.name),
1808
+ ...(request.place?.items ?? []).map((item) => item.name)
1809
+ ]);
1810
+ const things = unknown(story.items.list().filter((item) => !item.hidden), seenThings, (item) => item.name);
1811
+ const factions = unknown(story.factions.list(), /* @__PURE__ */ new Set([...known.factions, ...affiliations.map((entry) => entry.name)]), (faction) => faction.name);
1812
+ const lore = unknown(story.lore.list(), new Set(known.lore), (entry) => entry.title);
1813
+ const allExits = story.locations.allExits().length;
1814
+ const placeId = member.place?.location.id;
1815
+ const hidden = placeId === void 0 ? [] : story.items.contents({
1816
+ kind: "location",
1817
+ id: placeId
1818
+ }).filter((entry) => entry.item.hidden).map((entry) => entry.item.name);
1819
+ const events = Math.max(0, story.events.list().length - story.events.perceivedBy(member.character.id).length);
1820
+ const names = {
1821
+ people,
1822
+ places,
1823
+ things,
1824
+ factions,
1825
+ lore
1826
+ };
1827
+ return {
1828
+ character: member.character.name,
1829
+ attempt: request.attempt,
1830
+ given: {
1831
+ people: known.characters.length,
1832
+ places: known.locations.length,
1833
+ things: known.items.length,
1834
+ routes: known.routes.length,
1835
+ factions: known.factions.length,
1836
+ lore: known.lore.length,
1837
+ memories: {
1838
+ clear: memories.filter((memory) => memory.clarity === "clear").length,
1839
+ faded: memories.filter((memory) => memory.clarity === "faded").length,
1840
+ vague: memories.filter((memory) => memory.clarity === "vague").length
1841
+ },
1842
+ relationships: relationships.length,
1843
+ present: Math.max(0, (request.place?.here ?? request.cast).length - 1),
1844
+ carrying: carrying.length,
1845
+ cues: cues.length
1846
+ },
1847
+ withheld: {
1848
+ people: people.length,
1849
+ places: places.length,
1850
+ things: things.length,
1851
+ routes: Math.max(0, allExits - known.routes.length),
1852
+ factions: factions.length,
1853
+ lore: lore.length,
1854
+ hidden: hidden.length,
1855
+ events
1856
+ },
1857
+ ...withNames ? { names: Object.fromEntries(Object.entries({
1858
+ ...names,
1859
+ things: [...things, ...hidden.map((name) => `${name} (hidden)`)]
1860
+ }).filter(([, list]) => list.length > 0).map(([kind, list]) => [kind, list.slice(0, MAX_NAMES)])) } : {}
1861
+ };
1862
+ }
1780
1863
  // src/host/orchestration/turn-rules.ts
1781
1864
  /** Whether the game master still has to judge the player's action. */
1782
1865
  function judgeDue(state) {
@@ -2008,6 +2091,12 @@ async function askCharacters(deps, owner, number, keys, cast, state, run, signal
2008
2091
  commitment: previous.commitment
2009
2092
  } }
2010
2093
  };
2094
+ if (store !== void 0) try {
2095
+ const access = accessOf(store.story, request, store.settings().diagnostics.keepRuns);
2096
+ store.recordTrace?.(owner.turn, {}, (current) => ({ access: [...current.access ?? [], access].slice(-40) }));
2097
+ } catch (error) {
2098
+ deps.problem(`what ${member.character.name} was given could not be traced: ${error instanceof Error ? error.message : String(error)}`);
2099
+ }
2011
2100
  try {
2012
2101
  const action = await run(request, signal);
2013
2102
  const verdict = outputValidator.validate(action, request);
@@ -3026,6 +3115,60 @@ var TurnEngine = class {
3026
3115
  turn: store.story.metadata.get().turns
3027
3116
  }, cancel.signal);
3028
3117
  }
3118
+ /**
3119
+ * What a moment would bring back for the characters, as a turn would ask for it and without changing anything the story keeps: nothing is counted as recalled
3120
+ * and no turn begins. @throws {Error} when the chat has no story, or names a character that is not in it.
3121
+ */
3122
+ async recallPreview(chat, request, signal) {
3123
+ const store = this.stores(chat);
3124
+ if (store === void 0) throw new Error(`no story for chat ${chat}`);
3125
+ const cast = store.cast();
3126
+ const player = cast.find((member) => member.character.control === "player");
3127
+ const members = request.character === void 0 ? cast.filter((member) => member.character.control !== "player" && (player?.place === void 0 || member.place?.location.id === player.place.location.id)) : cast.filter((member) => member.key === request.character);
3128
+ if (request.character !== void 0 && members.length === 0) throw new Error(`no character "${request.character}" in the story`);
3129
+ const turn = store.story.metadata.get().turns + 1;
3130
+ const settings = store.settings();
3131
+ const queryVector = await store.queryVector(request.situation, signal);
3132
+ const characters = await Promise.all(members.map(async (member) => {
3133
+ const memories = await this.boundaries().recaller.recall({
3134
+ member,
3135
+ situation: request.situation,
3136
+ turn,
3137
+ policy: settings.memory,
3138
+ explain: true,
3139
+ peek: true,
3140
+ ...queryVector === void 0 ? {} : { queryVector }
3141
+ }, store.story, signal);
3142
+ const here = (member.place === void 0 ? cast : cast.filter((other) => other.place?.location.id === member.place?.location.id)).map((entry) => entry.character.id);
3143
+ const known = store.knowledge(member.character.id, turn, here);
3144
+ return {
3145
+ key: member.key,
3146
+ name: member.character.name,
3147
+ ...member.place === void 0 ? {} : { place: member.place.location.name },
3148
+ memories: memories.map(({ clarity, turn: from, text, why }) => ({
3149
+ clarity,
3150
+ turn: from,
3151
+ text,
3152
+ ...why === void 0 ? {} : { why }
3153
+ })),
3154
+ lore: known.lore,
3155
+ known: {
3156
+ characters: known.characters.length,
3157
+ factions: known.factions.length,
3158
+ places: known.locations.length,
3159
+ things: known.items.length,
3160
+ routes: known.routes.length
3161
+ }
3162
+ };
3163
+ }));
3164
+ return {
3165
+ turn,
3166
+ situation: request.situation,
3167
+ byMeaning: queryVector !== void 0,
3168
+ limit: settings.memory.recall,
3169
+ characters
3170
+ };
3171
+ }
3029
3172
  /** Whether a turn is being played: characters are being asked or the game master is between rounds. */
3030
3173
  playing(chat) {
3031
3174
  const turning = this.states.get(chat);
@@ -3680,7 +3823,9 @@ function apply(ctx) {
3680
3823
  ctx.roleplayOrchestration.reflect = (chat) => engine.reflect(chat);
3681
3824
  ctx.roleplayOrchestration.reflecting = (chat) => engine.reflecting(chat);
3682
3825
  ctx.roleplayOrchestration.playing = (chat) => engine.playing(chat);
3826
+ ctx.roleplayOrchestration.recallPreview = (chat, request, signal) => engine.recallPreview(chat, request, signal);
3683
3827
  return () => {
3828
+ ctx.roleplayOrchestration.recallPreview = () => Promise.reject(/* @__PURE__ */ new Error("the orchestration is not running"));
3684
3829
  ctx.roleplayOrchestration.reflect = () => Promise.reject(/* @__PURE__ */ new Error("the orchestration is not running"));
3685
3830
  ctx.roleplayOrchestration.reflecting = () => false;
3686
3831
  ctx.roleplayOrchestration.playing = () => false;
@@ -1,13 +1,13 @@
1
- import { a as chatSessionId } from "./access-CfQWbNZP.js";
2
- import { Bt as loadFactions, C as worldFieldChanges, D as UPDATE_FOLDER, F as editsSince, Ft as LOCATIONS_DIR, G as addressesToFetch, Gt as loadCalendar, I as writeSnapshot, It as loadLocations, Jt as loadCharacters, K as candidateUrls, Lt as ITEMS_DIR, Mt as loadTriggers, Nt as LORE_DIR, O as baseId, P as recordProvenance, Pt as loadLore, Q as writePortrait, Rt as loadItems, S as matchPieces, T as loadWorldParts, W as addressKey, Y as mergeReports, Yt as subfolders, Z as cardCharacter, _t as knowsCharacter, an as authoringChatSessionId, c as importPhase, gt as loadValidatedWorld, i as contextOf, in as authoredWorldOf, jt as TRIGGERS_FILE_NAME, k as cardPieces, q as fetchPictures, qt as CHARACTERS_DIR, s as worldOf, v as editWorldInfo, w as withScratchStory, zt as FACTIONS_DIR } from "./authoring-tools-CdHlvx32.js";
3
- import { Ct as CHARACTER_FILE_NAME, Dt as InvalidEditProblems, Q as IMPORT_FOLDER, St as parseFactionFile, Z as withPlayer, _t as ITEM_FILE_NAME, at as writeChoices, gt as parseLocationFile, ht as LOCATION_FILE_NAME, it as readImportFolder, mt as parseLoreFile, pt as LORE_FILE_NAME, q as writeWorldPrompt, tt as PICTURE_FILE, ut as loadVariables, wt as parseCharacterFile, x as extractStyleFrom, xt as FACTION_FILE_NAME, yt as parseItemFile } from "./presets-Bwnrx7p0.js";
4
- import { l as atomicWrite, n as encodeOutput, u as atomicWriteJson } from "./narration-CjB_KwwY.js";
5
- import { B as loadPlots, F as STORY_LANGUAGES, H as plotReferenceProblems, I as isStoryLanguage, J as formatIssue, L as textLanguage, P as LANGUAGE_NAMES, V as parsePlotsFile, Z as PROMPTS_FOLDER, it as shippedLanguages, lt as InvalidWorldError, pt as WorldNotFoundError, st as AgentUnavailableError, z as PLOTS_FILE_NAME } from "./hooks-CcQj_dJo.js";
1
+ import { c as chatSessionId, n as atomicWrite, r as atomicWriteJson } from "./access-CXtaZNbx.js";
2
+ import { Bt as loadFactions, D as baseId, E as UPDATE_FOLDER, F as writeSnapshot, Ft as LOCATIONS_DIR, G as candidateUrls, Gt as loadCalendar, It as loadLocations, J as mergeReports, Jt as loadCharacters, K as fetchPictures, Lt as ITEMS_DIR, Mt as loadTriggers, N as recordProvenance, Nt as LORE_DIR, O as cardPieces, P as editsSince, Pt as loadLore, Rt as loadItems, S as editWorldInfo, U as addressKey, W as addressesToFetch, X as cardCharacter, Yt as subfolders, Z as writePortrait, _t as knowsCharacter, an as authoringChatSessionId, b as matchPieces, c as importPhase, gt as withScratchStory, ht as loadValidatedWorld, i as contextOf, in as authoredWorldOf, jt as TRIGGERS_FILE_NAME, qt as CHARACTERS_DIR, s as worldOf, w as loadWorldParts, x as worldFieldChanges, zt as FACTIONS_DIR } from "./authoring-tools-B4mEdKp_.js";
3
+ import { Ct as CHARACTER_FILE_NAME, Dt as InvalidEditProblems, Q as IMPORT_FOLDER, St as parseFactionFile, Z as withPlayer, _t as ITEM_FILE_NAME, at as writeChoices, gt as parseLocationFile, ht as LOCATION_FILE_NAME, it as readImportFolder, mt as parseLoreFile, pt as LORE_FILE_NAME, q as writeWorldPrompt, tt as PICTURE_FILE, ut as loadVariables, wt as parseCharacterFile, x as extractStyleFrom, xt as FACTION_FILE_NAME, yt as parseItemFile } from "./presets-CvpsW_10.js";
4
+ import { n as encodeOutput } from "./narration-BVzew4-K.js";
5
+ import { B as PLOTS_FILE_NAME, F as LANGUAGE_NAMES, H as parsePlotsFile, I as STORY_LANGUAGES, J as Reader, L as isStoryLanguage, Q as PROMPTS_FOLDER, R as textLanguage, U as plotReferenceProblems, V as loadPlots, Y as formatIssue, at as shippedLanguages, ct as AgentUnavailableError, mt as WorldNotFoundError, ut as InvalidWorldError } from "./hooks-DTjHWTfx.js";
6
6
  import { i as translator, r as languageOf } from "./text-CbGQhK1-.js";
7
- import { b as mapLimit, h as readImageFileMetadata, u as referenceImagePath } from "./library-QFL6Z_Nr.js";
8
- import { n as readPreset } from "./preset-BqgY1Tz4.js";
9
- import { _ as API_PREFIX, a as packIds, d as packPath, f as readPack, h as PACK_MEDIA_TYPES, l as isPackId } from "./packs-BREPSfHy.js";
10
- import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-DdZ1-sgv.js";
7
+ import { h as readImageFileMetadata, u as referenceImagePath, x as mapLimit } from "./library-GIlrkOim.js";
8
+ import { n as readPreset } from "./preset-Cyoj1ZWa.js";
9
+ import { _ as API_PREFIX, a as packIds, d as packPath, f as readPack, h as PACK_MEDIA_TYPES, l as isPackId } from "./packs-UpK_cvI4.js";
10
+ import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-Cg6CQc5S.js";
11
11
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
12
12
  import { existsSync, lstatSync, statSync } from "node:fs";
13
13
  import { randomUUID } from "node:crypto";
@@ -2445,7 +2445,15 @@ async function find(world, kind, key) {
2445
2445
  }
2446
2446
  }
2447
2447
  }
2448
- function serializeDocument(kind, key, value) {
2448
+ function unreadProblem(kind, text, key) {
2449
+ let parsed = false;
2450
+ const { unread, read } = Reader.unreadBy(() => {
2451
+ parsed = formats[kind].parse(text, key).ok;
2452
+ });
2453
+ if (!parsed || unread.length === 0) return void 0;
2454
+ return `${unread.join(", ")} ${unread.length === 1 ? "is" : "are"} not read by anything, so a story would never see ${unread.length === 1 ? "it" : "them"}: put the words in the field that holds them. The fields a ${kind} reads: ${read.join(", ")}`;
2455
+ }
2456
+ function serializeDocument(kind, key, value, options = {}) {
2449
2457
  if (typeof value !== "object" || value === null || Array.isArray(value)) throw new InvalidEditProblems(["document must be a JSON object"]);
2450
2458
  const document = {
2451
2459
  ...value,
@@ -2454,6 +2462,8 @@ function serializeDocument(kind, key, value) {
2454
2462
  const text = `${JSON.stringify(document, null, 2)}\n`;
2455
2463
  const parsed = formats[kind].parse(text, key);
2456
2464
  if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
2465
+ const unread = options.refuseUnread === true ? unreadProblem(kind, text, key) : void 0;
2466
+ if (unread !== void 0) throw new InvalidEditProblems([unread]);
2457
2467
  return text;
2458
2468
  }
2459
2469
  async function readAuthoredEntityDocument(world, kind, key) {
@@ -2461,13 +2471,13 @@ async function readAuthoredEntityDocument(world, kind, key) {
2461
2471
  if (found === void 0) throw new InvalidEditProblems([`there is no ${kind} "${key}"`]);
2462
2472
  return JSON.parse((await readFile(found.file, "utf8")).replace(/^/, ""));
2463
2473
  }
2464
- async function createAuthoredEntity(world, kind, key, document) {
2474
+ async function createAuthoredEntity(world, kind, key, document, options = {}) {
2465
2475
  if (!validNewKey(key)) throw new InvalidEditProblems(["key must be letters (any script), digits, \".\", \"_\" or \"-\", starting with a letter or digit, at most 100 characters (no brackets, spaces or slashes)"]);
2466
2476
  if (await find(world, kind, key) !== void 0) throw new InvalidEditProblems([`the ${kind} "${key}" already exists`]);
2467
2477
  const format = formats[kind];
2468
2478
  const root = join(world.directory, format.directory);
2469
2479
  const folder = join(root, key);
2470
- const text = serializeDocument(kind, key, document);
2480
+ const text = serializeDocument(kind, key, document, options);
2471
2481
  await mkdir(root, { recursive: true });
2472
2482
  await mkdir(folder, { recursive: false });
2473
2483
  try {
@@ -2480,10 +2490,10 @@ async function createAuthoredEntity(world, kind, key, document) {
2480
2490
  throw error;
2481
2491
  }
2482
2492
  }
2483
- async function replaceAuthoredEntity(world, kind, key, document) {
2493
+ async function replaceAuthoredEntity(world, kind, key, document, options = {}) {
2484
2494
  const found = await find(world, kind, key);
2485
2495
  if (found === void 0) throw new InvalidEditProblems([`there is no ${kind} "${key}"`]);
2486
- await atomicWrite(found.file, serializeDocument(kind, key, document));
2496
+ await atomicWrite(found.file, serializeDocument(kind, key, document, options));
2487
2497
  }
2488
2498
  /** Deletions remain recoverable without making the trash visible to the world loaders. */
2489
2499
  async function deleteAuthoredEntity(world, kind, key) {
@@ -2639,4 +2649,4 @@ function registerPackJail(ctx, deps) {
2639
2649
  }
2640
2650
  export { DOCTOR_OPENING_SOURCE as $, worldEntityImageFile as A, languageOfDocuments as B, readWorldEditor as C, uploadWorldCharacterPortrait as D, replaceFile as E, PRESET_FILE as F, revertUpdate as G, findTargets as H, presetMessage as I, AuthoringSessions as J, startUpdate as K, presetTools as L, deleteTriggerDocument as M, readTriggerDocuments as N, uploadWorldEntityImage as O, writeTriggerDocument as P, agentServicesOf as Q, translateMessage as R, generateWorldEntityImage as S, removeWorldTrigger as T, finishUpdate as U, readWorldDocuments as V, pendingUpdate as W, ensureAuthoringChat as X, authoringTitle as Y, AgentSessions as Z, editWorldPlots as _, deleteWorldPackFile as a, entityFolder as b, createAuthoredEntity as c, replaceAuthoredEntity as d, appendEmptyTurn as et, editWorldCharacter as f, editWorldPlace as g, editWorldNarrationVoice as h, checkWorldPack as i, writeWorldTrigger as j, worldCharacterPortraitFile as k, deleteAuthoredEntity as l, editWorldLore as m, packFileProblem as n, listWorldPacks as o, editWorldFaction as p, updateStatus as q, registerPackJail as r, AUTHORED_ENTITY_KINDS as s, MAX_PACK_TEXT as t, appendNarratedTurn as tt, readAuthoredEntityDocument as u, editWorldRelation as v, readWorldTrigger as w, generateWorldCharacterPortrait as x, editWorldThing as y, translateTools as z };
2641
2651
 
2642
- //# sourceMappingURL=pack-jail-BMy6NcCY.js.map
2652
+ //# sourceMappingURL=pack-jail-hsNQNTOf.js.map
@@ -1,4 +1,4 @@
1
- import { q as Reader } from "./hooks-CcQj_dJo.js";
1
+ import { J as Reader } from "./hooks-DTjHWTfx.js";
2
2
  import { dirname, extname, join, posix, sep } from "node:path";
3
3
  import { copyFileSync, cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync } from "node:fs";
4
4
  import { createHash } from "node:crypto";
@@ -836,4 +836,4 @@ function anyTab(bases) {
836
836
  }
837
837
  export { API_PREFIX as _, packIds as a, describePack as c, packPath as d, readPack as f, SURFACE_NAMES as g, PACK_MEDIA_TYPES as h, inheritPacks as i, isPackId as l, PACK_LIMITS as m, anyTab as n, syncWorldPacks as o, PACK_ACTIONS as p, copyWorldPacks as r, worldPackStates as s, activePack as t, packFile as u };
838
838
 
839
- //# sourceMappingURL=packs-BREPSfHy.js.map
839
+ //# sourceMappingURL=packs-UpK_cvI4.js.map
@@ -1,12 +1,12 @@
1
- import { t as promptFor } from "./access-CfQWbNZP.js";
2
- import { c as runChild } from "./child-lYYeOwl2.js";
3
- import { n as generateTransientImage, t as generateReferenceImage } from "./generator-DdZ1-sgv.js";
4
- import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-BKh7eu80.js";
5
- import { c as nextSceneSerial, u as referenceImagePath } from "./library-QFL6Z_Nr.js";
6
- import { dirname, join, relative } from "node:path";
1
+ import { n as atomicWrite, t as promptFor } from "./access-CXtaZNbx.js";
2
+ import { c as runChild } from "./child-Dtv76jNx.js";
3
+ import { n as generateTransientImage, t as generateReferenceImage } from "./generator-Cg6CQc5S.js";
4
+ import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-BZJleAeH.js";
5
+ import { c as nextSceneSerial, u as referenceImagePath } from "./library-GIlrkOim.js";
6
+ import { join, relative } from "node:path";
7
7
  import { existsSync } from "node:fs";
8
- import { createHash, randomUUID } from "node:crypto";
9
- import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
8
+ import { createHash } from "node:crypto";
9
+ import { readFile } from "node:fs/promises";
10
10
  import { defineTool } from "@deepseek-ai/dsh-tools";
11
11
  import { characterKey, itemKey, locationKey } from "@dsh-agentic-roleplay/state";
12
12
  // src/host/images/presented.ts
@@ -26,13 +26,10 @@ async function present(sessionFolder, node, image) {
26
26
  const current = await presentedFor(sessionFolder, node);
27
27
  if (current.some((entry) => entry.path === image.path)) return;
28
28
  const file = fileOf(sessionFolder, node);
29
- await mkdir(dirname(file), { recursive: true });
30
- const temporary = `${file}.${process.pid}.${randomUUID()}.writing`;
31
- await writeFile(temporary, JSON.stringify({ images: [...current, {
29
+ await atomicWrite(file, JSON.stringify({ images: [...current, {
32
30
  ...image,
33
31
  at: (/* @__PURE__ */ new Date()).toISOString()
34
- }] }, null, 2));
35
- await rename(temporary, file);
32
+ }] }, null, 2), { createDirectory: true });
36
33
  }
37
34
  // src/host/images/image-search.ts
38
35
  const WORD = /[\p{L}\p{N}]+/gu;
@@ -145,9 +142,7 @@ async function readVectors(images) {
145
142
  }
146
143
  async function writeVectors(images, file) {
147
144
  const path = join(images, VECTORS_FILE);
148
- const temporary = `${path}.${process.pid}.${randomUUID()}.writing`;
149
- await writeFile(temporary, JSON.stringify(file));
150
- await rename(temporary, path);
145
+ await atomicWrite(path, JSON.stringify(file));
151
146
  }
152
147
  /**
153
148
  * The images that fit a description, by words and, when an embedding service is there, by meaning, the two rankings joined by reciprocal rank so that
@@ -846,4 +841,4 @@ async function runImagePresenter(job) {
846
841
  }
847
842
  export { tokensOf as a, searchImages as i, interpretImage as n, present as o, imageTools as r, presentedFor as s, runImagePresenter as t };
848
843
 
849
- //# sourceMappingURL=presenter-agent-B49-_iUm.js.map
844
+ //# sourceMappingURL=presenter-agent-DZOgBOR9.js.map
@@ -1,6 +1,6 @@
1
- import { Zt as ImportCardError, r as MAX_PREVIEW_TEXT } from "./authoring-tools-CdHlvx32.js";
2
- import { l as SAMPLING_RANGES } from "./child-lYYeOwl2.js";
3
- import { J as cleanText } from "./presets-Bwnrx7p0.js";
1
+ import { Zt as ImportCardError, r as MAX_PREVIEW_TEXT } from "./authoring-tools-B4mEdKp_.js";
2
+ import { l as SAMPLING_RANGES } from "./child-Dtv76jNx.js";
3
+ import { J as cleanText } from "./presets-CvpsW_10.js";
4
4
  // src/host/import/preset.ts
5
5
  /** The older preset layout keeps its texts under fixed keys. */
6
6
  const LEGACY_KEYS = [
@@ -239,4 +239,4 @@ function selectPrompts(file, enabled, keepSampling) {
239
239
  }
240
240
  export { readPreset as n, selectPrompts as r, previewPreset as t };
241
241
 
242
- //# sourceMappingURL=preset-BqgY1Tz4.js.map
242
+ //# sourceMappingURL=preset-Cyoj1ZWa.js.map
@@ -1,9 +1,9 @@
1
- import "./access-CfQWbNZP.js";
2
- import { G as listWorldPrompts, K as readWorldPrompt, Q as IMPORT_FOLDER, U as PROSE_PROMPTS, W as deleteWorldPrompt, Z as withPlayer, c as presetDirectory, l as readPreset, p as updatePresetInfo, q as writeWorldPrompt, t as PRESET_FILE, x as extractStyleFrom } from "./presets-Bwnrx7p0.js";
3
- import { n as readPreset$1 } from "./preset-BqgY1Tz4.js";
4
- import { i as contextOf } from "./authoring-tools-CdHlvx32.js";
1
+ import "./access-CXtaZNbx.js";
2
+ import { G as listWorldPrompts, K as readWorldPrompt, Q as IMPORT_FOLDER, U as PROSE_PROMPTS, W as deleteWorldPrompt, Z as withPlayer, c as presetDirectory, l as readPreset, p as updatePresetInfo, q as writeWorldPrompt, t as PRESET_FILE, x as extractStyleFrom } from "./presets-CvpsW_10.js";
3
+ import { n as readPreset$1 } from "./preset-Cyoj1ZWa.js";
4
+ import { i as contextOf } from "./authoring-tools-B4mEdKp_.js";
5
5
  import { i as translator, r as languageOf } from "./text-CbGQhK1-.js";
6
- import { at as shippedPromptsDirectory, it as shippedLanguages, tt as languageOf$1 } from "./hooks-CcQj_dJo.js";
6
+ import { at as shippedLanguages, nt as languageOf$1, ot as shippedPromptsDirectory } from "./hooks-DTjHWTfx.js";
7
7
  import { join } from "node:path";
8
8
  import { existsSync } from "node:fs";
9
9
  import { readFile, rm } from "node:fs/promises";
@@ -278,4 +278,4 @@ async function presetApproval(exec, next, carries) {
278
278
  }
279
279
  export { presetChatSessionId as a, presetAuthorTools as i, narrationImportMessage as n, presetOfChat as o, presetApproval as r, PresetReader as t };
280
280
 
281
- //# sourceMappingURL=preset-author-tools-BB_Dcv2o.js.map
281
+ //# sourceMappingURL=preset-author-tools-RSta6pHK.js.map
@@ -1,8 +1,8 @@
1
- import { n as limitAuthoringAgents } from "./authoring-tools-CdHlvx32.js";
2
- import { t as guardAuthoringTurns } from "./turn-guard-Bb8Ew-1z.js";
3
- import { i as presetAuthorTools, o as presetOfChat, r as presetApproval, t as PresetReader } from "./preset-author-tools-BB_Dcv2o.js";
4
- import "./hooks-CcQj_dJo.js";
5
- import { c as presetDirectory } from "./presets-Bwnrx7p0.js";
1
+ import { n as limitAuthoringAgents } from "./authoring-tools-B4mEdKp_.js";
2
+ import { t as guardAuthoringTurns } from "./turn-guard-BzNeGNnc.js";
3
+ import { i as presetAuthorTools, o as presetOfChat, r as presetApproval, t as PresetReader } from "./preset-author-tools-RSta6pHK.js";
4
+ import "./hooks-DTjHWTfx.js";
5
+ import { c as presetDirectory } from "./presets-CvpsW_10.js";
6
6
  import { join } from "node:path";
7
7
  import { existsSync } from "node:fs";
8
8
  // src/preset-authoring.ts
@@ -1,8 +1,8 @@
1
- import { i as VARIABLE_VISIBILITIES, n as VARIABLE_KINDS, r as VARIABLE_SUBJECTS } from "./access-CfQWbNZP.js";
2
- import "./narration-CjB_KwwY.js";
3
- import { J as formatIssue, K as readDocument, X as LANGUAGE_FOLDER, Y as errorMessage, Z as PROMPTS_FOLDER, at as shippedPromptsDirectory, it as shippedLanguages, nt as listFiles, q as Reader, rt as promptProblem, tt as languageOf } from "./hooks-CcQj_dJo.js";
4
- import { u as parseSampling } from "./child-lYYeOwl2.js";
5
- import { C as trOf, S as slug, b as mapLimit, w as uniqueKey, x as norm } from "./library-QFL6Z_Nr.js";
1
+ import { a as VARIABLE_KINDS, n as atomicWrite, o as VARIABLE_SUBJECTS, s as VARIABLE_VISIBILITIES } from "./access-CXtaZNbx.js";
2
+ import "./narration-BVzew4-K.js";
3
+ import { J as Reader, Q as PROMPTS_FOLDER, X as errorMessage, Y as formatIssue, Z as LANGUAGE_FOLDER, at as shippedLanguages, it as promptProblem, nt as languageOf, ot as shippedPromptsDirectory, q as readDocument, rt as listFiles } from "./hooks-DTjHWTfx.js";
4
+ import { u as parseSampling } from "./child-Dtv76jNx.js";
5
+ import { C as slug, S as norm, T as uniqueKey, w as trOf, x as mapLimit } from "./library-GIlrkOim.js";
6
6
  import { dirname, join } from "node:path";
7
7
  import { existsSync, readFileSync, readdirSync } from "node:fs";
8
8
  import { createHash, randomUUID } from "node:crypto";
@@ -1617,8 +1617,7 @@ async function readImportFolder(directory) {
1617
1617
  }
1618
1618
  async function writeChoices(directory, choices) {
1619
1619
  const file = join(directory, CHOICES_FILE);
1620
- await writeFile(`${file}.writing`, JSON.stringify(choices, null, 2));
1621
- await rename(`${file}.writing`, file);
1620
+ await atomicWrite(file, JSON.stringify(choices, null, 2));
1622
1621
  }
1623
1622
  /** Uploaded cards waiting to become worlds: one folder each under `<root>/imports/`. */
1624
1623
  var ImportStore = class {
@@ -2494,6 +2493,15 @@ const objects = (value) => Array.isArray(value) ? value.filter((entry) => typeof
2494
2493
  const put = (document, key, value) => {
2495
2494
  if (value !== void 0 && value !== "" && !(Array.isArray(value) && value.length === 0)) document[key] = value;
2496
2495
  };
2496
+ const normalisedText = /* @__PURE__ */ new WeakMap();
2497
+ const normalised = (item) => {
2498
+ let folded = normalisedText.get(item);
2499
+ if (folded === void 0) {
2500
+ folded = norm(item.text);
2501
+ normalisedText.set(item, folded);
2502
+ }
2503
+ return folded;
2504
+ };
2497
2505
  /** The pieces an entity is made from: the ones about it, then others that name it, within a budget of text. */
2498
2506
  function sourcesFor(entity, items, classified) {
2499
2507
  const names = [entity.name, ...entity.aliases].map(norm).filter((name) => name.length >= MIN_MENTION_CHARS);
@@ -2506,7 +2514,7 @@ function sourcesFor(entity, items, classified) {
2506
2514
  const mentions = items.filter((item) => !taken.has(item.id) && !isLeftOut(classified[item.id] ?? {
2507
2515
  roles: ["world"],
2508
2516
  targets: []
2509
- }) && names.some((name) => norm(item.text).includes(name))).slice(0, MAX_MENTIONS);
2517
+ }) && names.some((name) => normalised(item).includes(name))).slice(0, MAX_MENTIONS);
2510
2518
  const chosen = [];
2511
2519
  let used = 0;
2512
2520
  for (const item of [...tagged, ...mentions]) {
@@ -4001,4 +4009,4 @@ async function createPresetFromGuidance(root, request, guidance, shipped = shipp
4001
4009
  }
4002
4010
  export { ImportNotFoundError as $, sourcesFor as A, parseLoreEdit as At, noAt as B, inert as C, CHARACTER_FILE_NAME as Ct, pruneLoreSubjects as D, InvalidEditProblems as Dt, pruneLinks as E, readIdentifier as Et, isLeftOut as F, LORE_SCOPES as Ft, listWorldPrompts as G, yesAt as H, announceProblem as I, WEEKDAY_NAMES as It, cleanText as J, readWorldPrompt as K, askYesNo as L, DEFAULT_SLOTS as Lt, classifyItems as M, parseRelationEdit as Mt, findEntity as N, parseThingEdit as Nt, pruneMembers as O, parseCharacterEdit as Ot, ROLES as P, LORE_KINDS as Pt, IMPORT_FOLDER as Q, mergeReports as R, INTENT_STATUSES as Rt, extractVariables as S, parseFactionFile as St, pruneKnowledge as T, readVariableValues as Tt, PROSE_PROMPTS as U, routeVerdicts as V, deleteWorldPrompt as W, partsOf as X, itemise as Y, withPlayer as Z, characterDocument as _, ITEM_FILE_NAME as _t, isPresetName as a, writeChoices as at, extractStyle as b, parseSlotsFile as bt, presetDirectory as c, parseAuthoringCommand as ct, savePresetFromWorld as d, parseVariablesFile as dt, ImportStore as et, sha as f, variableProblems as ft, asWritten as g, parseLocationFile as gt, addLore as h, LOCATION_FILE_NAME as ht, deletePreset as i, readImportFolder as it, buildRoster as j, parsePlaceEdit as jt, pruneRelationships as k, parseFactionEdit as kt, readPreset as l, VARIABLES_FILE_NAME as lt, STANDING_PROMPT as m, parseLoreFile as mt, createPresetFromGuidance as n, openingText as nt, listPresets as o, IMPORT_COMMAND as ot, updatePresetInfo as p, LORE_FILE_NAME as pt, writeWorldPrompt as q, createPresetFromShipped as r, parseChoices as rt, loadPreset as s, parseImportCommand as st, PRESET_FILE as t, PICTURE_FILE as tt, reservePreset as u, loadVariables as ut, emptyExtracted as v, SLOTS_FILE_NAME as vt, loreDocuments as w, parseCharacterFile as wt, extractStyleFrom as x, FACTION_FILE_NAME as xt, extractEntities as y, parseItemFile as yt, modeFor as z };
4003
4011
 
4004
- //# sourceMappingURL=presets-Bwnrx7p0.js.map
4012
+ //# sourceMappingURL=presets-CvpsW_10.js.map