@dsh-agentic-roleplay/core 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +1 -1
  2. package/lib/{chat-AKrVcWIC.js → access-EbNdZFbk.js} +10 -2
  3. package/lib/authoring.js +469 -17
  4. package/lib/client.js +3013 -607
  5. package/lib/client.js.map +1 -1
  6. package/lib/compaction.js +2 -3
  7. package/lib/{activity-BbqFG9-3.js → deliver--uMhC6oO.js} +741 -55
  8. package/lib/{documents-ZVoUTnD2.js → documents-7GMc5NnW.js} +108 -5
  9. package/lib/{gallery-KGCdeCnM.js → gallery-DUeBMHQX.js} +2 -2
  10. package/lib/{generator-NYnNdpWb.js → generator-HPifO3Kk.js} +125 -20
  11. package/lib/images.js +3 -3
  12. package/lib/index.js +865 -15
  13. package/lib/{narration-DcnCqA1l.js → narration-CKZTk5UE.js} +19 -4
  14. package/lib/orchestration.js +373 -207
  15. package/lib/packs-alJTiDM2.js +1336 -0
  16. package/lib/{presenter-agent-7j1c7QEz.js → presenter-agent-PX1WVaJB.js} +4 -4
  17. package/package.json +5 -3
  18. package/packs/scene/map.html +12 -0
  19. package/packs/scene/map.js +55 -0
  20. package/packs/scene/pack.json +11 -0
  21. package/packs/scene/strip.html +11 -0
  22. package/packs/scene/strip.js +26 -0
  23. package/packs/scene/style.css +16 -0
  24. package/prompts/en/roleplay/ask-answerer.md +3 -0
  25. package/prompts/en/roleplay/ask-question.md +2 -0
  26. package/prompts/en/roleplay/character-decide.md +1 -1
  27. package/prompts/en/roleplay/character-lookup.md +1 -1
  28. package/prompts/en/roleplay/game-master.md +5 -1
  29. package/prompts/en/roleplay/ooc-empty.md +1 -1
  30. package/prompts/en/roleplay/reflection.md +9 -0
  31. package/prompts/en/world/procedure.md +1 -1
  32. package/prompts/en/world/welcome.md +1 -1
  33. package/prompts/zh/roleplay/ask-answerer.md +3 -0
  34. package/prompts/zh/roleplay/ask-question.md +2 -0
  35. package/prompts/zh/roleplay/character-decide.md +1 -1
  36. package/prompts/zh/roleplay/character-lookup.md +1 -1
  37. package/prompts/zh/roleplay/game-master.md +5 -1
  38. package/prompts/zh/roleplay/ooc-empty.md +1 -1
  39. package/prompts/zh/roleplay/reflection.md +9 -0
  40. package/prompts/zh/world/procedure.md +1 -1
  41. package/prompts/zh/world/welcome.md +1 -1
  42. package/starter-worlds/blackwater-observatory/ui/notebook/map.html +12 -0
  43. package/starter-worlds/blackwater-observatory/ui/notebook/map.js +40 -0
  44. package/starter-worlds/blackwater-observatory/ui/notebook/notebook.html +29 -0
  45. package/starter-worlds/blackwater-observatory/ui/notebook/notebook.js +45 -0
  46. package/starter-worlds/blackwater-observatory/ui/notebook/pack.json +31 -0
  47. package/starter-worlds/blackwater-observatory/ui/notebook/skin.css +16 -0
  48. package/starter-worlds/blackwater-observatory/ui/notebook/strip.html +11 -0
  49. package/starter-worlds/blackwater-observatory/ui/notebook/strip.js +12 -0
  50. package/starter-worlds/blackwater-observatory/ui/notebook/style.css +23 -0
  51. package/lib/access-C1nFQiyT.js +0 -12
  52. package/lib/worlds-DYgjdH8O.js +0 -504
@@ -1,10 +1,170 @@
1
- import { n as roleplaySessionOf } from "./chat-AKrVcWIC.js";
2
- import { p as inheritPrompts, w as SessionNotFoundError } from "./worlds-DYgjdH8O.js";
3
- import { u as inheritImages } from "./generator-NYnNdpWb.js";
1
+ import { r as roleplaySessionOf, t as promptFor } from "./access-EbNdZFbk.js";
2
+ import { V as SessionNotFoundError, i as inheritPacks, k as inheritPrompts } from "./packs-alJTiDM2.js";
3
+ import "./src-CWTNeL6Y.js";
4
+ import { A as runChild, D as childSampling, E as childModel, j as estimateAnswer, k as childTrace, u as inheritImages } from "./generator-HPifO3Kk.js";
4
5
  import { join } from "node:path";
