@dsh-agentic-roleplay/core 0.3.2 → 0.3.3

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.
@@ -0,0 +1,1843 @@
1
+ import { r as roleplaySessionOf, t as promptFor } from "./access-EbNdZFbk.js";
2
+ import { i as inheritPacks } from "./packs-BYjrAen6.js";
3
+ import "./settings-CA6icLL_.js";
4
+ import { _ as inheritPrompts, a as wrongLanguage } from "./language-DWVwi1R7.js";
5
+ import { B as languageOf, M as describeTime, N as describeWhen, V as translator, z as answerLimits } from "./deliver-De62a8i9.js";
6
+ import { a as runChild, i as childTrace, n as childSampling, o as estimateAnswer, t as childModel } from "./child-lPncV1ps.js";
7
+ import { u as inheritImages } from "./generator-B6FxlKOV.js";
8
+ import { join } from "node:path";
9
+ import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
10
+ import { createUserMessage } from "@deepseek-ai/dsh-llm";
11
+ import { MINUTE, characterKey, describeDuration, locationKey, mentioned, overlap, sessionDatabase, sessionFolder, tokens } from "@dsh-agentic-roleplay/state";
12
+ //#region ../dsh-roleplay-model/src/memory.ts
13
+ const MEMORY_KINDS = [
14
+ "belief",
15
+ "relationship",
16
+ "knowledge"
17
+ ];
18
+ /** How sure a character is of what it believes, from least to most. */
19
+ const MEMORY_CONFIDENCES = [
20
+ "doubtful",
21
+ "likely",
22
+ "sure"
23
+ ];
24
+ //#endregion
25
+ //#region src/host/orchestration/referent.ts
26
+ /**
27
+ * 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.
28
+ * 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.
29
+ */
30
+ function referent(character) {
31
+ const mark = [character.pronouns, character.gender].find((text) => text !== void 0 && text.trim() !== "")?.trim();
32
+ return mark === void 0 ? character.name : `${character.name} (${mark})`;
33
+ }
34
+ //#endregion
35
+ //#region src/host/orchestration/defaults.ts
36
+ const ENGLISH = translator("en");
37
+ /** What the instructions say about how long each part of a character's answer may run. */
38
+ const limitVariables = (language) => {
39
+ const limits = answerLimits(language);
40
+ return {
41
+ thoughtLimit: limits.thought,
42
+ intentLimit: limits.intent,
43
+ utteranceLimit: limits.utterance
44
+ };
45
+ };
46
+ function describe(character, tr) {
47
+ const lines = [tr("You are {name}.", { name: character.name })];
48
+ if (character.aliases.length > 0) lines.push(tr("You are also called {names}.", { names: character.aliases.join(tr(", ")) }));
49
+ const facts = [
50
+ character.age === void 0 ? void 0 : tr("age: {value}", { value: character.age }),
51
+ character.gender === void 0 ? void 0 : tr("gender: {value}", { value: character.gender }),
52
+ character.pronouns === void 0 ? void 0 : tr("pronouns: {value}", { value: character.pronouns })
53
+ ].filter((fact) => fact !== void 0);
54
+ if (facts.length > 0) lines.push(facts.join(tr("; ")) + tr("."));
55
+ for (const [label, text] of [
56
+ ["Summary", character.summary],
57
+ ["Personality", character.personality],
58
+ ["Background", character.background],
59
+ ["Appearance", character.appearance],
60
+ ["How you speak", character.speech.style]
61
+ ]) if (text.trim() !== "") lines.push(`${tr(label)}${tr(": ")}${text.trim()}`);
62
+ return lines.join("\n");
63
+ }
64
+ /** At most this many features and ways out of a place are told at once. */
65
+ const SHOWN_FEATURES = 12;
66
+ const SHOWN_EXITS = 12;
67
+ const sentence = (text) => {
68
+ return (/^[^.!?。!?]*[.!?。!?]?/u.exec(text.trim())?.[0] ?? text).trim();
69
+ };
70
+ /** At most this many things are listed at once: the rest are said to be there and left for a closer look. */
71
+ const SHOWN_ITEMS = 12;
72
+ /** One thing in a sentence: how many, what state it is in, where it is. */
73
+ function describeItem(item, { withKeys }, tr = ENGLISH) {
74
+ const name = `${item.quantity > 1 ? `${item.quantity} ` : ""}${item.name}${item.quality === "" ? "" : ` (${item.quality})`}`;
75
+ const extra = [
76
+ item.hidden ? tr("hidden") : "",
77
+ item.state === void 0 ? "" : item.state,
78
+ item.where ?? ""
79
+ ].filter((part) => part !== "").join(tr(", "));
80
+ const inside = item.contents === void 0 ? "" : tr(" holding {things}", { things: item.contents.join(tr(", ")) });
81
+ return `${withKeys ? `${item.key}: ` : ""}${name}${extra === "" ? "" : ` [${extra}]`}${inside}`;
82
+ }
83
+ /** A list of things, capped. */
84
+ function describeItems(items, options, tr = ENGLISH) {
85
+ return `${items.slice(0, SHOWN_ITEMS).map((item) => describeItem(item, options, tr)).join(tr("; "))}${items.length > SHOWN_ITEMS ? tr("; and {count} more", { count: items.length - SHOWN_ITEMS }) : ""}`;
86
+ }
87
+ /** What someone in a place is told about it: what it is like, what can be pointed at, and the ways out. */
88
+ function describePlace(view, { withKeys }, tr = ENGLISH) {
89
+ const { location, exits } = view;
90
+ const lines = [`${location.name}${withKeys ? ` (${view.key})` : ""}${location.description === "" ? "" : `: ${location.description}`}`];
91
+ if (location.features.length > 0) {
92
+ const shown = location.features.slice(0, SHOWN_FEATURES).map((feature) => `${withKeys ? `${feature.key}: ` : ""}${feature.name}${feature.description === "" ? "" : ` - ${sentence(feature.description)}`}`);
93
+ lines.push(`${tr("Things here: ")}${shown.join(tr("; "))}${location.features.length > SHOWN_FEATURES ? tr("; and {count} more", { count: location.features.length - SHOWN_FEATURES }) : ""}`);
94
+ }
95
+ if (exits.length > 0) {
96
+ const shown = exits.slice(0, SHOWN_EXITS).map(({ key, name, exit }) => `${withKeys ? `${key}: ` : ""}${name}${exit.description === "" ? "" : ` (${sentence(exit.description)})`}${exit.state === "open" ? "" : ` [${tr(exit.state)}${exit.note === "" ? "" : `: ${exit.note}`}]`}`);
97
+ lines.push(`${tr("Ways out: ")}${shown.join(tr("; "))}${exits.length > SHOWN_EXITS ? tr("; and {count} more", { count: exits.length - SHOWN_EXITS }) : ""}`);
98
+ }
99
+ if (view.items !== void 0 && view.items.length > 0) lines.push(`${tr("Lying about: ")}${describeItems(view.items, { withKeys }, tr)}`);
100
+ return lines;
101
+ }
102
+ /** How long the player has to have been away for it to be worth telling the game master. */
103
+ const NOTICEABLE_ABSENCE = 5 * MINUTE;
104
+ /** What the game master is told about time at the start of a turn, and how it passes. */
105
+ function timeNotice(time, language, tr) {
106
+ const now = tr("Time: {time}.", { time: describeTime(time.now, language) });
107
+ if (time.now.mode === "simulated") return `${now} ${tr("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.")}`;
108
+ const away = time.away !== void 0 && time.away >= NOTICEABLE_ABSENCE ? ` ${tr("The player was away for {duration} 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.", { duration: describeDuration(time.away, language) })}` : "";
109
+ return `${now} ${tr("The story's time follows the real clock: it cannot be skipped, and each round takes as long as it really took.")}${away}`;
110
+ }
111
+ /** What a character is told of its day, its commitments and what it is after. */
112
+ function describeAgenda(agenda, now, tr = ENGLISH, language = "en") {
113
+ const { zone } = agenda;
114
+ const when = (instant) => describeWhen(instant, now, zone, language);
115
+ const at = (place) => place === void 0 ? "" : tr(" at {place}", { place });
116
+ const lines = [];
117
+ if (agenda.now !== void 0) lines.push(tr("Your day, now: {activity}{place}, until {until}{note}.", {
118
+ activity: agenda.now.activity,
119
+ place: at(agenda.now.place),
120
+ until: when(agenda.now.until),
121
+ note: agenda.now.interruptible ? "" : tr(" (not something you would drop lightly)")
122
+ }));
123
+ if (agenda.next !== void 0) lines.push(tr("Your day, next: {activity}{place}, from {from}.", {
124
+ activity: agenda.next.activity,
125
+ place: at(agenda.next.place),
126
+ from: when(agenda.next.at)
127
+ }));
128
+ for (const engagement of agenda.engagements) {
129
+ const values = {
130
+ title: engagement.title,
131
+ place: at(engagement.place),
132
+ with: engagement.with.length === 0 ? "" : tr(", with {names}", { names: engagement.with.join(tr(", ")) }),
133
+ at: when(engagement.at)
134
+ };
135
+ lines.push(engagement.overdue ? tr("You were to: {title}{place}{with}, at {at}, which has passed and is still open.", values) : tr("You are due to: {title}{place}{with}, at {at}.", values));
136
+ }
137
+ if (agenda.goals.length > 0) {
138
+ lines.push(tr("What you are after:"));
139
+ for (const goal of agenda.goals) {
140
+ const by = goal.deadline === void 0 ? "" : goal.overdue ? tr(", by {deadline}, which has passed", { deadline: when(goal.deadline) }) : tr(", by {deadline}", { deadline: when(goal.deadline) });
141
+ lines.push(`- ${goal.name} (${goal.type})${by}${goal.description === "" ? "" : `${tr(": ")}${sentence(goal.description)}`}${goal.plan.length === 0 ? "" : tr(" Next: {plan}.", { plan: goal.plan.join(tr("; ")) })}`);
142
+ }
143
+ }
144
+ return lines;
145
+ }
146
+ /** What the game master is told of the characters' days at the start of a turn; nothing when there is nothing to tell. */
147
+ function describeSceneAgenda(agenda, now, tr = ENGLISH, language = "en") {
148
+ const lines = [];
149
+ const join = (entries) => entries.join(tr("; "));
150
+ if (agenda.moved.length > 0) lines.push(tr("By their routines since you last looked: {moves}.", { moves: join(agenda.moved.map((move) => tr("{name} went to {place} ({activity})", {
151
+ name: move.name,
152
+ place: move.to,
153
+ activity: move.activity
154
+ }))) }));
155
+ if (agenda.here.length > 0) lines.push(tr("With the player's character, and their days: {days}. The characters decide for themselves whether to keep to their day; the moment may keep them.", { days: join(agenda.here.map((entry) => `${entry.name}${tr(": ")}${entry.note}`)) }));
156
+ if (agenda.engagements.length > 0) {
157
+ const entries = agenda.engagements.map((engagement) => {
158
+ const values = {
159
+ title: engagement.title,
160
+ with: engagement.with.join(tr(", ")),
161
+ place: engagement.place === void 0 ? "" : tr(", at {place}", { place: engagement.place }),
162
+ when: describeWhen(engagement.at, now, agenda.zone, language)
163
+ };
164
+ return engagement.overdue ? tr("\"{title}\" ({with}{place}) was due {when} and is still open", values) : tr("\"{title}\" ({with}{place}) is due {when}", values);
165
+ });
166
+ lines.push(tr("Commitments due soon or overdue: {entries}.", { entries: join(entries) }));
167
+ }
168
+ return lines.join("\n");
169
+ }
170
+ /** In words, how a character stands with another, from the numbers of its profile; nothing for what is unremarkable. */
171
+ function describeAttitude(relation, tr = ENGLISH) {
172
+ return [
173
+ relation.familiarity >= .7 ? tr("knows them well") : relation.familiarity <= .15 ? tr("barely knows them") : "",
174
+ relation.trust >= .4 ? tr("trusts them") : relation.trust <= -.4 ? tr("distrusts them") : "",
175
+ relation.affinity >= .4 ? tr("is fond of them") : relation.affinity <= -.4 ? tr("dislikes them") : "",
176
+ relation.tension >= .5 ? tr("things are strained between them") : ""
177
+ ].filter((part) => part !== "").join(tr(", "));
178
+ }
179
+ function whereIs(member, tr = ENGLISH) {
180
+ const place = member.place;
181
+ if (place === void 0) return "";
182
+ return [place.position, place.feature === void 0 ? "" : tr("at {feature}", { feature: place.feature.name })].filter((part) => part !== "").join(tr(", "));
183
+ }
184
+ function present(cast, self, tr) {
185
+ return cast.map((member) => {
186
+ const { key, character, state } = member;
187
+ const seen = [state?.publicState, state?.activity].filter((text) => text !== void 0 && text.trim() !== "");
188
+ const where = whereIs(member);
189
+ return `- ${key === self ? character.name : referent(character)}${key === self ? tr(" (you)") : ""}${where === "" ? "" : ` (${where})`}${seen.length > 0 ? `${tr(": ")}${seen.join(tr("; "))}` : ""}`;
190
+ }).join("\n");
191
+ }
192
+ /** A bounded, advisory order for who is most likely to need a turn; reachability still governs activation. */
193
+ function describeActivationCandidates(cast, input, story, tr = ENGLISH) {
194
+ const player = cast.find((member) => member.character.control === "player");
195
+ if (player === void 0) return "";
196
+ const named = mentioned(input, cast.map((member) => member.character));
197
+ const cues = tokens(input);
198
+ const candidates = cast.filter((member) => member.character.control === "agent").map((member) => {
199
+ const relation = story.relationships.get(member.character.id, player.character.id);
200
+ const here = member.place === void 0 || player.place === void 0 || member.place.location.id === player.place.location.id;
201
+ const goal = story.intents.list(member.character.id, { status: "active" }).map((intent) => ({
202
+ intent,
203
+ match: overlap(cues, `${intent.name} ${intent.description}`, [])
204
+ })).sort((a, b) => b.match - a.match)[0];
205
+ const factionGoal = story.factionMemberships.ofCharacter(member.character.id, "active").flatMap((membership) => story.factionIntents.list(membership.factionId, { status: "active" }).map((intent) => ({
206
+ intent,
207
+ match: overlap(cues, `${intent.name} ${intent.description}`, []) * membership.commitment
208
+ }))).sort((a, b) => b.match - a.match)[0];
209
+ return {
210
+ member,
211
+ reasons: [
212
+ named.has(member.character.id) ? tr("named in the move") : "",
213
+ here ? tr("in the scene") : "",
214
+ (goal?.match ?? 0) >= 2 ? tr("own goal: {goal}", { goal: goal.intent.name }) : "",
215
+ (factionGoal?.match ?? 0) >= 2 ? tr("faction pressure: {goal}", { goal: factionGoal.intent.name }) : "",
216
+ relation !== void 0 && relation.tension >= .5 ? tr("high tension toward the player") : "",
217
+ relation !== void 0 && relation.trust <= -.4 ? tr("distrusts the player") : "",
218
+ relation !== void 0 && Math.abs(relation.affinity) >= .4 ? relation.affinity > 0 ? tr("cares about the player") : tr("dislikes the player") : ""
219
+ ].filter((reason) => reason !== ""),
220
+ 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
221
+ };
222
+ }).filter((entry) => entry.score > 0).sort((a, b) => b.score - a.score || a.member.key.localeCompare(b.member.key)).slice(0, 5);
223
+ if (candidates.length === 0) return "";
224
+ return `${tr("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(tr(", ")) || tr("socially implicated")}`).join("\n")}`;
225
+ }
226
+ function said(entry, tr) {
227
+ return entry.utterance === void 0 ? tr("- {name} intended: {intent} ({result}) {summary}", {
228
+ name: entry.name,
229
+ intent: entry.intent,
230
+ result: entry.result,
231
+ summary: entry.summary
232
+ }) : tr("- {name} said \"{utterance}\" and intended: {intent} ({result}) {summary}", {
233
+ name: entry.name,
234
+ utterance: entry.utterance,
235
+ intent: entry.intent,
236
+ result: entry.result,
237
+ summary: entry.summary
238
+ });
239
+ }
240
+ function age(at, now, tr) {
241
+ if (at === void 0 || now === void 0) return tr("some time ago");
242
+ const seconds = Math.max(0, Math.floor((now - at) / 1e3));
243
+ if (seconds < 60) return tr("just now");
244
+ const amount = Math.floor(seconds / (seconds >= 86400 ? 86400 : seconds >= 3600 ? 3600 : 60));
245
+ if (seconds >= 86400) return amount === 1 ? tr("1 day ago") : tr("{amount} days ago", { amount });
246
+ if (seconds >= 3600) return amount === 1 ? tr("1 hour ago") : tr("{amount} hours ago", { amount });
247
+ return amount === 1 ? tr("1 minute ago") : tr("{amount} minutes ago", { amount });
248
+ }
249
+ /** What a character remembers, in the way it remembers it: what is faded or vague is told as such, and what it is sure or doubtful of. */
250
+ function remembered(memories, tr, now) {
251
+ return memories.map((memory) => {
252
+ const clarity = memory.clarity === "clear" ? [] : [memory.clarity === "faded" ? tr("the details are fuzzy") : tr("you barely remember")];
253
+ const sure = memory.confidence === "sure" ? [tr("you are sure of it")] : memory.confidence === "doubtful" ? [tr("you doubt it")] : [];
254
+ const against = memory.disputed === true ? [tr("something you have seen since speaks against it")] : [];
255
+ return `- (${[
256
+ age(memory.at, now, tr),
257
+ ...clarity,
258
+ ...sure,
259
+ ...against,
260
+ ...memory.linked === true ? [tr("it comes to mind with the rest")] : []
261
+ ].join(tr(", "))}) ${memory.text}`;
262
+ }).join("\n");
263
+ }
264
+ /** Every character is told the same thing about the scene, plus who it is and what it remembers. */
265
+ const sharedContext = { brief(request) {
266
+ const { member, cast, situation, attempt, earlier, reaction, previous, memories, place, relationships, knowledge, affiliations, carrying, time, agenda } = request;
267
+ const language = languageOf(request.language);
268
+ const tr = translator(language);
269
+ const list = (entries) => entries.join(tr("; "));
270
+ const company = place === void 0 ? cast : place.here;
271
+ const sections = [
272
+ `${tr("Situation:")}\n${situation}`,
273
+ ...time === void 0 ? [] : [tr("Now: {time}.", { time: describeTime(time, language) })],
274
+ ...place === void 0 ? [] : [`${tr("Where you are:")}\n${describePlace(place, { withKeys: false }, tr).join("\n")}`],
275
+ `${tr("Present:")}\n${present(company, member.key, tr)}`
276
+ ];
277
+ if (request.upcoming !== void 0 && request.upcoming.length > 0) sections.push(`${tr("What you know is coming:")}\n${request.upcoming.map((entry) => `- ${entry.text}${entry.when === void 0 ? "" : ` (${entry.when})`}`).join("\n")}`);
278
+ if (request.cues !== void 0 && request.cues.length > 0) sections.push(`${tr("Just now you notice:")}\n${request.cues.map((cue) => `- ${cue}`).join("\n")}`);
279
+ if (request.tracked !== void 0 && request.tracked.self !== "") sections.push(`${tr("How you are (what you can tell of yourself):")}\n${request.tracked.self}`);
280
+ if (request.tracked !== void 0 && request.tracked.others.length > 0) sections.push(`${tr("What you can tell of the others here:")}\n${request.tracked.others.map((other) => `- ${other.name}: ${other.text}`).join("\n")}`);
281
+ const day = agenda === void 0 || time === void 0 ? [] : describeAgenda(agenda, time.now, tr, language);
282
+ if (day.length > 0) sections.push(`${tr("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")}`);
283
+ if (carrying !== void 0 && carrying.length > 0) sections.push(`${tr("What you have on you:")}\n${describeItems(carrying, { withKeys: false }, tr)}`);
284
+ if (relationships !== void 0 && relationships.length > 0) sections.push(`${tr("How you stand with people who bear on this moment (your own view, not objective fact):")}\n${relationships.map((relation) => {
285
+ const attitude = describeAttitude(relation, tr);
286
+ return `- ${relation.name}${relation.present ? tr(" (here)") : tr(" (not here)")} — ${relation.label}${relation.summary === "" ? "" : `${tr(": ")}${relation.summary}`}${attitude === "" ? "" : ` [${attitude}]`}`;
287
+ }).join("\n")}`);
288
+ if (affiliations !== void 0 && affiliations.length > 0) sections.push(`${tr("Your affiliations (their goals are pressures and commitments, not commands):")}\n${affiliations.map((entry) => {
289
+ const position = [entry.role, entry.rank].filter(Boolean).join(tr(", ")) || tr("member");
290
+ const goals = entry.goals.length === 0 ? "" : tr(" Goals: {goals}.", { goals: list(entry.goals) });
291
+ const state = entry.publicState === "" ? "" : ` ${entry.publicState}`;
292
+ const attitude = entry.relationship === void 0 ? "" : describeAttitude(entry.relationship, tr);
293
+ return tr("- {name}: {position}; {status}; commitment {commitment}.", {
294
+ name: entry.name,
295
+ position,
296
+ status: entry.status,
297
+ commitment: entry.commitment.toFixed(2)
298
+ }) + `${state}${goals}${attitude === "" ? "" : tr(" Your view: {attitude}.", { attitude })}`;
299
+ }).join("\n")}`);
300
+ if (knowledge !== void 0) {
301
+ const shown = (entries) => list(entries.slice(0, 30)) + (entries.length > 30 ? tr("; and {count} more you can recall if needed", { count: entries.length - 30 }) : "");
302
+ const lines = [
303
+ knowledge.characters.length === 0 ? void 0 : `${tr("People: ")}${shown(knowledge.characters)}`,
304
+ knowledge.factions.length === 0 ? void 0 : `${tr("Factions: ")}${shown(knowledge.factions)}`,
305
+ knowledge.locations.length === 0 ? void 0 : `${tr("Places: ")}${shown(knowledge.locations)}`,
306
+ knowledge.routes.length === 0 ? void 0 : `${tr("Routes: ")}${shown(knowledge.routes)}`,
307
+ knowledge.items.length === 0 ? void 0 : `${tr("Things: ")}${shown(knowledge.items)}`
308
+ ].filter((line) => line !== void 0);
309
+ if (lines.length > 0) sections.push(`${tr("What you know exists (this does not tell you where it is now or what state it is in):")}\n${lines.join("\n")}`);
310
+ }
311
+ if (memories !== void 0 && memories.length > 0) sections.splice(1, 0, `${tr("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, tr, time?.now)}`);
312
+ else if (memories !== void 0) sections.splice(1, 0, tr("What you remember that bears on this: nothing comes to mind."));
313
+ if (earlier !== void 0 && earlier.length > 0) sections.push(`${tr("Earlier in this scene, before this moment:")}\n${earlier.map((entry) => said(entry, tr)).join("\n")}`);
314
+ if (attempt === 2 && reaction !== void 0) {
315
+ sections.push(`${tr("What just happened, and what you are reacting to:")}\n${reaction.map((entry) => said(entry, tr)).join("\n")}`);
316
+ if (previous !== void 0) sections.push(tr("Your earlier intent did not work out: {intent}\nYou are trying again, knowing the above. Decide again what you do now.", { intent: previous.intent }));
317
+ }
318
+ return {
319
+ persona: [
320
+ describe(member.character, tr),
321
+ request.text("roleplay/character-rules", { name: member.character.name }),
322
+ request.text("roleplay/character-style", { name: member.character.name }),
323
+ ...request.lookup ? [request.text("roleplay/character-lookup")] : [],
324
+ request.text("roleplay/character-decide", {
325
+ name: member.character.name,
326
+ ...limitVariables(request.language ?? "en")
327
+ })
328
+ ].join("\n\n"),
329
+ prompt: sections.join("\n\n")
330
+ };
331
+ } };
332
+ /**
333
+ * 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
334
+ * 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
335
+ * another place can be asked when the moment reaches it.)
336
+ */
337
+ const everyoneActs = { plan({ cast, requested }) {
338
+ const placed = cast.some((member) => member.place !== void 0);
339
+ const available = cast.filter((member) => member.character.control === "agent");
340
+ const here = cast.find((member) => member.character.control === "player")?.place?.location.id;
341
+ const inScene = (member) => !placed || member.place !== void 0;
342
+ 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);
343
+ const unknown = requested.filter((key) => !available.some((member) => member.key === key));
344
+ 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(", ")})`);
345
+ const nowhere = [...new Set(requested)].map((key) => available.find((member) => member.key === key)).filter((member) => !inScene(member));
346
+ 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`);
347
+ return [...new Set(requested)];
348
+ } };
349
+ const acceptsAnyIntent = { validate: ({ intent }) => intent.trim() === "" ? {
350
+ ok: false,
351
+ reason: "the intent is empty"
352
+ } : { ok: true } };
353
+ /** A character whose intent failed and who is highly committed tries once more. */
354
+ const persistentRetry = { select({ reports, outcomes }) {
355
+ return reports.filter((report) => report.commitment === "high" && outcomes.some((outcome) => outcome.character === report.character && outcome.result === "failed")).map((report) => report.character);
356
+ } };
357
+ const acceptsAnyInput = { validate: () => ({ ok: true }) };
358
+ /** The game master narrates. */
359
+ const gameMasterNarrates = { narrate: () => Promise.resolve(void 0) };
360
+ /** Compares what was said, ignoring the quotes around it and the way whitespace is laid out. */
361
+ const WRAPPING_QUOTES = /^["“”„«»'‘’]+|["“”„«»'‘’]+$/g;
362
+ function sameWords(a, b) {
363
+ const plain = (text) => text.trim().replace(WRAPPING_QUOTES, "").replace(/\s+/g, " ").trim();
364
+ return plain(a) === plain(b);
365
+ }
366
+ /** How many earlier events the game master is reminded of at most. */
367
+ const REMINDED_EVENTS = 5;
368
+ /**
369
+ * The state of the scene, what is still open in the story, and the earlier events that the
370
+ * player's move brings to mind (by the session's search of words and meaning, and by who is named):
371
+ * those already folded out of the conversation into the summaries, whose detail the summaries may have lost.
372
+ */
373
+ /** Where the player is and what is there, who is with them, and who is elsewhere. */
374
+ function placedScene(cast, player, story, describeMember, tr, things) {
375
+ const here = player?.place?.location;
376
+ const sections = [];
377
+ if (here !== void 0) {
378
+ const view = {
379
+ key: locationKey(here),
380
+ location: here,
381
+ here: cast.filter((member) => member.place?.location.id === here.id),
382
+ ...things === void 0 ? {} : { items: things.at(here.id) },
383
+ exits: story.locations.exitsFrom(here.id).flatMap((exit) => {
384
+ const to = story.locations.get(exit.toId);
385
+ return to === void 0 ? [] : [{
386
+ key: locationKey(to),
387
+ name: to.name,
388
+ exit
389
+ }];
390
+ })
391
+ };
392
+ sections.push(tr("The player's character is in {place}", { place: describePlace(view, { withKeys: true }, tr).join("\n") }));
393
+ sections.push(`${tr("Characters here:")}\n${view.here.map(describeMember).join("\n")}`);
394
+ }
395
+ const elsewhere = cast.filter((member) => member.place !== void 0 && member.place.location.id !== here?.id);
396
+ if (elsewhere.length > 0) sections.push(`${tr("Characters elsewhere (they perceive nothing here unless the moment reaches them):")}\n${elsewhere.map((member) => tr("{member} - in {place} ({key})", {
397
+ member: describeMember(member),
398
+ place: member.place.location.name,
399
+ key: locationKey(member.place.location)
400
+ })).join("\n")}`);
401
+ const nowhere = cast.filter((member) => member.place === void 0);
402
+ if (nowhere.length > 0) sections.push(`${tr("Characters with no place (not part of this scene; they cannot be asked to act):")}\n${nowhere.map(describeMember).join("\n")}`);
403
+ return sections.join("\n\n");
404
+ }
405
+ const castSummary = { scene({ tracked, time, world, cast, turn, input, queryVector, story, items, language: code }) {
406
+ const language = languageOf(code);
407
+ const tr = translator(language);
408
+ const join = (entries) => entries.join(tr("; "));
409
+ const describeMember = (member) => {
410
+ const { key, character, state } = member;
411
+ const role = character.control === "player" ? tr("the player's character, \"{key}\"", { key }) : tr("acts through \"{key}\"", { key });
412
+ const seen = [state?.publicState, state?.activity].filter((text) => text !== void 0 && text.trim() !== "");
413
+ const where = whereIs(member, tr);
414
+ return `- ${referent(character)} (${role})${where === "" ? "" : ` [${where}]`}${character.summary === "" ? "" : `${tr(": ")}${character.summary}`}${seen.length > 0 ? ` ${tr("Currently: {state}", { state: join(seen) })}` : ""}`;
415
+ };
416
+ const player = cast.find((member) => member.character.control === "player");
417
+ const days = time?.agenda === void 0 ? "" : describeSceneAgenda(time.agenda, time.now.now, tr, language);
418
+ const scene = cast.some((member) => member.place !== void 0) ? placedScene(cast, player, story, describeMember, tr, items) : cast.map(describeMember).join("\n");
419
+ const parts = [
420
+ ...time === void 0 ? [] : [timeNotice(time, language, tr)],
421
+ ...days === "" ? [] : [days],
422
+ `${tr("Scene before turn {turn}:", { turn })}\n${scene}`
423
+ ];
424
+ const activation = describeActivationCandidates(cast, input, story, tr);
425
+ if (activation !== "") parts.push(activation);
426
+ if (items !== void 0) {
427
+ const carried = cast.flatMap((member) => {
428
+ const mine = items.carried(member.character.id);
429
+ return mine.length === 0 ? [] : [`- ${member.character.name} (${member.key}): ${describeItems(mine, { withKeys: true }, tr)}`];
430
+ });
431
+ if (carried.length > 0) parts.push(`${tr("What characters have on them:")}\n${carried.join("\n")}`);
432
+ }
433
+ if (world !== void 0 && world.happened.length > 0) parts.push(`${tr("The world acted since the last turn, by itself:")}\n${world.happened.map((line) => `- ${line}`).join("\n")}`);
434
+ if (world?.upcoming !== void 0 && world.upcoming.length > 0) parts.push(`${tr("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})`} ${tr("[known to {who}]", { who: entry.who })}`).join("\n")}`);
435
+ if (world !== void 0 && world.beats.length > 0) parts.push(`${tr("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")}`);
436
+ if (tracked !== void 0 && tracked.length > 0) parts.push(`${tr("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")}`);
437
+ const threads = story.threads.list("open");
438
+ if (threads.length > 0) parts.push(`${tr("Still open in the story:")}\n${threads.map((thread) => `- ${thread.text}`).join("\n")}`);
439
+ const folded = story.summaries.list().reduce((latest, summary) => Math.max(latest, summary.toTurn), 0);
440
+ if (folded > 0) {
441
+ const mentionedIds = mentioned(input, cast.map(({ character }) => character));
442
+ const cues = tokens(input);
443
+ const names = new Map(cast.map(({ character }) => [character.id, character.name]));
444
+ const byMeaning = story.searchEvents({
445
+ text: input,
446
+ ...queryVector === void 0 ? {} : { vector: queryVector },
447
+ toTurn: folded,
448
+ limit: REMINDED_EVENTS
449
+ });
450
+ const byCues = story.events.list({ toTurn: folded }).filter((event) => !byMeaning.some((found) => found.id === event.id)).map((event) => ({
451
+ event,
452
+ score: 3 * event.involves.filter((id) => mentionedIds.has(id)).length + overlap(cues, event.text, event.tags)
453
+ })).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);
454
+ const relevant = [...byMeaning, ...byCues].slice(0, REMINDED_EVENTS).sort((a, b) => a.turn - b.turn).map((event) => ({ event }));
455
+ if (relevant.length > 0) parts.push(`${tr("Earlier events that bear on what the player just did (from the records of the story):")}\n${relevant.map(({ event }) => {
456
+ const who = event.involves.map((id) => names.get(id)).filter((name) => name !== void 0).join(tr(", "));
457
+ return `- (${tr("turn {turn}", { turn: event.turn })}) ${event.text}${who === "" ? "" : ` [${who}]`}`;
458
+ }).join("\n")}`);
459
+ }
460
+ return parts.join("\n\n");
461
+ } };
462
+ const sameCharacter = (utterance, character) => utterance.character === character || utterance.name === character;
463
+ /** Every utterance appears once, exactly as given and in the order spoken, and no one speaks who did not. */
464
+ const exactUtterances = {
465
+ check(segments, required) {
466
+ const problems = [];
467
+ const used = /* @__PURE__ */ new Set();
468
+ let latest = 0;
469
+ segments.forEach((segment, index) => {
470
+ const at = `segment ${index + 1}`;
471
+ if (segment.type === "narration") {
472
+ if (segment.text.trim() === "") problems.push(`${at}: the narration is empty`);
473
+ return;
474
+ }
475
+ const own = required.flatMap((utterance, position) => sameCharacter(utterance, segment.character) ? [position] : []);
476
+ const free = own.filter((position) => !used.has(position));
477
+ const exact = free.find((position) => sameWords(segment.text, required[position].text));
478
+ if (exact !== void 0) {
479
+ used.add(exact);
480
+ const spoken = required[exact];
481
+ 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`);
482
+ latest = Math.max(latest, spoken.round);
483
+ } else if (free.length > 0) {
484
+ used.add(free[0]);
485
+ problems.push(`${at}: the utterance of ${required[free[0]].name} was changed; it must be exactly "${required[free[0]].text}"`);
486
+ } 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`);
487
+ else problems.push(`${at}: ${segment.character} has nothing to say this turn, so this utterance is invented; remove it`);
488
+ });
489
+ required.forEach((utterance, position) => {
490
+ 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}"`);
491
+ });
492
+ return problems;
493
+ },
494
+ repair(segments, required) {
495
+ const used = /* @__PURE__ */ new Set();
496
+ const kept = [];
497
+ for (const segment of segments) {
498
+ if (segment.type === "narration") {
499
+ if (segment.text.trim() !== "") kept.push({
500
+ segment,
501
+ round: void 0
502
+ });
503
+ continue;
504
+ }
505
+ const free = required.flatMap((utterance, position) => sameCharacter(utterance, segment.character) && !used.has(position) ? [position] : []);
506
+ const position = free.find((candidate) => sameWords(segment.text, required[candidate].text)) ?? free[0];
507
+ if (position === void 0) continue;
508
+ used.add(position);
509
+ const spoken = required[position];
510
+ kept.push({
511
+ segment: {
512
+ type: "utterance",
513
+ character: spoken.character,
514
+ name: spoken.name,
515
+ text: spoken.text
516
+ },
517
+ round: spoken.round
518
+ });
519
+ }
520
+ required.forEach((utterance, position) => {
521
+ if (used.has(position)) return;
522
+ const restored = {
523
+ type: "utterance",
524
+ character: utterance.character,
525
+ name: utterance.name,
526
+ text: utterance.text
527
+ };
528
+ const later = kept.findIndex((entry) => entry.round !== void 0 && entry.round > utterance.round);
529
+ kept.splice(later < 0 ? kept.length : later, 0, {
530
+ segment: restored,
531
+ round: utterance.round
532
+ });
533
+ });
534
+ return kept.map((entry) => entry.segment);
535
+ }
536
+ };
537
+ /** 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. */
538
+ const recordsRecall = { recall: ({ member, situation, turn, policy, queryVector, explain }, story, signal) => story.recallRanked({
539
+ characterId: member.character.id,
540
+ situation,
541
+ turn,
542
+ policy,
543
+ ...explain === true ? { explain } : {},
544
+ ...member.place === void 0 ? {} : { locationId: member.place.location.id }
545
+ }, signal, queryVector === void 0 ? {} : { queryVector }) };
546
+ /**
547
+ * Writes no memory. What the game master decided about each character is applied when the round is
548
+ * recorded, so without a memory keeper the story keeps its states and no events.
549
+ */
550
+ const writesNothing = { commit: () => Promise.resolve({
551
+ writes: 0,
552
+ notes: ""
553
+ }) };
554
+ /** Makes up nothing, and has nothing to fit in: without a world author the world stays as it was written. */
555
+ const declinesToAuthor = {
556
+ create: () => Promise.resolve({
557
+ created: [],
558
+ declined: "no world author is installed, so the world cannot grow"
559
+ }),
560
+ consolidate: () => Promise.resolve({
561
+ resolved: 0,
562
+ notes: ""
563
+ })
564
+ };
565
+ /** Lets no organisation act: without a strategist factions change only through what the story records. */
566
+ const factionsStayPut = { strategize: () => Promise.resolve({ acted: [] }) };
567
+ /** Reflects on nothing: without a reflector what characters believe changes only through what the story records. */
568
+ const reflectsOnNothing = { reflect: () => Promise.resolve({ characters: [] }) };
569
+ /** Judges nothing: without a judge a trigger that waits on a statement never sees it hold. */
570
+ const judgesNothing = { judge: () => Promise.resolve({ judged: 0 }) };
571
+ /** Offers nothing: without a suggester the player writes their own move. */
572
+ const offersNothing = { suggest: () => Promise.resolve([]) };
573
+ function defaultBoundaries() {
574
+ return {
575
+ planner: everyoneActs,
576
+ characterContext: sharedContext,
577
+ outputValidator: acceptsAnyIntent,
578
+ retryPolicy: persistentRetry,
579
+ inputValidator: acceptsAnyInput,
580
+ narrator: gameMasterNarrates,
581
+ narrationChecker: exactUtterances,
582
+ committer: writesNothing,
583
+ author: declinesToAuthor,
584
+ strategist: factionsStayPut,
585
+ reflector: reflectsOnNothing,
586
+ judge: judgesNothing,
587
+ suggester: offersNothing,
588
+ recaller: recordsRecall,
589
+ sceneContext: castSummary
590
+ };
591
+ }
592
+ //#endregion
593
+ //#region src/shared/timeline.ts
594
+ const emptyTimeline = () => ({
595
+ version: 1,
596
+ head: null,
597
+ next: 1,
598
+ nodes: []
599
+ });
600
+ /** The turns from the first to `id`, in order; none for the start. */
601
+ function pathTo(timeline, id) {
602
+ const byId = new Map(timeline.nodes.map((node) => [node.id, node]));
603
+ const path = [];
604
+ 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);
605
+ return path;
606
+ }
607
+ /** The turns that follow `parent`, in the order they were played. */
608
+ const childrenOf = (timeline, parent) => timeline.nodes.filter((node) => node.parent === parent);
609
+ /** The snapshot that holds the state before any turn. */
610
+ const START_SNAPSHOT = "start";
611
+ /** The snapshot that holds the state after a turn. */
612
+ const snapshotOf = (id) => `after-${id}`;
613
+ /** Builds what the client shows from the timeline. */
614
+ function viewOf(timeline) {
615
+ const turn = (node) => ({
616
+ id: node.id,
617
+ turn: node.turn,
618
+ player: node.player,
619
+ ...node.endSeq === void 0 ? {} : { endSeq: node.endSeq },
620
+ ...node.output === void 0 ? {} : { output: node.output },
621
+ restorable: node.snapshot !== void 0,
622
+ alternatives: childrenOf(timeline, node.parent).map((sibling) => sibling.id)
623
+ });
624
+ const on = new Set(pathTo(timeline, timeline.head).map((node) => node.id));
625
+ const withdrawn = timeline.nodes.filter((node) => !on.has(node.id) && node.userSeq >= 0).map((node) => ({
626
+ from: Math.min(node.startSeq ?? node.userSeq, node.userSeq),
627
+ to: node.endSeq ?? Number.MAX_SAFE_INTEGER
628
+ }));
629
+ return {
630
+ head: timeline.head,
631
+ path: pathTo(timeline, timeline.head).map(turn),
632
+ forward: childrenOf(timeline, timeline.head).map(turn),
633
+ canStart: true,
634
+ withdrawn
635
+ };
636
+ }
637
+ /** 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. */
638
+ function noticeText(node) {
639
+ 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");
640
+ const ooc = node.output?.ooc;
641
+ 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}`;
642
+ return `The story, as it went earlier (restored):\nThe player said: ${node.player}${ruling}\nIt was told to the player:\n${told}`;
643
+ }
644
+ //#endregion
645
+ //#region src/host/timeline/file.ts
646
+ const TIMELINE_FILE = "timeline.json";
647
+ function isNode(value) {
648
+ if (typeof value !== "object" || value === null) return false;
649
+ const node = value;
650
+ 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";
651
+ }
652
+ /**
653
+ * The timeline of a session, or an empty one when it has none yet.
654
+ * @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.
655
+ */
656
+ function readTimeline(folder) {
657
+ let text;
658
+ try {
659
+ text = readFileSync(join(folder, TIMELINE_FILE), "utf8");
660
+ } catch (error) {
661
+ if (error.code === "ENOENT") return emptyTimeline();
662
+ throw error;
663
+ }
664
+ const value = JSON.parse(text);
665
+ 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`);
666
+ return value;
667
+ }
668
+ /** Writes it aside and renames it, so a crash leaves the timeline as it was. */
669
+ function writeTimeline(folder, timeline) {
670
+ const target = join(folder, TIMELINE_FILE);
671
+ const aside = `${target}.writing`;
672
+ writeFileSync(aside, JSON.stringify(timeline, null, 2));
673
+ renameSync(aside, target);
674
+ }
675
+ //#endregion
676
+ //#region src/host/timeline/branch.ts
677
+ var BranchError = class extends Error {};
678
+ /**
679
+ * 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
680
+ * that ended last, and the state of the story after that turn.
681
+ * @param boundary - the seq of the last event the branch inherits.
682
+ * @param snapshots - the names of the snapshots the story has.
683
+ * @throws {BranchError} when the state at that point was not kept.
684
+ */
685
+ function branchTimeline(timeline, boundary, snapshots) {
686
+ const nodes = timeline.nodes.filter((node) => node.endSeq !== void 0 && node.endSeq <= boundary).map((node) => ({ ...node }));
687
+ for (const node of nodes) if (node.noticeSeq !== void 0 && node.noticeSeq > boundary) delete node.noticeSeq;
688
+ const last = nodes.reduce((found, node) => found === void 0 || node.endSeq > found.endSeq ? node : found, void 0);
689
+ const available = new Set(snapshots);
690
+ for (const node of nodes) if (node.snapshot !== void 0 && !available.has(node.snapshot)) delete node.snapshot;
691
+ const keep = [...nodes.flatMap((node) => node.snapshot === void 0 ? [] : [node.snapshot]), ...available.has("start") ? [START_SNAPSHOT] : []];
692
+ const branch = {
693
+ version: 1,
694
+ head: last?.id ?? null,
695
+ next: timeline.next,
696
+ nodes
697
+ };
698
+ if (last === void 0) {
699
+ if (!available.has("start")) throw new BranchError("the state at the start of the story was not kept, so it cannot be branched");
700
+ return {
701
+ timeline: branch,
702
+ from: { snapshot: START_SNAPSHOT },
703
+ keep
704
+ };
705
+ }
706
+ if (last.snapshot !== void 0) return {
707
+ timeline: branch,
708
+ from: { snapshot: last.snapshot },
709
+ keep
710
+ };
711
+ if (timeline.head === last.id) return {
712
+ timeline: branch,
713
+ from: { live: true },
714
+ keep
715
+ };
716
+ throw new BranchError(`the state of the story after its turn ${last.turn} was not kept, so it cannot be branched there`);
717
+ }
718
+ /** The name of a branch: the story's name with its trailing number counted up, or a 2 added. */
719
+ function branchName(name) {
720
+ const numbered = /^(.*?)(\d+)\s*$/.exec(name);
721
+ const next = numbered === null ? `${name} 2` : `${numbered[1]}${Number(numbered[2]) + 1}`;
722
+ return next.length > 200 ? `${[...name].slice(0, 190).join("").trimEnd()} 2` : next;
723
+ }
724
+ //#endregion
725
+ //#region src/host/timeline/plan.ts
726
+ /**
727
+ * Where the model's conversation has to be changed so that it carries the turns from the first to `target`, and no others.
728
+ * 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
729
+ * 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.
730
+ * @param surface - the seqs of the model's conversation, in order.
731
+ */
732
+ function planMove(timeline, target, surface) {
733
+ const onSurface = new Set(surface);
734
+ const path = pathTo(timeline, target);
735
+ let keptCount = 0;
736
+ let last = -1;
737
+ for (const node of path) {
738
+ const at = surface.indexOf(node.userSeq);
739
+ if (at <= last) break;
740
+ last = at;
741
+ keptCount += 1;
742
+ }
743
+ const kept = path.slice(0, keptCount);
744
+ const keptIds = new Set(kept.map((node) => node.id));
745
+ const byStart = [...timeline.nodes].sort((a, b) => a.userSeq - b.userSeq);
746
+ const seqs = /* @__PURE__ */ new Set();
747
+ byStart.forEach((node, index) => {
748
+ if (keptIds.has(node.id)) return;
749
+ if (node.noticeSeq !== void 0 && onSurface.has(node.noticeSeq)) seqs.add(node.noticeSeq);
750
+ if (!onSurface.has(node.userSeq)) return;
751
+ const end = node.endSeq ?? (byStart[index + 1]?.userSeq === void 0 ? Infinity : byStart[index + 1].userSeq - 1);
752
+ for (const seq of surface) if (seq >= node.userSeq && seq <= end) seqs.add(seq);
753
+ });
754
+ const shadow = [];
755
+ let run = [];
756
+ let previous = -2;
757
+ surface.forEach((seq, index) => {
758
+ if (!seqs.has(seq)) return;
759
+ if (index !== previous + 1 && run.length > 0) {
760
+ shadow.push({
761
+ startSeq: run[0],
762
+ endSeq: run.at(-1),
763
+ seqs: run
764
+ });
765
+ run = [];
766
+ }
767
+ run.push(seq);
768
+ previous = index;
769
+ });
770
+ if (run.length > 0) shadow.push({
771
+ startSeq: run[0],
772
+ endSeq: run.at(-1),
773
+ seqs: run
774
+ });
775
+ return {
776
+ shadow,
777
+ kept: kept.map((node) => node.id),
778
+ inject: path.slice(keptCount)
779
+ };
780
+ }
781
+ //#endregion
782
+ //#region src/host/timeline/service.ts
783
+ /** The text of the marker that stands for the turns it replaces: never empty, as a model service may refuse an empty message. */
784
+ const MARKER_TEXT = "(empty message)";
785
+ /** A turn that has not ended does not know yet where its own message is in the log. */
786
+ const UNKNOWN_SEQ = -1;
787
+ var TimelineError = class extends Error {};
788
+ /**
789
+ * What the story's turns are, and taking the story back to one of them (or forward again). The conversation with the model is
790
+ * only ever added to: the turns that no longer belong are replaced by a marker, which DSH keeps out of the next request, and
791
+ * 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.
792
+ * Everything here is one at a time per chat.
793
+ */
794
+ var Timelines = class {
795
+ deps;
796
+ queues = /* @__PURE__ */ new Map();
797
+ constructor(deps) {
798
+ this.deps = deps;
799
+ }
800
+ serial(chat, job) {
801
+ const run = (this.queues.get(chat) ?? Promise.resolve()).then(job, job);
802
+ this.queues.set(chat, run.catch(() => void 0));
803
+ return run;
804
+ }
805
+ idOf(chat) {
806
+ const id = roleplaySessionOf(chat);
807
+ if (id === void 0) throw new TimelineError(`${chat} is not a roleplay chat`);
808
+ return id;
809
+ }
810
+ folder(id) {
811
+ return sessionFolder(this.deps.sessionsDir(), id);
812
+ }
813
+ read(id) {
814
+ return readTimeline(this.folder(id));
815
+ }
816
+ view(id) {
817
+ return viewOf(this.read(id));
818
+ }
819
+ /**
820
+ * 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,
821
+ * with the records still waiting for the keeper in it (they are in the database, so a restored state carries them).
822
+ */
823
+ begin(chat, turn, player) {
824
+ return this.serial(chat, async () => {
825
+ this.deps.cancel?.(chat);
826
+ const id = this.idOf(chat);
827
+ const timeline = this.read(id);
828
+ this.keep(id, timeline, timeline.head);
829
+ const node = {
830
+ id: `n${timeline.next}`,
831
+ parent: timeline.head,
832
+ turn,
833
+ userSeq: UNKNOWN_SEQ,
834
+ player,
835
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
836
+ };
837
+ timeline.nodes.push(node);
838
+ timeline.next += 1;
839
+ timeline.head = node.id;
840
+ writeTimeline(this.folder(id), timeline);
841
+ this.prune(id, timeline);
842
+ return node;
843
+ });
844
+ }
845
+ /** What the turn delivered; and, once nothing writes to the story any more, its state is kept. */
846
+ delivered(chat, output) {
847
+ const id = this.idOf(chat);
848
+ const timeline = this.read(id);
849
+ const node = timeline.nodes.find((candidate) => candidate.id === timeline.head);
850
+ if (node === void 0) return void 0;
851
+ node.output = output;
852
+ writeTimeline(this.folder(id), timeline);
853
+ this.deps.engine.quiesce(chat).then(() => this.serial(chat, () => {
854
+ const current = this.read(id);
855
+ if (current.head === node.id) this.keep(id, current, node.id);
856
+ return Promise.resolve();
857
+ })).catch(() => void 0);
858
+ return node.id;
859
+ }
860
+ /**
861
+ * 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
862
+ * (it is not in the log yet when the turn begins).
863
+ */
864
+ ended(chat, session, seq) {
865
+ const id = this.idOf(chat);
866
+ const timeline = this.read(id);
867
+ const node = timeline.nodes.find((candidate) => candidate.id === timeline.head);
868
+ if (node === void 0 || node.endSeq !== void 0) return;
869
+ const after = Math.max(-1, ...timeline.nodes.filter((other) => other.id !== node.id).map((other) => other.endSeq ?? other.userSeq));
870
+ const human = session.snapshotEvents().find((event) => event.seq > after && event.type === "user/message" && event.data.source.kind === "user");
871
+ if (human === void 0) throw new TimelineError(`turn ${node.turn} has no message of the player in the log`);
872
+ node.userSeq = human.seq;
873
+ node.endSeq = seq;
874
+ const began = session.snapshotEvents().find((event) => event.type === "turn/start" && event.data.turn === node.turn);
875
+ node.startSeq = Math.min(began?.seq ?? human.seq, human.seq);
876
+ writeTimeline(this.folder(id), timeline);
877
+ }
878
+ /** Keeps the state as it is under the name of the turn it follows from, when that is not done yet. */
879
+ keep(id, timeline, at) {
880
+ if (this.deps.keepSnapshots(id) === 0) return;
881
+ const node = at === null ? void 0 : timeline.nodes.find((candidate) => candidate.id === at);
882
+ const name = node === void 0 ? START_SNAPSHOT : snapshotOf(node.id);
883
+ if (node !== void 0 && node.snapshot !== void 0) return;
884
+ if (node === void 0 && this.deps.state.snapshots(this.deps.sessionsDir(), id).includes("start")) return;
885
+ this.deps.state.snapshot(this.deps.sessionsDir(), id, name);
886
+ if (node !== void 0) {
887
+ node.snapshot = name;
888
+ writeTimeline(this.folder(id), timeline);
889
+ }
890
+ }
891
+ /** Lets the oldest snapshots go: only the turns most recently played keep theirs, and the one that holds the start stays. */
892
+ prune(id, timeline) {
893
+ const keep = this.deps.keepSnapshots(id);
894
+ const kept = timeline.nodes.filter((node) => node.snapshot !== void 0);
895
+ const dropped = kept.slice(0, Math.max(0, kept.length - keep));
896
+ if (dropped.length === 0) return;
897
+ for (const node of dropped) {
898
+ this.deps.state.removeSnapshot(this.deps.sessionsDir(), id, node.snapshot);
899
+ delete node.snapshot;
900
+ }
901
+ writeTimeline(this.folder(id), timeline);
902
+ }
903
+ /**
904
+ * 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,
905
+ * 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.
906
+ * @returns what the player said in the first turn that was left, to put back in the input; nothing when the story went forward.
907
+ * @throws {TimelineError} when there is no such turn, its state was not kept, or the chat is not loaded.
908
+ */
909
+ move(chat, target) {
910
+ return this.serial(chat, async () => {
911
+ const id = this.idOf(chat);
912
+ const timeline = this.read(id);
913
+ const to = target === null ? void 0 : timeline.nodes.find((node) => node.id === target);
914
+ if (target !== null && to === void 0) throw new TimelineError(`there is no turn "${target}"`);
915
+ const snapshot = target === null ? START_SNAPSHOT : to.snapshot;
916
+ 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");
917
+ const agent = await this.deps.agentOf(chat);
918
+ if (agent === void 0) throw new TimelineError(`the chat ${chat} is not loaded`);
919
+ if (agent.status !== "idle") {
920
+ agent.cancel({ kind: "user" }, { keepInbox: true });
921
+ await agent.whenIdle();
922
+ }
923
+ this.deps.cancel?.(chat);
924
+ this.deps.engine.stop(chat);
925
+ await this.deps.engine.quiesce(chat);
926
+ this.deps.engine.forget(chat);
927
+ const was = pathTo(timeline, timeline.head);
928
+ const plan = planMove(timeline, target, [...agent.session.surface.nodes]);
929
+ this.deps.state.restore(this.deps.sessionsDir(), id, snapshot);
930
+ this.reconcile(agent, plan);
931
+ timeline.head = target;
932
+ writeTimeline(this.folder(id), timeline);
933
+ const left = was.find((node) => !pathTo(timeline, target).some((kept) => kept.id === node.id));
934
+ return left === void 0 ? {} : { draft: left.player };
935
+ });
936
+ }
937
+ /** 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. */
938
+ reconcile(agent, plan) {
939
+ for (const run of plan.shadow) agent.session.append("user/message", createUserMessage({
940
+ content: [{
941
+ type: "text",
942
+ text: MARKER_TEXT
943
+ }],
944
+ source: { kind: "roleplay" }
945
+ }), {
946
+ surfaceOp: {
947
+ op: "replace",
948
+ startSeq: run.startSeq,
949
+ endSeq: run.endSeq
950
+ },
951
+ sourceEventSeqs: run.seqs
952
+ });
953
+ for (const node of plan.inject) node.noticeSeq = agent.session.append("user/message", createUserMessage({
954
+ content: [{
955
+ type: "text",
956
+ text: noticeText(node)
957
+ }],
958
+ source: { kind: "roleplay" }
959
+ }), { surfaceOp: "append" }).seq;
960
+ }
961
+ /**
962
+ * 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
963
+ * 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
964
+ * 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.
965
+ * @param cut - the seq of the last event of the log the branch inherits.
966
+ * @returns whether a session was made.
967
+ * @throws {BranchError} when the state at the cut was not kept; the branch is then not made.
968
+ */
969
+ adopt(chat, parent, cut, agent) {
970
+ return this.serial(parent, async () => {
971
+ const id = this.idOf(chat);
972
+ const from = this.idOf(parent);
973
+ const directory = this.deps.sessionsDir();
974
+ if (existsSync(sessionDatabase(directory, id)) || !existsSync(sessionDatabase(directory, from))) return false;
975
+ const branch = branchTimeline(this.read(from), cut, this.deps.state.snapshots(directory, from));
976
+ if ("live" in branch.from) await this.deps.engine.quiesce(parent);
977
+ const name = branchName(this.deps.state.openSession(directory, from).metadata.get().name);
978
+ this.deps.state.fork(directory, from, id, branch.from, {
979
+ name,
980
+ keep: branch.keep
981
+ });
982
+ try {
983
+ await inheritImages(this.folder(from), this.folder(id), branch.timeline.nodes.map((node) => node.id));
984
+ inheritPrompts(this.folder(from), this.folder(id));
985
+ inheritPacks(this.folder(from), this.folder(id));
986
+ const plan = planMove(branch.timeline, branch.timeline.head, [...agent.session.surface.nodes]);
987
+ this.reconcile(agent, plan);
988
+ writeTimeline(this.folder(id), branch.timeline);
989
+ } catch (error) {
990
+ this.deps.state.deleteSession(directory, id);
991
+ throw error;
992
+ }
993
+ return true;
994
+ });
995
+ }
996
+ /** The turns that follow a turn, for the choices the story can be taken to. */
997
+ forward(id) {
998
+ const timeline = this.read(id);
999
+ return childrenOf(timeline, timeline.head);
1000
+ }
1001
+ };
1002
+ //#endregion
1003
+ //#region src/host/orchestration/whereabouts.ts
1004
+ const within = (inner, outer, places) => {
1005
+ const byId = new Map(places.map((place) => [place.id, place]));
1006
+ const seen = /* @__PURE__ */ new Set();
1007
+ for (let at = inner; at !== void 0 && !seen.has(at.id); at = at.parentId === void 0 ? void 0 : byId.get(at.parentId)) {
1008
+ if (at.id === outer.id) return true;
1009
+ seen.add(at.id);
1010
+ }
1011
+ return false;
1012
+ };
1013
+ /** Whether two places are one scene: the same place, or one inside the other (a room and its building). */
1014
+ const sameScene = (a, b, places) => within(a, b, places) || within(b, a, places);
1015
+ /**
1016
+ * 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
1017
+ * 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.
1018
+ */
1019
+ function whereabouts(places, here, at) {
1020
+ const target = places.find((place) => locationKey(place) === at);
1021
+ if (target === void 0) return { kind: "unknown" };
1022
+ if (here === void 0) return { kind: "unplaced" };
1023
+ return within(here, target, places) || within(target, here, places) ? { kind: "here" } : {
1024
+ kind: "elsewhere",
1025
+ target,
1026
+ here
1027
+ };
1028
+ }
1029
+ //#endregion
1030
+ //#region src/host/memory/reflection.ts
1031
+ const LAST_KEY = "reflection.last";
1032
+ const CURSOR_KEY = "reflection.cursor";
1033
+ const ANCHOR_KEY = "reflection.anchor";
1034
+ const ERROR_KEY = "reflection.error";
1035
+ const DAY_MS = 864e5;
1036
+ const MAX_MATERIAL = 40;
1037
+ const MAX_BELIEFS_SHOWN = 40;
1038
+ const MAX_ADDED = 4;
1039
+ const MAX_CHANGES = 10;
1040
+ const MAX_TEXT = 300;
1041
+ /** An event this important is reason enough for a belief on its own. */
1042
+ const DECISIVE_IMPORTANCE = 4;
1043
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1044
+ function readLast(session) {
1045
+ const stored = session.metadata.getValue(LAST_KEY);
1046
+ return isRecord(stored) && typeof stored["turn"] === "number" ? stored : void 0;
1047
+ }
1048
+ function readCursor(session) {
1049
+ const stored = session.metadata.getValue(CURSOR_KEY);
1050
+ return isRecord(stored) ? Object.fromEntries(Object.entries(stored).filter((entry) => typeof entry[1] === "number")) : {};
1051
+ }
1052
+ function readAnchor(session) {
1053
+ const stored = session.metadata.getValue(ANCHOR_KEY);
1054
+ return isRecord(stored) && typeof stored["now"] === "number" ? {
1055
+ now: stored["now"],
1056
+ ...typeof stored["place"] === "number" ? { place: stored["place"] } : {}
1057
+ } : void 0;
1058
+ }
1059
+ function writeAnchor(session, place, now) {
1060
+ session.metadata.setValue(ANCHOR_KEY, {
1061
+ now,
1062
+ ...place === void 0 ? {} : { place: place.id }
1063
+ });
1064
+ }
1065
+ const playerPlace = (store) => store.cast().find((member) => member.character.control === "player")?.place?.location;
1066
+ /** What is known of the story's reflection: whether a pass runs, the latest that finished, and why the latest failed. */
1067
+ function reflectionStatus(session, running) {
1068
+ const last = readLast(session);
1069
+ const failure = session.metadata.getValue(ERROR_KEY);
1070
+ return {
1071
+ running,
1072
+ ...last === void 0 ? {} : { last },
1073
+ ...isRecord(failure) && typeof failure["message"] === "string" && typeof failure["at"] === "string" ? { error: {
1074
+ at: failure["at"],
1075
+ message: failure["message"]
1076
+ } } : {}
1077
+ };
1078
+ }
1079
+ function recordFailure(session, message) {
1080
+ session.metadata.setValue(ERROR_KEY, {
1081
+ at: (/* @__PURE__ */ new Date()).toISOString(),
1082
+ message: message.slice(0, 500)
1083
+ });
1084
+ }
1085
+ /**
1086
+ * Whether the story should reflect after this turn, and why. A pass waits until `minTurns` turns have passed since the last one; then it
1087
+ * comes after `everyTurns` turns, or when the scene has changed since the last pass (the player's character is somewhere that is neither
1088
+ * where it was nor inside or around it, or `sceneDays` of story time have passed). The first look only notes where the story stands.
1089
+ */
1090
+ function dueReflection(store, turn) {
1091
+ const { reflection } = store.settings();
1092
+ if (!reflection.auto) return void 0;
1093
+ const session = store.story;
1094
+ const { now } = store.time(turn);
1095
+ const here = playerPlace(store);
1096
+ const anchor = readAnchor(session);
1097
+ if (anchor === void 0) {
1098
+ writeAnchor(session, here, now);
1099
+ return;
1100
+ }
1101
+ const since = turn - (readLast(session)?.turn ?? 0);
1102
+ if (since < reflection.minTurns) return void 0;
1103
+ if (reflection.everyTurns > 0 && since >= reflection.everyTurns) return "turns";
1104
+ if (!reflection.onSceneChange) return void 0;
1105
+ const places = session.locations.list();
1106
+ const before = places.find((place) => place.id === anchor.place);
1107
+ if (here !== void 0 && before !== void 0 && !sameScene(here, before, places)) return "scene";
1108
+ if (reflection.sceneDays > 0 && now - anchor.now >= reflection.sceneDays * DAY_MS) return "scene";
1109
+ }
1110
+ /**
1111
+ * 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
1112
+ * still a draft, so that nothing is passed over that is sealed later.
1113
+ */
1114
+ function materialOf(session, minNew) {
1115
+ const cursor = readCursor(session);
1116
+ const found = [];
1117
+ for (const character of session.characters.list()) {
1118
+ if (character.control !== "agent" || character.kind !== "person" || character.tier === "background") continue;
1119
+ const taken = session.events.perceivedBy(character.id);
1120
+ const draft = taken.filter((entry) => !entry.event.sealed).map((entry) => entry.perception.id);
1121
+ const ceiling = draft.length === 0 ? Infinity : Math.min(...draft) - 1;
1122
+ 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);
1123
+ if (fresh.length < minNew) continue;
1124
+ const beliefs = session.memories.list(character.id).sort((a, b) => b.importance - a.importance || a.id - b.id).slice(0, MAX_BELIEFS_SHOWN);
1125
+ found.push({
1126
+ character,
1127
+ fresh,
1128
+ beliefs
1129
+ });
1130
+ }
1131
+ return found.sort((a, b) => b.fresh.length - a.fresh.length);
1132
+ }
1133
+ const idList = {
1134
+ type: "array",
1135
+ items: { type: "integer" }
1136
+ };
1137
+ const RESULT = {
1138
+ type: "object",
1139
+ properties: {
1140
+ add: {
1141
+ type: "array",
1142
+ description: "New beliefs, at most four. Leave empty when nothing new can be firmly said.",
1143
+ items: {
1144
+ type: "object",
1145
+ properties: {
1146
+ kind: {
1147
+ type: "string",
1148
+ enum: [...MEMORY_KINDS],
1149
+ description: "belief: what it holds true or suspects; relationship: how it stands with someone; knowledge: something it knows."
1150
+ },
1151
+ text: {
1152
+ type: "string",
1153
+ 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."
1154
+ },
1155
+ about: {
1156
+ type: "array",
1157
+ items: { type: "string" },
1158
+ description: "The names of the characters it is about."
1159
+ },
1160
+ importance: {
1161
+ type: "integer",
1162
+ description: `From 1 (passing) to 5 (it shapes how they act).`
1163
+ },
1164
+ confidence: {
1165
+ type: "string",
1166
+ enum: [...MEMORY_CONFIDENCES],
1167
+ description: "How sure they are: doubtful, likely (when you leave it out) or sure, which needs things from at least two different turns."
1168
+ },
1169
+ perceptions: {
1170
+ ...idList,
1171
+ description: "The numbers of the things it took in that this rests on."
1172
+ },
1173
+ beliefs: {
1174
+ ...idList,
1175
+ description: "The numbers of the beliefs it generalises or builds on, if any."
1176
+ }
1177
+ },
1178
+ required: [
1179
+ "kind",
1180
+ "text",
1181
+ "importance",
1182
+ "perceptions"
1183
+ ],
1184
+ additionalProperties: false
1185
+ }
1186
+ },
1187
+ revise: {
1188
+ type: "array",
1189
+ description: "Beliefs to firm up, doubt or correct in the light of what came after them.",
1190
+ items: {
1191
+ type: "object",
1192
+ properties: {
1193
+ id: {
1194
+ type: "integer",
1195
+ description: "The number of the belief, as listed."
1196
+ },
1197
+ text: {
1198
+ type: "string",
1199
+ description: "The belief as it should read now."
1200
+ },
1201
+ importance: {
1202
+ type: "integer",
1203
+ description: `From 1 to 5.`
1204
+ },
1205
+ confidence: {
1206
+ type: "string",
1207
+ enum: [...MEMORY_CONFIDENCES],
1208
+ description: "How sure they are now. Raise it only for what supports the belief; lower it only together with contradicted_by."
1209
+ },
1210
+ perceptions: {
1211
+ ...idList,
1212
+ description: "The numbers of the things it took in since that support the belief or bear on it."
1213
+ },
1214
+ contradicted_by: {
1215
+ ...idList,
1216
+ description: "The numbers of the things it took in since that speak against the belief; the belief is then doubted, and its confidence must be lowered."
1217
+ }
1218
+ },
1219
+ required: ["id"],
1220
+ additionalProperties: false
1221
+ }
1222
+ },
1223
+ doubt: {
1224
+ type: "array",
1225
+ description: "Beliefs that something the character took in since speaks against, which it still holds but with more doubt: name the belief and the numbers of what speaks against it, and its confidence is lowered for you. This is the way to answer a belief that a later event contradicts, instead of revising or dropping it.",
1226
+ items: {
1227
+ type: "object",
1228
+ properties: {
1229
+ id: {
1230
+ type: "integer",
1231
+ description: "The number of the belief, as listed."
1232
+ },
1233
+ contradicted_by: {
1234
+ ...idList,
1235
+ description: "The numbers of the things it took in since that speak against the belief."
1236
+ },
1237
+ text: {
1238
+ type: "string",
1239
+ description: "The belief reworded to say what is now in doubt, when its words need it; one or two sentences, and nothing but the belief: its confidence and the numbers are not part of the text."
1240
+ }
1241
+ },
1242
+ required: ["id", "contradicted_by"],
1243
+ additionalProperties: false
1244
+ }
1245
+ },
1246
+ drop: {
1247
+ type: "array",
1248
+ description: "Beliefs to let go: settled or overturned by what came after, or merged into another.",
1249
+ items: {
1250
+ type: "object",
1251
+ properties: {
1252
+ id: { type: "integer" },
1253
+ perceptions: {
1254
+ ...idList,
1255
+ description: "What it took in since that settles or overturns it."
1256
+ },
1257
+ merged_into: {
1258
+ type: "integer",
1259
+ description: "The number of the belief that now says the same, instead of a reason from what it took in."
1260
+ }
1261
+ },
1262
+ required: ["id"],
1263
+ additionalProperties: false
1264
+ }
1265
+ }
1266
+ },
1267
+ required: [
1268
+ "add",
1269
+ "revise",
1270
+ "drop"
1271
+ ],
1272
+ additionalProperties: false
1273
+ };
1274
+ function shownOf(session, material) {
1275
+ const turnOf = (perceptionId) => {
1276
+ const seen = session.events.getPerception(perceptionId);
1277
+ return seen === void 0 ? void 0 : session.events.get(seen.eventId)?.turn;
1278
+ };
1279
+ return {
1280
+ perceptions: new Map(material.fresh.map((entry) => [entry.perception.id, entry])),
1281
+ beliefs: new Map(material.beliefs.map((belief) => [belief.id, belief])),
1282
+ supportTurns: new Map(material.beliefs.map((belief) => [belief.id, new Set(session.memories.evidenceOf(belief.id).filter((entry) => entry.relation === "supports").flatMap((entry) => turnOf(entry.perceptionId) ?? []))]))
1283
+ };
1284
+ }
1285
+ const rankOf = (confidence) => MEMORY_CONFIDENCES.indexOf(confidence);
1286
+ /** What a model writes into a belief's text when it has not put it in the fields: its confidence, importance or the numbers it rests on. */
1287
+ const MIXED_IN = /\((?:[^)]*\b(?:doubtful|likely|sure|importance)\b[^)]*|[^)]*\bperceptions?\s*\[?\d[^)]*)\)|\bperceptions?\s*\[\d/i;
1288
+ /** One step less sure, and no less than doubtful. */
1289
+ const lowered = (confidence) => MEMORY_CONFIDENCES[Math.max(0, rankOf(confidence) - 1)];
1290
+ /**
1291
+ * 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
1292
+ * 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
1293
+ * into another. Nothing is judged about whether the belief is wise; only whether it is grounded in what the character was given.
1294
+ */
1295
+ function proposalProblems(proposal, shown, resolveName, tr = translator("en")) {
1296
+ const problems = [];
1297
+ const add = proposal.add ?? [];
1298
+ const revise = proposal.revise ?? [];
1299
+ const drop = proposal.drop ?? [];
1300
+ const doubt = proposal.doubt ?? [];
1301
+ if (add.length > MAX_ADDED) problems.push(tr("add: at most {max} new beliefs in one pass; merge or choose", { max: MAX_ADDED }));
1302
+ if (add.length + revise.length + drop.length + doubt.length > MAX_CHANGES) problems.push(tr("at most {max} changes in one pass", { max: MAX_CHANGES }));
1303
+ const cited = (ids, where) => (ids ?? []).flatMap((id) => {
1304
+ const entry = shown.perceptions.get(id);
1305
+ if (entry === void 0) problems.push(tr("{where}: there is no thing it took in numbered {id}", {
1306
+ where,
1307
+ id
1308
+ }));
1309
+ return entry === void 0 ? [] : [entry];
1310
+ });
1311
+ const known = (value, where) => {
1312
+ const fine = value === void 0 || MEMORY_CONFIDENCES.includes(value);
1313
+ if (!fine) problems.push(tr("{where}: confidence is one of {options}", {
1314
+ where,
1315
+ options: MEMORY_CONFIDENCES.join(", ")
1316
+ }));
1317
+ return fine;
1318
+ };
1319
+ add.forEach((belief, index) => {
1320
+ const where = `add[${index}]`;
1321
+ if (!MEMORY_KINDS.includes(belief.kind)) problems.push(tr("{where}: unknown kind \"{kind}\"", {
1322
+ where,
1323
+ kind: belief.kind
1324
+ }));
1325
+ if (belief.text.trim() === "") problems.push(tr("{where}: say what it believes", { where }));
1326
+ else if (belief.text.trim().length > MAX_TEXT) problems.push(tr("{where}: at most {max} characters; say it shorter", {
1327
+ where,
1328
+ max: MAX_TEXT
1329
+ }));
1330
+ if (!Number.isInteger(belief.importance) || belief.importance < 1 || belief.importance > 5) problems.push(tr("{where}: importance runs from {min} to {max}", {
1331
+ where,
1332
+ min: 1,
1333
+ max: 5
1334
+ }));
1335
+ const sure = known(belief.confidence, where) && belief.confidence === "sure";
1336
+ const events = cited(belief.perceptions, where);
1337
+ const built = (belief.beliefs ?? []).flatMap((id) => {
1338
+ const found = shown.beliefs.get(id);
1339
+ if (found === void 0) problems.push(tr("{where}: there is no belief numbered {id}", {
1340
+ where,
1341
+ id
1342
+ }));
1343
+ return found === void 0 ? [] : [found];
1344
+ });
1345
+ const turns = /* @__PURE__ */ new Set([...events.map((entry) => entry.event.turn), ...built.map((found) => found.turn)]);
1346
+ if (turns.size < 2 && !events.some((entry) => entry.event.importance >= DECISIVE_IMPORTANCE)) problems.push(tr("{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", { where }));
1347
+ if (sure && turns.size < 2) problems.push(tr("{where}: to be sure of something it must rest on things from at least two different turns", { where }));
1348
+ for (const name of belief.about ?? []) if (resolveName(name) === void 0) problems.push(tr("{where}: \"{name}\" is not a character; name them as they are named", {
1349
+ where,
1350
+ name
1351
+ }));
1352
+ });
1353
+ const touched = /* @__PURE__ */ new Set();
1354
+ const touch = (id, where) => {
1355
+ if (touched.has(id)) problems.push(tr("{where}: belief {id} is already changed in this pass", {
1356
+ where,
1357
+ id
1358
+ }));
1359
+ touched.add(id);
1360
+ };
1361
+ const fresh = (events, belief, where) => {
1362
+ if (events.length === 0) problems.push(tr("{where}: say what it took in since that bears on it", { where }));
1363
+ for (const entry of events) if (entry.event.turn < belief.turn) problems.push(tr("{where}: thing {id} came before the belief was formed; cite what came after", {
1364
+ where,
1365
+ id: entry.perception.id
1366
+ }));
1367
+ };
1368
+ revise.forEach((change, index) => {
1369
+ const where = `revise[${index}]`;
1370
+ const belief = shown.beliefs.get(change.id);
1371
+ if (belief === void 0) {
1372
+ problems.push(tr("{where}: there is no belief numbered {id}", {
1373
+ where,
1374
+ id: change.id
1375
+ }));
1376
+ return;
1377
+ }
1378
+ touch(change.id, where);
1379
+ const supports = cited(change.perceptions, where);
1380
+ const against = cited(change.contradicted_by, where);
1381
+ if (change.text === void 0 && change.importance === void 0 && change.confidence === void 0 && against.length === 0) problems.push(tr("{where}: say what changes", { where }));
1382
+ if (change.text !== void 0 && change.text.trim().length > MAX_TEXT) problems.push(tr("{where}: the text is longer than {max} characters. A belief is not rewritten to hold what speaks against it: leave the text out and list the belief under doubt with the numbers of what speaks against it, and put what was learned as a new belief of its own", {
1383
+ where,
1384
+ max: MAX_TEXT
1385
+ }));
1386
+ else if (change.text !== void 0 && change.text.trim() === "") problems.push(tr("{where}: the text must be there and at most {max} characters; leave it out to keep the belief as it is", {
1387
+ where,
1388
+ max: MAX_TEXT
1389
+ }));
1390
+ if (change.text !== void 0 && MIXED_IN.test(change.text)) problems.push(tr("{where}: the confidence, the importance and the numbers are fields of their own, not part of the text", { where }));
1391
+ if (change.importance !== void 0 && (!Number.isInteger(change.importance) || change.importance < 1 || change.importance > 5)) problems.push(tr("{where}: importance runs from {min} to {max}", {
1392
+ where,
1393
+ min: 1,
1394
+ max: 5
1395
+ }));
1396
+ fresh([...supports, ...against], belief, where);
1397
+ if (!known(change.confidence, where) || change.confidence === void 0) {
1398
+ if (against.length > 0) problems.push(tr("{where}: a belief that something contradicts must be doubted: lower its confidence", { where }));
1399
+ return;
1400
+ }
1401
+ if (against.length > 0 && rankOf(change.confidence) >= rankOf(belief.confidence)) problems.push(tr("{where}: a belief that something contradicts must be doubted: lower its confidence", { where }));
1402
+ if (against.length === 0 && rankOf(change.confidence) < rankOf(belief.confidence)) problems.push(tr("{where}: to doubt a belief, name what contradicts it in contradicted_by", { where }));
1403
+ if (change.confidence === "sure" && belief.confidence !== "sure") {
1404
+ if ((/* @__PURE__ */ new Set([...shown.supportTurns?.get(belief.id) ?? [], ...supports.map((entry) => entry.event.turn)])).size < 2) problems.push(tr("{where}: to be sure of something it must rest on things from at least two different turns", { where }));
1405
+ }
1406
+ });
1407
+ doubt.forEach((change, index) => {
1408
+ const where = `doubt[${index}]`;
1409
+ const belief = shown.beliefs.get(change.id);
1410
+ if (belief === void 0) {
1411
+ problems.push(tr("{where}: there is no belief numbered {id}", {
1412
+ where,
1413
+ id: change.id
1414
+ }));
1415
+ return;
1416
+ }
1417
+ touch(change.id, where);
1418
+ const against = cited(change.contradicted_by, where);
1419
+ if (against.length === 0) problems.push(tr("{where}: name what speaks against the belief in contradicted_by", { where }));
1420
+ fresh(against, belief, where);
1421
+ if (change.text !== void 0 && (change.text.trim() === "" || change.text.trim().length > MAX_TEXT)) problems.push(tr("{where}: the text must be there and at most {max} characters; leave it out to keep the belief as it is", {
1422
+ where,
1423
+ max: MAX_TEXT
1424
+ }));
1425
+ if (change.text !== void 0 && MIXED_IN.test(change.text)) problems.push(tr("{where}: the confidence, the importance and the numbers are fields of their own, not part of the text", { where }));
1426
+ });
1427
+ const dropped = new Set(drop.map((entry) => entry.id));
1428
+ drop.forEach((change, index) => {
1429
+ const where = `drop[${index}]`;
1430
+ const belief = shown.beliefs.get(change.id);
1431
+ if (belief === void 0) {
1432
+ problems.push(tr("{where}: there is no belief numbered {id}", {
1433
+ where,
1434
+ id: change.id
1435
+ }));
1436
+ return;
1437
+ }
1438
+ touch(change.id, where);
1439
+ if (change.merged_into !== void 0) {
1440
+ if (change.merged_into === change.id || !shown.beliefs.has(change.merged_into) || dropped.has(change.merged_into)) problems.push(tr("{where}: merge into a belief that stays", { where }));
1441
+ return;
1442
+ }
1443
+ fresh(cited(change.perceptions, where), belief, where);
1444
+ });
1445
+ return problems;
1446
+ }
1447
+ /**
1448
+ * The proposal with its mechanical mistakes mended instead of refused: things cited that were not shown, beliefs that do not exist, names that are
1449
+ * not characters, confidence the evidence cannot carry, changes that name a belief twice, and new beliefs that rest on one passing moment. A model
1450
+ * that is refused such a thing sends it again, five times, and the pass is lost; mended, the proposal is what the refusal would have asked for.
1451
+ * What needs the model's judgment (the words of a belief, what it rests on when nothing valid is left) is still refused by `proposalProblems`.
1452
+ */
1453
+ /** A text cut to the limit at the end of a sentence, or failing that at a word. */
1454
+ function shortened(text) {
1455
+ const trimmed = text.trim();
1456
+ if (trimmed.length <= MAX_TEXT) return trimmed;
1457
+ const head = trimmed.slice(0, MAX_TEXT);
1458
+ const sentence = Math.max(head.lastIndexOf(". "), head.lastIndexOf("! "), head.lastIndexOf("? "), head.lastIndexOf("。"), head.lastIndexOf("!"), head.lastIndexOf("?"));
1459
+ if (sentence >= MAX_TEXT / 3) return head.slice(0, sentence + 1).trim();
1460
+ const word = head.lastIndexOf(" ");
1461
+ return (word >= MAX_TEXT / 2 ? head.slice(0, word) : head.slice(0, 299)).trim() + "…";
1462
+ }
1463
+ /** What a rewrite of an existing belief keeps of its text: nothing when it is too long, because a belief is doubted for what speaks against it, not rewritten. */
1464
+ const keptText = (text) => text === void 0 || text.trim() === "" || text.trim().length > MAX_TEXT ? {} : { text };
1465
+ function settleProposal(proposal, shown, resolveName) {
1466
+ const known = (ids) => [...new Set(ids ?? [])].filter((id) => shown.perceptions.has(id));
1467
+ const after = (ids, belief) => known(ids).filter((id) => shown.perceptions.get(id).event.turn >= belief.turn);
1468
+ const turnsOf = (ids, built) => /* @__PURE__ */ new Set([...ids.map((id) => shown.perceptions.get(id).event.turn), ...built.map((found) => found.turn)]);
1469
+ const decisive = (ids) => ids.some((id) => shown.perceptions.get(id).event.importance >= DECISIVE_IMPORTANCE);
1470
+ const clamp = (importance) => Math.min(5, Math.max(1, Math.round(importance)));
1471
+ const add = (proposal.add ?? []).flatMap((belief) => {
1472
+ if (typeof belief.text !== "string" || belief.text.trim() === "") return [];
1473
+ const perceptions = known(belief.perceptions);
1474
+ const built = [...new Set(belief.beliefs ?? [])].flatMap((id) => shown.beliefs.get(id) ?? []);
1475
+ const turns = turnsOf(perceptions, built);
1476
+ if (turns.size < 2 && !decisive(perceptions)) return [];
1477
+ const about = (belief.about ?? []).filter((name) => resolveName(name) !== void 0);
1478
+ const { confidence: _confidence, ...rest } = belief;
1479
+ const confidence = belief.confidence === "sure" && turns.size < 2 ? "likely" : belief.confidence;
1480
+ return [{
1481
+ ...rest,
1482
+ text: shortened(belief.text),
1483
+ kind: MEMORY_KINDS.includes(belief.kind) ? belief.kind : "belief",
1484
+ importance: clamp(belief.importance),
1485
+ perceptions,
1486
+ beliefs: built.map((found) => found.id),
1487
+ about,
1488
+ ...confidence === void 0 ? {} : { confidence }
1489
+ }];
1490
+ }).slice(0, MAX_ADDED);
1491
+ const taken = /* @__PURE__ */ new Set();
1492
+ const fresh = (changes, mend) => (changes ?? []).flatMap((change) => {
1493
+ const belief = shown.beliefs.get(change.id);
1494
+ if (belief === void 0 || taken.has(change.id)) return [];
1495
+ const mended = mend(change, belief);
1496
+ if (mended !== void 0) taken.add(change.id);
1497
+ return mended === void 0 ? [] : [mended];
1498
+ });
1499
+ const doubt = fresh(proposal.doubt, (change, belief) => {
1500
+ const against = after(change.contradicted_by, belief);
1501
+ const { text: _text, ...rest } = change;
1502
+ return against.length === 0 ? void 0 : {
1503
+ ...rest,
1504
+ ...keptText(change.text),
1505
+ contradicted_by: against
1506
+ };
1507
+ });
1508
+ const revise = fresh(proposal.revise, (change, belief) => {
1509
+ const supports = after(change.perceptions, belief);
1510
+ const against = after(change.contradicted_by, belief);
1511
+ const { confidence, text: _text, ...rest } = change;
1512
+ let mended = confidence;
1513
+ if (confidence !== void 0 && !MEMORY_CONFIDENCES.includes(confidence)) mended = void 0;
1514
+ else if (confidence !== void 0 && against.length > 0 && rankOf(confidence) >= rankOf(belief.confidence)) mended = lowered(belief.confidence);
1515
+ else if (confidence !== void 0 && against.length === 0 && rankOf(confidence) < rankOf(belief.confidence)) mended = void 0;
1516
+ else if (confidence === "sure" && belief.confidence !== "sure" && (/* @__PURE__ */ new Set([...shown.supportTurns?.get(belief.id) ?? [], ...supports.map((id) => shown.perceptions.get(id).event.turn)])).size < 2) mended = void 0;
1517
+ const result = {
1518
+ ...rest,
1519
+ ...keptText(change.text),
1520
+ perceptions: supports,
1521
+ contradicted_by: against,
1522
+ ...mended === void 0 ? {} : { confidence: mended },
1523
+ ...change.importance === void 0 ? {} : { importance: clamp(change.importance) }
1524
+ };
1525
+ return result.text === void 0 && result.importance === void 0 && result.confidence === void 0 && against.length === 0 ? void 0 : result;
1526
+ });
1527
+ const drop = fresh(proposal.drop, (change, belief) => {
1528
+ if (change.merged_into !== void 0 && change.merged_into !== change.id && shown.beliefs.has(change.merged_into) && !(proposal.drop ?? []).some((other) => other.id === change.merged_into)) return {
1529
+ id: change.id,
1530
+ merged_into: change.merged_into
1531
+ };
1532
+ const settled = after(change.perceptions, belief);
1533
+ return settled.length === 0 ? void 0 : {
1534
+ id: change.id,
1535
+ perceptions: settled
1536
+ };
1537
+ });
1538
+ const room = Math.max(0, MAX_CHANGES - add.length);
1539
+ const changes = [
1540
+ ...revise.map((change) => ["revise", change]),
1541
+ ...doubt.map((change) => ["doubt", change]),
1542
+ ...drop.map((change) => ["drop", change])
1543
+ ].slice(0, room);
1544
+ const only = (kind) => changes.filter((entry) => entry[0] === kind).map((entry) => entry[1]);
1545
+ return {
1546
+ add,
1547
+ revise: only("revise"),
1548
+ doubt: only("doubt"),
1549
+ drop: only("drop")
1550
+ };
1551
+ }
1552
+ /**
1553
+ * The proposal with every contradiction the checks found doubted. What the proposal itself does to such a belief (revise, doubt or drop it) is replaced by
1554
+ * the doubt: a belief that something contradicts is not rewritten or let go in the same pass, and what was learned stays in the new beliefs it adds.
1555
+ */
1556
+ function withDoubts(proposal, found) {
1557
+ if (found.length === 0) return proposal;
1558
+ const doubted = new Set(found.map((entry) => entry.belief));
1559
+ const kept = (changes) => (changes ?? []).filter((change) => !doubted.has(change.id));
1560
+ return {
1561
+ ...proposal,
1562
+ revise: kept(proposal.revise),
1563
+ drop: kept(proposal.drop),
1564
+ doubt: [...kept(proposal.doubt), ...found.map((entry) => ({
1565
+ id: entry.belief,
1566
+ contradicted_by: entry.things
1567
+ }))]
1568
+ };
1569
+ }
1570
+ const keysOf = (names, resolveName) => (names ?? []).flatMap((name) => {
1571
+ const key = resolveName(name);
1572
+ return key === void 0 ? [] : [key];
1573
+ });
1574
+ /** The edit that writes a proposal that passed. */
1575
+ function editOf(turn, character, proposal, resolveName, confidenceOf = () => void 0) {
1576
+ const who = characterKey(character);
1577
+ return {
1578
+ turn,
1579
+ beliefs: (proposal.add ?? []).map((belief) => ({
1580
+ character: who,
1581
+ kind: belief.kind,
1582
+ text: belief.text.trim(),
1583
+ about: keysOf(belief.about, resolveName),
1584
+ importance: belief.importance,
1585
+ ...belief.confidence === void 0 ? {} : { confidence: belief.confidence },
1586
+ evidenceFor: belief.perceptions ?? []
1587
+ })),
1588
+ beliefEdits: [...proposal.revise ?? [], ...(proposal.doubt ?? []).map((change) => ({
1589
+ id: change.id,
1590
+ ...change.text === void 0 ? {} : { text: change.text },
1591
+ confidence: lowered(confidenceOf(change.id) ?? "likely"),
1592
+ contradicted_by: change.contradicted_by
1593
+ }))].map((change) => ({
1594
+ id: change.id,
1595
+ ...change.text === void 0 ? {} : { text: change.text.trim() },
1596
+ ..."importance" in change && change.importance !== void 0 ? { importance: change.importance } : {},
1597
+ ...change.confidence === void 0 ? {} : { confidence: change.confidence },
1598
+ evidenceFor: "perceptions" in change ? change.perceptions ?? [] : [],
1599
+ evidenceAgainst: change.contradicted_by ?? []
1600
+ })),
1601
+ beliefRetractions: (proposal.drop ?? []).map((change) => change.id)
1602
+ };
1603
+ }
1604
+ /** The most things a belief is pointed at: the model checks a few against it, not everything. */
1605
+ const MAX_BEARING = 4;
1606
+ /** How many words, besides these, a belief and a thing taken in must share for one to be pointed at the other. */
1607
+ const SHARED_WORDS = 2;
1608
+ const FUNCTION_WORDS = new Set("the and that with have has had from which they them their this these those were was been being are for not but you your our his her its who whom what when where why how into onto about after before over under then than there here would could should will just also only some any all out too very can may might must did does done doing got get".split(" "));
1609
+ /**
1610
+ * What the character took in since that bears on a belief, which is where a contradiction is found: a model told only to look for one rationalises, but
1611
+ * one pointed at the few things about the same subject compares them. A thing bears on a belief when its event involves the people the belief is about,
1612
+ * or when it shares words with the belief (beliefs are often about a subject and no one in particular).
1613
+ */
1614
+ function bearingOn(belief, fresh) {
1615
+ const people = fresh.filter((entry) => belief.about.length > 0 && entry.event.involves.some((id) => belief.about.includes(id))).slice(-4);
1616
+ const own = [...tokens(belief.text)].filter((token) => !FUNCTION_WORDS.has(token));
1617
+ const chosen = new Set(people.map((entry) => entry.perception.id));
1618
+ const alike = fresh.map((entry) => {
1619
+ const words = tokens(entry.perception.content);
1620
+ return {
1621
+ id: entry.perception.id,
1622
+ shared: own.filter((token) => words.has(token)).length
1623
+ };
1624
+ }).filter((entry) => entry.shared >= SHARED_WORDS && !chosen.has(entry.id)).sort((a, b) => b.shared - a.shared || b.id - a.id).slice(0, MAX_BEARING - chosen.size);
1625
+ return [...chosen, ...alike.map((entry) => entry.id)].sort((x, y) => x - y);
1626
+ }
1627
+ /** The most beliefs of one character checked against what bears on them in one pass: each is a request of its own. */
1628
+ const MAX_CHECKS = 6;
1629
+ /** The fewest things taken in that a failed sorting is tried again with half of. */
1630
+ const MIN_TO_HALVE = 8;
1631
+ const CHECK_RESULT = {
1632
+ type: "object",
1633
+ properties: {
1634
+ reason: {
1635
+ type: "string",
1636
+ description: "One short sentence, written first, without quotation marks: what the belief claims and what the things say, side by side, and whether they can all be true together."
1637
+ },
1638
+ things: {
1639
+ ...idList,
1640
+ description: "The numbers of the things that cannot be true together with the belief; none when they all can be."
1641
+ },
1642
+ verdict: {
1643
+ type: "string",
1644
+ enum: ["consistent", "contradicted"],
1645
+ description: "consistent: the belief and every one of the things can be true together; contradicted: at least one thing cannot be true if the belief is."
1646
+ }
1647
+ },
1648
+ required: [
1649
+ "reason",
1650
+ "things",
1651
+ "verdict"
1652
+ ],
1653
+ additionalProperties: false
1654
+ };
1655
+ /** Why an answer to the check of one belief cannot be taken, or nothing when it can. */
1656
+ function checkProblem(answer, belief, shown, near, tr = translator("en")) {
1657
+ if ((answer.reason ?? "").trim() === "") return tr("say in a sentence what the belief claims and what the things say, before the verdict");
1658
+ if (answer.verdict !== "consistent" && answer.verdict !== "contradicted") return tr("the verdict is consistent or contradicted");
1659
+ const things = answer.things ?? [];
1660
+ if (answer.verdict === "consistent") return things.length === 0 ? void 0 : tr("a belief that can be true together with all of them names none of them");
1661
+ if (things.length === 0) return tr("name the things that cannot be true together with the belief");
1662
+ for (const id of things) {
1663
+ const entry = shown.perceptions.get(id);
1664
+ if (!near.has(id) || entry === void 0) return tr("there is no thing listed numbered {id}", { id });
1665
+ if (entry.event.turn < belief.turn) return tr("thing {id} came before the belief was formed", { id });
1666
+ }
1667
+ }
1668
+ function checkBrief(character, belief, things, now, zone, time, tr) {
1669
+ return [
1670
+ tr("A belief held by {name}: {text}", {
1671
+ name: referent(character),
1672
+ text: belief.text
1673
+ }),
1674
+ tr("What they took in since that bears on it:"),
1675
+ ...things.map((entry) => {
1676
+ const at = time(entry.event.turn, entry.event.round);
1677
+ return `- p${entry.perception.id}${at === void 0 ? "" : ` (${describeWhen(at, now, zone)})`}: ${entry.perception.content}`;
1678
+ }),
1679
+ tr("Can the belief and each of these be true together? Name the ones that cannot be.")
1680
+ ].join("\n");
1681
+ }
1682
+ function brief(session, material, doubted, now, zone, time, tr) {
1683
+ const { character, fresh, beliefs } = material;
1684
+ const named = (id) => session.characters.get(id)?.name ?? String(id);
1685
+ const { disputed } = session.memories.evidenceIndex(character.id);
1686
+ const believed = beliefs.map((belief) => {
1687
+ const about = belief.about.length === 0 ? "" : tr(", about {names}", { names: belief.about.map(named).join(tr(" and ")) });
1688
+ const dispute = disputed.has(belief.id) || doubted.has(belief.id) ? tr(", something taken in since speaks against it") : "";
1689
+ return `- b${belief.id} (${tr("{kind}, importance {importance}, {confidence}{about}{dispute}", {
1690
+ kind: belief.kind,
1691
+ importance: belief.importance,
1692
+ confidence: tr(belief.confidence),
1693
+ about,
1694
+ dispute
1695
+ })}): ${belief.text}`;
1696
+ });
1697
+ const taken = fresh.map((entry) => {
1698
+ const at = time(entry.event.turn, entry.event.round);
1699
+ return `- p${entry.perception.id}${at === void 0 ? "" : ` (${describeWhen(at, now, zone)})`}: ${entry.perception.content}`;
1700
+ });
1701
+ return [
1702
+ tr("Character: {name}{summary}", {
1703
+ name: referent(character),
1704
+ summary: character.summary === "" ? "" : ` - ${character.summary}`
1705
+ }),
1706
+ tr("What they believe now:"),
1707
+ ...believed.length === 0 ? [tr("(nothing yet)")] : believed,
1708
+ tr("What they have taken in since:"),
1709
+ ...taken,
1710
+ tr("Sort their memory.")
1711
+ ].join("\n");
1712
+ }
1713
+ /**
1714
+ * 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
1715
+ * 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
1716
+ * and leaves the characters not yet done as they were.
1717
+ */
1718
+ function memoryReflector(deps) {
1719
+ return { async reflect(job, signal) {
1720
+ const parent = deps.agentOf(job.chat);
1721
+ if (parent === void 0) throw new Error(`no agent for chat ${job.chat}`);
1722
+ const { store } = job;
1723
+ const session = store.story;
1724
+ const settings = store.settings();
1725
+ const { now, zone } = store.time(job.turn);
1726
+ const due = materialOf(session, job.reason === "manual" ? 1 : settings.reflection.minNew);
1727
+ const taken = job.reason === "manual" ? due : due.slice(0, settings.reflection.perRun);
1728
+ const resolveName = (name) => {
1729
+ const found = session.characters.findByName(name.trim());
1730
+ return found.length === 1 ? characterKey(found[0]) : void 0;
1731
+ };
1732
+ const tr = translator(languageOf(settings.prompts.language));
1733
+ const characters = [];
1734
+ const failures = [];
1735
+ const sort = async (material) => {
1736
+ const shown = shownOf(session, material);
1737
+ const found = [];
1738
+ let checked = 0;
1739
+ for (const belief of material.beliefs) {
1740
+ const near = bearingOn(belief, material.fresh);
1741
+ if (near.length === 0 || checked >= MAX_CHECKS) continue;
1742
+ checked += 1;
1743
+ const things = near.flatMap((id) => shown.perceptions.get(id) ?? []);
1744
+ let verdict;
1745
+ try {
1746
+ verdict = await runChild({
1747
+ parent,
1748
+ signal,
1749
+ reasoningEffort: settings.reasoning.children,
1750
+ sampling: childSampling(settings, "records", estimateAnswer([MAX_TEXT * 2, 100], settings.prompts.language)),
1751
+ ...childModel(settings, "records"),
1752
+ trace: childTrace(store, "records", `reflection check ${material.character.name} b${belief.id}`),
1753
+ persona: promptFor(parent, "roleplay/reflection-check", settings.prompts.language),
1754
+ prompt: checkBrief(material.character, belief, things, now, zone, (turn, round) => session.clock.at(turn, round), tr),
1755
+ result: CHECK_RESULT,
1756
+ beforeSubmit: (value) => {
1757
+ const problem = checkProblem(value, belief, shown, new Set(near), tr);
1758
+ return problem === void 0 ? void 0 : tr("not acceptable: {problems}", { problems: problem });
1759
+ },
1760
+ maxCalls: 2
1761
+ });
1762
+ } catch (error) {
1763
+ if (signal.aborted) throw error;
1764
+ }
1765
+ if (verdict?.verdict === "contradicted") found.push({
1766
+ belief: belief.id,
1767
+ things: verdict.things
1768
+ });
1769
+ }
1770
+ const doubted = new Set(found.map((entry) => entry.belief));
1771
+ const proposal = withDoubts(settleProposal(await runChild({
1772
+ parent,
1773
+ signal,
1774
+ reasoningEffort: settings.reasoning.children,
1775
+ sampling: childSampling(settings, "records", estimateAnswer(Array.from({ length: 14 }, () => MAX_TEXT), settings.prompts.language)),
1776
+ ...childModel(settings, "records"),
1777
+ trace: childTrace(store, "records", `reflection ${material.character.name}`),
1778
+ persona: promptFor(parent, "roleplay/reflection", settings.prompts.language),
1779
+ prompt: brief(session, material, doubted, now, zone, (turn, round) => session.clock.at(turn, round), tr),
1780
+ result: RESULT,
1781
+ beforeSubmit: (value) => {
1782
+ const given = settleProposal(value, shown, resolveName);
1783
+ const problems = [...proposalProblems(given, shown, resolveName, tr), ...[wrongLanguage(settings.prompts.language, { beliefs: [
1784
+ ...given.add ?? [],
1785
+ ...given.revise ?? [],
1786
+ ...given.doubt ?? []
1787
+ ].map((belief) => belief.text ?? "").join(" ") })].flatMap((problem) => problem === void 0 ? [] : [problem])];
1788
+ return problems.length === 0 ? void 0 : tr("not acceptable: {problems}", { problems: problems.join("; ") });
1789
+ },
1790
+ maxCalls: 3
1791
+ }), shown, resolveName), found);
1792
+ const reached = Math.max(...material.fresh.map((entry) => entry.perception.id));
1793
+ session.transaction(() => {
1794
+ session.edit(editOf(job.turn, material.character, proposal, resolveName, (belief) => shown.beliefs.get(belief)?.confidence));
1795
+ session.metadata.setValue(CURSOR_KEY, {
1796
+ ...readCursor(session),
1797
+ [characterKey(material.character)]: reached
1798
+ });
1799
+ });
1800
+ return {
1801
+ name: material.character.name,
1802
+ added: proposal.add?.length ?? 0,
1803
+ revised: (proposal.revise?.length ?? 0) + (proposal.doubt?.length ?? 0),
1804
+ dropped: proposal.drop?.length ?? 0
1805
+ };
1806
+ };
1807
+ const sortWithRetry = async (material) => {
1808
+ try {
1809
+ return await sort(material);
1810
+ } catch (error) {
1811
+ if (signal.aborted || material.fresh.length < MIN_TO_HALVE) throw error;
1812
+ return await sort({
1813
+ ...material,
1814
+ fresh: material.fresh.slice(0, Math.ceil(material.fresh.length / 2))
1815
+ });
1816
+ }
1817
+ };
1818
+ for (const material of taken) try {
1819
+ characters.push(await sortWithRetry(material));
1820
+ } catch (error) {
1821
+ if (signal.aborted) throw error;
1822
+ failures.push(`${material.character.name}: ${error instanceof Error ? error.message : String(error)}`);
1823
+ }
1824
+ if (failures.length > 0 && characters.length === 0) throw new Error(failures.join("; "));
1825
+ session.metadata.setValue(LAST_KEY, {
1826
+ turn: job.turn,
1827
+ at: (/* @__PURE__ */ new Date()).toISOString(),
1828
+ reason: job.reason,
1829
+ characters
1830
+ });
1831
+ writeAnchor(session, playerPlace(store), now);
1832
+ if (failures.length > 0) recordFailure(session, tr("{names} could not be sorted this time and will be tried again: {reason}", {
1833
+ names: failures.map((entry) => entry.split(":")[0]).join(", "),
1834
+ reason: failures[0].slice(failures[0].indexOf(":") + 2)
1835
+ }));
1836
+ else session.metadata.deleteValue(ERROR_KEY);
1837
+ return { characters };
1838
+ } };
1839
+ }
1840
+ //#endregion
1841
+ export { whereabouts as a, readTimeline as c, sameWords as d, referent as f, reflectionStatus as i, pathTo as l, memoryReflector as n, TimelineError as o, recordFailure as r, Timelines as s, dueReflection as t, defaultBoundaries as u };
1842
+
1843
+ //# sourceMappingURL=reflection-md7BCYCl.js.map