@dsh-agentic-roleplay/core 0.2.1 → 0.3.1

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 (48) hide show
  1. package/lib/{chat-AKrVcWIC.js → access-EbNdZFbk.js} +10 -2
  2. package/lib/authoring.js +193 -227
  3. package/lib/client.js +2710 -1322
  4. package/lib/client.js.map +1 -1
  5. package/lib/compaction.js +2 -3
  6. package/lib/deliver-BDW5WZvc.js +2262 -0
  7. package/lib/{documents-Bu5uYRZB.js → documents-DtlY2IRt.js} +958 -10
  8. package/lib/{gallery-DUeBMHQX.js → gallery-DACG5eh2.js} +2 -2
  9. package/lib/{generator-HPifO3Kk.js → generator-DGYcLMp7.js} +2 -2
  10. package/lib/images.js +3 -3
  11. package/lib/index.js +419 -23
  12. package/lib/{narration-BRyHU0H2.js → narration-5ig7Dg28.js} +12 -2
  13. package/lib/orchestration.js +458 -342
  14. package/lib/{packs-ByP1J-zj.js → packs-CkRZDCsV.js} +51 -5
  15. package/lib/{presenter-agent-G43ODV8I.js → presenter-agent-PK9JYExk.js} +4 -4
  16. package/package.json +5 -4
  17. package/packs/scene/map.html +12 -0
  18. package/packs/scene/map.js +55 -0
  19. package/packs/scene/pack.json +11 -0
  20. package/packs/scene/strip.html +11 -0
  21. package/packs/scene/strip.js +26 -0
  22. package/packs/scene/style.css +16 -0
  23. package/prompts/en/roleplay/character-decide.md +1 -1
  24. package/prompts/en/roleplay/character-rules.md +1 -1
  25. package/prompts/en/roleplay/chronicler.md +1 -1
  26. package/prompts/en/roleplay/game-master.md +1 -1
  27. package/prompts/en/roleplay/reflection.md +9 -0
  28. package/prompts/en/roleplay/style.md +1 -1
  29. package/prompts/en/roleplay/suggester.md +1 -1
  30. package/prompts/en/translate/document.md +6 -0
  31. package/prompts/en/translate/glossary.md +5 -0
  32. package/prompts/en/translate/notice.md +2 -0
  33. package/prompts/en/world/procedure.md +1 -1
  34. package/prompts/en/world/welcome.md +1 -1
  35. package/prompts/zh/roleplay/character-decide.md +1 -1
  36. package/prompts/zh/roleplay/character-rules.md +1 -1
  37. package/prompts/zh/roleplay/chronicler.md +1 -1
  38. package/prompts/zh/roleplay/game-master.md +1 -1
  39. package/prompts/zh/roleplay/reflection.md +9 -0
  40. package/prompts/zh/roleplay/style.md +1 -1
  41. package/prompts/zh/roleplay/suggester.md +1 -1
  42. package/prompts/zh/translate/document.md +6 -0
  43. package/prompts/zh/translate/glossary.md +5 -0
  44. package/prompts/zh/translate/notice.md +2 -0
  45. package/prompts/zh/world/procedure.md +1 -1
  46. package/prompts/zh/world/welcome.md +1 -1
  47. package/lib/access-C1nFQiyT.js +0 -12
  48. package/lib/activity-t7OBgHlc.js +0 -1386