5
- import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
6
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
6
7
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
7
- import { DAY, MINUTE, SECOND, clockTime, dayPart, describeDuration, describeInstant, isSessionId, localTime, locationKey, mentioned, nextTimeOfDay, overlap, sessionDatabase, sessionFolder, tokens } from "@dsh-agentic-roleplay/state";
8
+ import { DAY, MINUTE, SECOND, characterKey, clockTime, dayPart, describeDuration, describeInstant, isSessionId, localTime, locationKey, mentioned, nextTimeOfDay, overlap, sessionDatabase, sessionFolder, tokens } from "@dsh-agentic-roleplay/state";
9
+ //#region ../dsh-roleplay-model/src/memory.ts
10
+ const MEMORY_KINDS = [
11
+ "belief",
12
+ "relationship",
13
+ "knowledge"
14
+ ];
15
+ //#endregion
16
+ //#region src/host/orchestration/protocol.ts
17
+ const COMMITMENTS = [
18
+ "low",
19
+ "medium",
20
+ "high"
21
+ ];
22
+ const RESULTS = [
23
+ "succeeded",
24
+ "partial",
25
+ "failed"
26
+ ];
27
+ const MAX_ACCOUNT = 300;
28
+ /**
29
+ * How long, in characters, each text of a character's answer is asked to run to: the instructions state these, and the most a character's request may produce is estimated from them.
30
+ * A character of a script written without spaces says more in fewer.
31
+ */
32
+ const ANSWER_LIMITS = {
33
+ en: {
34
+ thought: 240,
35
+ intent: 300,
36
+ utterance: 600,
37
+ account: MAX_ACCOUNT
38
+ },
39
+ zh: {
40
+ thought: 100,
41
+ intent: 120,
42
+ utterance: 240,
43
+ account: 120
44
+ }
45
+ };
46
+ const answerLimits = (language) => language.toLowerCase().startsWith("zh") ? ANSWER_LIMITS.zh : ANSWER_LIMITS.en;
47
+ /** What the answer of a character comes to at most, in tokens (an answer about what happened out of sight has its account too). */
48
+ function answerEstimate(language, away) {
49
+ const limits = answerLimits(language);
50
+ return estimateAnswer([
51
+ limits.thought,
52
+ limits.intent,
53
+ limits.utterance,
54
+ ...away ? [limits.account] : []
55
+ ], language);
56
+ }
57
+ /**
58
+ * What a character is asked to produce; the sub-agent runtime enforces it. The order is the order of what depends on what: the thought comes first so that the
59
+ * choice that follows is made after it, which an engine that does not write fields in order simply does without (it is optional and read by no one).
60
+ */
61
+ const CHARACTER_ACTION_SCHEMA = {
62
+ type: "object",
63
+ properties: {
64
+ thought: {
65
+ type: "string",
66
+ description: "First, in your own voice and a sentence or two: what you notice in the moment and what you want from it. No one is shown it."
67
+ },
68
+ intent: {
69
+ type: "string",
70
+ description: "What the character does, or tries to do, now, as an action in one or two sentences, without any speech."
71
+ },
72
+ utterance: {
73
+ type: "string",
74
+ description: "What the character says aloud, word for word and in its own voice, exactly as it will be shown. Leave out when it says nothing."
75
+ },
76
+ commitment: {
77
+ type: "string",
78
+ enum: [...COMMITMENTS],
79
+ description: "How hard the character will keep trying if this does not work out: low gives up at once, high persists."
80
+ }
81
+ },
82
+ required: [
83
+ "thought",
84
+ "intent",
85
+ "commitment"
86
+ ],
87
+ additionalProperties: false
88
+ };
89
+ /** The schema for a character acting away from the player: the same answer, which also says in a line what happened, so no second request is needed. */
90
+ const AWAY_ACTION_SCHEMA = {
91
+ ...CHARACTER_ACTION_SCHEMA,
92
+ properties: {
93
+ ...CHARACTER_ACTION_SCHEMA.properties,
94
+ account: {
95
+ type: "string",
96
+ description: "One sentence, in the third person and the past tense, of what came of this, as someone who only saw it from outside would tell it afterwards: no thoughts, no secrets."
97
+ }
98
+ },
99
+ required: [
100
+ "thought",
101
+ "intent",
102
+ "commitment",
103
+ "account"
104
+ ]
105
+ };
106
+ /** @throws {Error} when the value is not a character action. */
107
+ const QUOTE_PAIRS = [
108
+ ["\"", "\""],
109
+ ["“", "”"],
110
+ ["「", "」"],
111
+ ["『", "』"],
112
+ ["«", "»"],
113
+ ["‘", "’"]
114
+ ];
115
+ /** Words said aloud, without the quotation marks a model puts around them: the output puts its own. */
116
+ function unquoted(text) {
117
+ let words = text.trim();
118
+ for (let again = true; again;) {
119
+ again = false;
120
+ for (const [open, close] of QUOTE_PAIRS) if (words.length >= 2 && words.startsWith(open) && words.endsWith(close) && !words.slice(open.length, -close.length).includes(close)) {
121
+ words = words.slice(open.length, words.length - close.length).trim();
122
+ again = true;
123
+ }
124
+ }
125
+ return words;
126
+ }
127
+ const LEAKED_FIELD = /<\/?(?:intent|parameter(?:=\w+)?)>/g;
128
+ /** A model that writes the markup of its call into a field puts the next field's text inside this one. */
129
+ function splitLeakedFields(intent) {
130
+ const at = intent.search(/<parameter=utterance>/);
131
+ if (at === -1) return { intent: intent.replace(LEAKED_FIELD, " ") };
132
+ const spoken = intent.slice(at).replace(LEAKED_FIELD, " ").trim();
133
+ return {
134
+ intent: intent.slice(0, at).replace(LEAKED_FIELD, " "),
135
+ ...spoken === "" ? {} : { utterance: spoken }
136
+ };
137
+ }
138
+ function parseCharacterAction(value) {
139
+ if (typeof value !== "object" || value === null) throw new Error("the character did not answer with an object");
140
+ const { intent: rawIntent, utterance: rawUtterance, commitment, account } = value;
141
+ const { intent, utterance } = typeof rawIntent === "string" && rawUtterance === void 0 ? splitLeakedFields(rawIntent) : {
142
+ intent: rawIntent,
143
+ utterance: rawUtterance
144
+ };
145
+ if (typeof intent !== "string" || intent.trim() === "") throw new Error("the character gave no intent");
146
+ if (!COMMITMENTS.includes(commitment)) throw new Error(`the character gave an unknown commitment "${String(commitment)}"`);
147
+ if (utterance !== void 0 && typeof utterance !== "string") throw new Error("the character's utterance is not text");
148
+ const spoken = utterance === void 0 ? void 0 : unquoted(utterance);
149
+ const told = typeof account === "string" ? account.trim().slice(0, MAX_ACCOUNT) : "";
150
+ return {
151
+ intent: intent.trim(),
152
+ ...spoken === void 0 || spoken === "" ? {} : { utterance: spoken },
153
+ commitment,
154
+ ...told === "" ? {} : { account: told }
155
+ };
156
+ }
157
+ //#endregion
158
+ //#region src/host/orchestration/referent.ts
159
+ /**
160
+ * How a person is named wherever the text may go on to say what they do: the name with the pronouns the world gave them, or the gender when only that is given.
161
+ * A model that is not told guesses, and a wrong guess written into a record or a narration is never corrected; nothing is made up when the world says neither.
162
+ */
163
+ function referent(character) {
164
+ const mark = [character.pronouns, character.gender].find((text) => text !== void 0 && text.trim() !== "")?.trim();
165
+ return mark === void 0 ? character.name : `${character.name} (${mark})`;
166
+ }
167
+ //#endregion
8
168
  //#region src/host/clock/story-clock.ts
9
169
  var ClockError = class extends Error {};
10
170
  /** A moment as it is told next to `now`: the clock when it is the same day, the date as well when it is not. */
@@ -141,6 +301,15 @@ function skipTime(session, config, turn, round, wall, request) {
141
301
  }
142
302
  //#endregion
143
303
  //#region src/host/orchestration/defaults.ts
304
+ /** What the instructions say about how long each part of a character's answer may run. */
305
+ const limitVariables = (language) => {
306
+ const limits = answerLimits(language);
307
+ return {
308
+ thoughtLimit: limits.thought,
309
+ intentLimit: limits.intent,
310
+ utteranceLimit: limits.utterance
311
+ };
312
+ };
144
313
  function describe(character) {
145
314
  const lines = [`You are ${character.name}.`];
146
315
  if (character.aliases.length > 0) lines.push(`You are also called ${character.aliases.join(", ")}.`);
@@ -246,7 +415,7 @@ function present(cast, self) {
246
415
  const { key, character, state } = member;
247
416
  const seen = [state?.publicState, state?.activity].filter((text) => text !== void 0 && text.trim() !== "");
248
417
  const where = whereIs(member);
249
- return `- ${character.name}${key === self ? " (you)" : ""}${where === "" ? "" : ` (${where})`}${seen.length > 0 ? `: ${seen.join("; ")}` : ""}`;
418
+ return `- ${key === self ? character.name : referent(character)}${key === self ? " (you)" : ""}${where === "" ? "" : ` (${where})`}${seen.length > 0 ? `: ${seen.join("; ")}` : ""}`;
250
419
  }).join("\n");
