@dsh-agentic-roleplay/core 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/lib/authoring.js +18 -223
  2. package/lib/client.js +1838 -489
  3. package/lib/client.js.map +1 -1
  4. package/lib/compaction.js +1 -1
  5. package/lib/deliver-BSsDtF6X.js +3443 -0
  6. package/lib/{documents-7GMc5NnW.js → documents-B5XAdfo2.js} +992 -14
  7. package/lib/{gallery-DUeBMHQX.js → gallery-DS5-qH9F.js} +2 -2
  8. package/lib/{generator-HPifO3Kk.js → generator-BzeepLd2.js} +3 -3
  9. package/lib/images.js +3 -3
  10. package/lib/index.js +351 -13
  11. package/lib/narration-DK2kiIjE.js +141 -0
  12. package/lib/orchestration.js +867 -1547
  13. package/lib/{packs-alJTiDM2.js → packs-BCGK9KZV.js} +51 -7
  14. package/lib/{presenter-agent-PX1WVaJB.js → presenter-agent-Cp-J0onD.js} +3 -3
  15. package/lib/{narration-CKZTk5UE.js → settings-CA6icLL_.js} +158 -142
  16. package/package.json +4 -4
  17. package/packs/scene/strip.js +1 -1
  18. package/prompts/en/roleplay/character-decide.md +1 -1
  19. package/prompts/en/roleplay/character-rules.md +1 -1
  20. package/prompts/en/roleplay/chronicler.md +1 -1
  21. package/prompts/en/roleplay/dice.md +7 -0
  22. package/prompts/en/roleplay/game-master.md +3 -1
  23. package/prompts/en/roleplay/reflection.md +4 -2
  24. package/prompts/en/roleplay/style.md +1 -1
  25. package/prompts/en/roleplay/suggester.md +1 -1
  26. package/prompts/en/translate/document.md +6 -0
  27. package/prompts/en/translate/glossary.md +5 -0
  28. package/prompts/en/translate/notice.md +2 -0
  29. package/prompts/zh/roleplay/character-decide.md +1 -1
  30. package/prompts/zh/roleplay/character-rules.md +1 -1
  31. package/prompts/zh/roleplay/chronicler.md +1 -1
  32. package/prompts/zh/roleplay/dice.md +7 -0
  33. package/prompts/zh/roleplay/game-master.md +3 -1
  34. package/prompts/zh/roleplay/reflection.md +4 -2
  35. package/prompts/zh/roleplay/style.md +1 -1
  36. package/prompts/zh/roleplay/suggester.md +1 -1
  37. package/prompts/zh/translate/document.md +6 -0
  38. package/prompts/zh/translate/glossary.md +5 -0
  39. package/prompts/zh/translate/notice.md +2 -0
  40. package/lib/deliver--uMhC6oO.js +0 -1878
  41. package/lib/src-CWTNeL6Y.js +0 -128