@@ -1,1386 +0,0 @@
1
- import { n as roleplaySessionOf } from "./chat-AKrVcWIC.js";
2
- import { B as SessionNotFoundError, i as inheritPacks, k as inheritPrompts } from "./packs-ByP1J-zj.js";
3
- import { j as estimateAnswer, u as inheritImages } from "./generator-HPifO3Kk.js";
4
- import { join } from "node:path";
5
- import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
6
- import { createUserMessage } from "@deepseek-ai/dsh-llm";
7
- import { DAY, MINUTE, SECOND, clockTime, dayPart, describeDuration, describeInstant, isSessionId, localTime, locationKey, mentioned, nextTimeOfDay, overlap, sessionDatabase, sessionFolder, tokens } from "@dsh-agentic-roleplay/state";
8
- //#region src/host/orchestration/protocol.ts
9
- const COMMITMENTS = [
10
- "low",
11
- "medium",
12
- "high"
13
- ];
14
- const RESULTS = [
15
- "succeeded",
16
- "partial",
17
- "failed"
18
- ];
19
- const MAX_ACCOUNT = 300;
20
- /**
21
- * 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.
22
- * A character of a script written without spaces says more in fewer.
23
- */
24
- const ANSWER_LIMITS = {
25
- en: {
26
- thought: 240,
27
- intent: 300,
28
- utterance: 600,
29
- account: MAX_ACCOUNT
30
- },
31
- zh: {
32
- thought: 100,
33
- intent: 120,
34
- utterance: 240,
35
- account: 120
36
- }
37
- };
38
- const answerLimits = (language) => language.toLowerCase().startsWith("zh") ? ANSWER_LIMITS.zh : ANSWER_LIMITS.en;
39
- /** What the answer of a character comes to at most, in tokens (an answer about what happened out of sight has its account too). */
40
- function answerEstimate(language, away) {
41
- const limits = answerLimits(language);
42
- return estimateAnswer([
43
- limits.thought,
44
- limits.intent,
45
- limits.utterance,
46
- ...away ? [limits.account] : []
47
- ], language);
48
- }
49
- /**
50
- * 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
51
- * 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).
52
- */
53
- const CHARACTER_ACTION_SCHEMA = {
54
- type: "object",
55
- properties: {
56
- thought: {
57
- type: "string",
58
- 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."
59
- },
60
- intent: {
61
- type: "string",
62
- description: "What the character does, or tries to do, now, as an action in one or two sentences, without any speech."
63
- },
64
- utterance: {
65
- type: "string",
66
- 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."
67
- },
68
- commitment: {
69
- type: "string",
70
- enum: [...COMMITMENTS],
71
- description: "How hard the character will keep trying if this does not work out: low gives up at once, high persists."
72
- }
73
- },
74
- required: [
75
- "thought",
76
- "intent",
77
- "commitment"
78
- ],
79
- additionalProperties: false
80
- };
81
- /** 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. */
82
- const AWAY_ACTION_SCHEMA = {
83
- ...CHARACTER_ACTION_SCHEMA,
84
- properties: {
85
- ...CHARACTER_ACTION_SCHEMA.properties,
86
- account: {
87
- type: "string",
88
- 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."
89
- }
90
- },
91
- required: [
92
- "thought",
93
- "intent",
94
- "commitment",
95
- "account"
96
- ]
97
- };
98
- /** @throws {Error} when the value is not a character action. */
99
- const QUOTE_PAIRS = [
100
- ["\"", "\""],
101
- ["“", "”"],
102
- ["「", "」"],
103
- ["『", "』"],
104
- ["«", "»"],
105
- ["‘", "’"]
106
- ];
107
- /** Words said aloud, without the quotation marks a model puts around them: the output puts its own. */
108
- function unquoted(text) {
109
- let words = text.trim();
110
- for (let again = true; again;) {
111
- again = false;
112
- 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)) {
113
- words = words.slice(open.length, words.length - close.length).trim();
114
- again = true;
115
- }
116
- }
117
- return words;
118
- }
119
- const LEAKED_FIELD = /<\/?(?:intent|parameter(?:=\w+)?)>/g;
120
- /** A model that writes the markup of its call into a field puts the next field's text inside this one. */
121
- function splitLeakedFields(intent) {
122
- const at = intent.search(/<parameter=utterance>/);
123
- if (at === -1) return { intent: intent.replace(LEAKED_FIELD, " ") };
124
- const spoken = intent.slice(at).replace(LEAKED_FIELD, " ").trim();
125
- return {
126
- intent: intent.slice(0, at).replace(LEAKED_FIELD, " "),
127
- ...spoken === "" ? {} : { utterance: spoken }
128
- };
129
- }
130
- function parseCharacterAction(value) {
131
- if (typeof value !== "object" || value === null) throw new Error("the character did not answer with an object");
132
- const { intent: rawIntent, utterance: rawUtterance, commitment, account } = value;
133
- const { intent, utterance } = typeof rawIntent === "string" && rawUtterance === void 0 ? splitLeakedFields(rawIntent) : {
134
- intent: rawIntent,
135
- utterance: rawUtterance
136
- };
137
- if (typeof intent !== "string" || intent.trim() === "") throw new Error("the character gave no intent");
138
- if (!COMMITMENTS.includes(commitment)) throw new Error(`the character gave an unknown commitment "${String(commitment)}"`);
139
- if (utterance !== void 0 && typeof utterance !== "string") throw new Error("the character's utterance is not text");
140
- const spoken = utterance === void 0 ? void 0 : unquoted(utterance);
141
- const told = typeof account === "string" ? account.trim().slice(0, MAX_ACCOUNT) : "";
142
- return {
143
- intent: intent.trim(),
144
- ...spoken === void 0 || spoken === "" ? {} : { utterance: spoken },
145
- commitment,
146
- ...told === "" ? {} : { account: told }
147
- };
148
- }
149
- //#endregion
150
- //#region src/host/orchestration/referent.ts
151
- /**
152
- * 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.
153
- * 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.
154
- */
155
- function referent(character) {
156
- const mark = [character.pronouns, character.gender].find((text) => text !== void 0 && text.trim() !== "")?.trim();
157
- return mark === void 0 ? character.name : `${character.name} (${mark})`;
158
- }
159
- //#endregion
160
- //#region src/host/clock/story-clock.ts
161
- var ClockError = class extends Error {};
162
- /** 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. */
163
- function describeWhen(instant, now, zone) {
164
- const a = localTime(instant, zone);
165
- const b = localTime(now, zone);
166
- return a.year === b.year && a.month === b.month && a.day === b.day ? clockTime(instant, zone) : describeInstant(instant, zone);
167
- }
168
- /** The time in a sentence: the day and date, the clock, and the part of the day. */
169
- function describeTime(time) {
170
- return `${describeInstant(time.now, time.zone)} (${dayPart(localTime(time.now, time.zone).minuteOfDay)})`;
171
- }
172
- /** The time zone the story is read in. */
173
- const zoneOf = (config) => config.timeZone === "" ? "UTC" : config.timeZone;
174
- /** 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. */
175
- function ensure(session, config, turn, wall) {
176
- const current = session.clock.get();
177
- if (current === void 0) {
178
- session.clock.start(config.mode, config.mode === "real" ? wall : Math.floor(wall / MINUTE) * MINUTE);
179
- return session.clock.get() ?? {
180
- mode: config.mode,
181
- now: wall
182
- };
183
- }
184
- if (current.mode !== "real" || config.mode !== "simulated") return current;
185
- session.clock.resync("simulated", Math.max(current.now, wall), turn, "the story's time was detached from the real clock");
186
- return session.clock.get() ?? current;
187
- }
188
- const timeOf = (state, config) => ({
189
- mode: state.mode,
190
- now: state.now,
191
- zone: zoneOf(config)
192
- });
193
- /** What time it is, without letting any pass. */
194
- function readTime(session, config, turn, wall) {
195
- return session.transaction(() => timeOf(ensure(session, config, turn, wall), config));
196
- }
197
- /**
198
- * The start of a turn. Following the wall clock, the time since the last turn passed outside the story:
199
- * `away` says how long.
200
- */
201
- function beginTurn(session, config, turn, wall) {
202
- return session.transaction(() => {
203
- const state = ensure(session, config, turn, wall);
204
- if (state.mode === "real" && wall > state.now) {
205
- session.clock.advance({
206
- to: wall,
207
- turn,
208
- round: 0,
209
- kind: "real",
210
- reason: "between turns"
211
- });
212
- return {
213
- time: timeOf({
214
- mode: "real",
215
- now: wall
216
- }, config),
217
- away: wall - state.now
218
- };
219
- }
220
- return { time: timeOf(state, config) };
221
- });
222
- }
223
- /**
224
- * A round passes. Simulated, it takes what the game master said (or the default), and at least as long as the
225
- * journey the player's character made (`minimum`); following the wall clock, it takes as long as it took.
226
- */
227
- function endRound(session, config, turn, round, wall, stated, minimum) {
228
- return session.transaction(() => {
229
- const state = ensure(session, config, turn, wall);
230
- if (state.mode === "real") {
231
- const to = Math.max(state.now, wall);
232
- session.clock.advance({
233
- to,
234
- turn,
235
- round,
236
- kind: "real"
237
- });
238
- return {
239
- from: state.now,
240
- to,
241
- zone: zoneOf(config)
242
- };
243
- }
244
- const took = Math.max(stated ?? config.roundSeconds, minimum ?? 0) * SECOND;
245
- session.clock.advance({
246
- to: state.now + took,
247
- turn,
248
- round,
249
- kind: "elapsed"
250
- });
251
- return {
252
- from: state.now,
253
- to: state.now + took,
254
- zone: zoneOf(config)
255
- };
256
- });
257
- }
258
- /**
259
- * Skip ahead in the story's own time.
260
- * @throws {ClockError} when time follows the wall clock, the request is not one, or it asks for more than the chat allows.
261
- */
262
- function skipTime(session, config, turn, round, wall, request) {
263
- return session.transaction(() => {
264
- const state = ensure(session, config, turn, wall);
265
- if (state.mode === "real") throw new ClockError("the story's time follows the wall clock, so it cannot be skipped");
266
- const zone = zoneOf(config);
267
- const reason = request.reason.trim();
268
- if (reason === "") throw new ClockError("say what happens in the time that passes (reason)");
269
- let to;
270
- if ("byMinutes" in request) {
271
- if (!Number.isInteger(request.byMinutes) || request.byMinutes < 1) throw new ClockError("by_minutes must be a whole number of minutes, at least 1");
272
- to = state.now + request.byMinutes * MINUTE;
273
- } else try {
274
- to = nextTimeOfDay(state.now, zone, request.untilTime, request.daysLater);
275
- } catch (error) {
276
- throw new ClockError(error instanceof RangeError ? error.message : String(error));
277
- }
278
- 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`);
279
- session.clock.advance({
280
- to,
281
- turn,
282
- round,
283
- kind: "skip",
284
- reason
285
- });
286
- return {
287
- from: state.now,
288
- to,
289
- zone,
290
- reason
291
- };
292
- });
293
- }
294
- //#endregion
295
- //#region src/host/orchestration/defaults.ts
296
- /** What the instructions say about how long each part of a character's answer may run. */
297
- const limitVariables = (language) => {
298
- const limits = answerLimits(language);
299
- return {
300
- thoughtLimit: limits.thought,
301
- intentLimit: limits.intent,
302
- utteranceLimit: limits.utterance
303
- };
304
- };
305
- function describe(character) {
306
- const lines = [`You are ${character.name}.`];
307
- if (character.aliases.length > 0) lines.push(`You are also called ${character.aliases.join(", ")}.`);
308
- const facts = [
309
- character.age === void 0 ? void 0 : `age: ${character.age}`,
310
- character.gender === void 0 ? void 0 : `gender: ${character.gender}`,
311
- character.pronouns === void 0 ? void 0 : `pronouns: ${character.pronouns}`
312
- ].filter((fact) => fact !== void 0);
313
- if (facts.length > 0) lines.push(facts.join("; ") + ".");
314
- for (const [label, text] of [
315
- ["Summary", character.summary],
316
- ["Personality", character.personality],
317
- ["Background", character.background],
318
- ["Appearance", character.appearance],
319
- ["How you speak", character.speech.style]
320
- ]) if (text.trim() !== "") lines.push(`${label}: ${text.trim()}`);
321
- return lines.join("\n");
322
- }
323
- /** At most this many features and ways out of a place are told at once. */
324
- const SHOWN_FEATURES = 12;
325
- const SHOWN_EXITS = 12;
326
- const sentence = (text) => {
327
- return (/^[^.!?。!?]*[.!?。!?]?/u.exec(text.trim())?.[0] ?? text).trim();
328
- };
329
- /** At most this many things are listed at once: the rest are said to be there and left for a closer look. */
330
- const SHOWN_ITEMS = 12;
331
- /** One thing in a sentence: how many, what state it is in, where it is. */
332
- function describeItem(item, { withKeys }) {
333
- const name = `${item.quantity > 1 ? `${item.quantity} ` : ""}${item.name}${item.quality === "" ? "" : ` (${item.quality})`}`;
334
- const extra = [
335
- item.hidden ? "hidden" : "",
336
- item.state === void 0 ? "" : item.state,
337
- item.where ?? ""
338
- ].filter((part) => part !== "").join(", ");
339
- const inside = item.contents === void 0 ? "" : ` holding ${item.contents.join(", ")}`;
340
- return `${withKeys ? `${item.key}: ` : ""}${name}${extra === "" ? "" : ` [${extra}]`}${inside}`;
341
- }
342
- /** A list of things, capped. */
343
- function describeItems(items, options) {
344
- return `${items.slice(0, SHOWN_ITEMS).map((item) => describeItem(item, options)).join("; ")}${items.length > SHOWN_ITEMS ? `; and ${items.length - SHOWN_ITEMS} more` : ""}`;
345
- }
346
- /** What someone in a place is told about it: what it is like, what can be pointed at, and the ways out. */
347
- function describePlace(view, { withKeys }) {
348
- const { location, exits } = view;
349
- const lines = [`${location.name}${withKeys ? ` (${view.key})` : ""}${location.description === "" ? "" : `: ${location.description}`}`];
350
- if (location.features.length > 0) {
351
- const shown = location.features.slice(0, SHOWN_FEATURES).map((feature) => `${withKeys ? `${feature.key}: ` : ""}${feature.name}${feature.description === "" ? "" : ` - ${sentence(feature.description)}`}`);
352
- lines.push(`Things here: ${shown.join("; ")}${location.features.length > SHOWN_FEATURES ? `; and ${location.features.length - SHOWN_FEATURES} more` : ""}`);
353
- }
354
- if (exits.length > 0) {
355
- 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}`}]`}`);
356
- lines.push(`Ways out: ${shown.join("; ")}${exits.length > SHOWN_EXITS ? `; and ${exits.length - SHOWN_EXITS} more` : ""}`);
357
- }
358
- if (view.items !== void 0 && view.items.length > 0) lines.push(`Lying about: ${describeItems(view.items, { withKeys })}`);
359
- return lines;
360
- }
361
- /** How long the player has to have been away for it to be worth telling the game master. */
362
- const NOTICEABLE_ABSENCE = 5 * MINUTE;
363
- /** What the game master is told about time at the start of a turn, and how it passes. */
364
- function timeNotice(time) {
365
- const now = `Time: ${describeTime(time.now)}.`;
366
- 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.`;
367
- 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.` : ""}`;
368
- }
369
- /** What a character is told of its day, its commitments and what it is after. */
370
- function describeAgenda(agenda, now) {
371
- const { zone } = agenda;
372
- const at = (place) => place === void 0 ? "" : ` at ${place}`;
373
- const lines = [];
374
- 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)"}.`);
375
- if (agenda.next !== void 0) lines.push(`Your day, next: ${agenda.next.activity}${at(agenda.next.place)}, from ${describeWhen(agenda.next.at, now, zone)}.`);
376
- 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" : ""}.`);
377
- if (agenda.goals.length > 0) {
378
- lines.push("What you are after:");
379
- 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("; ")}.`}`);
380
- }
381
- return lines;
382
- }
383
- /** What the game master is told of the characters' days at the start of a turn; nothing when there is nothing to tell. */
384
- function describeSceneAgenda(agenda, now) {
385
- const lines = [];
386
- 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("; ")}.`);
387
- 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.`);
388
- 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("; ")}.`);
389
- return lines.join("\n");
390
- }
391
- /** In words, how a character stands with another, from the numbers of its profile; nothing for what is unremarkable. */
392
- function describeAttitude(relation) {
393
- return [
394
- relation.familiarity >= .7 ? "knows them well" : relation.familiarity <= .15 ? "barely knows them" : "",
395
- relation.trust >= .4 ? "trusts them" : relation.trust <= -.4 ? "distrusts them" : "",
396
- relation.affinity >= .4 ? "is fond of them" : relation.affinity <= -.4 ? "dislikes them" : "",
397
- relation.tension >= .5 ? "things are strained between them" : ""
398
- ].filter((part) => part !== "").join(", ");
399
- }
400
- function whereIs(member) {
401
- const place = member.place;
402
- if (place === void 0) return "";
403
- return [place.position, place.feature === void 0 ? "" : `at ${place.feature.name}`].filter((part) => part !== "").join(", ");
404
- }
405
- function present(cast, self) {
406
- return cast.map((member) => {
407
- const { key, character, state } = member;
408
- const seen = [state?.publicState, state?.activity].filter((text) => text !== void 0 && text.trim() !== "");
409
- const where = whereIs(member);
410
- return `- ${key === self ? character.name : referent(character)}${key === self ? " (you)" : ""}${where === "" ? "" : ` (${where})`}${seen.length > 0 ? `: ${seen.join("; ")}` : ""}`;
411
- }).join("\n");
412
- }
413
- /** A bounded, advisory order for who is most likely to need a turn; reachability still governs activation. */
414
- function describeActivationCandidates(cast, input, story) {
415
- const player = cast.find((member) => member.character.control === "player");
416
- if (player === void 0) return "";
417
- const named = mentioned(input, cast.map((member) => member.character));
418
- const cues = tokens(input);
419
- const candidates = cast.filter((member) => member.character.control === "agent").map((member) => {
420
- const relation = story.relationships.get(member.character.id, player.character.id);
421
- const here = member.place === void 0 || player.place === void 0 || member.place.location.id === player.place.location.id;
422
- const goal = story.intents.list(member.character.id, { status: "active" }).map((intent) => ({
423
- intent,
424
- match: overlap(cues, `${intent.name} ${intent.description}`, [])
425
- })).sort((a, b) => b.match - a.match)[0];
426
- const factionGoal = story.factionMemberships.ofCharacter(member.character.id, "active").flatMap((membership) => story.factionIntents.list(membership.factionId, { status: "active" }).map((intent) => ({
427
- intent,
428
- match: overlap(cues, `${intent.name} ${intent.description}`, []) * membership.commitment
429
- }))).sort((a, b) => b.match - a.match)[0];
430
- return {
431
- member,
432
- reasons: [
433
- named.has(member.character.id) ? "named in the move" : "",
434
- here ? "in the scene" : "",
435
- (goal?.match ?? 0) >= 2 ? `own goal: ${goal.intent.name}` : "",
436
- (factionGoal?.match ?? 0) >= 2 ? `faction pressure: ${factionGoal.intent.name}` : "",
437
- relation !== void 0 && relation.tension >= .5 ? "high tension toward the player" : "",
438
- relation !== void 0 && relation.trust <= -.4 ? "distrusts the player" : "",
439
- relation !== void 0 && Math.abs(relation.affinity) >= .4 ? relation.affinity > 0 ? "cares about the player" : "dislikes the player" : ""
440
- ].filter((reason) => reason !== ""),
441
- 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
442
- };
443
- }).filter((entry) => entry.score > 0).sort((a, b) => b.score - a.score || a.member.key.localeCompare(b.member.key)).slice(0, 5);
444
- if (candidates.length === 0) return "";
445
- 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")}`;
446
- }
447
- function said(entry) {
448
- return `- ${entry.name}${entry.utterance === void 0 ? "" : ` said "${entry.utterance}" and`} intended: ${entry.intent} (${entry.result}) ${entry.summary}`;
449
- }
450
- function age(at, now) {
451
- if (at === void 0 || now === void 0) return "some time ago";
452
- const seconds = Math.max(0, Math.floor((now - at) / 1e3));
453
- if (seconds < 60) return "just now";
454
- const unit = [
455
- {
456
- seconds: 86400,
457
- name: "day"
458
- },
459
- {
460
- seconds: 3600,
461
- name: "hour"
462
- },
463
- {
464
- seconds: 60,
465
- name: "minute"
466
- }
467
- ].find((candidate) => seconds >= candidate.seconds);
468
- const amount = Math.floor(seconds / unit.seconds);
469
- return `${amount} ${unit.name}${amount === 1 ? "" : "s"} ago`;
470
- }
471
- /** What a character remembers, in the way it remembers it: what is faded or vague is told as such. */
472
- function remembered(memories, now) {
473
- return memories.map((memory) => {
474
- 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}`;
475
- }).join("\n");
476
- }
477
- /** Every character is told the same thing about the scene, plus who it is and what it remembers. */
478
- const sharedContext = { brief(request) {
479
- const { member, cast, situation, attempt, earlier, reaction, previous, memories, place, relationships, knowledge, affiliations, carrying, time, agenda } = request;
480
- const company = place === void 0 ? cast : place.here;
481
- const sections = [
482
- `Situation:\n${situation}`,
483
- ...time === void 0 ? [] : [`Now: ${describeTime(time)}.`],
484
- ...place === void 0 ? [] : [`Where you are:\n${describePlace(place, { withKeys: false }).join("\n")}`],
485
- `Present:\n${present(company, member.key)}`
486
- ];
487
- 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")}`);
488
- if (request.cues !== void 0 && request.cues.length > 0) sections.push(`Just now you notice:\n${request.cues.map((cue) => `- ${cue}`).join("\n")}`);
489
- if (request.tracked !== void 0 && request.tracked.self !== "") sections.push(`How you are (what you can tell of yourself):\n${request.tracked.self}`);
490
- 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")}`);
491
- const day = agenda === void 0 || time === void 0 ? [] : describeAgenda(agenda, time.now);
492
- 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")}`);
493
- if (carrying !== void 0 && carrying.length > 0) sections.push(`What you have on you:\n${describeItems(carrying, { withKeys: false })}`);
494
- 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) => {
495
- const attitude = describeAttitude(relation);
496
- return `- ${relation.name}${relation.present ? " (here)" : " (not here)"} — ${relation.label}${relation.summary === "" ? "" : `: ${relation.summary}`}${attitude === "" ? "" : ` [${attitude}]`}`;
497
- }).join("\n")}`);
498
- if (affiliations !== void 0 && affiliations.length > 0) sections.push(`Your affiliations (their goals are pressures and commitments, not commands):\n${affiliations.map((entry) => {
499
- const position = [entry.role, entry.rank].filter(Boolean).join(", ") || "member";
500
- const goals = entry.goals.length === 0 ? "" : ` Goals: ${entry.goals.join("; ")}.`;
501
- const state = entry.publicState === "" ? "" : ` ${entry.publicState}`;
502
- const attitude = entry.relationship === void 0 ? "" : describeAttitude(entry.relationship);
503
- return `- ${entry.name}: ${position}; ${entry.status}; commitment ${entry.commitment.toFixed(2)}.${state}${goals}${attitude === "" ? "" : ` Your view: ${attitude}.`}`;
504
- }).join("\n")}`);
505
- if (knowledge !== void 0) {
506
- const shown = (entries) => entries.slice(0, 30).join("; ") + (entries.length > 30 ? `; and ${entries.length - 30} more you can recall if needed` : "");
507
- const lines = [
508
- knowledge.characters.length === 0 ? void 0 : `People: ${shown(knowledge.characters)}`,
509
- knowledge.factions.length === 0 ? void 0 : `Factions: ${shown(knowledge.factions)}`,
510
- knowledge.locations.length === 0 ? void 0 : `Places: ${shown(knowledge.locations)}`,
511
- knowledge.routes.length === 0 ? void 0 : `Routes: ${shown(knowledge.routes)}`,
512
- knowledge.items.length === 0 ? void 0 : `Things: ${shown(knowledge.items)}`
513
- ].filter((line) => line !== void 0);
514
- 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")}`);
515
- }
516
- 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)}`);
517
- else if (memories !== void 0) sections.splice(1, 0, "What you remember that bears on this: nothing comes to mind.");
518
- if (earlier !== void 0 && earlier.length > 0) sections.push(`Earlier in this scene, before this moment:\n${earlier.map(said).join("\n")}`);
519
- if (attempt === 2 && reaction !== void 0) {
520
- sections.push(`What just happened, and what you are reacting to:\n${reaction.map(said).join("\n")}`);
521
- 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.`);
522
- }
523
- return {
524
- persona: [
525
- describe(member.character),
526
- request.text("roleplay/character-rules", { name: member.character.name }),
527
- request.text("roleplay/character-style", { name: member.character.name }),
528
- ...request.lookup ? [request.text("roleplay/character-lookup")] : [],
529
- request.text("roleplay/character-decide", {
530
- name: member.character.name,
531
- ...limitVariables(request.language ?? "en")
532
- })
533
- ].join("\n\n"),
534
- prompt: sections.join("\n\n")
535
- };
536
- } };
537
- /**
538
- * 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
539
- * 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
540
- * another place can be asked when the moment reaches it.)
541
- */
542
- const everyoneActs = { plan({ cast, requested }) {
543
- const placed = cast.some((member) => member.place !== void 0);
544
- const available = cast.filter((member) => member.character.control === "agent");
545
- const here = cast.find((member) => member.character.control === "player")?.place?.location.id;
546
- const inScene = (member) => !placed || member.place !== void 0;
547
- 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);
548
- const unknown = requested.filter((key) => !available.some((member) => member.key === key));
549
- 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(", ")})`);
550
- const nowhere = [...new Set(requested)].map((key) => available.find((member) => member.key === key)).filter((member) => !inScene(member));
551
- 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`);
552
- return [...new Set(requested)];
553
- } };
554
- const acceptsAnyIntent = { validate: ({ intent }) => intent.trim() === "" ? {
555
- ok: false,
556
- reason: "the intent is empty"
557
- } : { ok: true } };
558
- /** A character whose intent failed and who is highly committed tries once more. */
559
- const persistentRetry = { select({ reports, outcomes }) {
560
- return reports.filter((report) => report.commitment === "high" && outcomes.some((outcome) => outcome.character === report.character && outcome.result === "failed")).map((report) => report.character);
561
- } };
562
- const acceptsAnyInput = { validate: () => ({ ok: true }) };
563
- /** The game master narrates. */
564
- const gameMasterNarrates = { narrate: () => Promise.resolve(void 0) };
565
- /** Compares what was said, ignoring the quotes around it and the way whitespace is laid out. */
566
- const WRAPPING_QUOTES = /^["“”„«»'‘’]+|["“”„«»'‘’]+$/g;
567
- function sameWords(a, b) {
568
- const plain = (text) => text.trim().replace(WRAPPING_QUOTES, "").replace(/\s+/g, " ").trim();
569
- return plain(a) === plain(b);
570
- }
571
- /** How many earlier events the game master is reminded of at most. */
572
- const REMINDED_EVENTS = 5;
573
- /**
574
- * The state of the scene, what is still open in the story, and the earlier events that the
575
- * player's move brings to mind (by the session's search of words and meaning, and by who is named):
576
- * those already folded out of the conversation into the summaries, whose detail the summaries may have lost.
577
- */
578
- /** Where the player is and what is there, who is with them, and who is elsewhere. */
579
- function placedScene(cast, player, story, describeMember, things) {
580
- const here = player?.place?.location;
581
- const sections = [];
582
- if (here !== void 0) {
583
- const view = {
584
- key: locationKey(here),
585
- location: here,
586
- here: cast.filter((member) => member.place?.location.id === here.id),
587
- ...things === void 0 ? {} : { items: things.at(here.id) },
588
- exits: story.locations.exitsFrom(here.id).flatMap((exit) => {
589
- const to = story.locations.get(exit.toId);
590
- return to === void 0 ? [] : [{
591
- key: locationKey(to),
592
- name: to.name,
593
- exit
594
- }];
595
- })
596
- };
597
- sections.push(`The player's character is in ${describePlace(view, { withKeys: true }).join("\n")}`);
598
- sections.push(`Characters here:\n${view.here.map(describeMember).join("\n")}`);
599
- }
600
- const elsewhere = cast.filter((member) => member.place !== void 0 && member.place.location.id !== here?.id);
601
- 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")}`);
602
- const nowhere = cast.filter((member) => member.place === void 0);
603
- 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")}`);
604
- return sections.join("\n\n");
605
- }
606
- const castSummary = { scene({ tracked, time, world, cast, turn, input, queryVector, story, items }) {
607
- const describeMember = (member) => {
608
- const { key, character, state } = member;
609
- const role = character.control === "player" ? `the player's character, "${key}"` : `acts through "${key}"`;
610
- const seen = [state?.publicState, state?.activity].filter((text) => text !== void 0 && text.trim() !== "");
611
- const where = whereIs(member);
612
- return `- ${referent(character)} (${role})${where === "" ? "" : ` [${where}]`}${character.summary === "" ? "" : `: ${character.summary}`}${seen.length > 0 ? ` Currently: ${seen.join("; ")}` : ""}`;
613
- };
614
- const player = cast.find((member) => member.character.control === "player");
615
- const days = time?.agenda === void 0 ? "" : describeSceneAgenda(time.agenda, time.now.now);
616
- const parts = [
617
- ...time === void 0 ? [] : [timeNotice(time)],
618
- ...days === "" ? [] : [days],
619
- `Scene before turn ${turn}:\n${cast.some((member) => member.place !== void 0) ? placedScene(cast, player, story, describeMember, items) : cast.map(describeMember).join("\n")}`
620
- ];
621
- const activation = describeActivationCandidates(cast, input, story);
622
- if (activation !== "") parts.push(activation);
623
- if (items !== void 0) {
624
- const carried = cast.flatMap((member) => {
625
- const mine = items.carried(member.character.id);
626
- return mine.length === 0 ? [] : [`- ${member.character.name} (${member.key}): ${describeItems(mine, { withKeys: true })}`];
627
- });
628
- if (carried.length > 0) parts.push(`What characters have on them:\n${carried.join("\n")}`);
629
- }
630
- 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")}`);
631
- 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")}`);
632
- 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")}`);
633
- 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")}`);
634
- const threads = story.threads.list("open");
635
- if (threads.length > 0) parts.push(`Still open in the story:\n${threads.map((thread) => `- ${thread.text}`).join("\n")}`);
636
- const folded = story.summaries.list().reduce((latest, summary) => Math.max(latest, summary.toTurn), 0);
637
- if (folded > 0) {
638
- const mentionedIds = mentioned(input, cast.map(({ character }) => character));
639
- const cues = tokens(input);
640
- const names = new Map(cast.map(({ character }) => [character.id, character.name]));
641
- const byMeaning = story.searchEvents({
642
- text: input,
643
- ...queryVector === void 0 ? {} : { vector: queryVector },
644
- toTurn: folded,
645
- limit: REMINDED_EVENTS
646
- });
647
- const byCues = story.events.list({ toTurn: folded }).filter((event) => !byMeaning.some((found) => found.id === event.id)).map((event) => ({
648
- event,
649
- score: 3 * event.involves.filter((id) => mentionedIds.has(id)).length + overlap(cues, event.text, event.tags)
650
- })).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);
651
- const relevant = [...byMeaning, ...byCues].slice(0, REMINDED_EVENTS).sort((a, b) => a.turn - b.turn).map((event) => ({ event }));
652
- 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 }) => {
653
- const who = event.involves.map((id) => names.get(id)).filter((name) => name !== void 0).join(", ");
654
- return `- (turn ${event.turn}) ${event.text}${who === "" ? "" : ` [${who}]`}`;
655
- }).join("\n")}`);
656
- }
657
- return parts.join("\n\n");
658
- } };
659
- const sameCharacter = (utterance, character) => utterance.character === character || utterance.name === character;
660
- /** Every utterance appears once, exactly as given and in the order spoken, and no one speaks who did not. */
661
- const exactUtterances = {
662
- check(segments, required) {
663
- const problems = [];
664
- const used = /* @__PURE__ */ new Set();
665
- let latest = 0;
666
- segments.forEach((segment, index) => {
667
- const at = `segment ${index + 1}`;
668
- if (segment.type === "narration") {
669
- if (segment.text.trim() === "") problems.push(`${at}: the narration is empty`);
670
- return;
671
- }
672
- const own = required.flatMap((utterance, position) => sameCharacter(utterance, segment.character) ? [position] : []);
673
- const free = own.filter((position) => !used.has(position));
674
- const exact = free.find((position) => sameWords(segment.text, required[position].text));
675
- if (exact !== void 0) {
676
- used.add(exact);
677
- const spoken = required[exact];
678
- 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`);
679
- latest = Math.max(latest, spoken.round);
680
- } else if (free.length > 0) {
681
- used.add(free[0]);
682
- problems.push(`${at}: the utterance of ${required[free[0]].name} was changed; it must be exactly "${required[free[0]].text}"`);
683
- } 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`);
684
- else problems.push(`${at}: ${segment.character} has nothing to say this turn, so this utterance is invented; remove it`);
685
- });
686
- required.forEach((utterance, position) => {
687
- 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}"`);
688
- });
689
- return problems;
690
- },
691
- repair(segments, required) {
692
- const used = /* @__PURE__ */ new Set();
693
- const kept = [];
694
- for (const segment of segments) {
695
- if (segment.type === "narration") {
696
- if (segment.text.trim() !== "") kept.push({
697
- segment,
698
- round: void 0
699
- });
700
- continue;
701
- }
702
- const free = required.flatMap((utterance, position) => sameCharacter(utterance, segment.character) && !used.has(position) ? [position] : []);
703
- const position = free.find((candidate) => sameWords(segment.text, required[candidate].text)) ?? free[0];
704
- if (position === void 0) continue;
705
- used.add(position);
706
- const spoken = required[position];
707
- kept.push({
708
- segment: {
709
- type: "utterance",
710
- character: spoken.character,
711
- name: spoken.name,
712
- text: spoken.text
713
- },
714
- round: spoken.round
715
- });
716
- }
717
- required.forEach((utterance, position) => {
718
- if (used.has(position)) return;
719
- const restored = {
720
- type: "utterance",
721
- character: utterance.character,
722
- name: utterance.name,
723
- text: utterance.text
724
- };
725
- const later = kept.findIndex((entry) => entry.round !== void 0 && entry.round > utterance.round);
726
- kept.splice(later < 0 ? kept.length : later, 0, {
727
- segment: restored,
728
- round: utterance.round
729
- });
730
- });
731
- return kept.map((entry) => entry.segment);
732
- }
733
- };
734
- /** 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. */
735
- const recordsRecall = { recall: ({ member, situation, turn, policy, queryVector, explain }, story, signal) => story.recallRanked({
736
- characterId: member.character.id,
737
- situation,
738
- turn,
739
- policy,
740
- ...explain === true ? { explain } : {},
741
- ...member.place === void 0 ? {} : { locationId: member.place.location.id }
742
- }, signal, queryVector === void 0 ? {} : { queryVector }) };
743
- /**
744
- * Writes no memory. What the game master decided about each character is applied when the round is
745
- * recorded, so without a memory keeper the story keeps its states and no events.
746
- */
747
- const writesNothing = { commit: () => Promise.resolve({
748
- writes: 0,
749
- notes: ""
750
- }) };
751
- /** Makes up nothing, and has nothing to fit in: without a world author the world stays as it was written. */
752
- const declinesToAuthor = {
753
- create: () => Promise.resolve({
754
- created: [],
755
- declined: "no world author is installed, so the world cannot grow"
756
- }),
757
- consolidate: () => Promise.resolve({
758
- resolved: 0,
759
- notes: ""
760
- })
761
- };
762
- /** Lets no organisation act: without a strategist factions change only through what the story records. */
763
- const factionsStayPut = { strategize: () => Promise.resolve({ acted: [] }) };
764
- /** Judges nothing: without a judge a trigger that waits on a statement never sees it hold. */
765
- const judgesNothing = { judge: () => Promise.resolve({ judged: 0 }) };
766
- /** Offers nothing: without a suggester the player writes their own move. */
767
- const offersNothing = { suggest: () => Promise.resolve([]) };
768
- function defaultBoundaries() {
769
- return {
770
- planner: everyoneActs,
771
- characterContext: sharedContext,
772
- outputValidator: acceptsAnyIntent,
773
- retryPolicy: persistentRetry,
774
- inputValidator: acceptsAnyInput,
775
- narrator: gameMasterNarrates,
776
- narrationChecker: exactUtterances,
777
- committer: writesNothing,
778
- author: declinesToAuthor,
779
- strategist: factionsStayPut,
780
- judge: judgesNothing,
781
- suggester: offersNothing,
782
- recaller: recordsRecall,
783
- sceneContext: castSummary
784
- };
785
- }
786
- //#endregion
787
- //#region src/shared/timeline.ts
788
- const emptyTimeline = () => ({
789
- version: 1,
790
- head: null,
791
- next: 1,
792
- nodes: []
793
- });
794
- /** The turns from the first to `id`, in order; none for the start. */
795
- function pathTo(timeline, id) {
796
- const byId = new Map(timeline.nodes.map((node) => [node.id, node]));
797
- const path = [];
798
- 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);
799
- return path;
800
- }
801
- /** The turns that follow `parent`, in the order they were played. */
802
- const childrenOf = (timeline, parent) => timeline.nodes.filter((node) => node.parent === parent);
803
- /** The snapshot that holds the state before any turn. */
804
- const START_SNAPSHOT = "start";
805
- /** The snapshot that holds the state after a turn. */
806
- const snapshotOf = (id) => `after-${id}`;
807
- /** Builds what the client shows from the timeline. */
808
- function viewOf(timeline) {
809
- const turn = (node) => ({
810
- id: node.id,
811
- turn: node.turn,
812
- player: node.player,
813
- ...node.endSeq === void 0 ? {} : { endSeq: node.endSeq },
814
- ...node.output === void 0 ? {} : { output: node.output },
815
- restorable: node.snapshot !== void 0,
816
- alternatives: childrenOf(timeline, node.parent).map((sibling) => sibling.id)
817
- });
818
- const on = new Set(pathTo(timeline, timeline.head).map((node) => node.id));
819
- const withdrawn = timeline.nodes.filter((node) => !on.has(node.id) && node.userSeq >= 0).map((node) => ({
820
- from: Math.min(node.startSeq ?? node.userSeq, node.userSeq),
821
- to: node.endSeq ?? Number.MAX_SAFE_INTEGER
822
- }));
823
- return {
824
- head: timeline.head,
825
- path: pathTo(timeline, timeline.head).map(turn),
826
- forward: childrenOf(timeline, timeline.head).map(turn),
827
- canStart: true,
828
- withdrawn
829
- };
830
- }
831
- /** 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. */
832
- function noticeText(node) {
833
- 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");
834
- const ooc = node.output?.ooc;
835
- 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}`;
836
- return `The story, as it went earlier (restored):\nThe player said: ${node.player}${ruling}\nIt was told to the player:\n${told}`;
837
- }
838
- //#endregion
839
- //#region src/host/timeline/file.ts
840
- const TIMELINE_FILE = "timeline.json";
841
- function isNode(value) {
842
- if (typeof value !== "object" || value === null) return false;
843
- const node = value;
844
- 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";
845
- }
846
- /**
847
- * The timeline of a session, or an empty one when it has none yet.
848
- * @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.
849
- */
850
- function readTimeline(folder) {
851
- let text;
852
- try {
853
- text = readFileSync(join(folder, TIMELINE_FILE), "utf8");
854
- } catch (error) {
855
- if (error.code === "ENOENT") return emptyTimeline();
856
- throw error;
857
- }
858
- const value = JSON.parse(text);
859
- 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`);
860
- return value;
861
- }
862
- /** Writes it aside and renames it, so a crash leaves the timeline as it was. */
863
- function writeTimeline(folder, timeline) {
864
- const target = join(folder, TIMELINE_FILE);
865
- const aside = `${target}.writing`;
866
- writeFileSync(aside, JSON.stringify(timeline, null, 2));
867
- renameSync(aside, target);
868
- }
869
- //#endregion
870
- //#region src/host/timeline/branch.ts
871
- var BranchError = class extends Error {};
872
- /**
873
- * 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
874
- * that ended last, and the state of the story after that turn.
875
- * @param boundary - the seq of the last event the branch inherits.
876
- * @param snapshots - the names of the snapshots the story has.
877
- * @throws {BranchError} when the state at that point was not kept.
878
- */
879
- function branchTimeline(timeline, boundary, snapshots) {
880
- const nodes = timeline.nodes.filter((node) => node.endSeq !== void 0 && node.endSeq <= boundary).map((node) => ({ ...node }));
881
- for (const node of nodes) if (node.noticeSeq !== void 0 && node.noticeSeq > boundary) delete node.noticeSeq;
882
- const last = nodes.reduce((found, node) => found === void 0 || node.endSeq > found.endSeq ? node : found, void 0);
883
- const available = new Set(snapshots);
884
- for (const node of nodes) if (node.snapshot !== void 0 && !available.has(node.snapshot)) delete node.snapshot;
885
- const keep = [...nodes.flatMap((node) => node.snapshot === void 0 ? [] : [node.snapshot]), ...available.has("start") ? [START_SNAPSHOT] : []];
886
- const branch = {
887
- version: 1,
888
- head: last?.id ?? null,
889
- next: timeline.next,
890
- nodes
891
- };
892
- if (last === void 0) {
893
- if (!available.has("start")) throw new BranchError("the state at the start of the story was not kept, so it cannot be branched");
894
- return {
895
- timeline: branch,
896
- from: { snapshot: START_SNAPSHOT },
897
- keep
898
- };
899
- }
900
- if (last.snapshot !== void 0) return {
901
- timeline: branch,
902
- from: { snapshot: last.snapshot },
903
- keep
904
- };
905
- if (timeline.head === last.id) return {
906
- timeline: branch,
907
- from: { live: true },
908
- keep
909
- };
910
- throw new BranchError(`the state of the story after its turn ${last.turn} was not kept, so it cannot be branched there`);
911
- }
912
- /** The name of a branch: the story's name with its trailing number counted up, or a 2 added. */
913
- function branchName(name) {
914
- const numbered = /^(.*?)(\d+)\s*$/.exec(name);
915
- const next = numbered === null ? `${name} 2` : `${numbered[1]}${Number(numbered[2]) + 1}`;
916
- return next.length > 200 ? `${[...name].slice(0, 190).join("").trimEnd()} 2` : next;
917
- }
918
- //#endregion
919
- //#region src/host/timeline/plan.ts
920
- /**
921
- * Where the model's conversation has to be changed so that it carries the turns from the first to `target`, and no others.
922
- * 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
923
- * 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.
924
- * @param surface - the seqs of the model's conversation, in order.
925
- */
926
- function planMove(timeline, target, surface) {
927
- const onSurface = new Set(surface);
928
- const path = pathTo(timeline, target);
929
- let keptCount = 0;
930
- let last = -1;
931
- for (const node of path) {
932
- const at = surface.indexOf(node.userSeq);
933
- if (at <= last) break;
934
- last = at;
935
- keptCount += 1;
936
- }
937
- const kept = path.slice(0, keptCount);
938
- const keptIds = new Set(kept.map((node) => node.id));
939
- const byStart = [...timeline.nodes].sort((a, b) => a.userSeq - b.userSeq);
940
- const seqs = /* @__PURE__ */ new Set();
941
- byStart.forEach((node, index) => {
942
- if (keptIds.has(node.id)) return;
943
- if (node.noticeSeq !== void 0 && onSurface.has(node.noticeSeq)) seqs.add(node.noticeSeq);
944
- if (!onSurface.has(node.userSeq)) return;
945
- const end = node.endSeq ?? (byStart[index + 1]?.userSeq === void 0 ? Infinity : byStart[index + 1].userSeq - 1);
946
- for (const seq of surface) if (seq >= node.userSeq && seq <= end) seqs.add(seq);
947
- });
948
- const shadow = [];
949
- let run = [];
950
- let previous = -2;
951
- surface.forEach((seq, index) => {
952
- if (!seqs.has(seq)) return;
953
- if (index !== previous + 1 && run.length > 0) {
954
- shadow.push({
955
- startSeq: run[0],
956
- endSeq: run.at(-1),
957
- seqs: run
958
- });
959
- run = [];
960
- }
961
- run.push(seq);
962
- previous = index;
963
- });
964
- if (run.length > 0) shadow.push({
965
- startSeq: run[0],
966
- endSeq: run.at(-1),
967
- seqs: run
968
- });
969
- return {
970
- shadow,
971
- kept: kept.map((node) => node.id),
972
- inject: path.slice(keptCount)
973
- };
974
- }
975
- //#endregion
976
- //#region src/host/timeline/service.ts
977
- /** The text of the marker that stands for the turns it replaces: never empty, as a model service may refuse an empty message. */
978
- const MARKER_TEXT = "(empty message)";
979
- /** A turn that has not ended does not know yet where its own message is in the log. */
980
- const UNKNOWN_SEQ = -1;
981
- var TimelineError = class extends Error {};
982
- /**
983
- * What the story's turns are, and taking the story back to one of them (or forward again). The conversation with the model is
984
- * only ever added to: the turns that no longer belong are replaced by a marker, which DSH keeps out of the next request, and
985
- * 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.
986
- * Everything here is one at a time per chat.
987
- */
988
- var Timelines = class {
989
- deps;
990
- queues = /* @__PURE__ */ new Map();
991
- constructor(deps) {
992
- this.deps = deps;
993
- }
994
- serial(chat, job) {
995
- const run = (this.queues.get(chat) ?? Promise.resolve()).then(job, job);
996
- this.queues.set(chat, run.catch(() => void 0));
997
- return run;
998
- }
999
- idOf(chat) {
1000
- const id = roleplaySessionOf(chat);
1001
- if (id === void 0) throw new TimelineError(`${chat} is not a roleplay chat`);
1002
- return id;
1003
- }
1004
- folder(id) {
1005
- return sessionFolder(this.deps.sessionsDir(), id);
1006
- }
1007
- read(id) {
1008
- return readTimeline(this.folder(id));
1009
- }
1010
- view(id) {
1011
- return viewOf(this.read(id));
1012
- }
1013
- /**
1014
- * 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,
1015
- * with the records still waiting for the keeper in it (they are in the database, so a restored state carries them).
1016
- */
1017
- begin(chat, turn, player) {
1018
- return this.serial(chat, async () => {
1019
- this.deps.cancel?.(chat);
1020
- const id = this.idOf(chat);
1021
- const timeline = this.read(id);
1022
- this.keep(id, timeline, timeline.head);
1023
- const node = {
1024
- id: `n${timeline.next}`,
1025
- parent: timeline.head,
1026
- turn,
1027
- userSeq: UNKNOWN_SEQ,
1028
- player,
1029
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
1030
- };
1031
- timeline.nodes.push(node);
1032
- timeline.next += 1;
1033
- timeline.head = node.id;
1034
- writeTimeline(this.folder(id), timeline);
1035
- this.prune(id, timeline);
1036
- return node;
1037
- });
1038
- }
1039
- /** What the turn delivered; and, once nothing writes to the story any more, its state is kept. */
1040
- delivered(chat, output) {
1041
- const id = this.idOf(chat);
1042
- const timeline = this.read(id);
1043
- const node = timeline.nodes.find((candidate) => candidate.id === timeline.head);
1044
- if (node === void 0) return void 0;
1045
- node.output = output;
1046
- writeTimeline(this.folder(id), timeline);
1047
- this.deps.engine.quiesce(chat).then(() => this.serial(chat, () => {
1048
- const current = this.read(id);
1049
- if (current.head === node.id) this.keep(id, current, node.id);
1050
- return Promise.resolve();
1051
- })).catch(() => void 0);
1052
- return node.id;
1053
- }
1054
- /**
1055
- * 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
1056
- * (it is not in the log yet when the turn begins).
1057
- */
1058
- ended(chat, session, seq) {
1059
- const id = this.idOf(chat);
1060
- const timeline = this.read(id);
1061
- const node = timeline.nodes.find((candidate) => candidate.id === timeline.head);
1062
- if (node === void 0 || node.endSeq !== void 0) return;
1063
- const after = Math.max(-1, ...timeline.nodes.filter((other) => other.id !== node.id).map((other) => other.endSeq ?? other.userSeq));
1064
- const human = session.snapshotEvents().find((event) => event.seq > after && event.type === "user/message" && event.data.source.kind === "user");
1065
- if (human === void 0) throw new TimelineError(`turn ${node.turn} has no message of the player in the log`);
1066
- node.userSeq = human.seq;
1067
- node.endSeq = seq;
1068
- const began = session.snapshotEvents().find((event) => event.type === "turn/start" && event.data.turn === node.turn);
1069
- node.startSeq = Math.min(began?.seq ?? human.seq, human.seq);
1070
- writeTimeline(this.folder(id), timeline);
1071
- }
1072
- /** Keeps the state as it is under the name of the turn it follows from, when that is not done yet. */
1073
- keep(id, timeline, at) {
1074
- if (this.deps.keepSnapshots(id) === 0) return;
1075
- const node = at === null ? void 0 : timeline.nodes.find((candidate) => candidate.id === at);
1076
- const name = node === void 0 ? START_SNAPSHOT : snapshotOf(node.id);
1077
- if (node !== void 0 && node.snapshot !== void 0) return;
1078
- if (node === void 0 && this.deps.state.snapshots(this.deps.sessionsDir(), id).includes("start")) return;
1079
- this.deps.state.snapshot(this.deps.sessionsDir(), id, name);
1080
- if (node !== void 0) {
1081
- node.snapshot = name;
1082
- writeTimeline(this.folder(id), timeline);
1083
- }
1084
- }
1085
- /** Lets the oldest snapshots go: only the turns most recently played keep theirs, and the one that holds the start stays. */
1086
- prune(id, timeline) {
1087
- const keep = this.deps.keepSnapshots(id);
1088
- const kept = timeline.nodes.filter((node) => node.snapshot !== void 0);
1089
- const dropped = kept.slice(0, Math.max(0, kept.length - keep));
1090
- if (dropped.length === 0) return;
1091
- for (const node of dropped) {
1092
- this.deps.state.removeSnapshot(this.deps.sessionsDir(), id, node.snapshot);
1093
- delete node.snapshot;
1094
- }
1095
- writeTimeline(this.folder(id), timeline);
1096
- }
1097
- /**
1098
- * 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,
1099
- * 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.
1100
- * @returns what the player said in the first turn that was left, to put back in the input; nothing when the story went forward.
1101
- * @throws {TimelineError} when there is no such turn, its state was not kept, or the chat is not loaded.
1102
- */
1103
- move(chat, target) {
1104
- return this.serial(chat, async () => {
1105
- const id = this.idOf(chat);
1106
- const timeline = this.read(id);
1107
- const to = target === null ? void 0 : timeline.nodes.find((node) => node.id === target);
1108
- if (target !== null && to === void 0) throw new TimelineError(`there is no turn "${target}"`);
1109
- const snapshot = target === null ? START_SNAPSHOT : to.snapshot;
1110
- 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");
1111
- const agent = await this.deps.agentOf(chat);
1112
- if (agent === void 0) throw new TimelineError(`the chat ${chat} is not loaded`);
1113
- if (agent.status !== "idle") {
1114
- agent.cancel({ kind: "user" }, { keepInbox: true });
1115
- await agent.whenIdle();
1116
- }
1117
- this.deps.cancel?.(chat);
1118
- this.deps.engine.stop(chat);
1119
- await this.deps.engine.quiesce(chat);
1120
- this.deps.engine.forget(chat);
1121
- const was = pathTo(timeline, timeline.head);
1122
- const plan = planMove(timeline, target, [...agent.session.surface.nodes]);
1123
- this.deps.state.restore(this.deps.sessionsDir(), id, snapshot);
1124
- this.reconcile(agent, plan);
1125
- timeline.head = target;
1126
- writeTimeline(this.folder(id), timeline);
1127
- const left = was.find((node) => !pathTo(timeline, target).some((kept) => kept.id === node.id));
1128
- return left === void 0 ? {} : { draft: left.player };
1129
- });
1130
- }
1131
- /** 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. */
1132
- reconcile(agent, plan) {
1133
- for (const run of plan.shadow) agent.session.append("user/message", createUserMessage({
1134
- content: [{
1135
- type: "text",
1136
- text: MARKER_TEXT
1137
- }],
1138
- source: { kind: "roleplay" }
1139
- }), {
1140
- surfaceOp: {
1141
- op: "replace",
1142
- startSeq: run.startSeq,
1143
- endSeq: run.endSeq
1144
- },
1145
- sourceEventSeqs: run.seqs
1146
- });
1147
- for (const node of plan.inject) node.noticeSeq = agent.session.append("user/message", createUserMessage({
1148
- content: [{
1149
- type: "text",
1150
- text: noticeText(node)
1151
- }],
1152
- source: { kind: "roleplay" }
1153
- }), { surfaceOp: "append" }).seq;
1154
- }
1155
- /**
1156
- * 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
1157
- * 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
1158
- * 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.
1159
- * @param cut - the seq of the last event of the log the branch inherits.
1160
- * @returns whether a session was made.
1161
- * @throws {BranchError} when the state at the cut was not kept; the branch is then not made.
1162
- */
1163
- adopt(chat, parent, cut, agent) {
1164
- return this.serial(parent, async () => {
1165
- const id = this.idOf(chat);
1166
- const from = this.idOf(parent);
1167
- const directory = this.deps.sessionsDir();
1168
- if (existsSync(sessionDatabase(directory, id)) || !existsSync(sessionDatabase(directory, from))) return false;
1169
- const branch = branchTimeline(this.read(from), cut, this.deps.state.snapshots(directory, from));
1170
- if ("live" in branch.from) await this.deps.engine.quiesce(parent);
1171
- const name = branchName(this.deps.state.openSession(directory, from).metadata.get().name);
1172
- this.deps.state.fork(directory, from, id, branch.from, {
1173
- name,
1174
- keep: branch.keep
1175
- });
1176
- try {
1177
- await inheritImages(this.folder(from), this.folder(id), branch.timeline.nodes.map((node) => node.id));
1178
- inheritPrompts(this.folder(from), this.folder(id));
1179
- inheritPacks(this.folder(from), this.folder(id));
1180
- const plan = planMove(branch.timeline, branch.timeline.head, [...agent.session.surface.nodes]);
1181
- this.reconcile(agent, plan);
1182
- writeTimeline(this.folder(id), branch.timeline);
1183
- } catch (error) {
1184
- this.deps.state.deleteSession(directory, id);
1185
- throw error;
1186
- }
1187
- return true;
1188
- });
1189
- }
1190
- /** The turns that follow a turn, for the choices the story can be taken to. */
1191
- forward(id) {
1192
- const timeline = this.read(id);
1193
- return childrenOf(timeline, timeline.head);
1194
- }
1195
- };
1196
- //#endregion
1197
- //#region src/shared/notes.ts
1198
- const NOTE_KINDS = [
1199
- "suggestions",
1200
- "away",
1201
- "world"
1202
- ];
1203
- //#endregion
1204
- //#region src/host/sessions/notes.ts
1205
- const KEY$1 = "notes";
1206
- const isNote = (value) => {
1207
- if (typeof value !== "object" || value === null) return false;
1208
- const note = value;
1209
- return NOTE_KINDS.includes(note["kind"]) && typeof note["turn"] === "number" && Array.isArray(note["lines"]) && note["lines"].every((line) => typeof line === "string");
1210
- };
1211
- /** The notes of a session, at most one per kind. */
1212
- function readNotes(session) {
1213
- const stored = session.metadata.getValue(KEY$1);
1214
- return Array.isArray(stored) ? stored.filter(isNote) : [];
1215
- }
1216
- /** Replaces the note of the same kind. */
1217
- function putNote(session, note) {
1218
- session.metadata.setValue(KEY$1, [...readNotes(session).filter((existing) => existing.kind !== note.kind), note]);
1219
- }
1220
- /** The most lines one note keeps: what is past it is not told. */
1221
- const MAX_NOTE_LINES = 8;
1222
- /** Adds lines to the note of the kind when it is of the same turn, else starts it. */
1223
- function addToNote(session, kind, turn, lines) {
1224
- if (lines.length === 0) return;
1225
- putNote(session, {
1226
- kind,
1227
- turn,
1228
- lines: [...readNotes(session).find((note) => note.kind === kind && note.turn === turn)?.lines ?? [], ...lines].slice(0, MAX_NOTE_LINES)
1229
- });
1230
- }
1231
- /** Removes every note: they belong to the turn that made them. */
1232
- function clearNotes(session) {
1233
- if (readNotes(session).length > 0) session.metadata.setValue(KEY$1, []);
1234
- }
1235
- /**
1236
- * The notes of a session, for the player's screen.
1237
- * @throws {SessionNotFoundError} when the id names no session.
1238
- */
1239
- function notesOfSession(deps, id) {
1240
- if (!isSessionId(id) || !existsSync(sessionDatabase(deps.sessionsDir(), id))) throw new SessionNotFoundError(`no session "${id}"`);
1241
- return readNotes(deps.open(id));
1242
- }
1243
- //#endregion
1244
- //#region src/host/pacing/director.ts
1245
- const PLOTS_METADATA_KEY = "roleplay.pacing.plots";
1246
- function populatePlots(metadata, plots) {
1247
- const progress = plots.map((plot) => ({
1248
- plot,
1249
- status: plot.start,
1250
- introduced: [],
1251
- rejected: [],
1252
- lastNudgeTurn: 0
1253
- }));
1254
- metadata.setValue(PLOTS_METADATA_KEY, progress);
1255
- }
1256
- function addSessionPlot(store, plot) {
1257
- const plots = progressOf(store);
1258
- if (plots.some((entry) => entry.plot.id === plot.id)) throw new Error(`there is already a plot "${plot.id}"`);
1259
- plots.push({
1260
- plot,
1261
- status: plot.start,
1262
- introduced: [],
1263
- rejected: [],
1264
- lastNudgeTurn: 0
1265
- });
1266
- store.story.metadata.setValue(PLOTS_METADATA_KEY, plots);
1267
- }
1268
- function plotAuthorNeeded(store, turn) {
1269
- if (progressOf(store).length > 0 || turn < 5) return false;
1270
- return store.story.events.list({
1271
- fromTurn: Math.max(1, turn - 2),
1272
- toTurn: turn - 1
1273
- }).length === 0 && store.story.threads.list("open").length === 0;
1274
- }
1275
- function plotProgressOf(metadata) {
1276
- const value = metadata.getValue(PLOTS_METADATA_KEY);
1277
- return Array.isArray(value) ? value : [];
1278
- }
1279
- function progressOf(store) {
1280
- return plotProgressOf(store.story.metadata);
1281
- }
1282
- /** Select one uncommitted possibility when the story has genuinely gone quiet; selection never makes it happen. */
1283
- function pacingAdvice(store, turn) {
1284
- const plots = progressOf(store);
1285
- if (plots.length === 0) return void 0;
1286
- const now = store.story.clock.get()?.now;
1287
- const recent = store.story.events.list({
1288
- fromTurn: Math.max(1, turn - 2),
1289
- toTurn: turn - 1
1290
- });
1291
- const openThreads = store.story.threads.list("open");
1292
- for (const progress of plots) {
1293
- if (![
1294
- "available",
1295
- "engaged",
1296
- "cooling"
1297
- ].includes(progress.status)) continue;
1298
- const quietTurns = progress.plot.pacing.quietTurns + (openThreads.length === 0 ? 0 : 2);
1299
- if (recent.length > 0 || turn <= quietTurns) continue;
1300
- if (turn - progress.lastNudgeTurn < progress.plot.pacing.cooldownTurns) continue;
1301
- if (now !== void 0 && progress.lastNudgeAt !== void 0 && now - progress.lastNudgeAt < progress.plot.pacing.cooldownDays * 864e5) continue;
1302
- 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];
1303
- if (step === void 0) continue;
1304
- const quietFor = turn - progress.lastNudgeTurn;
1305
- progress.lastNudgeTurn = turn;
1306
- if (now !== void 0) progress.lastNudgeAt = now;
1307
- progress.status = progress.status === "available" ? "engaged" : progress.status;
1308
- store.story.metadata.setValue(PLOTS_METADATA_KEY, plots);
1309
- return {
1310
- need: quietFor > progress.plot.pacing.quietTurns * 2 ? "clear" : "gentle",
1311
- 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",
1312
- plot: progress.plot.id,
1313
- plotName: progress.plot.name,
1314
- development: step.id,
1315
- mode: step.mode,
1316
- guidance: step.guidance || step.text,
1317
- avoid: step.avoid
1318
- };
1319
- }
1320
- }
1321
- function describePacingAdvice(advice) {
1322
- 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.`;
1323
- }
1324
- function updatePlotProgress(store, plotId, developmentId, action) {
1325
- const plots = progressOf(store);
1326
- const progress = plots.find((entry) => entry.plot.id === plotId);
1327
- if (progress === void 0) throw new Error(`there is no plot "${plotId}"`);
1328
- if (action === "resolved" || action === "abandoned") progress.status = action;
1329
- else {
1330
- if (developmentId === void 0) throw new Error(`${action} needs a development`);
1331
- if (![...progress.plot.hooks, ...progress.plot.developments].some((step) => step.id === developmentId)) throw new Error(`plot "${plotId}" has no development "${developmentId}"`);
1332
- const target = action === "introduced" ? progress.introduced : progress.rejected;
1333
- if (!target.includes(developmentId)) target.push(developmentId);
1334
- if (action === "introduced") progress.status = "engaged";
1335
- }
1336
- store.story.metadata.setValue(PLOTS_METADATA_KEY, plots);
1337
- return progress;
1338
- }
1339
- //#endregion
1340
- //#region src/host/sessions/activity.ts
1341
- const KEY = "activity";
1342
- const isEntry = (value) => {
1343
- if (typeof value !== "object" || value === null) return false;
1344
- const entry = value;
1345
- 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");
1346
- };
1347
- /** The recorded runs, oldest first. */
1348
- function readActivity(session) {
1349
- const stored = session.metadata.getValue(KEY);
1350
- return Array.isArray(stored) ? stored.filter(isEntry) : [];
1351
- }
1352
- /** Files the run and returns the runs that fell off the end of the record to make room. */
1353
- function recordActivity(session, entry) {
1354
- const all = [...readActivity(session), entry];
1355
- session.metadata.setValue(KEY, all.slice(-60));
1356
- return all.slice(0, -60);
1357
- }
1358
- const RUN_FOLDER = "activity";
1359
- const RUN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
1360
- const runFile = (folder, run) => {
1361
- if (!RUN_ID.test(run)) throw new RangeError(`"${run}" is not a run`);
1362
- return join(folder, RUN_FOLDER, `${run}.json`);
1363
- };
1364
- /** 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. */
1365
- function keepRunDetail(folder, run, detail) {
1366
- const file = runFile(folder, run);
1367
- mkdirSync(join(folder, RUN_FOLDER), { recursive: true });
1368
- writeFileSync(`${file}.tmp`, JSON.stringify(detail));
1369
- renameSync(`${file}.tmp`, file);
1370
- }
1371
- /** The stored detail of a run, or nothing when it was not kept or has been dropped. */
1372
- function readRunDetail(folder, run) {
1373
- try {
1374
- return JSON.parse(readFileSync(runFile(folder, run), "utf8"));
1375
- } catch (error) {
1376
- if (error.code === "ENOENT") return void 0;
1377
- throw error;
1378
- }
1379
- }
1380
- function forgetRunDetails(folder, dropped) {
1381
- for (const entry of dropped) if (entry.run !== void 0) rmSync(runFile(folder, entry.run), { force: true });
1382
- }
1383
- //#endregion
1384
- export { readTime as A, defaultBoundaries as C, describeTime as D, beginTurn as E, CHARACTER_ACTION_SCHEMA as F, RESULTS as I, answerEstimate as L, zoneOf as M, referent as N, describeWhen as O, AWAY_ACTION_SCHEMA as P, parseCharacterAction as R, pathTo as S, ClockError as T, putNote as _, recordActivity as a, Timelines as b, describePacingAdvice as c, plotProgressOf as d, populatePlots as f, notesOfSession as g, clearNotes as h, readRunDetail as i, skipTime as j, endRound as k, pacingAdvice as l, addToNote as m, keepRunDetail as n, PLOTS_METADATA_KEY as o, updatePlotProgress as p, readActivity as r, addSessionPlot as s, forgetRunDetails as t, plotAuthorNeeded as u, readNotes as v, sameWords as w, readTimeline as x, TimelineError as y };
1385
-
1386
- //# sourceMappingURL=activity-t7OBgHlc.js.map