251
420
  }
252
421
  /** A bounded, advisory order for who is most likely to need a turn; reachability still governs activation. */
@@ -310,9 +479,7 @@ function age(at, now) {
310
479
  /** What a character remembers, in the way it remembers it: what is faded or vague is told as such. */
311
480
  function remembered(memories, now) {
312
481
  return memories.map((memory) => {
313
- if (memory.clarity === "clear") return `- (${age(memory.at, now)}) ${memory.text}`;
314
- if (memory.clarity === "faded") return `- (${age(memory.at, now)}, the details are fuzzy) ${memory.text}`;
315
- return `- (${age(memory.at, now)}, you barely remember) ${memory.text}`;
482
+ return `- (${memory.clarity === "clear" ? age(memory.at, now) : `${age(memory.at, now)}, ${memory.clarity === "faded" ? "the details are fuzzy" : "you barely remember"}`}${memory.linked === true ? ", it comes to mind with the rest" : ""}) ${memory.text}`;
316
483
  }).join("\n");
317
484
  }
318
485
  /** Every character is told the same thing about the scene, plus who it is and what it remembers. */
@@ -355,6 +522,7 @@ const sharedContext = { brief(request) {
355
522
  if (lines.length > 0) sections.push(`What you know exists (this does not tell you where it is now or what state it is in):\n${lines.join("\n")}`);
356
523
  }
357
524
  if (memories !== void 0 && memories.length > 0) sections.splice(1, 0, `What you remember that bears on this (only what you took in yourself; do not claim to remember more, and be unsure of what is fuzzy):\n${remembered(memories, time?.now)}`);
525
+ else if (memories !== void 0) sections.splice(1, 0, "What you remember that bears on this: nothing comes to mind.");
358
526
  if (earlier !== void 0 && earlier.length > 0) sections.push(`Earlier in this scene, before this moment:\n${earlier.map(said).join("\n")}`);
359
527
  if (attempt === 2 && reaction !== void 0) {
360
528
  sections.push(`What just happened, and what you are reacting to:\n${reaction.map(said).join("\n")}`);
@@ -366,7 +534,10 @@ const sharedContext = { brief(request) {
366
534
  request.text("roleplay/character-rules", { name: member.character.name }),
367
535
  request.text("roleplay/character-style", { name: member.character.name }),
368
536
  ...request.lookup ? [request.text("roleplay/character-lookup")] : [],
369
- request.text("roleplay/character-decide", { name: member.character.name })
537
+ request.text("roleplay/character-decide", {
538
+ name: member.character.name,
539
+ ...limitVariables(request.language ?? "en")
540
+ })
370
541
  ].join("\n\n"),
371
542
  prompt: sections.join("\n\n")
372
543
  };
@@ -446,7 +617,7 @@ const castSummary = { scene({ tracked, time, world, cast, turn, input, queryVect
446
617
  const role = character.control === "player" ? `the player's character, "${key}"` : `acts through "${key}"`;
447
618
  const seen = [state?.publicState, state?.activity].filter((text) => text !== void 0 && text.trim() !== "");
448
619
  const where = whereIs(member);
449
- return `- ${character.name} (${role})${where === "" ? "" : ` [${where}]`}${character.summary === "" ? "" : `: ${character.summary}`}${seen.length > 0 ? ` Currently: ${seen.join("; ")}` : ""}`;
620
+ return `- ${referent(character)} (${role})${where === "" ? "" : ` [${where}]`}${character.summary === "" ? "" : `: ${character.summary}`}${seen.length > 0 ? ` Currently: ${seen.join("; ")}` : ""}`;
450
621
  };
451
622
  const player = cast.find((member) => member.character.control === "player");
452
623
  const days = time?.agenda === void 0 ? "" : describeSceneAgenda(time.agenda, time.now.now);
@@ -569,11 +740,12 @@ const exactUtterances = {
569
740
  }
570
741
  };
571
742
  /** What a character is reminded of is what the story's records bring back for it: by the cues of the moment, by its words, and by its meaning when vectors exist. */
572
- const recordsRecall = { recall: ({ member, situation, turn, policy, queryVector }, story, signal) => story.recallRanked({
743
+ const recordsRecall = { recall: ({ member, situation, turn, policy, queryVector, explain }, story, signal) => story.recallRanked({
573
744
  characterId: member.character.id,
574
745
  situation,
575
746
  turn,
576
747
  policy,
748
+ ...explain === true ? { explain } : {},
577
749
  ...member.place === void 0 ? {} : { locationId: member.place.location.id }
578
750
  }, signal, queryVector === void 0 ? {} : { queryVector }) };
579
751
  /**
@@ -597,6 +769,8 @@ const declinesToAuthor = {
597
769
  };
598
770
  /** Lets no organisation act: without a strategist factions change only through what the story records. */
599
771
  const factionsStayPut = { strategize: () => Promise.resolve({ acted: [] }) };
772
+ /** Reflects on nothing: without a reflector what characters believe changes only through what the story records. */
773
+ const reflectsOnNothing = { reflect: () => Promise.resolve({ characters: [] }) };
600
774
  /** Judges nothing: without a judge a trigger that waits on a statement never sees it hold. */
601
775
  const judgesNothing = { judge: () => Promise.resolve({ judged: 0 }) };
602
776
  /** Offers nothing: without a suggester the player writes their own move. */
@@ -613,6 +787,7 @@ function defaultBoundaries() {
613
787
  committer: writesNothing,
614
788
  author: declinesToAuthor,
615
789
  strategist: factionsStayPut,
790
+ reflector: reflectsOnNothing,
616
791
  judge: judgesNothing,
617
792
  suggester: offersNothing,
618
793
  recaller: recordsRecall,
@@ -667,7 +842,8 @@ function viewOf(timeline) {
667
842
  /** Where a notice stands for a turn that is not told by its own events: the player's words and what was delivered, as plain text. */
668
843
  function noticeText(node) {
669
844
  const told = node.output === void 0 ? "(nothing was delivered)" : node.output.segments.map((segment) => segment.type === "utterance" ? `${segment.name}: "${segment.text}"` : segment.text).join("\n");
670
- const ruling = node.output?.ooc === void 0 ? "" : `\nThe command was ruled ${node.output.ooc.legal ? "legal" : "illegal and refused"}: ${node.output.ooc.note}`;
845
+ const ooc = node.output?.ooc;
846
+ const ruling = ooc === void 0 ? "" : ooc.question === true ? `\nThe question was answered out of character: ${ooc.note}` : `\nThe command was ruled ${ooc.legal ? "legal" : "illegal and refused"}: ${ooc.note}`;
671
847
  return `The story, as it went earlier (restored):\nThe player said: ${node.player}${ruling}\nIt was told to the player:\n${told}`;
672
848
  }
673
849
  //#endregion
@@ -1011,6 +1187,7 @@ var Timelines = class {
1011
1187
  try {
1012
1188
  await inheritImages(this.folder(from), this.folder(id), branch.timeline.nodes.map((node) => node.id));
1013
1189
  inheritPrompts(this.folder(from), this.folder(id));
1190
+ inheritPacks(this.folder(from), this.folder(id));
1014
1191
  const plan = planMove(branch.timeline, branch.timeline.head, [...agent.session.surface.nodes]);
1015
1192
  this.reconcile(agent, plan);
1016
1193
  writeTimeline(this.folder(id), branch.timeline);
@@ -1028,6 +1205,82 @@ var Timelines = class {
1028
1205
  }
1029
1206
  };
1030
1207
  //#endregion
1208
+ //#region src/host/orchestration/observation.ts
1209
+ /** What a character takes in where it stands and of what it carries: the place, the ways out and what they lead to, what lies in the open, what it holds. */
1210
+ function observeSurroundings(session, characterId, turn) {
1211
+ const placement = session.placements.get("character", characterId);
1212
+ if (placement !== void 0) {
1213
+ session.knowledge.learn(characterId, "location", placement.locationId, turn, true);
1214
+ for (const exit of session.locations.exitsFrom(placement.locationId)) {
1215
+ session.knowledge.learn(characterId, "exit", exit.id, turn, true);
1216
+ session.knowledge.learn(characterId, "location", exit.toId, turn);
1217
+ }
1218
+ for (const { item } of session.items.contents({
1219
+ kind: "location",
1220
+ id: placement.locationId
1221
+ })) if (!item.hidden) session.knowledge.learn(characterId, "item", item.id, turn, true);
1222
+ }
1223
+ for (const { item } of session.items.contents({
1224
+ kind: "character",
1225
+ id: characterId
1226
+ })) session.knowledge.learn(characterId, "item", item.id, turn, true);
1227
+ }
1228
+ /**
1229
+ * The player's character is never asked to act, so nothing else shows it its surroundings: it takes them in when a turn begins, which is
1230
+ * how it comes to know the way back from where it went.
1231
+ */
1232
+ function observeAsPlayer(session, turn) {
1233
+ const player = session.characters.list().find((character) => character.control === "player");
1234
+ if (player !== void 0) observeSurroundings(session, player.id, turn);
1235
+ }
1236
+ //#endregion
1237
+ //#region src/shared/notes.ts
1238
+ const NOTE_KINDS = [
1239
+ "suggestions",
1240
+ "away",
1241
+ "world"
1242
+ ];
1243
+ //#endregion
1244
+ //#region src/host/sessions/notes.ts
1245
+ const KEY$2 = "notes";
1246
+ const isNote = (value) => {
1247
+ if (typeof value !== "object" || value === null) return false;
1248
+ const note = value;
1249
+ return NOTE_KINDS.includes(note["kind"]) && typeof note["turn"] === "number" && Array.isArray(note["lines"]) && note["lines"].every((line) => typeof line === "string");
1250
+ };
1251
+ /** The notes of a session, at most one per kind. */
1252
+ function readNotes(session) {
1253
+ const stored = session.metadata.getValue(KEY$2);
1254
+ return Array.isArray(stored) ? stored.filter(isNote) : [];
1255
+ }
1256
+ /** Replaces the note of the same kind. */
1257
+ function putNote(session, note) {
1258
+ session.metadata.setValue(KEY$2, [...readNotes(session).filter((existing) => existing.kind !== note.kind), note]);
1259
+ }
1260
+ /** The most lines one note keeps: what is past it is not told. */
1261
+ const MAX_NOTE_LINES = 8;
1262
+ /** Adds lines to the note of the kind when it is of the same turn, else starts it. */
1263
+ function addToNote(session, kind, turn, lines) {
1264
+ if (lines.length === 0) return;
1265
+ putNote(session, {
1266
+ kind,
1267
+ turn,
1268
+ lines: [...readNotes(session).find((note) => note.kind === kind && note.turn === turn)?.lines ?? [], ...lines].slice(0, MAX_NOTE_LINES)
1269
+ });
1270
+ }
1271
+ /** Removes every note: they belong to the turn that made them. */
1272
+ function clearNotes(session) {
1273
+ if (readNotes(session).length > 0) session.metadata.setValue(KEY$2, []);
1274
+ }
1275
+ /**
1276
+ * The notes of a session, for the player's screen.
1277
+ * @throws {SessionNotFoundError} when the id names no session.
1278
+ */
1279
+ function notesOfSession(deps, id) {
1280
+ if (!isSessionId(id) || !existsSync(sessionDatabase(deps.sessionsDir(), id))) throw new SessionNotFoundError(`no session "${id}"`);
1281
+ return readNotes(deps.open(id));
1282
+ }
1283
+ //#endregion
1031
1284
  //#region src/host/pacing/director.ts
1032
1285
  const PLOTS_METADATA_KEY = "roleplay.pacing.plots";
1033
1286
  function populatePlots(metadata, plots) {
@@ -1124,55 +1377,426 @@ function updatePlotProgress(store, plotId, developmentId, action) {
1124
1377
  return progress;
1125
1378
  }
1126
1379
  //#endregion
1127
- //#region src/shared/notes.ts
1128
- const NOTE_KINDS = [
1129
- "suggestions",
1130
- "away",
1131
- "world"
1132
- ];
1133
- //#endregion
1134
- //#region src/host/sessions/notes.ts
1135
- const KEY$1 = "notes";
1136
- const isNote = (value) => {
1137
- if (typeof value !== "object" || value === null) return false;
1138
- const note = value;
1139
- return NOTE_KINDS.includes(note["kind"]) && typeof note["turn"] === "number" && Array.isArray(note["lines"]) && note["lines"].every((line) => typeof line === "string");
1380
+ //#region src/host/orchestration/whereabouts.ts
1381
+ const within = (inner, outer, places) => {
1382
+ const byId = new Map(places.map((place) => [place.id, place]));
1383
+ const seen = /* @__PURE__ */ new Set();
1384
+ for (let at = inner; at !== void 0 && !seen.has(at.id); at = at.parentId === void 0 ? void 0 : byId.get(at.parentId)) {
1385
+ if (at.id === outer.id) return true;
1386
+ seen.add(at.id);
1387
+ }
1388
+ return false;
1140
1389
  };
1141
- /** The notes of a session, at most one per kind. */
1142
- function readNotes(session) {
1143
- const stored = session.metadata.getValue(KEY$1);
1144
- return Array.isArray(stored) ? stored.filter(isNote) : [];
1390
+ /** Whether two places are one scene: the same place, or one inside the other (a room and its building). */
1391
+ const sameScene = (a, b, places) => within(a, b, places) || within(b, a, places);
1392
+ /**
1393
+ * Compares the place an action is said to happen at (by key) with where the character is. Only a proven mismatch counts: a character that is
1394
+ * nowhere, or a world without places, is no evidence, and a place that contains the other (a room and its building) is the same for this.
1395
+ */
1396
+ function whereabouts(places, here, at) {
1397
+ const target = places.find((place) => locationKey(place) === at);
1398
+ if (target === void 0) return { kind: "unknown" };
1399
+ if (here === void 0) return { kind: "unplaced" };
1400
+ return within(here, target, places) || within(target, here, places) ? { kind: "here" } : {
1401
+ kind: "elsewhere",
1402
+ target,
1403
+ here
1404
+ };
1145
1405
  }
1146
- /** Replaces the note of the same kind. */
1147
- function putNote(session, note) {
1148
- session.metadata.setValue(KEY$1, [...readNotes(session).filter((existing) => existing.kind !== note.kind), note]);
1406
+ //#endregion
1407
+ //#region src/host/memory/reflection.ts
1408
+ const LAST_KEY = "reflection.last";
1409
+ const CURSOR_KEY = "reflection.cursor";
1410
+ const ANCHOR_KEY = "reflection.anchor";
1411
+ const ERROR_KEY = "reflection.error";
1412
+ const DAY_MS = 864e5;
1413
+ const MAX_MATERIAL = 40;
1414
+ const MAX_BELIEFS_SHOWN = 40;
1415
+ const MAX_ADDED = 4;
1416
+ const MAX_CHANGES = 10;
1417
+ const MAX_TEXT = 300;
1418
+ /** An event this important is reason enough for a belief on its own. */
1419
+ const DECISIVE_IMPORTANCE = 4;
1420
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1421
+ function readLast(session) {
1422
+ const stored = session.metadata.getValue(LAST_KEY);
1423
+ return isRecord(stored) && typeof stored["turn"] === "number" ? stored : void 0;
1149
1424
  }
1150
- /** The most lines one note keeps: what is past it is not told. */
1151
- const MAX_NOTE_LINES = 8;
1152
- /** Adds lines to the note of the kind when it is of the same turn, else starts it. */
1153
- function addToNote(session, kind, turn, lines) {
1154
- if (lines.length === 0) return;
1155
- putNote(session, {
1156
- kind,
1157
- turn,
1158
- lines: [...readNotes(session).find((note) => note.kind === kind && note.turn === turn)?.lines ?? [], ...lines].slice(0, MAX_NOTE_LINES)
1425
+ function readCursor(session) {
1426
+ const stored = session.metadata.getValue(CURSOR_KEY);
1427
+ return isRecord(stored) ? Object.fromEntries(Object.entries(stored).filter((entry) => typeof entry[1] === "number")) : {};
1428
+ }
1429
+ function readAnchor(session) {
1430
+ const stored = session.metadata.getValue(ANCHOR_KEY);
1431
+ return isRecord(stored) && typeof stored["now"] === "number" ? {
1432
+ now: stored["now"],
1433
+ ...typeof stored["place"] === "number" ? { place: stored["place"] } : {}
1434
+ } : void 0;
1435
+ }
1436
+ function writeAnchor(session, place, now) {
1437
+ session.metadata.setValue(ANCHOR_KEY, {
1438
+ now,
1439
+ ...place === void 0 ? {} : { place: place.id }
1159
1440
  });
1160
1441
  }
1161
- /** Removes every note: they belong to the turn that made them. */
1162
- function clearNotes(session) {
1163
- if (readNotes(session).length > 0) session.metadata.setValue(KEY$1, []);
1442
+ const playerPlace = (store) => store.cast().find((member) => member.character.control === "player")?.place?.location;
1443
+ /** What is known of the story's reflection: whether a pass runs, the latest that finished, and why the latest failed. */
1444
+ function reflectionStatus(session, running) {
1445
+ const last = readLast(session);
1446
+ const failure = session.metadata.getValue(ERROR_KEY);
1447
+ return {
1448
+ running,
1449
+ ...last === void 0 ? {} : { last },
1450
+ ...isRecord(failure) && typeof failure["message"] === "string" && typeof failure["at"] === "string" ? { error: {
1451
+ at: failure["at"],
1452
+ message: failure["message"]
1453
+ } } : {}
1454
+ };
1455
+ }
1456
+ function recordFailure(session, message) {
1457
+ session.metadata.setValue(ERROR_KEY, {
1458
+ at: (/* @__PURE__ */ new Date()).toISOString(),
1459
+ message: message.slice(0, 500)
1460
+ });
1164
1461
  }
1165
1462
  /**
1166
- * The notes of a session, for the player's screen.
1167
- * @throws {SessionNotFoundError} when the id names no session.
1463
+ * Whether the story should reflect after this turn, and why. A pass waits until `minTurns` turns have passed since the last one; then it
1464
+ * comes after `everyTurns` turns, or when the scene has changed since the last pass (the player's character is somewhere that is neither
1465
+ * where it was nor inside or around it, or `sceneDays` of story time have passed). The first look only notes where the story stands.
1168
1466
  */
1169
- function notesOfSession(deps, id) {
1170
- if (!isSessionId(id) || !existsSync(sessionDatabase(deps.sessionsDir(), id))) throw new SessionNotFoundError(`no session "${id}"`);
1171
- return readNotes(deps.open(id));
1467
+ function dueReflection(store, turn) {
1468
+ const { reflection } = store.settings();
1469
+ if (!reflection.auto) return void 0;
1470
+ const session = store.story;
1471
+ const { now } = store.time(turn);
1472
+ const here = playerPlace(store);
1473
+ const anchor = readAnchor(session);
1474
+ if (anchor === void 0) {
1475
+ writeAnchor(session, here, now);
1476
+ return;
1477
+ }
1478
+ const since = turn - (readLast(session)?.turn ?? 0);
1479
+ if (since < reflection.minTurns) return void 0;
1480
+ if (reflection.everyTurns > 0 && since >= reflection.everyTurns) return "turns";
1481
+ if (!reflection.onSceneChange) return void 0;
1482
+ const places = session.locations.list();
1483
+ const before = places.find((place) => place.id === anchor.place);
1484
+ if (here !== void 0 && before !== void 0 && !sameScene(here, before, places)) return "scene";
1485
+ if (reflection.sceneDays > 0 && now - anchor.now >= reflection.sceneDays * DAY_MS) return "scene";
1486
+ }
1487
+ /**
1488
+ * The characters that have enough new to sort, the most first. Only what the story has made final counts, and only up to the first thing
1489
+ * still a draft, so that nothing is passed over that is sealed later.
1490
+ */
1491
+ function materialOf(session, minNew) {
1492
+ const cursor = readCursor(session);
1493
+ const found = [];
1494
+ for (const character of session.characters.list()) {
1495
+ if (character.control !== "agent" || character.kind !== "person" || character.tier === "background") continue;
1496
+ const taken = session.events.perceivedBy(character.id);
1497
+ const draft = taken.filter((entry) => !entry.event.sealed).map((entry) => entry.perception.id);
1498
+ const ceiling = draft.length === 0 ? Infinity : Math.min(...draft) - 1;
1499
+ const fresh = taken.filter((entry) => entry.event.sealed && entry.perception.id > (cursor[characterKey(character)] ?? 0) && entry.perception.id <= ceiling).sort((a, b) => a.perception.id - b.perception.id).slice(0, MAX_MATERIAL);
1500
+ if (fresh.length < minNew) continue;
1501
+ const beliefs = session.memories.list(character.id).sort((a, b) => b.importance - a.importance || a.id - b.id).slice(0, MAX_BELIEFS_SHOWN);
1502
+ found.push({
1503
+ character,
1504
+ fresh,
1505
+ beliefs
1506
+ });
1507
+ }
1508
+ return found.sort((a, b) => b.fresh.length - a.fresh.length);
1509
+ }
1510
+ const idList = {
1511
+ type: "array",
1512
+ items: { type: "integer" }
1513
+ };
1514
+ const RESULT = {
1515
+ type: "object",
1516
+ properties: {
1517
+ add: {
1518
+ type: "array",
1519
+ description: "New beliefs, at most four. Leave empty when nothing new can be firmly said.",
1520
+ items: {
1521
+ type: "object",
1522
+ properties: {
1523
+ kind: {
1524
+ type: "string",
1525
+ enum: [...MEMORY_KINDS],
1526
+ description: "belief: what it holds true or suspects; relationship: how it stands with someone; knowledge: something it knows."
1527
+ },
1528
+ text: {
1529
+ type: "string",
1530
+ description: "What the character believes, in one or two sentences, in its own terms. Say plainly when it is a suspicion, a rumour or a guess."
1531
+ },
1532
+ about: {
1533
+ type: "array",
1534
+ items: { type: "string" },
1535
+ description: "The names of the characters it is about."
1536
+ },
1537
+ importance: {
1538
+ type: "integer",
1539
+ description: `From 1 (passing) to 5 (it shapes how they act).`
1540
+ },
1541
+ perceptions: {
1542
+ ...idList,
1543
+ description: "The numbers of the things it took in that this rests on."
1544
+ },
1545
+ beliefs: {
1546
+ ...idList,
1547
+ description: "The numbers of the beliefs it generalises or builds on, if any."
1548
+ }
1549
+ },
1550
+ required: [
1551
+ "kind",
1552
+ "text",
1553
+ "importance",
1554
+ "perceptions"
1555
+ ],
1556
+ additionalProperties: false
1557
+ }
1558
+ },
1559
+ revise: {
1560
+ type: "array",
1561
+ description: "Beliefs to firm up, doubt or correct in the light of what came after them.",
1562
+ items: {
1563
+ type: "object",
1564
+ properties: {
1565
+ id: {
1566
+ type: "integer",
1567
+ description: "The number of the belief, as listed."
1568
+ },
1569
+ text: {
1570
+ type: "string",
1571
+ description: "The belief as it should read now."
1572
+ },
1573
+ importance: {
1574
+ type: "integer",
1575
+ description: `From 1 to 5.`
1576
+ },
1577
+ perceptions: {
1578
+ ...idList,
1579
+ description: "The numbers of the things it took in since that bear on it."
1580
+ }
1581
+ },
1582
+ required: ["id", "perceptions"],
1583
+ additionalProperties: false
1584
+ }
1585
+ },
1586
+ drop: {
1587
+ type: "array",
1588
+ description: "Beliefs to let go: settled or overturned by what came after, or merged into another.",
1589
+ items: {
1590
+ type: "object",
1591
+ properties: {
1592
+ id: { type: "integer" },
1593
+ perceptions: {
1594
+ ...idList,
1595
+ description: "What it took in since that settles or overturns it."
1596
+ },
1597
+ merged_into: {
1598
+ type: "integer",
1599
+ description: "The number of the belief that now says the same, instead of a reason from what it took in."
1600
+ }
1601
+ },
1602
+ required: ["id"],
1603
+ additionalProperties: false
1604
+ }
1605
+ }
1606
+ },
1607
+ required: [
1608
+ "add",
1609
+ "revise",
1610
+ "drop"
1611
+ ],
1612
+ additionalProperties: false
1613
+ };
1614
+ const shownOf = (material) => ({
1615
+ perceptions: new Map(material.fresh.map((entry) => [entry.perception.id, entry])),
1616
+ beliefs: new Map(material.beliefs.map((belief) => [belief.id, belief]))
1617
+ });
1618
+ /**
1619
+ * Why a proposal cannot be written, or nothing when it can. A belief must rest on what the character took in: on things from at least two
1620
+ * different turns, or on one event that turned the story; a belief is changed or let go only for what came after it, or for being merged
1621
+ * into another. Nothing is judged about whether the belief is wise; only whether it is grounded in what the character was given.
1622
+ */
1623
+ function proposalProblems(proposal, shown, resolveName) {
1624
+ const problems = [];
1625
+ const add = proposal.add ?? [];
1626
+ const revise = proposal.revise ?? [];
1627
+ const drop = proposal.drop ?? [];
1628
+ if (add.length > MAX_ADDED) problems.push(`add: at most ${MAX_ADDED} new beliefs in one pass; merge or choose`);
1629
+ if (add.length + revise.length + drop.length > MAX_CHANGES) problems.push(`at most ${MAX_CHANGES} changes in one pass`);
1630
+ const cited = (ids, where) => (ids ?? []).flatMap((id) => {
1631
+ const entry = shown.perceptions.get(id);
1632
+ if (entry === void 0) problems.push(`${where}: there is no thing it took in numbered ${id}`);
1633
+ return entry === void 0 ? [] : [entry];
1634
+ });
1635
+ add.forEach((belief, index) => {
1636
+ const where = `add[${index}]`;
1637
+ if (!MEMORY_KINDS.includes(belief.kind)) problems.push(`${where}: unknown kind "${belief.kind}"`);
1638
+ if (belief.text.trim() === "") problems.push(`${where}: say what it believes`);
1639
+ else if (belief.text.trim().length > MAX_TEXT) problems.push(`${where}: at most ${MAX_TEXT} characters; say it shorter`);
1640
+ if (!Number.isInteger(belief.importance) || belief.importance < 1 || belief.importance > 5) problems.push(`${where}: importance runs from 1 to 5`);
1641
+ const events = cited(belief.perceptions, where);
1642
+ const built = (belief.beliefs ?? []).flatMap((id) => {
1643
+ const known = shown.beliefs.get(id);
1644
+ if (known === void 0) problems.push(`${where}: there is no belief numbered ${id}`);
1645
+ return known === void 0 ? [] : [known];
1646
+ });
1647
+ if ((/* @__PURE__ */ new Set([...events.map((entry) => entry.event.turn), ...built.map((known) => known.turn)])).size < 2 && !events.some((entry) => entry.event.importance >= DECISIVE_IMPORTANCE)) problems.push(`${where}: one passing moment is not yet a belief; rest it on things from at least two different turns, or on one event that turned the story`);
1648
+ for (const name of belief.about ?? []) if (resolveName(name) === void 0) problems.push(`${where}: "${name}" is not a character; name them as they are named`);
1649
+ });
1650
+ const touched = /* @__PURE__ */ new Set();
1651
+ const touch = (id, where) => {
1652
+ if (touched.has(id)) problems.push(`${where}: belief ${id} is already changed in this pass`);
1653
+ touched.add(id);
1654
+ };
1655
+ const fresh = (events, belief, where) => {
1656
+ if (events.length === 0) problems.push(`${where}: say what it took in since that bears on it`);
1657
+ for (const entry of events) if (entry.event.turn < belief.turn) problems.push(`${where}: thing ${entry.perception.id} came before the belief was formed; cite what came after`);
1658
+ };
1659
+ revise.forEach((change, index) => {
1660
+ const where = `revise[${index}]`;
1661
+ const belief = shown.beliefs.get(change.id);
1662
+ if (belief === void 0) {
1663
+ problems.push(`${where}: there is no belief numbered ${change.id}`);
1664
+ return;
1665
+ }
1666
+ touch(change.id, where);
1667
+ if (change.text === void 0 && change.importance === void 0) problems.push(`${where}: say what changes`);
1668
+ if (change.text !== void 0 && (change.text.trim() === "" || change.text.trim().length > MAX_TEXT)) problems.push(`${where}: the text must be there and at most ${MAX_TEXT} characters`);
1669
+ if (change.importance !== void 0 && (!Number.isInteger(change.importance) || change.importance < 1 || change.importance > 5)) problems.push(`${where}: importance runs from 1 to 5`);
1670
+ fresh(cited(change.perceptions, where), belief, where);
1671
+ });
1672
+ const dropped = new Set(drop.map((entry) => entry.id));
1673
+ drop.forEach((change, index) => {
1674
+ const where = `drop[${index}]`;
1675
+ const belief = shown.beliefs.get(change.id);
1676
+ if (belief === void 0) {
1677
+ problems.push(`${where}: there is no belief numbered ${change.id}`);
1678
+ return;
1679
+ }
1680
+ touch(change.id, where);
1681
+ if (change.merged_into !== void 0) {
1682
+ if (change.merged_into === change.id || !shown.beliefs.has(change.merged_into) || dropped.has(change.merged_into)) problems.push(`${where}: merge into a belief that stays`);
1683
+ return;
1684
+ }
1685
+ fresh(cited(change.perceptions, where), belief, where);
1686
+ });
1687
+ return problems;
1688
+ }
1689
+ const keysOf = (names, resolveName) => (names ?? []).flatMap((name) => {
1690
+ const key = resolveName(name);
1691
+ return key === void 0 ? [] : [key];
1692
+ });
1693
+ /** The edit that writes a proposal that passed. */
1694
+ function editOf(turn, character, proposal, resolveName) {
1695
+ const who = characterKey(character);
1696
+ return {
1697
+ turn,
1698
+ beliefs: (proposal.add ?? []).map((belief) => ({
1699
+ character: who,
1700
+ kind: belief.kind,
1701
+ text: belief.text.trim(),
1702
+ about: keysOf(belief.about, resolveName),
1703
+ importance: belief.importance
1704
+ })),
1705
+ beliefEdits: (proposal.revise ?? []).map((change) => ({
1706
+ id: change.id,
1707
+ ...change.text === void 0 ? {} : { text: change.text.trim() },
1708
+ ...change.importance === void 0 ? {} : { importance: change.importance }
1709
+ })),
1710
+ beliefRetractions: (proposal.drop ?? []).map((change) => change.id)
1711
+ };
1712
+ }
1713
+ function brief(session, material, now, zone, time) {
1714
+ const { character, fresh, beliefs } = material;
1715
+ const named = (id) => session.characters.get(id)?.name ?? String(id);
1716
+ const believed = beliefs.map((belief) => {
1717
+ const about = belief.about.length === 0 ? "" : `, about ${belief.about.map(named).join(" and ")}`;
1718
+ return `- b${belief.id} (${belief.kind}, importance ${belief.importance}${about}): ${belief.text}`;
1719
+ });
1720
+ const taken = fresh.map((entry) => {
1721
+ const at = time(entry.event.turn, entry.event.round);
1722
+ return `- p${entry.perception.id}${at === void 0 ? "" : ` (${describeWhen(at, now, zone)})`}: ${entry.perception.content}`;
1723
+ });
1724
+ return [
1725
+ `Character: ${referent(character)}${character.summary === "" ? "" : ` - ${character.summary}`}`,
1726
+ "What they believe now:",
1727
+ ...believed.length === 0 ? ["(nothing yet)"] : believed,
1728
+ "What they have taken in since:",
1729
+ ...taken,
1730
+ "Sort their memory."
1731
+ ].join("\n");
1732
+ }
1733
+ /**
1734
+ * Has the characters with the most new to sort sort it into what they believe, one request each, one after another. Each answer is checked
1735
+ * against what the character was shown before it is written, and the writing of one character is all or nothing; a failure stops the pass
1736
+ * and leaves the characters not yet done as they were.
1737
+ */
1738
+ function memoryReflector(deps) {
1739
+ return { async reflect(job, signal) {
1740
+ const parent = deps.agentOf(job.chat);
1741
+ if (parent === void 0) throw new Error(`no agent for chat ${job.chat}`);
1742
+ const { store } = job;
1743
+ const session = store.story;
1744
+ const settings = store.settings();
1745
+ const { now, zone } = store.time(job.turn);
1746
+ const due = materialOf(session, job.reason === "manual" ? 1 : settings.reflection.minNew);
1747
+ const taken = job.reason === "manual" ? due : due.slice(0, settings.reflection.perRun);
1748
+ const resolveName = (name) => {
1749
+ const found = session.characters.findByName(name.trim());
1750
+ return found.length === 1 ? characterKey(found[0]) : void 0;
1751
+ };
1752
+ const characters = [];
1753
+ for (const material of taken) {
1754
+ const shown = shownOf(material);
1755
+ const proposal = await runChild({
1756
+ parent,
1757
+ signal,
1758
+ reasoningEffort: settings.reasoning.children,
1759
+ sampling: childSampling(settings, "records"),
1760
+ ...childModel(settings, "records"),
1761
+ trace: childTrace(store, "records", `reflection ${material.character.name}`),
1762
+ persona: promptFor(parent, "roleplay/reflection", settings.prompts.language),
1763
+ prompt: brief(session, material, now, zone, (turn, round) => session.clock.at(turn, round)),
1764
+ result: RESULT,
1765
+ beforeSubmit: (value) => {
1766
+ const problems = proposalProblems(value, shown, resolveName);
1767
+ return problems.length === 0 ? void 0 : `not acceptable: ${problems.join("; ")}`;
1768
+ },
1769
+ maxCalls: 3
1770
+ });
1771
+ const reached = Math.max(...material.fresh.map((entry) => entry.perception.id));
1772
+ session.transaction(() => {
1773
+ session.edit(editOf(job.turn, material.character, proposal, resolveName));
1774
+ session.metadata.setValue(CURSOR_KEY, {
1775
+ ...readCursor(session),
1776
+ [characterKey(material.character)]: reached
1777
+ });
1778
+ });
1779
+ characters.push({
1780
+ name: material.character.name,
1781
+ added: proposal.add?.length ?? 0,
1782
+ revised: proposal.revise?.length ?? 0,
1783
+ dropped: proposal.drop?.length ?? 0
1784
+ });
1785
+ }
1786
+ session.metadata.setValue(LAST_KEY, {
1787
+ turn: job.turn,
1788
+ at: (/* @__PURE__ */ new Date()).toISOString(),
1789
+ reason: job.reason,
1790
+ characters
1791
+ });
1792
+ writeAnchor(session, playerPlace(store), now);
1793
+ session.metadata.deleteValue(ERROR_KEY);
1794
+ return { characters };
1795
+ } };
1172
1796
  }
1173
1797
  //#endregion
1174
1798
  //#region src/host/sessions/activity.ts
1175
- const KEY = "activity";
1799
+ const KEY$1 = "activity";
1176
1800
  const isEntry = (value) => {
1177
1801
  if (typeof value !== "object" || value === null) return false;
1178
1802
  const entry = value;
@@ -1180,13 +1804,75 @@ const isEntry = (value) => {
1180
1804
  };
1181
1805
  /** The recorded runs, oldest first. */
1182
1806
  function readActivity(session) {
1183
- const stored = session.metadata.getValue(KEY);
1807
+ const stored = session.metadata.getValue(KEY$1);
1184
1808
  return Array.isArray(stored) ? stored.filter(isEntry) : [];
1185
1809
  }
1810
+ /** Files the run and returns the runs that fell off the end of the record to make room. */
1186
1811
  function recordActivity(session, entry) {
1187
- session.metadata.setValue(KEY, [...readActivity(session), entry].slice(-60));
1812
+ const all = [...readActivity(session), entry];
1813
+ session.metadata.setValue(KEY$1, all.slice(-60));
1814
+ return all.slice(0, -60);
1815
+ }
1816
+ const RUN_FOLDER = "activity";
1817
+ const RUN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
1818
+ const runFile = (folder, run) => {
1819
+ if (!RUN_ID.test(run)) throw new RangeError(`"${run}" is not a run`);
1820
+ return join(folder, RUN_FOLDER, `${run}.json`);
1821
+ };
1822
+ /** Stores what a helper was told and did, beside the session's database: it is bulky, and only read to find out what went wrong. */
1823
+ function keepRunDetail(folder, run, detail) {
1824
+ const file = runFile(folder, run);
1825
+ mkdirSync(join(folder, RUN_FOLDER), { recursive: true });
1826
+ writeFileSync(`${file}.tmp`, JSON.stringify(detail));
1827
+ renameSync(`${file}.tmp`, file);
1828
+ }
1829
+ /** The stored detail of a run, or nothing when it was not kept or has been dropped. */
1830
+ function readRunDetail(folder, run) {
1831
+ try {
1832
+ return JSON.parse(readFileSync(runFile(folder, run), "utf8"));
1833
+ } catch (error) {
1834
+ if (error.code === "ENOENT") return void 0;
1835
+ throw error;
1836
+ }
1837
+ }
1838
+ function forgetRunDetails(folder, dropped) {
1839
+ for (const entry of dropped) if (entry.run !== void 0) rmSync(runFile(folder, entry.run), { force: true });
1840
+ }
1841
+ //#endregion
1842
+ //#region src/host/triggers/deliver.ts
1843
+ const KEY = "triggers.withdrawn";
1844
+ /** Why a note was withdrawn instead of told, by the number of the note. */
1845
+ function readWithdrawn(session) {
1846
+ const stored = session.metadata.getValue(KEY);
1847
+ if (!Array.isArray(stored)) return {};
1848
+ return Object.fromEntries(stored.flatMap((entry) => {
1849
+ const { note, reason } = entry ?? {};
1850
+ return typeof note === "number" && typeof reason === "string" ? [[note, reason]] : [];
1851
+ }));
1852
+ }
1853
+ /**
1854
+ * Tells these notes as the story stands now: each is written from the story at this moment, and one that no longer applies is let go and the
1855
+ * reason kept (`readWithdrawn`). @returns what is to be told, with the number of its note.
1856
+ */
1857
+ function deliverNow(session, notes, clock) {
1858
+ const { shown, withdrawn } = session.deliverNotes(notes, clock);
1859
+ if (withdrawn.length > 0) session.transaction(() => {
1860
+ for (const { note } of withdrawn) session.triggers.resolveNote(note.id, "lapsed");
1861
+ const before = Object.entries(readWithdrawn(session)).map(([note, reason]) => ({
1862
+ note: Number(note),
1863
+ reason
1864
+ }));
1865
+ session.metadata.setValue(KEY, [...before, ...withdrawn.map(({ note, reason }) => ({
1866
+ note: note.id,
1867
+ reason
1868
+ }))].slice(-100));
1869
+ });
1870
+ return shown.map(({ note, text }) => ({
1871
+ id: note.id,
1872
+ text
1873
+ }));
1188
1874
  }
1189
1875
  //#endregion
1190
- export { describeWhen as C, zoneOf as D, skipTime as E, describeTime as S, readTime as T, Timelines as _, notesOfSession as a, ClockError as b, PLOTS_METADATA_KEY as c, pacingAdvice as d, plotAuthorNeeded as f, TimelineError as g, updatePlotProgress as h, clearNotes as i, addSessionPlot as l, populatePlots as m, recordActivity as n, putNote as o, plotProgressOf as p, addToNote as r, readNotes as s, readActivity as t, describePacingAdvice as u, defaultBoundaries as v, endRound as w, beginTurn as x, sameWords as y };
1876
+ export { readTimeline as A, skipTime as B, notesOfSession as C, observeSurroundings as D, observeAsPlayer as E, beginTurn as F, RESULTS as G, referent as H, describeTime as I, answerEstimate as K, describeWhen as L, defaultBoundaries as M, sameWords as N, TimelineError as O, ClockError as P, endRound as R, clearNotes as S, readNotes as T, AWAY_ACTION_SCHEMA as U, zoneOf as V, CHARACTER_ACTION_SCHEMA as W, plotAuthorNeeded as _, readActivity as a, updatePlotProgress as b, dueReflection as c, reflectionStatus as d, whereabouts as f, pacingAdvice as g, describePacingAdvice as h, keepRunDetail as i, pathTo as j, Timelines as k, memoryReflector as l, addSessionPlot as m, readWithdrawn as n, readRunDetail as o, PLOTS_METADATA_KEY as p, parseCharacterAction as q, forgetRunDetails as r, recordActivity as s, deliverNow as t, recordFailure as u, plotProgressOf as v, putNote as w, addToNote as x, populatePlots as y, readTime as z };
1191
1877
 
1192
- //# sourceMappingURL=activity-BbqFG9-3.js.map
1878
+ //# sourceMappingURL=deliver--uMhC6oO.js.map