@@ -1,1878 +0,0 @@
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";
5
- import { join } from "node:path";
6
- import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
7
- import { createUserMessage } from "@deepseek-ai/dsh-llm";
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
168
- //#region src/host/clock/story-clock.ts
169
- var ClockError = class extends Error {};
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. */
171
- function describeWhen(instant, now, zone) {
172
- const a = localTime(instant, zone);
173
- const b = localTime(now, zone);
174
- return a.year === b.year && a.month === b.month && a.day === b.day ? clockTime(instant, zone) : describeInstant(instant, zone);
175
- }
176
- /** The time in a sentence: the day and date, the clock, and the part of the day. */
177
- function describeTime(time) {
178
- return `${describeInstant(time.now, time.zone)} (${dayPart(localTime(time.now, time.zone).minuteOfDay)})`;
179
- }
180
- /** The time zone the story is read in. */
181
- const zoneOf = (config) => config.timeZone === "" ? "UTC" : config.timeZone;
182
- /** The clock, started when a session has none yet, and detached from the real clock when the settings say so. The mode the story has is the one it keeps otherwise. */
183
- function ensure(session, config, turn, wall) {
184
- const current = session.clock.get();
185
- if (current === void 0) {
186
- session.clock.start(config.mode, config.mode === "real" ? wall : Math.floor(wall / MINUTE) * MINUTE);
187
- return session.clock.get() ?? {
188
- mode: config.mode,
189
- now: wall
190
- };
191
- }
192
- if (current.mode !== "real" || config.mode !== "simulated") return current;
193
- session.clock.resync("simulated", Math.max(current.now, wall), turn, "the story's time was detached from the real clock");
194
- return session.clock.get() ?? current;
195
- }
196
- const timeOf = (state, config) => ({
197
- mode: state.mode,
198
- now: state.now,
199
- zone: zoneOf(config)
200
- });
201
- /** What time it is, without letting any pass. */
202
- function readTime(session, config, turn, wall) {
203
- return session.transaction(() => timeOf(ensure(session, config, turn, wall), config));
204
- }
205
- /**
206
- * The start of a turn. Following the wall clock, the time since the last turn passed outside the story:
207
- * `away` says how long.
208
- */
209
- function beginTurn(session, config, turn, wall) {
210
- return session.transaction(() => {
211
- const state = ensure(session, config, turn, wall);
212
- if (state.mode === "real" && wall > state.now) {
213
- session.clock.advance({
214
- to: wall,
215
- turn,
216
- round: 0,
217
- kind: "real",
218
- reason: "between turns"
219
- });
220
- return {
221
- time: timeOf({
222
- mode: "real",
223
- now: wall
224
- }, config),
225
- away: wall - state.now
226
- };
227
- }
228
- return { time: timeOf(state, config) };
229
- });
230
- }
231
- /**
232
- * A round passes. Simulated, it takes what the game master said (or the default), and at least as long as the
233
- * journey the player's character made (`minimum`); following the wall clock, it takes as long as it took.
234
- */
235
- function endRound(session, config, turn, round, wall, stated, minimum) {
236
- return session.transaction(() => {
237
- const state = ensure(session, config, turn, wall);
238
- if (state.mode === "real") {
239
- const to = Math.max(state.now, wall);
240
- session.clock.advance({
241
- to,
242
- turn,
243
- round,
244
- kind: "real"
245
- });
246
- return {
247
- from: state.now,
248
- to,
249
- zone: zoneOf(config)
250
- };
251
- }
252
- const took = Math.max(stated ?? config.roundSeconds, minimum ?? 0) * SECOND;
253
- session.clock.advance({
254
- to: state.now + took,
255
- turn,
256
- round,
257
- kind: "elapsed"
258
- });
259
- return {
260
- from: state.now,
261
- to: state.now + took,
262
- zone: zoneOf(config)
263
- };
264
- });
265
- }
266
- /**
267
- * Skip ahead in the story's own time.
268
- * @throws {ClockError} when time follows the wall clock, the request is not one, or it asks for more than the chat allows.
269
- */
270
- function skipTime(session, config, turn, round, wall, request) {
271
- return session.transaction(() => {
272
- const state = ensure(session, config, turn, wall);
273
- if (state.mode === "real") throw new ClockError("the story's time follows the wall clock, so it cannot be skipped");
274
- const zone = zoneOf(config);
275
- const reason = request.reason.trim();
276
- if (reason === "") throw new ClockError("say what happens in the time that passes (reason)");
277
- let to;
278
- if ("byMinutes" in request) {
279
- if (!Number.isInteger(request.byMinutes) || request.byMinutes < 1) throw new ClockError("by_minutes must be a whole number of minutes, at least 1");
280
- to = state.now + request.byMinutes * MINUTE;
281
- } else try {
282
- to = nextTimeOfDay(state.now, zone, request.untilTime, request.daysLater);
283
- } catch (error) {
284
- throw new ClockError(error instanceof RangeError ? error.message : String(error));
285
- }
286
- if (to - state.now > config.maxSkipDays * DAY) throw new ClockError(`that is ${Math.round((to - state.now) / DAY)} days from now (${describeInstant(state.now, zone)}), more than the ${config.maxSkipDays} days this chat allows in one skip`);
287
- session.clock.advance({
288
- to,
289
- turn,
290
- round,
291
- kind: "skip",
292
- reason
293
- });
294
- return {
295
- from: state.now,
296
- to,
297
- zone,
298
- reason
299
- };
300
- });
301
- }
302
- //#endregion
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
- };
313
- function describe(character) {
314
- const lines = [`You are ${character.name}.`];
315
- if (character.aliases.length > 0) lines.push(`You are also called ${character.aliases.join(", ")}.`);
316
- const facts = [
317
- character.age === void 0 ? void 0 : `age: ${character.age}`,
318
- character.gender === void 0 ? void 0 : `gender: ${character.gender}`,
319
- character.pronouns === void 0 ? void 0 : `pronouns: ${character.pronouns}`
320
- ].filter((fact) => fact !== void 0);
321
- if (facts.length > 0) lines.push(facts.join("; ") + ".");
322
- for (const [label, text] of [
323
- ["Summary", character.summary],
324
- ["Personality", character.personality],
325
- ["Background", character.background],
326
- ["Appearance", character.appearance],
327
- ["How you speak", character.speech.style]
328
- ]) if (text.trim() !== "") lines.push(`${label}: ${text.trim()}`);
329
- return lines.join("\n");
330
- }
331
- /** At most this many features and ways out of a place are told at once. */
332
- const SHOWN_FEATURES = 12;
333
- const SHOWN_EXITS = 12;
334
- const sentence = (text) => {
335
- return (/^[^.!?。!?]*[.!?。!?]?/u.exec(text.trim())?.[0] ?? text).trim();
336
- };
337
- /** At most this many things are listed at once: the rest are said to be there and left for a closer look. */
338
- const SHOWN_ITEMS = 12;
339
- /** One thing in a sentence: how many, what state it is in, where it is. */
340
- function describeItem(item, { withKeys }) {
341
- const name = `${item.quantity > 1 ? `${item.quantity} ` : ""}${item.name}${item.quality === "" ? "" : ` (${item.quality})`}`;
342
- const extra = [
343
- item.hidden ? "hidden" : "",
344
- item.state === void 0 ? "" : item.state,
345
- item.where ?? ""
346
- ].filter((part) => part !== "").join(", ");
347
- const inside = item.contents === void 0 ? "" : ` holding ${item.contents.join(", ")}`;
348
- return `${withKeys ? `${item.key}: ` : ""}${name}${extra === "" ? "" : ` [${extra}]`}${inside}`;
349
- }
350
- /** A list of things, capped. */
351
- function describeItems(items, options) {
352
- return `${items.slice(0, SHOWN_ITEMS).map((item) => describeItem(item, options)).join("; ")}${items.length > SHOWN_ITEMS ? `; and ${items.length - SHOWN_ITEMS} more` : ""}`;
353
- }
354
- /** What someone in a place is told about it: what it is like, what can be pointed at, and the ways out. */
355
- function describePlace(view, { withKeys }) {
356
- const { location, exits } = view;
357
- const lines = [`${location.name}${withKeys ? ` (${view.key})` : ""}${location.description === "" ? "" : `: ${location.description}`}`];
358
- if (location.features.length > 0) {
359
- const shown = location.features.slice(0, SHOWN_FEATURES).map((feature) => `${withKeys ? `${feature.key}: ` : ""}${feature.name}${feature.description === "" ? "" : ` - ${sentence(feature.description)}`}`);
360
- lines.push(`Things here: ${shown.join("; ")}${location.features.length > SHOWN_FEATURES ? `; and ${location.features.length - SHOWN_FEATURES} more` : ""}`);
361
- }
362
- if (exits.length > 0) {
363
- const shown = exits.slice(0, SHOWN_EXITS).map(({ key, name, exit }) => `${withKeys ? `${key}: ` : ""}${name}${exit.description === "" ? "" : ` (${sentence(exit.description)})`}${exit.state === "open" ? "" : ` [${exit.state}${exit.note === "" ? "" : `: ${exit.note}`}]`}`);
364
- lines.push(`Ways out: ${shown.join("; ")}${exits.length > SHOWN_EXITS ? `; and ${exits.length - SHOWN_EXITS} more` : ""}`);
365
- }
366
- if (view.items !== void 0 && view.items.length > 0) lines.push(`Lying about: ${describeItems(view.items, { withKeys })}`);
367
- return lines;
368
- }
369
- /** How long the player has to have been away for it to be worth telling the game master. */
370
- const NOTICEABLE_ABSENCE = 5 * MINUTE;
371
- /** What the game master is told about time at the start of a turn, and how it passes. */
372
- function timeNotice(time) {
373
- const now = `Time: ${describeTime(time.now)}.`;
374
- if (time.now.mode === "simulated") return `${now} The story's time moves only as you say: each round takes what you give it (elapsed_seconds in resolve_round, or the default), and advance_time skips ahead.`;
375
- return `${now} The story's time follows the real clock: it cannot be skipped, and each round takes as long as it really took.${time.away !== void 0 && time.away >= NOTICEABLE_ABSENCE ? ` The player was away for ${describeDuration(time.away)} of real time and the story went on meanwhile: characters have been about their own business, so do not assume anyone is where or as the player left them unless the records say so.` : ""}`;
376
- }
377
- /** What a character is told of its day, its commitments and what it is after. */
378
- function describeAgenda(agenda, now) {
379
- const { zone } = agenda;
380
- const at = (place) => place === void 0 ? "" : ` at ${place}`;
381
- const lines = [];
382
- if (agenda.now !== void 0) lines.push(`Your day, now: ${agenda.now.activity}${at(agenda.now.place)}, until ${describeWhen(agenda.now.until, now, zone)}${agenda.now.interruptible ? "" : " (not something you would drop lightly)"}.`);
383
- if (agenda.next !== void 0) lines.push(`Your day, next: ${agenda.next.activity}${at(agenda.next.place)}, from ${describeWhen(agenda.next.at, now, zone)}.`);
384
- for (const engagement of agenda.engagements) lines.push(`${engagement.overdue ? "You were to" : "You are due to"}: ${engagement.title}${at(engagement.place)}${engagement.with.length === 0 ? "" : `, with ${engagement.with.join(", ")}`}, at ${describeWhen(engagement.at, now, zone)}${engagement.overdue ? ", which has passed and is still open" : ""}.`);
385
- if (agenda.goals.length > 0) {
386
- lines.push("What you are after:");
387
- for (const goal of agenda.goals) lines.push(`- ${goal.name} (${goal.type})${goal.deadline === void 0 ? "" : `, by ${describeWhen(goal.deadline, now, zone)}${goal.overdue ? ", which has passed" : ""}`}${goal.description === "" ? "" : `: ${sentence(goal.description)}`}${goal.plan.length === 0 ? "" : ` Next: ${goal.plan.join("; ")}.`}`);
388
- }
389
- return lines;
390
- }
391
- /** What the game master is told of the characters' days at the start of a turn; nothing when there is nothing to tell. */
392
- function describeSceneAgenda(agenda, now) {
393
- const lines = [];
394
- if (agenda.moved.length > 0) lines.push(`By their routines since you last looked: ${agenda.moved.map((move) => `${move.name} went to ${move.to} (${move.activity})`).join("; ")}.`);
395
- if (agenda.here.length > 0) lines.push(`With the player's character, and their days: ${agenda.here.map((entry) => `${entry.name}: ${entry.note}`).join("; ")}. The characters decide for themselves whether to keep to their day; the moment may keep them.`);
396
- if (agenda.engagements.length > 0) lines.push(`Commitments due soon or overdue: ${agenda.engagements.map((engagement) => `"${engagement.title}" (${engagement.with.join(", ")}${engagement.place === void 0 ? "" : `, at ${engagement.place}`}) ${engagement.overdue ? "was due" : "is due"} ${describeWhen(engagement.at, now, agenda.zone)}${engagement.overdue ? " and is still open" : ""}`).join("; ")}.`);
397
- return lines.join("\n");
398
- }
399
- /** In words, how a character stands with another, from the numbers of its profile; nothing for what is unremarkable. */
400
- function describeAttitude(relation) {
401
- return [
402
- relation.familiarity >= .7 ? "knows them well" : relation.familiarity <= .15 ? "barely knows them" : "",
403
- relation.trust >= .4 ? "trusts them" : relation.trust <= -.4 ? "distrusts them" : "",
404
- relation.affinity >= .4 ? "is fond of them" : relation.affinity <= -.4 ? "dislikes them" : "",
405
- relation.tension >= .5 ? "things are strained between them" : ""
406
- ].filter((part) => part !== "").join(", ");
407
- }
408
- function whereIs(member) {
409
- const place = member.place;
410
- if (place === void 0) return "";
411
- return [place.position, place.feature === void 0 ? "" : `at ${place.feature.name}`].filter((part) => part !== "").join(", ");
412
- }
413
- function present(cast, self) {
414
- return cast.map((member) => {
415
- const { key, character, state } = member;
416
- const seen = [state?.publicState, state?.activity].filter((text) => text !== void 0 && text.trim() !== "");
417
- const where = whereIs(member);
418
- return `- ${key === self ? character.name : referent(character)}${key === self ? " (you)" : ""}${where === "" ? "" : ` (${where})`}${seen.length > 0 ? `: ${seen.join("; ")}` : ""}`;
419
- }).join("\n");
420
- }
421
- /** A bounded, advisory order for who is most likely to need a turn; reachability still governs activation. */
422
- function describeActivationCandidates(cast, input, story) {
423
- const player = cast.find((member) => member.character.control === "player");
424
- if (player === void 0) return "";
425
- const named = mentioned(input, cast.map((member) => member.character));
426
- const cues = tokens(input);
427
- const candidates = cast.filter((member) => member.character.control === "agent").map((member) => {
428
- const relation = story.relationships.get(member.character.id, player.character.id);
429
- const here = member.place === void 0 || player.place === void 0 || member.place.location.id === player.place.location.id;
430
- const goal = story.intents.list(member.character.id, { status: "active" }).map((intent) => ({
431
- intent,
432
- match: overlap(cues, `${intent.name} ${intent.description}`, [])
433
- })).sort((a, b) => b.match - a.match)[0];
434
- const factionGoal = story.factionMemberships.ofCharacter(member.character.id, "active").flatMap((membership) => story.factionIntents.list(membership.factionId, { status: "active" }).map((intent) => ({
435
- intent,
436
- match: overlap(cues, `${intent.name} ${intent.description}`, []) * membership.commitment
437
- }))).sort((a, b) => b.match - a.match)[0];
438
- return {
439
- member,
440
- reasons: [
441
- named.has(member.character.id) ? "named in the move" : "",
442
- here ? "in the scene" : "",
443
- (goal?.match ?? 0) >= 2 ? `own goal: ${goal.intent.name}` : "",
444
- (factionGoal?.match ?? 0) >= 2 ? `faction pressure: ${factionGoal.intent.name}` : "",
445
- relation !== void 0 && relation.tension >= .5 ? "high tension toward the player" : "",
446
- relation !== void 0 && relation.trust <= -.4 ? "distrusts the player" : "",
447
- relation !== void 0 && Math.abs(relation.affinity) >= .4 ? relation.affinity > 0 ? "cares about the player" : "dislikes the player" : ""
448
- ].filter((reason) => reason !== ""),
449
- score: (named.has(member.character.id) ? 4 : 0) + (here ? 2 : 0) + Math.min(2, (goal?.match ?? 0) / 2) + Math.min(2, (factionGoal?.match ?? 0) / 2) + (relation?.tension ?? 0) + Math.max(0, -(relation?.trust ?? 0)) * .5 + Math.abs(relation?.affinity ?? 0) * .5
450
- };
451
- }).filter((entry) => entry.score > 0).sort((a, b) => b.score - a.score || a.member.key.localeCompare(b.member.key)).slice(0, 5);
452
- if (candidates.length === 0) return "";
453
- return `Likely characters to activate, in priority order (advice only; activate only whoever the moment actually reaches):\n${candidates.map(({ member, reasons }) => `- ${member.character.name} (${member.key}): ${reasons.join(", ") || "socially implicated"}`).join("\n")}`;
454
- }
455
- function said(entry) {
456
- return `- ${entry.name}${entry.utterance === void 0 ? "" : ` said "${entry.utterance}" and`} intended: ${entry.intent} (${entry.result}) ${entry.summary}`;
457
- }
458
- function age(at, now) {
459
- if (at === void 0 || now === void 0) return "some time ago";
460
- const seconds = Math.max(0, Math.floor((now - at) / 1e3));
461
- if (seconds < 60) return "just now";
462
- const unit = [
463
- {
464
- seconds: 86400,
465
- name: "day"
466
- },
467
- {
468
- seconds: 3600,
469
- name: "hour"
470
- },
471
- {
472
- seconds: 60,
473
- name: "minute"
474
- }
475
- ].find((candidate) => seconds >= candidate.seconds);
476
- const amount = Math.floor(seconds / unit.seconds);
477
- return `${amount} ${unit.name}${amount === 1 ? "" : "s"} ago`;
478
- }
479
- /** What a character remembers, in the way it remembers it: what is faded or vague is told as such. */
480
- function remembered(memories, now) {
481
- return memories.map((memory) => {
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}`;
483
- }).join("\n");
484
- }
485
- /** Every character is told the same thing about the scene, plus who it is and what it remembers. */
486
- const sharedContext = { brief(request) {
487
- const { member, cast, situation, attempt, earlier, reaction, previous, memories, place, relationships, knowledge, affiliations, carrying, time, agenda } = request;
488
- const company = place === void 0 ? cast : place.here;
489
- const sections = [
490
- `Situation:\n${situation}`,
491
- ...time === void 0 ? [] : [`Now: ${describeTime(time)}.`],
492
- ...place === void 0 ? [] : [`Where you are:\n${describePlace(place, { withKeys: false }).join("\n")}`],
493
- `Present:\n${present(company, member.key)}`
494
- ];
495
- if (request.upcoming !== void 0 && request.upcoming.length > 0) sections.push(`What you know is coming:\n${request.upcoming.map((entry) => `- ${entry.text}${entry.when === void 0 ? "" : ` (${entry.when})`}`).join("\n")}`);
496
- if (request.cues !== void 0 && request.cues.length > 0) sections.push(`Just now you notice:\n${request.cues.map((cue) => `- ${cue}`).join("\n")}`);
497
- if (request.tracked !== void 0 && request.tracked.self !== "") sections.push(`How you are (what you can tell of yourself):\n${request.tracked.self}`);
498
- if (request.tracked !== void 0 && request.tracked.others.length > 0) sections.push(`What you can tell of the others here:\n${request.tracked.others.map((other) => `- ${other.name}: ${other.text}`).join("\n")}`);
499
- const day = agenda === void 0 || time === void 0 ? [] : describeAgenda(agenda, time.now);
500
- if (day.length > 0) sections.push(`Your day and what you are after (plans, not orders: keep them, put them off or drop them as the moment and your character suggest):\n${day.join("\n")}`);
501
- if (carrying !== void 0 && carrying.length > 0) sections.push(`What you have on you:\n${describeItems(carrying, { withKeys: false })}`);
502
- if (relationships !== void 0 && relationships.length > 0) sections.push(`How you stand with people who bear on this moment (your own view, not objective fact):\n${relationships.map((relation) => {
503
- const attitude = describeAttitude(relation);
504
- return `- ${relation.name}${relation.present ? " (here)" : " (not here)"} — ${relation.label}${relation.summary === "" ? "" : `: ${relation.summary}`}${attitude === "" ? "" : ` [${attitude}]`}`;
505
- }).join("\n")}`);
506
- if (affiliations !== void 0 && affiliations.length > 0) sections.push(`Your affiliations (their goals are pressures and commitments, not commands):\n${affiliations.map((entry) => {
507
- const position = [entry.role, entry.rank].filter(Boolean).join(", ") || "member";
508
- const goals = entry.goals.length === 0 ? "" : ` Goals: ${entry.goals.join("; ")}.`;
509
- const state = entry.publicState === "" ? "" : ` ${entry.publicState}`;
510
- const attitude = entry.relationship === void 0 ? "" : describeAttitude(entry.relationship);
511
- return `- ${entry.name}: ${position}; ${entry.status}; commitment ${entry.commitment.toFixed(2)}.${state}${goals}${attitude === "" ? "" : ` Your view: ${attitude}.`}`;
512
- }).join("\n")}`);
513
- if (knowledge !== void 0) {
514
- const shown = (entries) => entries.slice(0, 30).join("; ") + (entries.length > 30 ? `; and ${entries.length - 30} more you can recall if needed` : "");
515
- const lines = [
516
- knowledge.characters.length === 0 ? void 0 : `People: ${shown(knowledge.characters)}`,
517
- knowledge.factions.length === 0 ? void 0 : `Factions: ${shown(knowledge.factions)}`,
518
- knowledge.locations.length === 0 ? void 0 : `Places: ${shown(knowledge.locations)}`,
519
- knowledge.routes.length === 0 ? void 0 : `Routes: ${shown(knowledge.routes)}`,
520
- knowledge.items.length === 0 ? void 0 : `Things: ${shown(knowledge.items)}`
521
- ].filter((line) => line !== void 0);
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")}`);
523
- }
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.");
526
- if (earlier !== void 0 && earlier.length > 0) sections.push(`Earlier in this scene, before this moment:\n${earlier.map(said).join("\n")}`);
527
- if (attempt === 2 && reaction !== void 0) {
528
- sections.push(`What just happened, and what you are reacting to:\n${reaction.map(said).join("\n")}`);
529
- if (previous !== void 0) sections.push(`Your earlier intent did not work out: ${previous.intent}\nYou are trying again, knowing the above. Decide again what you do now.`);
530
- }
531
- return {
532
- persona: [
533
- describe(member.character),
534
- request.text("roleplay/character-rules", { name: member.character.name }),
535
- request.text("roleplay/character-style", { name: member.character.name }),
536
- ...request.lookup ? [request.text("roleplay/character-lookup")] : [],
537
- request.text("roleplay/character-decide", {
538
- name: member.character.name,
539
- ...limitVariables(request.language ?? "en")
540
- })
541
- ].join("\n\n"),
542
- prompt: sections.join("\n\n")
543
- };
544
- } };
545
- /**
546
- * Whoever is with the player's character acts, unless the game master names who (it always does in play). While the world has places, a character that is in none
547
- * is not part of the scene: asking it to act is refused, so that someone the story never placed cannot answer from nowhere. (A character in
548
- * another place can be asked when the moment reaches it.)
549
- */
550
- const everyoneActs = { plan({ cast, requested }) {
551
- const placed = cast.some((member) => member.place !== void 0);
552
- const available = cast.filter((member) => member.character.control === "agent");
553
- const here = cast.find((member) => member.character.control === "player")?.place?.location.id;
554
- const inScene = (member) => !placed || member.place !== void 0;
555
- if (requested === void 0 || requested.length === 0) return available.filter((member) => placed && here !== void 0 ? member.place?.location.id === here : inScene(member)).map((member) => member.key);
556
- const unknown = requested.filter((key) => !available.some((member) => member.key === key));
557
- if (unknown.length > 0) throw new Error(`cannot activate ${unknown.join(", ")}: not a character that acts on its own (available: ${available.map((member) => member.key).join(", ")})`);
558
- const nowhere = [...new Set(requested)].map((key) => available.find((member) => member.key === key)).filter((member) => !inScene(member));
559
- if (nowhere.length > 0) throw new Error(`cannot activate ${nowhere.map((member) => member.key).join(", ")}: in no place, so not part of this scene. Only characters that have a place act (${available.filter(inScene).map((member) => member.key).join(", ") || "nobody"}); leave the others out`);
560
- return [...new Set(requested)];
561
- } };
562
- const acceptsAnyIntent = { validate: ({ intent }) => intent.trim() === "" ? {
563
- ok: false,
564
- reason: "the intent is empty"
565
- } : { ok: true } };
566
- /** A character whose intent failed and who is highly committed tries once more. */
567
- const persistentRetry = { select({ reports, outcomes }) {
568
- return reports.filter((report) => report.commitment === "high" && outcomes.some((outcome) => outcome.character === report.character && outcome.result === "failed")).map((report) => report.character);
569
- } };
570
- const acceptsAnyInput = { validate: () => ({ ok: true }) };
571
- /** The game master narrates. */
572
- const gameMasterNarrates = { narrate: () => Promise.resolve(void 0) };
573
- /** Compares what was said, ignoring the quotes around it and the way whitespace is laid out. */
574
- const WRAPPING_QUOTES = /^["“”„«»'‘’]+|["“”„«»'‘’]+$/g;
575
- function sameWords(a, b) {
576
- const plain = (text) => text.trim().replace(WRAPPING_QUOTES, "").replace(/\s+/g, " ").trim();
577
- return plain(a) === plain(b);
578
- }
579
- /** How many earlier events the game master is reminded of at most. */
580
- const REMINDED_EVENTS = 5;
581
- /**
582
- * The state of the scene, what is still open in the story, and the earlier events that the
583
- * player's move brings to mind (by the session's search of words and meaning, and by who is named):
584
- * those already folded out of the conversation into the summaries, whose detail the summaries may have lost.
585
- */
586
- /** Where the player is and what is there, who is with them, and who is elsewhere. */
587
- function placedScene(cast, player, story, describeMember, things) {
588
- const here = player?.place?.location;
589
- const sections = [];
590
- if (here !== void 0) {
591
- const view = {
592
- key: locationKey(here),
593
- location: here,
594
- here: cast.filter((member) => member.place?.location.id === here.id),
595
- ...things === void 0 ? {} : { items: things.at(here.id) },
596
- exits: story.locations.exitsFrom(here.id).flatMap((exit) => {
597
- const to = story.locations.get(exit.toId);
598
- return to === void 0 ? [] : [{
599
- key: locationKey(to),
600
- name: to.name,
601
- exit
602
- }];
603
- })
604
- };
605
- sections.push(`The player's character is in ${describePlace(view, { withKeys: true }).join("\n")}`);
606
- sections.push(`Characters here:\n${view.here.map(describeMember).join("\n")}`);
607
- }
608
- const elsewhere = cast.filter((member) => member.place !== void 0 && member.place.location.id !== here?.id);
609
- if (elsewhere.length > 0) sections.push(`Characters elsewhere (they perceive nothing here unless the moment reaches them):\n${elsewhere.map((member) => `${describeMember(member)} - in ${member.place.location.name} (${locationKey(member.place.location)})`).join("\n")}`);
610
- const nowhere = cast.filter((member) => member.place === void 0);
611
- if (nowhere.length > 0) sections.push(`Characters with no place (not part of this scene; they cannot be asked to act):\n${nowhere.map(describeMember).join("\n")}`);
612
- return sections.join("\n\n");
613
- }
614
- const castSummary = { scene({ tracked, time, world, cast, turn, input, queryVector, story, items }) {
615
- const describeMember = (member) => {
616
- const { key, character, state } = member;
617
- const role = character.control === "player" ? `the player's character, "${key}"` : `acts through "${key}"`;
618
- const seen = [state?.publicState, state?.activity].filter((text) => text !== void 0 && text.trim() !== "");
619
- const where = whereIs(member);
620
- return `- ${referent(character)} (${role})${where === "" ? "" : ` [${where}]`}${character.summary === "" ? "" : `: ${character.summary}`}${seen.length > 0 ? ` Currently: ${seen.join("; ")}` : ""}`;
621
- };
622
- const player = cast.find((member) => member.character.control === "player");
623
- const days = time?.agenda === void 0 ? "" : describeSceneAgenda(time.agenda, time.now.now);
624
- const parts = [
625
- ...time === void 0 ? [] : [timeNotice(time)],
626
- ...days === "" ? [] : [days],
627
- `Scene before turn ${turn}:\n${cast.some((member) => member.place !== void 0) ? placedScene(cast, player, story, describeMember, items) : cast.map(describeMember).join("\n")}`
628
- ];
629
- const activation = describeActivationCandidates(cast, input, story);
630
- if (activation !== "") parts.push(activation);
631
- if (items !== void 0) {
632
- const carried = cast.flatMap((member) => {
633
- const mine = items.carried(member.character.id);
634
- return mine.length === 0 ? [] : [`- ${member.character.name} (${member.key}): ${describeItems(mine, { withKeys: true })}`];
635
- });
636
- if (carried.length > 0) parts.push(`What characters have on them:\n${carried.join("\n")}`);
637
- }
638
- if (world !== void 0 && world.happened.length > 0) parts.push(`The world acted since the last turn, by itself:\n${world.happened.map((line) => `- ${line}`).join("\n")}`);
639
- if (world?.upcoming !== void 0 && world.upcoming.length > 0) parts.push(`Known beforehand, still to come (who knows of it; it will happen by itself when its time comes):\n${world.upcoming.map((entry) => `- ${entry.text}${entry.when === void 0 ? "" : ` (${entry.when})`} [known to ${entry.who}]`).join("\n")}`);
640
- if (world !== void 0 && world.beats.length > 0) parts.push(`Weave these into the story when it fits, then say you did with addressed in narrate (each stays for a few turns and is then let go):\n${world.beats.map((beat) => `- [${beat.id}] ${beat.text}`).join("\n")}`);
641
- if (tracked !== void 0 && tracked.length > 0) parts.push(`What the story keeps track of (change it with variable_changes in an outcome when what happened calls for it):\n${tracked.map((line) => `- ${line}`).join("\n")}`);
642
- const threads = story.threads.list("open");
643
- if (threads.length > 0) parts.push(`Still open in the story:\n${threads.map((thread) => `- ${thread.text}`).join("\n")}`);
644
- const folded = story.summaries.list().reduce((latest, summary) => Math.max(latest, summary.toTurn), 0);
645
- if (folded > 0) {
646
- const mentionedIds = mentioned(input, cast.map(({ character }) => character));
647
- const cues = tokens(input);
648
- const names = new Map(cast.map(({ character }) => [character.id, character.name]));
649
- const byMeaning = story.searchEvents({
650
- text: input,
651
- ...queryVector === void 0 ? {} : { vector: queryVector },
652
- toTurn: folded,
653
- limit: REMINDED_EVENTS
654
- });
655
- const byCues = story.events.list({ toTurn: folded }).filter((event) => !byMeaning.some((found) => found.id === event.id)).map((event) => ({
656
- event,
657
- score: 3 * event.involves.filter((id) => mentionedIds.has(id)).length + overlap(cues, event.text, event.tags)
658
- })).filter(({ score }) => score >= 2).sort((a, b) => b.score + .5 * b.event.importance - a.score - .5 * a.event.importance || b.event.turn - a.event.turn).map(({ event }) => event);
659
- const relevant = [...byMeaning, ...byCues].slice(0, REMINDED_EVENTS).sort((a, b) => a.turn - b.turn).map((event) => ({ event }));
660
- if (relevant.length > 0) parts.push(`Earlier events that bear on what the player just did (from the records of the story):\n${relevant.map(({ event }) => {
661
- const who = event.involves.map((id) => names.get(id)).filter((name) => name !== void 0).join(", ");
662
- return `- (turn ${event.turn}) ${event.text}${who === "" ? "" : ` [${who}]`}`;
663
- }).join("\n")}`);
664
- }
665
- return parts.join("\n\n");
666
- } };
667
- const sameCharacter = (utterance, character) => utterance.character === character || utterance.name === character;
668
- /** Every utterance appears once, exactly as given and in the order spoken, and no one speaks who did not. */
669
- const exactUtterances = {
670
- check(segments, required) {
671
- const problems = [];
672
- const used = /* @__PURE__ */ new Set();
673
- let latest = 0;
674
- segments.forEach((segment, index) => {
675
- const at = `segment ${index + 1}`;
676
- if (segment.type === "narration") {
677
- if (segment.text.trim() === "") problems.push(`${at}: the narration is empty`);
678
- return;
679
- }
680
- const own = required.flatMap((utterance, position) => sameCharacter(utterance, segment.character) ? [position] : []);
681
- const free = own.filter((position) => !used.has(position));
682
- const exact = free.find((position) => sameWords(segment.text, required[position].text));
683
- if (exact !== void 0) {
684
- used.add(exact);
685
- const spoken = required[exact];
686
- if (spoken.round < latest) problems.push(`${at}: the utterance of ${spoken.name} from round ${spoken.round} comes after one from a later round; utterances keep the order they were spoken in`);
687
- latest = Math.max(latest, spoken.round);
688
- } else if (free.length > 0) {
689
- used.add(free[0]);
690
- problems.push(`${at}: the utterance of ${required[free[0]].name} was changed; it must be exactly "${required[free[0]].text}"`);
691
- } else if (own.length > 0) problems.push(`${at}: ${required[own[0]].name} has no more utterances to say; this one is repeated or invented, remove it`);
692
- else problems.push(`${at}: ${segment.character} has nothing to say this turn, so this utterance is invented; remove it`);
693
- });
694
- required.forEach((utterance, position) => {
695
- if (!used.has(position)) problems.push(`the utterance of ${utterance.name}${utterance.round > 1 ? ` (round ${utterance.round})` : ""} is missing; it must appear exactly as "${utterance.text}"`);
696
- });
697
- return problems;
698
- },
699
- repair(segments, required) {
700
- const used = /* @__PURE__ */ new Set();
701
- const kept = [];
702
- for (const segment of segments) {
703
- if (segment.type === "narration") {
704
- if (segment.text.trim() !== "") kept.push({
705
- segment,
706
- round: void 0
707
- });
708
- continue;
709
- }
710
- const free = required.flatMap((utterance, position) => sameCharacter(utterance, segment.character) && !used.has(position) ? [position] : []);
711
- const position = free.find((candidate) => sameWords(segment.text, required[candidate].text)) ?? free[0];
712
- if (position === void 0) continue;
713
- used.add(position);
714
- const spoken = required[position];
715
- kept.push({
716
- segment: {
717
- type: "utterance",
718
- character: spoken.character,
719
- name: spoken.name,
720
- text: spoken.text
721
- },
722
- round: spoken.round
723
- });
724
- }
725
- required.forEach((utterance, position) => {
726
- if (used.has(position)) return;
727
- const restored = {
728
- type: "utterance",
729
- character: utterance.character,
730
- name: utterance.name,
731
- text: utterance.text
732
- };
733
- const later = kept.findIndex((entry) => entry.round !== void 0 && entry.round > utterance.round);
734
- kept.splice(later < 0 ? kept.length : later, 0, {
735
- segment: restored,
736
- round: utterance.round
737
- });
738
- });
739
- return kept.map((entry) => entry.segment);
740
- }
741
- };
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. */
743
- const recordsRecall = { recall: ({ member, situation, turn, policy, queryVector, explain }, story, signal) => story.recallRanked({
744
- characterId: member.character.id,
745
- situation,
746
- turn,
747
- policy,
748
- ...explain === true ? { explain } : {},
749
- ...member.place === void 0 ? {} : { locationId: member.place.location.id }
750
- }, signal, queryVector === void 0 ? {} : { queryVector }) };
751
- /**
752
- * Writes no memory. What the game master decided about each character is applied when the round is
753
- * recorded, so without a memory keeper the story keeps its states and no events.
754
- */
755
- const writesNothing = { commit: () => Promise.resolve({
756
- writes: 0,
757
- notes: ""
758
- }) };
759
- /** Makes up nothing, and has nothing to fit in: without a world author the world stays as it was written. */
760
- const declinesToAuthor = {
761
- create: () => Promise.resolve({
762
- created: [],
763
- declined: "no world author is installed, so the world cannot grow"
764
- }),
765
- consolidate: () => Promise.resolve({
766
- resolved: 0,
767
- notes: ""
768
- })
769
- };
770
- /** Lets no organisation act: without a strategist factions change only through what the story records. */
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: [] }) };
774
- /** Judges nothing: without a judge a trigger that waits on a statement never sees it hold. */
775
- const judgesNothing = { judge: () => Promise.resolve({ judged: 0 }) };
776
- /** Offers nothing: without a suggester the player writes their own move. */
777
- const offersNothing = { suggest: () => Promise.resolve([]) };
778
- function defaultBoundaries() {
779
- return {
780
- planner: everyoneActs,
781
- characterContext: sharedContext,
782
- outputValidator: acceptsAnyIntent,
783
- retryPolicy: persistentRetry,
784
- inputValidator: acceptsAnyInput,
785
- narrator: gameMasterNarrates,
786
- narrationChecker: exactUtterances,
787
- committer: writesNothing,
788
- author: declinesToAuthor,
789
- strategist: factionsStayPut,
790
- reflector: reflectsOnNothing,
791
- judge: judgesNothing,
792
- suggester: offersNothing,
793
- recaller: recordsRecall,
794
- sceneContext: castSummary
795
- };
796
- }
797
- //#endregion
798
- //#region src/shared/timeline.ts
799
- const emptyTimeline = () => ({
800
- version: 1,
801
- head: null,
802
- next: 1,
803
- nodes: []
804
- });
805
- /** The turns from the first to `id`, in order; none for the start. */
806
- function pathTo(timeline, id) {
807
- const byId = new Map(timeline.nodes.map((node) => [node.id, node]));
808
- const path = [];
809
- for (let at = id === null ? void 0 : byId.get(id); at !== void 0; at = at.parent === null ? void 0 : byId.get(at.parent)) path.unshift(at);
810
- return path;
811
- }
812
- /** The turns that follow `parent`, in the order they were played. */
813
- const childrenOf = (timeline, parent) => timeline.nodes.filter((node) => node.parent === parent);
814
- /** The snapshot that holds the state before any turn. */
815
- const START_SNAPSHOT = "start";
816
- /** The snapshot that holds the state after a turn. */
817
- const snapshotOf = (id) => `after-${id}`;
818
- /** Builds what the client shows from the timeline. */
819
- function viewOf(timeline) {
820
- const turn = (node) => ({
821
- id: node.id,
822
- turn: node.turn,
823
- player: node.player,
824
- ...node.endSeq === void 0 ? {} : { endSeq: node.endSeq },
825
- ...node.output === void 0 ? {} : { output: node.output },
826
- restorable: node.snapshot !== void 0,
827
- alternatives: childrenOf(timeline, node.parent).map((sibling) => sibling.id)
828
- });
829
- const on = new Set(pathTo(timeline, timeline.head).map((node) => node.id));
830
- const withdrawn = timeline.nodes.filter((node) => !on.has(node.id) && node.userSeq >= 0).map((node) => ({
831
- from: Math.min(node.startSeq ?? node.userSeq, node.userSeq),
832
- to: node.endSeq ?? Number.MAX_SAFE_INTEGER
833
- }));
834
- return {
835
- head: timeline.head,
836
- path: pathTo(timeline, timeline.head).map(turn),
837
- forward: childrenOf(timeline, timeline.head).map(turn),
838
- canStart: true,
839
- withdrawn
840
- };
841
- }
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. */
843
- function noticeText(node) {
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");
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}`;
847
- return `The story, as it went earlier (restored):\nThe player said: ${node.player}${ruling}\nIt was told to the player:\n${told}`;
848
- }
849
- //#endregion
850
- //#region src/host/timeline/file.ts
851
- const TIMELINE_FILE = "timeline.json";
852
- function isNode(value) {
853
- if (typeof value !== "object" || value === null) return false;
854
- const node = value;
855
- return typeof node["id"] === "string" && (node["parent"] === null || typeof node["parent"] === "string") && typeof node["turn"] === "number" && typeof node["userSeq"] === "number" && typeof node["player"] === "string" && typeof node["createdAt"] === "string";
856
- }
857
- /**
858
- * The timeline of a session, or an empty one when it has none yet.
859
- * @throws {Error} when the file is there and is not a timeline: it holds what lets the story be taken back, so it is not replaced silently.
860
- */
861
- function readTimeline(folder) {
862
- let text;
863
- try {
864
- text = readFileSync(join(folder, TIMELINE_FILE), "utf8");
865
- } catch (error) {
866
- if (error.code === "ENOENT") return emptyTimeline();
867
- throw error;
868
- }
869
- const value = JSON.parse(text);
870
- if (value.version !== 1 || !Array.isArray(value.nodes) || !value.nodes.every(isNode) || typeof value.next !== "number" || value.head !== null && typeof value.head !== "string") throw new Error(`${join(folder, TIMELINE_FILE)} is not a timeline`);
871
- return value;
872
- }
873
- /** Writes it aside and renames it, so a crash leaves the timeline as it was. */
874
- function writeTimeline(folder, timeline) {
875
- const target = join(folder, TIMELINE_FILE);
876
- const aside = `${target}.writing`;
877
- writeFileSync(aside, JSON.stringify(timeline, null, 2));
878
- renameSync(aside, target);
879
- }
880
- //#endregion
881
- //#region src/host/timeline/branch.ts
882
- var BranchError = class extends Error {};
883
- /**
884
- * What a branch of a story cut at a log event keeps of the timeline: the turns that ended at or before it, standing at the one
885
- * that ended last, and the state of the story after that turn.
886
- * @param boundary - the seq of the last event the branch inherits.
887
- * @param snapshots - the names of the snapshots the story has.
888
- * @throws {BranchError} when the state at that point was not kept.
889
- */
890
- function branchTimeline(timeline, boundary, snapshots) {
891
- const nodes = timeline.nodes.filter((node) => node.endSeq !== void 0 && node.endSeq <= boundary).map((node) => ({ ...node }));
892
- for (const node of nodes) if (node.noticeSeq !== void 0 && node.noticeSeq > boundary) delete node.noticeSeq;
893
- const last = nodes.reduce((found, node) => found === void 0 || node.endSeq > found.endSeq ? node : found, void 0);
894
- const available = new Set(snapshots);
895
- for (const node of nodes) if (node.snapshot !== void 0 && !available.has(node.snapshot)) delete node.snapshot;
896
- const keep = [...nodes.flatMap((node) => node.snapshot === void 0 ? [] : [node.snapshot]), ...available.has("start") ? [START_SNAPSHOT] : []];
897
- const branch = {
898
- version: 1,
899
- head: last?.id ?? null,
900
- next: timeline.next,
901
- nodes
902
- };
903
- if (last === void 0) {
904
- if (!available.has("start")) throw new BranchError("the state at the start of the story was not kept, so it cannot be branched");
905
- return {
906
- timeline: branch,
907
- from: { snapshot: START_SNAPSHOT },
908
- keep
909
- };
910
- }
911
- if (last.snapshot !== void 0) return {
912
- timeline: branch,
913
- from: { snapshot: last.snapshot },
914
- keep
915
- };
916
- if (timeline.head === last.id) return {
917
- timeline: branch,
918
- from: { live: true },
919
- keep
920
- };
921
- throw new BranchError(`the state of the story after its turn ${last.turn} was not kept, so it cannot be branched there`);
922
- }
923
- /** The name of a branch: the story's name with its trailing number counted up, or a 2 added. */
924
- function branchName(name) {
925
- const numbered = /^(.*?)(\d+)\s*$/.exec(name);
926
- const next = numbered === null ? `${name} 2` : `${numbered[1]}${Number(numbered[2]) + 1}`;
927
- return next.length > 200 ? `${[...name].slice(0, 190).join("").trimEnd()} 2` : next;
928
- }
929
- //#endregion
930
- //#region src/host/timeline/plan.ts
931
- /**
932
- * Where the model's conversation has to be changed so that it carries the turns from the first to `target`, and no others.
933
- * A turn is on the conversation when its own message is, or the notice that stands for it. The turns that stay are the longest
934
- * run from the first that is on it; whatever else of the timeline is on it is shadowed, and the rest of the way is told by notices.
935
- * @param surface - the seqs of the model's conversation, in order.
936
- */
937
- function planMove(timeline, target, surface) {
938
- const onSurface = new Set(surface);
939
- const path = pathTo(timeline, target);
940
- let keptCount = 0;
941
- let last = -1;
942
- for (const node of path) {
943
- const at = surface.indexOf(node.userSeq);
944
- if (at <= last) break;
945
- last = at;
946
- keptCount += 1;
947
- }
948
- const kept = path.slice(0, keptCount);
949
- const keptIds = new Set(kept.map((node) => node.id));
950
- const byStart = [...timeline.nodes].sort((a, b) => a.userSeq - b.userSeq);
951
- const seqs = /* @__PURE__ */ new Set();
952
- byStart.forEach((node, index) => {
953
- if (keptIds.has(node.id)) return;
954
- if (node.noticeSeq !== void 0 && onSurface.has(node.noticeSeq)) seqs.add(node.noticeSeq);
955
- if (!onSurface.has(node.userSeq)) return;
956
- const end = node.endSeq ?? (byStart[index + 1]?.userSeq === void 0 ? Infinity : byStart[index + 1].userSeq - 1);
957
- for (const seq of surface) if (seq >= node.userSeq && seq <= end) seqs.add(seq);
958
- });
959
- const shadow = [];
960
- let run = [];
961
- let previous = -2;
962
- surface.forEach((seq, index) => {
963
- if (!seqs.has(seq)) return;
964
- if (index !== previous + 1 && run.length > 0) {
965
- shadow.push({
966
- startSeq: run[0],
967
- endSeq: run.at(-1),
968
- seqs: run
969
- });
970
- run = [];
971
- }
972
- run.push(seq);
973
- previous = index;
974
- });
975
- if (run.length > 0) shadow.push({
976
- startSeq: run[0],
977
- endSeq: run.at(-1),
978
- seqs: run
979
- });
980
- return {
981
- shadow,
982
- kept: kept.map((node) => node.id),
983
- inject: path.slice(keptCount)
984
- };
985
- }
986
- //#endregion
987
- //#region src/host/timeline/service.ts
988
- /** The text of the marker that stands for the turns it replaces: never empty, as a model service may refuse an empty message. */
989
- const MARKER_TEXT = "(empty message)";
990
- /** A turn that has not ended does not know yet where its own message is in the log. */
991
- const UNKNOWN_SEQ = -1;
992
- var TimelineError = class extends Error {};
993
- /**
994
- * What the story's turns are, and taking the story back to one of them (or forward again). The conversation with the model is
995
- * only ever added to: the turns that no longer belong are replaced by a marker, which DSH keeps out of the next request, and
996
- * a turn that comes back is told once as a notice. The state of the story is put back from the snapshot taken when the turn settled.
997
- * Everything here is one at a time per chat.
998
- */
999
- var Timelines = class {
1000
- deps;
1001
- queues = /* @__PURE__ */ new Map();
1002
- constructor(deps) {
1003
- this.deps = deps;
1004
- }
1005
- serial(chat, job) {
1006
- const run = (this.queues.get(chat) ?? Promise.resolve()).then(job, job);
1007
- this.queues.set(chat, run.catch(() => void 0));
1008
- return run;
1009
- }
1010
- idOf(chat) {
1011
- const id = roleplaySessionOf(chat);
1012
- if (id === void 0) throw new TimelineError(`${chat} is not a roleplay chat`);
1013
- return id;
1014
- }
1015
- folder(id) {
1016
- return sessionFolder(this.deps.sessionsDir(), id);
1017
- }
1018
- read(id) {
1019
- return readTimeline(this.folder(id));
1020
- }
1021
- view(id) {
1022
- return viewOf(this.read(id));
1023
- }
1024
- /**
1025
- * The player has said something and a turn begins: the turn is added to the timeline after the head, and the state the earlier one left is kept at once,
1026
- * with the records still waiting for the keeper in it (they are in the database, so a restored state carries them).
1027
- */
1028
- begin(chat, turn, player) {
1029
- return this.serial(chat, async () => {
1030
- this.deps.cancel?.(chat);
1031
- const id = this.idOf(chat);
1032
- const timeline = this.read(id);
1033
- this.keep(id, timeline, timeline.head);
1034
- const node = {
1035
- id: `n${timeline.next}`,
1036
- parent: timeline.head,
1037
- turn,
1038
- userSeq: UNKNOWN_SEQ,
1039
- player,
1040
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
1041
- };
1042
- timeline.nodes.push(node);
1043
- timeline.next += 1;
1044
- timeline.head = node.id;
1045
- writeTimeline(this.folder(id), timeline);
1046
- this.prune(id, timeline);
1047
- return node;
1048
- });
1049
- }
1050
- /** What the turn delivered; and, once nothing writes to the story any more, its state is kept. */
1051
- delivered(chat, output) {
1052
- const id = this.idOf(chat);
1053
- const timeline = this.read(id);
1054
- const node = timeline.nodes.find((candidate) => candidate.id === timeline.head);
1055
- if (node === void 0) return void 0;
1056
- node.output = output;
1057
- writeTimeline(this.folder(id), timeline);
1058
- this.deps.engine.quiesce(chat).then(() => this.serial(chat, () => {
1059
- const current = this.read(id);
1060
- if (current.head === node.id) this.keep(id, current, node.id);
1061
- return Promise.resolve();
1062
- })).catch(() => void 0);
1063
- return node.id;
1064
- }
1065
- /**
1066
- * The turn ended in the log. Its own message is found now: it is the first message of the player after the last turn that ended
1067
- * (it is not in the log yet when the turn begins).
1068
- */
1069
- ended(chat, session, seq) {
1070
- const id = this.idOf(chat);
1071
- const timeline = this.read(id);
1072
- const node = timeline.nodes.find((candidate) => candidate.id === timeline.head);
1073
- if (node === void 0 || node.endSeq !== void 0) return;
1074
- const after = Math.max(-1, ...timeline.nodes.filter((other) => other.id !== node.id).map((other) => other.endSeq ?? other.userSeq));
1075
- const human = session.snapshotEvents().find((event) => event.seq > after && event.type === "user/message" && event.data.source.kind === "user");
1076
- if (human === void 0) throw new TimelineError(`turn ${node.turn} has no message of the player in the log`);
1077
- node.userSeq = human.seq;
1078
- node.endSeq = seq;
1079
- const began = session.snapshotEvents().find((event) => event.type === "turn/start" && event.data.turn === node.turn);
1080
- node.startSeq = Math.min(began?.seq ?? human.seq, human.seq);
1081
- writeTimeline(this.folder(id), timeline);
1082
- }
1083
- /** Keeps the state as it is under the name of the turn it follows from, when that is not done yet. */
1084
- keep(id, timeline, at) {
1085
- if (this.deps.keepSnapshots(id) === 0) return;
1086
- const node = at === null ? void 0 : timeline.nodes.find((candidate) => candidate.id === at);
1087
- const name = node === void 0 ? START_SNAPSHOT : snapshotOf(node.id);
1088
- if (node !== void 0 && node.snapshot !== void 0) return;
1089
- if (node === void 0 && this.deps.state.snapshots(this.deps.sessionsDir(), id).includes("start")) return;
1090
- this.deps.state.snapshot(this.deps.sessionsDir(), id, name);
1091
- if (node !== void 0) {
1092
- node.snapshot = name;
1093
- writeTimeline(this.folder(id), timeline);
1094
- }
1095
- }
1096
- /** Lets the oldest snapshots go: only the turns most recently played keep theirs, and the one that holds the start stays. */
1097
- prune(id, timeline) {
1098
- const keep = this.deps.keepSnapshots(id);
1099
- const kept = timeline.nodes.filter((node) => node.snapshot !== void 0);
1100
- const dropped = kept.slice(0, Math.max(0, kept.length - keep));
1101
- if (dropped.length === 0) return;
1102
- for (const node of dropped) {
1103
- this.deps.state.removeSnapshot(this.deps.sessionsDir(), id, node.snapshot);
1104
- delete node.snapshot;
1105
- }
1106
- writeTimeline(this.folder(id), timeline);
1107
- }
1108
- /**
1109
- * Takes the story to the state after a turn (`null` for the start): what is in flight stops, the state is put back from the snapshot,
1110
- * the turns that no longer belong are replaced by a marker on the model's conversation, and the turns that come back are told as notices.
1111
- * @returns what the player said in the first turn that was left, to put back in the input; nothing when the story went forward.
1112
- * @throws {TimelineError} when there is no such turn, its state was not kept, or the chat is not loaded.
1113
- */
1114
- move(chat, target) {
1115
- return this.serial(chat, async () => {
1116
- const id = this.idOf(chat);
1117
- const timeline = this.read(id);
1118
- const to = target === null ? void 0 : timeline.nodes.find((node) => node.id === target);
1119
- if (target !== null && to === void 0) throw new TimelineError(`there is no turn "${target}"`);
1120
- const snapshot = target === null ? START_SNAPSHOT : to.snapshot;
1121
- if (snapshot === void 0 || !this.deps.state.snapshots(this.deps.sessionsDir(), id).includes(snapshot)) throw new TimelineError("the state of the story at that turn was not kept");
1122
- const agent = await this.deps.agentOf(chat);
1123
- if (agent === void 0) throw new TimelineError(`the chat ${chat} is not loaded`);
1124
- if (agent.status !== "idle") {
1125
- agent.cancel({ kind: "user" }, { keepInbox: true });
1126
- await agent.whenIdle();
1127
- }
1128
- this.deps.cancel?.(chat);
1129
- this.deps.engine.stop(chat);
1130
- await this.deps.engine.quiesce(chat);
1131
- this.deps.engine.forget(chat);
1132
- const was = pathTo(timeline, timeline.head);
1133
- const plan = planMove(timeline, target, [...agent.session.surface.nodes]);
1134
- this.deps.state.restore(this.deps.sessionsDir(), id, snapshot);
1135
- this.reconcile(agent, plan);
1136
- timeline.head = target;
1137
- writeTimeline(this.folder(id), timeline);
1138
- const left = was.find((node) => !pathTo(timeline, target).some((kept) => kept.id === node.id));
1139
- return left === void 0 ? {} : { draft: left.player };
1140
- });
1141
- }
1142
- /** Makes the model's conversation carry the turns of a plan and no others: what does not belong is replaced by a marker, and the turns that come back are told as notices. */
1143
- reconcile(agent, plan) {
1144
- for (const run of plan.shadow) agent.session.append("user/message", createUserMessage({
1145
- content: [{
1146
- type: "text",
1147
- text: MARKER_TEXT
1148
- }],
1149
- source: { kind: "roleplay" }
1150
- }), {
1151
- surfaceOp: {
1152
- op: "replace",
1153
- startSeq: run.startSeq,
1154
- endSeq: run.endSeq
1155
- },
1156
- sourceEventSeqs: run.seqs
1157
- });
1158
- for (const node of plan.inject) node.noticeSeq = agent.session.append("user/message", createUserMessage({
1159
- content: [{
1160
- type: "text",
1161
- text: noticeText(node)
1162
- }],
1163
- source: { kind: "roleplay" }
1164
- }), { surfaceOp: "append" }).seq;
1165
- }
1166
- /**
1167
- * A chat DSH made as a branch of a roleplay chat gets a session of its own: the state of the story where the branch was cut (its snapshot, or
1168
- * the live state when the story stands there and has not kept one yet), the turns it inherits, the settings, and a name. The branch's own chat is
1169
- * made to carry the turns it inherits and no others. A chat that already has its session (it is only loaded again) is left as it is.
1170
- * @param cut - the seq of the last event of the log the branch inherits.
1171
- * @returns whether a session was made.
1172
- * @throws {BranchError} when the state at the cut was not kept; the branch is then not made.
1173
- */
1174
- adopt(chat, parent, cut, agent) {
1175
- return this.serial(parent, async () => {
1176
- const id = this.idOf(chat);
1177
- const from = this.idOf(parent);
1178
- const directory = this.deps.sessionsDir();
1179
- if (existsSync(sessionDatabase(directory, id)) || !existsSync(sessionDatabase(directory, from))) return false;
1180
- const branch = branchTimeline(this.read(from), cut, this.deps.state.snapshots(directory, from));
1181
- if ("live" in branch.from) await this.deps.engine.quiesce(parent);
1182
- const name = branchName(this.deps.state.openSession(directory, from).metadata.get().name);
1183
- this.deps.state.fork(directory, from, id, branch.from, {
1184
- name,
1185
- keep: branch.keep
1186
- });
1187
- try {
1188
- await inheritImages(this.folder(from), this.folder(id), branch.timeline.nodes.map((node) => node.id));
1189
- inheritPrompts(this.folder(from), this.folder(id));
1190
- inheritPacks(this.folder(from), this.folder(id));
1191
- const plan = planMove(branch.timeline, branch.timeline.head, [...agent.session.surface.nodes]);
1192
- this.reconcile(agent, plan);
1193
- writeTimeline(this.folder(id), branch.timeline);
1194
- } catch (error) {
1195
- this.deps.state.deleteSession(directory, id);
1196
- throw error;
1197
- }
1198
- return true;
1199
- });
1200
- }
1201
- /** The turns that follow a turn, for the choices the story can be taken to. */
1202
- forward(id) {
1203
- const timeline = this.read(id);
1204
- return childrenOf(timeline, timeline.head);
1205
- }
1206
- };
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
1284
- //#region src/host/pacing/director.ts
1285
- const PLOTS_METADATA_KEY = "roleplay.pacing.plots";
1286
- function populatePlots(metadata, plots) {
1287
- const progress = plots.map((plot) => ({
1288
- plot,
1289
- status: plot.start,
1290
- introduced: [],
1291
- rejected: [],
1292
- lastNudgeTurn: 0
1293
- }));
1294
- metadata.setValue(PLOTS_METADATA_KEY, progress);
1295
- }
1296
- function addSessionPlot(store, plot) {
1297
- const plots = progressOf(store);
1298
- if (plots.some((entry) => entry.plot.id === plot.id)) throw new Error(`there is already a plot "${plot.id}"`);
1299
- plots.push({
1300
- plot,
1301
- status: plot.start,
1302
- introduced: [],
1303
- rejected: [],
1304
- lastNudgeTurn: 0
1305
- });
1306
- store.story.metadata.setValue(PLOTS_METADATA_KEY, plots);
1307
- }
1308
- function plotAuthorNeeded(store, turn) {
1309
- if (progressOf(store).length > 0 || turn < 5) return false;
1310
- return store.story.events.list({
1311
- fromTurn: Math.max(1, turn - 2),
1312
- toTurn: turn - 1
1313
- }).length === 0 && store.story.threads.list("open").length === 0;
1314
- }
1315
- function plotProgressOf(metadata) {
1316
- const value = metadata.getValue(PLOTS_METADATA_KEY);
1317
- return Array.isArray(value) ? value : [];
1318
- }
1319
- function progressOf(store) {
1320
- return plotProgressOf(store.story.metadata);
1321
- }
1322
- /** Select one uncommitted possibility when the story has genuinely gone quiet; selection never makes it happen. */
1323
- function pacingAdvice(store, turn) {
1324
- const plots = progressOf(store);
1325
- if (plots.length === 0) return void 0;
1326
- const now = store.story.clock.get()?.now;
1327
- const recent = store.story.events.list({
1328
- fromTurn: Math.max(1, turn - 2),
1329
- toTurn: turn - 1
1330
- });
1331
- const openThreads = store.story.threads.list("open");
1332
- for (const progress of plots) {
1333
- if (![
1334
- "available",
1335
- "engaged",
1336
- "cooling"
1337
- ].includes(progress.status)) continue;
1338
- const quietTurns = progress.plot.pacing.quietTurns + (openThreads.length === 0 ? 0 : 2);
1339
- if (recent.length > 0 || turn <= quietTurns) continue;
1340
- if (turn - progress.lastNudgeTurn < progress.plot.pacing.cooldownTurns) continue;
1341
- if (now !== void 0 && progress.lastNudgeAt !== void 0 && now - progress.lastNudgeAt < progress.plot.pacing.cooldownDays * 864e5) continue;
1342
- const step = [...progress.plot.hooks, ...progress.plot.developments].filter((step) => !progress.introduced.includes(step.id) && !progress.rejected.includes(step.id) && step.prerequisites.every((id) => progress.introduced.includes(id)))[0];
1343
- if (step === void 0) continue;
1344
- const quietFor = turn - progress.lastNudgeTurn;
1345
- progress.lastNudgeTurn = turn;
1346
- if (now !== void 0) progress.lastNudgeAt = now;
1347
- progress.status = progress.status === "available" ? "engaged" : progress.status;
1348
- store.story.metadata.setValue(PLOTS_METADATA_KEY, plots);
1349
- return {
1350
- need: quietFor > progress.plot.pacing.quietTurns * 2 ? "clear" : "gentle",
1351
- reason: openThreads.length === 0 ? "no recorded development or immediate thread has guided the last few turns" : "the open threads have remained without recorded development for several turns",
1352
- plot: progress.plot.id,
1353
- plotName: progress.plot.name,
1354
- development: step.id,
1355
- mode: step.mode,
1356
- guidance: step.guidance || step.text,
1357
- avoid: step.avoid
1358
- };
1359
- }
1360
- }
1361
- function describePacingAdvice(advice) {
1362
- return `Pacing opportunity (${advice.need}; advice only, not an event): ${advice.plotName} [plot ${advice.plot}] / development ${advice.development}\nWhy now: ${advice.reason}.\nPossible nudge (${advice.mode}): ${advice.guidance}${advice.avoid.length === 0 ? "" : `\nDo not: ${advice.avoid.join("; ")}.`}\nUse it only if it fits the present scene. Do not make the player accept it, do not make a character act without activate_characters, and do not mark the development complete merely because it was offered.`;
1363
- }
1364
- function updatePlotProgress(store, plotId, developmentId, action) {
1365
- const plots = progressOf(store);
1366
- const progress = plots.find((entry) => entry.plot.id === plotId);
1367
- if (progress === void 0) throw new Error(`there is no plot "${plotId}"`);
1368
- if (action === "resolved" || action === "abandoned") progress.status = action;
1369
- else {
1370
- if (developmentId === void 0) throw new Error(`${action} needs a development`);
1371
- if (![...progress.plot.hooks, ...progress.plot.developments].some((step) => step.id === developmentId)) throw new Error(`plot "${plotId}" has no development "${developmentId}"`);
1372
- const target = action === "introduced" ? progress.introduced : progress.rejected;
1373
- if (!target.includes(developmentId)) target.push(developmentId);
1374
- if (action === "introduced") progress.status = "engaged";
1375
- }
1376
- store.story.metadata.setValue(PLOTS_METADATA_KEY, plots);
1377
- return progress;
1378
- }
1379
- //#endregion
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;
1389
- };
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
- };
1405
- }
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;
1424
- }
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 }
1440
- });
1441
- }
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
- });
1461
- }
1462
- /**
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.
1466
- */
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
- } };
1796
- }
1797
- //#endregion
1798
- //#region src/host/sessions/activity.ts
1799
- const KEY$1 = "activity";
1800
- const isEntry = (value) => {
1801
- if (typeof value !== "object" || value === null) return false;
1802
- const entry = value;
1803
- return typeof entry["at"] === "number" && typeof entry["label"] === "string" && typeof entry["model"] === "string" && typeof entry["ms"] === "number" && typeof entry["calls"] === "number" && (entry["error"] === void 0 || typeof entry["error"] === "string");
1804
- };
1805
- /** The recorded runs, oldest first. */
1806
- function readActivity(session) {
1807
- const stored = session.metadata.getValue(KEY$1);
1808
- return Array.isArray(stored) ? stored.filter(isEntry) : [];
1809
- }
1810
- /** Files the run and returns the runs that fell off the end of the record to make room. */
1811
- function recordActivity(session, entry) {
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
- }));
1874
- }
1875
- //#endregion
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 };
1877
-
1878
- //# sourceMappingURL=deliver--uMhC6oO.js.map