@dsh-agentic-roleplay/core 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/lib/{chat-AKrVcWIC.js → access-EbNdZFbk.js} +10 -2
  2. package/lib/authoring.js +193 -227
  3. package/lib/client.js +2710 -1322
  4. package/lib/client.js.map +1 -1
  5. package/lib/compaction.js +2 -3
  6. package/lib/deliver-BDW5WZvc.js +2262 -0
  7. package/lib/{documents-Bu5uYRZB.js → documents-DtlY2IRt.js} +958 -10
  8. package/lib/{gallery-DUeBMHQX.js → gallery-DACG5eh2.js} +2 -2
  9. package/lib/{generator-HPifO3Kk.js → generator-DGYcLMp7.js} +2 -2
  10. package/lib/images.js +3 -3
  11. package/lib/index.js +419 -23
  12. package/lib/{narration-BRyHU0H2.js → narration-5ig7Dg28.js} +12 -2
  13. package/lib/orchestration.js +458 -342
  14. package/lib/{packs-ByP1J-zj.js → packs-CkRZDCsV.js} +51 -5
  15. package/lib/{presenter-agent-G43ODV8I.js → presenter-agent-PK9JYExk.js} +4 -4
  16. package/package.json +5 -4
  17. package/packs/scene/map.html +12 -0
  18. package/packs/scene/map.js +55 -0
  19. package/packs/scene/pack.json +11 -0
  20. package/packs/scene/strip.html +11 -0
  21. package/packs/scene/strip.js +26 -0
  22. package/packs/scene/style.css +16 -0
  23. package/prompts/en/roleplay/character-decide.md +1 -1
  24. package/prompts/en/roleplay/character-rules.md +1 -1
  25. package/prompts/en/roleplay/chronicler.md +1 -1
  26. package/prompts/en/roleplay/game-master.md +1 -1
  27. package/prompts/en/roleplay/reflection.md +9 -0
  28. package/prompts/en/roleplay/style.md +1 -1
  29. package/prompts/en/roleplay/suggester.md +1 -1
  30. package/prompts/en/translate/document.md +6 -0
  31. package/prompts/en/translate/glossary.md +5 -0
  32. package/prompts/en/translate/notice.md +2 -0
  33. package/prompts/en/world/procedure.md +1 -1
  34. package/prompts/en/world/welcome.md +1 -1
  35. package/prompts/zh/roleplay/character-decide.md +1 -1
  36. package/prompts/zh/roleplay/character-rules.md +1 -1
  37. package/prompts/zh/roleplay/chronicler.md +1 -1
  38. package/prompts/zh/roleplay/game-master.md +1 -1
  39. package/prompts/zh/roleplay/reflection.md +9 -0
  40. package/prompts/zh/roleplay/style.md +1 -1
  41. package/prompts/zh/roleplay/suggester.md +1 -1
  42. package/prompts/zh/translate/document.md +6 -0
  43. package/prompts/zh/translate/glossary.md +5 -0
  44. package/prompts/zh/translate/notice.md +2 -0
  45. package/prompts/zh/world/procedure.md +1 -1
  46. package/prompts/zh/world/welcome.md +1 -1
  47. package/lib/access-C1nFQiyT.js +0 -12
  48. package/lib/activity-t7OBgHlc.js +0 -1386
@@ -0,0 +1,2262 @@
1
+ import { r as roleplaySessionOf, t as promptFor } from "./access-EbNdZFbk.js";
2
+ import { K as SessionNotFoundError, P as inheritPrompts, S as wrongLanguage, i as inheritPacks } from "./packs-CkRZDCsV.js";
3
+ import "./src-CWTNeL6Y.js";
4
+ import { A as runChild, D as childSampling, E as childModel, j as estimateAnswer, k as childTrace, u as inheritImages } from "./generator-DGYcLMp7.js";
5
+ import { join } from "node:path";
6
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
7
+ import { createUserMessage } from "@deepseek-ai/dsh-llm";
8
+ import { DAY, MINUTE, SECOND, addLocalDays, characterKey, clockTime, dayPart, describeDuration, describeInstant, holidaysOn, isSessionId, localTime, locationKey, mentioned, nextTimeOfDay, overlap, readCalendar, seasonOf, sessionDatabase, sessionFolder, tokens } from "@dsh-agentic-roleplay/state";
9
+ //#region ../dsh-roleplay-model/src/memory.ts
10
+ const MEMORY_KINDS = [
11
+ "belief",
12
+ "relationship",
13
+ "knowledge"
14
+ ];
15
+ /** How sure a character is of what it believes, from least to most. */
16
+ const MEMORY_CONFIDENCES = [
17
+ "doubtful",
18
+ "likely",
19
+ "sure"
20
+ ];
21
+ //#endregion
22
+ //#region ../dsh-roleplay-model/src/messages-zh.ts
23
+ /** The Chinese of the texts built in code, by the English that stands in the code. A `{name}` is filled in and must stand in both. */
24
+ const ZH = {
25
+ ", ": ",",
26
+ "; ": ";",
27
+ ": ": ":",
28
+ ".": "。",
29
+ " and ": "和",
30
+ "doubtful": "存疑",
31
+ "likely": "较有把握",
32
+ "sure": "确信",
33
+ "open": "畅通",
34
+ "locked": "已上锁",
35
+ "blocked": "被堵住",
36
+ "night": "夜里",
37
+ "morning": "上午",
38
+ "afternoon": "下午",
39
+ "evening": "傍晚",
40
+ "spring": "春季",
41
+ "summer": "夏季",
42
+ "autumn": "秋季",
43
+ "winter": "冬季",
44
+ "today is {holidays}": "今天是{holidays}",
45
+ "Summary": "概述",
46
+ "Personality": "性格",
47
+ "Background": "背景",
48
+ "Appearance": "外貌",
49
+ "How you speak": "说话方式",
50
+ "You are {name}.": "你是{name}。",
51
+ "You are also called {names}.": "你也被称作{names}。",
52
+ "age: {value}": "年龄:{value}",
53
+ "gender: {value}": "性别:{value}",
54
+ "pronouns: {value}": "代词:{value}",
55
+ "Situation:": "当前情形:",
56
+ "Now: {time}.": "现在是:{time}。",
57
+ "Where you are:": "你所在之处:",
58
+ "Present:": "在场的人:",
59
+ " (you)": "(你)",
60
+ "What you know is coming:": "你知道即将发生的事:",
61
+ "Just now you notice:": "此刻你注意到:",
62
+ "How you are (what you can tell of yourself):": "你的状态(你自己能感觉到的):",
63
+ "What you can tell of the others here:": "你能看出在场其他人的情况:",
64
+ "What you have on you:": "你身上带着:",
65
+ "Things here: ": "这里有:",
66
+ "Ways out: ": "出路:",
67
+ "Lying about: ": "散落在周围的:",
68
+ "hidden": "隐蔽",
69
+ " holding {things}": ",里面有{things}",
70
+ "; and {count} more": ";另有{count}项",
71
+ "at {feature}": "在{feature}",
72
+ "; and {count} more you can recall if needed": ";另有{count}项,需要时你可以回想起来",
73
+ "What you know exists (this does not tell you where it is now or what state it is in):": "你知道存在的事物(这并不说明它现在在哪里、处于什么状态):",
74
+ "People: ": "人物:",
75
+ "Factions: ": "组织:",
76
+ "Places: ": "地点:",
77
+ "Routes: ": "路径:",
78
+ "Things: ": "物品:",
79
+ "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):": "你的日程与你想达成的事(只是计划,不是命令:依当下情形和你的性格,可以照做、推迟或放弃):",
80
+ "Your day, now: {activity}{place}, until {until}{note}.": "你此刻的日程:{activity}{place},持续到{until}{note}。",
81
+ "Your day, next: {activity}{place}, from {from}.": "你接下来的日程:{activity}{place},{from}开始。",
82
+ " at {place}": ",在{place}",
83
+ " (not something you would drop lightly)": "(你不会轻易放下)",
84
+ ", with {names}": ",与{names}一起",
85
+ "You were to: {title}{place}{with}, at {at}, which has passed and is still open.": "你本应:{title}{place}{with},时间是{at},已经过了,事情仍未了结。",
86
+ "You are due to: {title}{place}{with}, at {at}.": "你约定要:{title}{place}{with},时间是{at}。",
87
+ "What you are after:": "你想达成的事:",
88
+ ", by {deadline}, which has passed": ",限期{deadline},已过",
89
+ ", by {deadline}": ",限期{deadline}",
90
+ " Next: {plan}.": " 下一步:{plan}。",
91
+ "How you stand with people who bear on this moment (your own view, not objective fact):": "你与和此刻相关的人的关系(是你自己的看法,不是客观事实):",
92
+ " (here)": "(在场)",
93
+ " (not here)": "(不在场)",
94
+ "knows them well": "很了解对方",
95
+ "barely knows them": "几乎不了解对方",
96
+ "trusts them": "信任对方",
97
+ "distrusts them": "不信任对方",
98
+ "is fond of them": "喜欢对方",
99
+ "dislikes them": "不喜欢对方",
100
+ "things are strained between them": "彼此关系紧张",
101
+ "Your affiliations (their goals are pressures and commitments, not commands):": "你的所属组织(其目标是压力和承诺,不是命令):",
102
+ "member": "成员",
103
+ " Goals: {goals}.": " 目标:{goals}。",
104
+ "- {name}: {position}; {status}; commitment {commitment}.": "- {name}:{position};{status};投入程度 {commitment}。",
105
+ " Your view: {attitude}.": " 你的看法:{attitude}。",
106
+ "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):": "你记得的、与此相关的事(只限你自己亲身经历的;不要声称记得更多,模糊的地方要保持不确定):",
107
+ "What you remember that bears on this: nothing comes to mind.": "你记得的、与此相关的事:想不起任何事。",
108
+ "some time ago": "一段时间以前",
109
+ "just now": "刚才",
110
+ "1 day ago": "1天前",
111
+ "{amount} days ago": "{amount}天前",
112
+ "1 hour ago": "1小时前",
113
+ "{amount} hours ago": "{amount}小时前",
114
+ "1 minute ago": "1分钟前",
115
+ "{amount} minutes ago": "{amount}分钟前",
116
+ "the details are fuzzy": "细节已经模糊",
117
+ "you barely remember": "你几乎记不清了",
118
+ "you are sure of it": "你对此确信无疑",
119
+ "you doubt it": "你对此存疑",
120
+ "something you have seen since speaks against it": "此后你所见所闻有与之相悖的地方",
121
+ "it comes to mind with the rest": "它和其余的事一起浮现在脑海",
122
+ "Earlier in this scene, before this moment:": "这一幕此刻之前发生的事:",
123
+ "What just happened, and what you are reacting to:": "刚才发生的事,以及你在回应的是什么:",
124
+ "- {name} intended: {intent} ({result}) {summary}": "- {name}打算:{intent}({result}){summary}",
125
+ "- {name} said \"{utterance}\" and intended: {intent} ({result}) {summary}": "- {name}说了“{utterance}”,并打算:{intent}({result}){summary}",
126
+ "Your earlier intent did not work out: {intent}\nYou are trying again, knowing the above. Decide again what you do now.": "你先前的打算没有成功:{intent}\n你带着上面这些再试一次。重新决定你现在做什么。",
127
+ "Character: {name}{summary}": "角色:{name}{summary}",
128
+ "What they believe now:": "他们现在的看法:",
129
+ "(nothing yet)": "(暂时没有)",
130
+ "What they have taken in since:": "他们此后经历的事:",
131
+ "Sort their memory.": "请整理他们的记忆。",
132
+ "not acceptable: {problems}": "不可接受:{problems}",
133
+ "{kind}, importance {importance}, {confidence}{about}{dispute}": "{kind},重要性 {importance},{confidence}{about}{dispute}",
134
+ ", about {names}": ",关于{names}",
135
+ ", something taken in since speaks against it": ",此后经历的事与之相悖",
136
+ "add: at most {max} new beliefs in one pass; merge or choose": "add:一次最多 {max} 条新看法;请合并或取舍",
137
+ "at most {max} changes in one pass": "一次最多 {max} 处修改",
138
+ "{where}: there is no thing it took in numbered {id}": "{where}:没有编号为 {id} 的经历",
139
+ "{where}: confidence is one of {options}": "{where}:confidence 须为 {options} 之一",
140
+ "{where}: unknown kind \"{kind}\"": "{where}:未知的 kind “{kind}”",
141
+ "{where}: say what it believes": "{where}:请写出它相信什么",
142
+ "{where}: at most {max} characters; say it shorter": "{where}:最多 {max} 个字符;请写得更短",
143
+ "{where}: importance runs from {min} to {max}": "{where}:importance 取值为 {min} 到 {max}",
144
+ "{where}: there is no belief numbered {id}": "{where}:没有编号为 {id} 的看法",
145
+ "{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}:一个转瞬即逝的瞬间还不是看法;请以至少两个不同回合的经历为依据,或以一件扭转了故事的事件为依据",
146
+ "{where}: to be sure of something it must rest on things from at least two different turns": "{where}:要对某事确信,必须以至少两个不同回合的经历为依据",
147
+ "{where}: \"{name}\" is not a character; name them as they are named": "{where}:“{name}”不是角色;请使用他们的名字",
148
+ "{where}: belief {id} is already changed in this pass": "{where}:看法 {id} 在这一轮中已经修改过",
149
+ "{where}: say what it took in since that bears on it": "{where}:请写出此后与之相关的经历",
150
+ "{where}: thing {id} came before the belief was formed; cite what came after": "{where}:经历 {id} 发生在看法形成之前;请引用之后发生的事",
151
+ "{where}: say what changes": "{where}:请写出有何改变",
152
+ "{where}: the text must be there and at most {max} characters": "{where}:必须有文字,且最多 {max} 个字符",
153
+ "{where}: a belief that something contradicts must be doubted: lower its confidence": "{where}:被事实相悖的看法必须存疑:请降低其 confidence",
154
+ "{where}: to doubt a belief, name what contradicts it in contradicted_by": "{where}:要对看法存疑,请在 contradicted_by 中写明与之相悖的经历",
155
+ "{where}: merge into a belief that stays": "{where}:请合并到保留的看法中",
156
+ "Time: {time}.": "时间:{time}。",
157
+ "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.": "故事的时间只按你说的推进:每一轮耗时由你给定(resolve_round 的 elapsed_seconds,或取默认值),advance_time 可以跳过一段时间。",
158
+ "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}的真实时间,其间故事仍在继续:角色们各忙各的事,除非记录另有说明,不要假定任何人还在玩家离开时的位置或状态。",
159
+ "The story's time follows the real clock: it cannot be skipped, and each round takes as long as it really took.": "故事时间跟随真实时钟:无法跳过,每一轮耗时就是它实际花费的时间。",
160
+ "By their routines since you last looked: {moves}.": "按各自的日程,自你上次查看以来:{moves}。",
161
+ "{name} went to {place} ({activity})": "{name}去了{place}({activity})",
162
+ "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}。是否照日程行事由角色自己决定;当下的情形也可能拖住他们。",
163
+ ", at {place}": ",在{place}",
164
+ "\"{title}\" ({with}{place}) was due {when} and is still open": "“{title}”({with}{place})原定{when},仍未了结",
165
+ "\"{title}\" ({with}{place}) is due {when}": "“{title}”({with}{place})定于{when}",
166
+ "Commitments due soon or overdue: {entries}.": "即将到期或已逾期的约定:{entries}。",
167
+ "named in the move": "被这一步行动点到",
168
+ "in the scene": "在场",
169
+ "own goal: {goal}": "自身目标:{goal}",
170
+ "faction pressure: {goal}": "组织压力:{goal}",
171
+ "high tension toward the player": "对玩家高度紧张",
172
+ "distrusts the player": "不信任玩家",
173
+ "cares about the player": "在意玩家",
174
+ "dislikes the player": "不喜欢玩家",
175
+ "Likely characters to activate, in priority order (advice only; activate only whoever the moment actually reaches):": "可能需要启动的角色,按优先级排列(仅供参考;只启动当下真正牵涉到的人):",
176
+ "socially implicated": "社交上被牵涉",
177
+ "The player's character is in {place}": "玩家角色在{place}",
178
+ "Characters here:": "在这里的角色:",
179
+ "Characters elsewhere (they perceive nothing here unless the moment reaches them):": "在别处的角色(除非当下波及他们,否则感知不到这里的事):",
180
+ "{member} - in {place} ({key})": "{member} - 在{place}({key})",
181
+ "Characters with no place (not part of this scene; they cannot be asked to act):": "没有所在地点的角色(不属于这一幕;不能让他们行动):",
182
+ "the player's character, \"{key}\"": "玩家角色,“{key}”",
183
+ "acts through \"{key}\"": "通过“{key}”行动",
184
+ "Currently: {state}": "目前:{state}",
185
+ "Scene before turn {turn}:": "第 {turn} 回合之前的场景:",
186
+ "What characters have on them:": "角色们身上带着:",
187
+ "The world acted since the last turn, by itself:": "自上一回合以来,世界自行发生的事:",
188
+ "Known beforehand, still to come (who knows of it; it will happen by itself when its time comes):": "事先已知、尚未发生的事(谁知道;时候到了会自行发生):",
189
+ "[known to {who}]": "[知情者:{who}]",
190
+ "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):": "合适时把这些织入故事,然后在 narrate 的 addressed 中说明已处理(每条会保留几个回合,之后放弃):",
191
+ "What the story keeps track of (change it with variable_changes in an outcome when what happened calls for it):": "故事追踪的内容(发生的事需要时,在结果中用 variable_changes 修改):",
192
+ "Still open in the story:": "故事中仍未了结的事:",
193
+ "Earlier events that bear on what the player just did (from the records of the story):": "与玩家刚才的行动相关的早先事件(来自故事记录):",
194
+ "turn {turn}": "第 {turn} 回合",
195
+ "You were to {title}, at {when}": "你本应{title},时间是{when}",
196
+ "You were to {title} at {place}, at {when}": "你本应在{place}:{title},时间是{when}",
197
+ " ({note})": "({note})",
198
+ "It is {now} now and the time has passed.": "现在是{now},时间已经过了。",
199
+ "It is {now} now.": "现在是{now}。",
200
+ "It was with: {who}.": "同你一起的有:{who}。",
201
+ "You are not with the player's character, and nothing of this happens in front of anyone: decide what you do about it.": "你不和玩家的角色在一起,这件事也不会发生在任何人面前:决定你要怎么处理。",
202
+ "The time you had for \"{goal}\" has passed ({when}; it is {now} now)": "你为“{goal}”预留的时间已过({when};现在是{now})",
203
+ "You are not with the player's character and nothing of this happens in front of anyone: decide what you do about it.": "你不和玩家的角色在一起,这件事也不会发生在任何人面前:决定你要怎么处理。",
204
+ "{names} noticed: {text}": "{names}注意到:{text}",
205
+ "{name} went to {place}.": "{name}去了{place}。"
206
+ };
207
+ //#endregion
208
+ //#region ../dsh-roleplay-model/src/messages.ts
209
+ /** The language a setting such as `zh-CN` or `en` stands for; English when it is none that is known. */
210
+ function languageOf(code) {
211
+ return (code ?? "").trim().toLowerCase().startsWith("zh") ? "zh" : "en";
212
+ }
213
+ const fill = (template, values) => values === void 0 ? template : template.replace(/\{(\w+)\}/g, (whole, name) => name in values ? String(values[name]) : whole);
214
+ const CATALOGUES = { zh: ZH };
215
+ /**
216
+ * The texts the engine builds for a model (briefs, reports, refusals) in a language. The text written in the code is the English one and the key of
217
+ * the others; a text a language lacks is told in English, and a test keeps that from happening.
218
+ */
219
+ function translator(language) {
220
+ const catalogue = language === "en" ? void 0 : CATALOGUES[language];
221
+ return (text, values) => fill(catalogue?.[text] ?? text, values);
222
+ }
223
+ //#endregion
224
+ //#region src/host/orchestration/protocol.ts
225
+ const COMMITMENTS = [
226
+ "low",
227
+ "medium",
228
+ "high"
229
+ ];
230
+ const RESULTS = [
231
+ "succeeded",
232
+ "partial",
233
+ "failed"
234
+ ];
235
+ const MAX_ACCOUNT = 300;
236
+ /**
237
+ * How long, in characters, each text of a character's answer is asked to run to: the instructions state these, and the most a character's request may produce is estimated from them.
238
+ * A character of a script written without spaces says more in fewer.
239
+ */
240
+ const ANSWER_LIMITS = {
241
+ en: {
242
+ thought: 240,
243
+ intent: 300,
244
+ utterance: 600,
245
+ account: MAX_ACCOUNT
246
+ },
247
+ zh: {
248
+ thought: 100,
249
+ intent: 120,
250
+ utterance: 240,
251
+ account: 120
252
+ }
253
+ };
254
+ const answerLimits = (language) => language.toLowerCase().startsWith("zh") ? ANSWER_LIMITS.zh : ANSWER_LIMITS.en;
255
+ /** What the answer of a character comes to at most, in tokens (an answer about what happened out of sight has its account too). */
256
+ function answerEstimate(language, away) {
257
+ const limits = answerLimits(language);
258
+ return estimateAnswer([
259
+ limits.thought,
260
+ limits.intent,
261
+ limits.utterance,
262
+ ...away ? [limits.account] : []
263
+ ], language);
264
+ }
265
+ /**
266
+ * What a character is asked to produce; the sub-agent runtime enforces it. The order is the order of what depends on what: the thought comes first so that the
267
+ * choice that follows is made after it, which an engine that does not write fields in order simply does without (it is optional and read by no one).
268
+ */
269
+ const CHARACTER_ACTION_SCHEMA = {
270
+ type: "object",
271
+ properties: {
272
+ thought: {
273
+ type: "string",
274
+ description: "First, in your own voice and a sentence or two: what you notice in the moment and what you want from it. No one is shown it."
275
+ },
276
+ intent: {
277
+ type: "string",
278
+ description: "What the character does, or tries to do, now, as an action in one or two sentences, without any speech."
279
+ },
280
+ utterance: {
281
+ type: "string",
282
+ description: "What the character says aloud, word for word and in its own voice, exactly as it will be shown. Leave out when it says nothing."
283
+ },
284
+ commitment: {
285
+ type: "string",
286
+ enum: [...COMMITMENTS],
287
+ description: "How hard the character will keep trying if this does not work out: low gives up at once, high persists."
288
+ }
289
+ },
290
+ required: [
291
+ "thought",
292
+ "intent",
293
+ "commitment"
294
+ ],
295
+ additionalProperties: false
296
+ };
297
+ /** The schema for a character acting away from the player: the same answer, which also says in a line what happened, so no second request is needed. */
298
+ const AWAY_ACTION_SCHEMA = {
299
+ ...CHARACTER_ACTION_SCHEMA,
300
+ properties: {
301
+ ...CHARACTER_ACTION_SCHEMA.properties,
302
+ account: {
303
+ type: "string",
304
+ description: "One sentence, in the third person and the past tense, of what came of this, as someone who only saw it from outside would tell it afterwards: no thoughts, no secrets."
305
+ }
306
+ },
307
+ required: [
308
+ "thought",
309
+ "intent",
310
+ "commitment",
311
+ "account"
312
+ ]
313
+ };
314
+ /** @throws {Error} when the value is not a character action. */
315
+ const QUOTE_PAIRS = [
316
+ ["\"", "\""],
317
+ ["“", "”"],
318
+ ["「", "」"],
319
+ ["『", "』"],
320
+ ["«", "»"],
321
+ ["‘", "’"]
322
+ ];
323
+ /** Words said aloud, without the quotation marks a model puts around them: the output puts its own. */
324
+ function unquoted(text) {
325
+ let words = text.trim();
326
+ for (let again = true; again;) {
327
+ again = false;
328
+ for (const [open, close] of QUOTE_PAIRS) if (words.length >= 2 && words.startsWith(open) && words.endsWith(close) && !words.slice(open.length, -close.length).includes(close)) {
329
+ words = words.slice(open.length, words.length - close.length).trim();
330
+ again = true;
331
+ }
332
+ }
333
+ return words;
334
+ }
335
+ const LEAKED_FIELD = /<\/?(?:intent|parameter(?:=\w+)?)>/g;
336
+ /** A model that writes the markup of its call into a field puts the next field's text inside this one. */
337
+ function splitLeakedFields(intent) {
338
+ const at = intent.search(/<parameter=utterance>/);
339
+ if (at === -1) return { intent: intent.replace(LEAKED_FIELD, " ") };
340
+ const spoken = intent.slice(at).replace(LEAKED_FIELD, " ").trim();
341
+ return {
342
+ intent: intent.slice(0, at).replace(LEAKED_FIELD, " "),
343
+ ...spoken === "" ? {} : { utterance: spoken }
344
+ };
345
+ }
346
+ function parseCharacterAction(value) {
347
+ if (typeof value !== "object" || value === null) throw new Error("the character did not answer with an object");
348
+ const { intent: rawIntent, utterance: rawUtterance, commitment, account } = value;
349
+ const { intent, utterance } = typeof rawIntent === "string" && rawUtterance === void 0 ? splitLeakedFields(rawIntent) : {
350
+ intent: rawIntent,
351
+ utterance: rawUtterance
352
+ };
353
+ if (typeof intent !== "string" || intent.trim() === "") throw new Error("the character gave no intent");
354
+ if (!COMMITMENTS.includes(commitment)) throw new Error(`the character gave an unknown commitment "${String(commitment)}"`);
355
+ if (utterance !== void 0 && typeof utterance !== "string") throw new Error("the character's utterance is not text");
356
+ const spoken = utterance === void 0 ? void 0 : unquoted(utterance);
357
+ const told = typeof account === "string" ? account.trim().slice(0, MAX_ACCOUNT) : "";
358
+ return {
359
+ intent: intent.trim(),
360
+ ...spoken === void 0 || spoken === "" ? {} : { utterance: spoken },
361
+ commitment,
362
+ ...told === "" ? {} : { account: told }
363
+ };
364
+ }
365
+ //#endregion
366
+ //#region src/host/orchestration/referent.ts
367
+ /**
368
+ * 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.
369
+ * 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.
370
+ */
371
+ function referent(character) {
372
+ const mark = [character.pronouns, character.gender].find((text) => text !== void 0 && text.trim() !== "")?.trim();
373
+ return mark === void 0 ? character.name : `${character.name} (${mark})`;
374
+ }
375
+ //#endregion
376
+ //#region src/host/clock/story-clock.ts
377
+ var ClockError = class extends Error {};
378
+ /** A moment as it is told next to `now`: the clock when it is the same day, the date as well when it is not. */
379
+ function describeWhen(instant, now, zone, language = "en") {
380
+ const a = localTime(instant, zone);
381
+ const b = localTime(now, zone);
382
+ return a.year === b.year && a.month === b.month && a.day === b.day ? clockTime(instant, zone) : describeInstant(instant, zone, language);
383
+ }
384
+ /**
385
+ * The time in a sentence: the day and date, the clock, and the part of the day; and, when the world has a calendar, the season and the holidays that
386
+ * fall on the day.
387
+ */
388
+ function describeTime(time, language = "en") {
389
+ const { calendar } = time;
390
+ const tr = translator(language);
391
+ const base = `${describeInstant(time.now, time.zone, language)} (${tr(dayPart(localTime(time.now, time.zone).minuteOfDay))})`;
392
+ if (calendar === void 0 || calendar.holidays.length === 0 && calendar.hemisphere === "north") return base;
393
+ const day = addLocalDays(time.now, time.zone, 0);
394
+ const holidays = holidaysOn(calendar, day).map((holiday) => holiday.name);
395
+ return `${base}${tr(", ")}${tr(seasonOf(day, calendar.hemisphere))}${holidays.length === 0 ? "" : `${tr("; ")}${tr("today is {holidays}", { holidays: holidays.join(tr(", ")) })}`}`;
396
+ }
397
+ /** The time zone the story is read in. */
398
+ const zoneOf = (config) => config.timeZone === "" ? "UTC" : config.timeZone;
399
+ /** The clock, started when a session has none yet, and detached from the real clock when the settings say so. The mode the story has is the one it keeps otherwise. */
400
+ function ensure(session, config, turn, wall) {
401
+ const current = session.clock.get();
402
+ if (current === void 0) {
403
+ session.clock.start(config.mode, config.mode === "real" ? wall : Math.floor(wall / MINUTE) * MINUTE);
404
+ return session.clock.get() ?? {
405
+ mode: config.mode,
406
+ now: wall
407
+ };
408
+ }
409
+ if (current.mode !== "real" || config.mode !== "simulated") return current;
410
+ session.clock.resync("simulated", Math.max(current.now, wall), turn, "the story's time was detached from the real clock");
411
+ return session.clock.get() ?? current;
412
+ }
413
+ function timeOf(session, state, config) {
414
+ const calendar = session.metadata === void 0 ? void 0 : readCalendar(session.metadata);
415
+ return {
416
+ mode: state.mode,
417
+ now: state.now,
418
+ zone: zoneOf(config),
419
+ ...calendar === void 0 || calendar.holidays.length === 0 && calendar.hemisphere === "north" ? {} : { calendar }
420
+ };
421
+ }
422
+ /** What time it is, without letting any pass. */
423
+ function readTime(session, config, turn, wall) {
424
+ return session.transaction(() => timeOf(session, ensure(session, config, turn, wall), config));
425
+ }
426
+ /**
427
+ * The start of a turn. Following the wall clock, the time since the last turn passed outside the story:
428
+ * `away` says how long.
429
+ */
430
+ function beginTurn(session, config, turn, wall) {
431
+ return session.transaction(() => {
432
+ const state = ensure(session, config, turn, wall);
433
+ if (state.mode === "real" && wall > state.now) {
434
+ session.clock.advance({
435
+ to: wall,
436
+ turn,
437
+ round: 0,
438
+ kind: "real",
439
+ reason: "between turns"
440
+ });
441
+ return {
442
+ time: timeOf(session, {
443
+ mode: "real",
444
+ now: wall
445
+ }, config),
446
+ away: wall - state.now
447
+ };
448
+ }
449
+ return { time: timeOf(session, state, config) };
450
+ });
451
+ }
452
+ /**
453
+ * A round passes. Simulated, it takes what the game master said (or the default), and at least as long as the
454
+ * journey the player's character made (`minimum`); following the wall clock, it takes as long as it took.
455
+ */
456
+ function endRound(session, config, turn, round, wall, stated, minimum) {
457
+ return session.transaction(() => {
458
+ const state = ensure(session, config, turn, wall);
459
+ if (state.mode === "real") {
460
+ const to = Math.max(state.now, wall);
461
+ session.clock.advance({
462
+ to,
463
+ turn,
464
+ round,
465
+ kind: "real"
466
+ });
467
+ return {
468
+ from: state.now,
469
+ to,
470
+ zone: zoneOf(config)
471
+ };
472
+ }
473
+ const took = Math.max(stated ?? config.roundSeconds, minimum ?? 0) * SECOND;
474
+ session.clock.advance({
475
+ to: state.now + took,
476
+ turn,
477
+ round,
478
+ kind: "elapsed"
479
+ });
480
+ return {
481
+ from: state.now,
482
+ to: state.now + took,
483
+ zone: zoneOf(config)
484
+ };
485
+ });
486
+ }
487
+ /**
488
+ * Skip ahead in the story's own time.
489
+ * @throws {ClockError} when time follows the wall clock, the request is not one, or it asks for more than the chat allows.
490
+ */
491
+ function skipTime(session, config, turn, round, wall, request) {
492
+ return session.transaction(() => {
493
+ const state = ensure(session, config, turn, wall);
494
+ if (state.mode === "real") throw new ClockError("the story's time follows the wall clock, so it cannot be skipped");
495
+ const zone = zoneOf(config);
496
+ const reason = request.reason.trim();
497
+ if (reason === "") throw new ClockError("say what happens in the time that passes (reason)");
498
+ let to;
499
+ if ("byMinutes" in request) {
500
+ if (!Number.isInteger(request.byMinutes) || request.byMinutes < 1) throw new ClockError("by_minutes must be a whole number of minutes, at least 1");
501
+ to = state.now + request.byMinutes * MINUTE;
502
+ } else try {
503
+ to = nextTimeOfDay(state.now, zone, request.untilTime, request.daysLater);
504
+ } catch (error) {
505
+ throw new ClockError(error instanceof RangeError ? error.message : String(error));
506
+ }
507
+ if (to - state.now > config.maxSkipDays * DAY) throw new ClockError(`that is ${Math.round((to - state.now) / DAY)} days from now (${describeInstant(state.now, zone)}), more than the ${config.maxSkipDays} days this chat allows in one skip`);
508
+ session.clock.advance({
509
+ to,
510
+ turn,
511
+ round,
512
+ kind: "skip",
513
+ reason
514
+ });
515
+ return {
516
+ from: state.now,
517
+ to,
518
+ zone,
519
+ reason
520
+ };
521
+ });
522
+ }
523
+ //#endregion
524
+ //#region src/host/orchestration/defaults.ts
525
+ const ENGLISH = translator("en");
526
+ /** What the instructions say about how long each part of a character's answer may run. */
527
+ const limitVariables = (language) => {
528
+ const limits = answerLimits(language);
529
+ return {
530
+ thoughtLimit: limits.thought,
531
+ intentLimit: limits.intent,
532
+ utteranceLimit: limits.utterance
533
+ };
534
+ };
535
+ function describe(character, tr) {
536
+ const lines = [tr("You are {name}.", { name: character.name })];
537
+ if (character.aliases.length > 0) lines.push(tr("You are also called {names}.", { names: character.aliases.join(tr(", ")) }));
538
+ const facts = [
539
+ character.age === void 0 ? void 0 : tr("age: {value}", { value: character.age }),
540
+ character.gender === void 0 ? void 0 : tr("gender: {value}", { value: character.gender }),
541
+ character.pronouns === void 0 ? void 0 : tr("pronouns: {value}", { value: character.pronouns })
542
+ ].filter((fact) => fact !== void 0);
543
+ if (facts.length > 0) lines.push(facts.join(tr("; ")) + tr("."));
544
+ for (const [label, text] of [
545
+ ["Summary", character.summary],
546
+ ["Personality", character.personality],
547
+ ["Background", character.background],
548
+ ["Appearance", character.appearance],
549
+ ["How you speak", character.speech.style]
550
+ ]) if (text.trim() !== "") lines.push(`${tr(label)}${tr(": ")}${text.trim()}`);
551
+ return lines.join("\n");
552
+ }
553
+ /** At most this many features and ways out of a place are told at once. */
554
+ const SHOWN_FEATURES = 12;
555
+ const SHOWN_EXITS = 12;
556
+ const sentence = (text) => {
557
+ return (/^[^.!?。!?]*[.!?。!?]?/u.exec(text.trim())?.[0] ?? text).trim();
558
+ };
559
+ /** At most this many things are listed at once: the rest are said to be there and left for a closer look. */
560
+ const SHOWN_ITEMS = 12;
561
+ /** One thing in a sentence: how many, what state it is in, where it is. */
562
+ function describeItem(item, { withKeys }, tr = ENGLISH) {
563
+ const name = `${item.quantity > 1 ? `${item.quantity} ` : ""}${item.name}${item.quality === "" ? "" : ` (${item.quality})`}`;
564
+ const extra = [
565
+ item.hidden ? tr("hidden") : "",
566
+ item.state === void 0 ? "" : item.state,
567
+ item.where ?? ""
568
+ ].filter((part) => part !== "").join(tr(", "));
569
+ const inside = item.contents === void 0 ? "" : tr(" holding {things}", { things: item.contents.join(tr(", ")) });
570
+ return `${withKeys ? `${item.key}: ` : ""}${name}${extra === "" ? "" : ` [${extra}]`}${inside}`;
571
+ }
572
+ /** A list of things, capped. */
573
+ function describeItems(items, options, tr = ENGLISH) {
574
+ 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 }) : ""}`;
575
+ }
576
+ /** What someone in a place is told about it: what it is like, what can be pointed at, and the ways out. */
577
+ function describePlace(view, { withKeys }, tr = ENGLISH) {
578
+ const { location, exits } = view;
579
+ const lines = [`${location.name}${withKeys ? ` (${view.key})` : ""}${location.description === "" ? "" : `: ${location.description}`}`];
580
+ if (location.features.length > 0) {
581
+ const shown = location.features.slice(0, SHOWN_FEATURES).map((feature) => `${withKeys ? `${feature.key}: ` : ""}${feature.name}${feature.description === "" ? "" : ` - ${sentence(feature.description)}`}`);
582
+ lines.push(`${tr("Things here: ")}${shown.join(tr("; "))}${location.features.length > SHOWN_FEATURES ? tr("; and {count} more", { count: location.features.length - SHOWN_FEATURES }) : ""}`);
583
+ }
584
+ if (exits.length > 0) {
585
+ 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}`}]`}`);
586
+ lines.push(`${tr("Ways out: ")}${shown.join(tr("; "))}${exits.length > SHOWN_EXITS ? tr("; and {count} more", { count: exits.length - SHOWN_EXITS }) : ""}`);
587
+ }
588
+ if (view.items !== void 0 && view.items.length > 0) lines.push(`${tr("Lying about: ")}${describeItems(view.items, { withKeys }, tr)}`);
589
+ return lines;
590
+ }
591
+ /** How long the player has to have been away for it to be worth telling the game master. */
592
+ const NOTICEABLE_ABSENCE = 5 * MINUTE;
593
+ /** What the game master is told about time at the start of a turn, and how it passes. */
594
+ function timeNotice(time, language, tr) {
595
+ const now = tr("Time: {time}.", { time: describeTime(time.now, language) });
596
+ 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.")}`;
597
+ 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) })}` : "";
598
+ 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}`;
599
+ }
600
+ /** What a character is told of its day, its commitments and what it is after. */
601
+ function describeAgenda(agenda, now, tr = ENGLISH, language = "en") {
602
+ const { zone } = agenda;
603
+ const when = (instant) => describeWhen(instant, now, zone, language);
604
+ const at = (place) => place === void 0 ? "" : tr(" at {place}", { place });
605
+ const lines = [];
606
+ if (agenda.now !== void 0) lines.push(tr("Your day, now: {activity}{place}, until {until}{note}.", {
607
+ activity: agenda.now.activity,
608
+ place: at(agenda.now.place),
609
+ until: when(agenda.now.until),
610
+ note: agenda.now.interruptible ? "" : tr(" (not something you would drop lightly)")
611
+ }));
612
+ if (agenda.next !== void 0) lines.push(tr("Your day, next: {activity}{place}, from {from}.", {
613
+ activity: agenda.next.activity,
614
+ place: at(agenda.next.place),
615
+ from: when(agenda.next.at)
616
+ }));
617
+ for (const engagement of agenda.engagements) {
618
+ const values = {
619
+ title: engagement.title,
620
+ place: at(engagement.place),
621
+ with: engagement.with.length === 0 ? "" : tr(", with {names}", { names: engagement.with.join(tr(", ")) }),
622
+ at: when(engagement.at)
623
+ };
624
+ 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));
625
+ }
626
+ if (agenda.goals.length > 0) {
627
+ lines.push(tr("What you are after:"));
628
+ for (const goal of agenda.goals) {
629
+ 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) });
630
+ 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("; ")) })}`);
631
+ }
632
+ }
633
+ return lines;
634
+ }
635
+ /** What the game master is told of the characters' days at the start of a turn; nothing when there is nothing to tell. */
636
+ function describeSceneAgenda(agenda, now, tr = ENGLISH, language = "en") {
637
+ const lines = [];
638
+ const join = (entries) => entries.join(tr("; "));
639
+ 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})", {
640
+ name: move.name,
641
+ place: move.to,
642
+ activity: move.activity
643
+ }))) }));
644
+ 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}`)) }));
645
+ if (agenda.engagements.length > 0) {
646
+ const entries = agenda.engagements.map((engagement) => {
647
+ const values = {
648
+ title: engagement.title,
649
+ with: engagement.with.join(tr(", ")),
650
+ place: engagement.place === void 0 ? "" : tr(", at {place}", { place: engagement.place }),
651
+ when: describeWhen(engagement.at, now, agenda.zone, language)
652
+ };
653
+ return engagement.overdue ? tr("\"{title}\" ({with}{place}) was due {when} and is still open", values) : tr("\"{title}\" ({with}{place}) is due {when}", values);
654
+ });
655
+ lines.push(tr("Commitments due soon or overdue: {entries}.", { entries: join(entries) }));
656
+ }
657
+ return lines.join("\n");
658
+ }
659
+ /** In words, how a character stands with another, from the numbers of its profile; nothing for what is unremarkable. */
660
+ function describeAttitude(relation, tr = ENGLISH) {
661
+ return [
662
+ relation.familiarity >= .7 ? tr("knows them well") : relation.familiarity <= .15 ? tr("barely knows them") : "",
663
+ relation.trust >= .4 ? tr("trusts them") : relation.trust <= -.4 ? tr("distrusts them") : "",
664
+ relation.affinity >= .4 ? tr("is fond of them") : relation.affinity <= -.4 ? tr("dislikes them") : "",
665
+ relation.tension >= .5 ? tr("things are strained between them") : ""
666
+ ].filter((part) => part !== "").join(tr(", "));
667
+ }
668
+ function whereIs(member, tr = ENGLISH) {
669
+ const place = member.place;
670
+ if (place === void 0) return "";
671
+ return [place.position, place.feature === void 0 ? "" : tr("at {feature}", { feature: place.feature.name })].filter((part) => part !== "").join(tr(", "));
672
+ }
673
+ function present(cast, self, tr) {
674
+ return cast.map((member) => {
675
+ const { key, character, state } = member;
676
+ const seen = [state?.publicState, state?.activity].filter((text) => text !== void 0 && text.trim() !== "");
677
+ const where = whereIs(member);
678
+ return `- ${key === self ? character.name : referent(character)}${key === self ? tr(" (you)") : ""}${where === "" ? "" : ` (${where})`}${seen.length > 0 ? `${tr(": ")}${seen.join(tr("; "))}` : ""}`;
679
+ }).join("\n");
680
+ }
681
+ /** A bounded, advisory order for who is most likely to need a turn; reachability still governs activation. */
682
+ function describeActivationCandidates(cast, input, story, tr = ENGLISH) {
683
+ const player = cast.find((member) => member.character.control === "player");
684
+ if (player === void 0) return "";
685
+ const named = mentioned(input, cast.map((member) => member.character));
686
+ const cues = tokens(input);
687
+ const candidates = cast.filter((member) => member.character.control === "agent").map((member) => {
688
+ const relation = story.relationships.get(member.character.id, player.character.id);
689
+ const here = member.place === void 0 || player.place === void 0 || member.place.location.id === player.place.location.id;
690
+ const goal = story.intents.list(member.character.id, { status: "active" }).map((intent) => ({
691
+ intent,
692
+ match: overlap(cues, `${intent.name} ${intent.description}`, [])
693
+ })).sort((a, b) => b.match - a.match)[0];
694
+ const factionGoal = story.factionMemberships.ofCharacter(member.character.id, "active").flatMap((membership) => story.factionIntents.list(membership.factionId, { status: "active" }).map((intent) => ({
695
+ intent,
696
+ match: overlap(cues, `${intent.name} ${intent.description}`, []) * membership.commitment
697
+ }))).sort((a, b) => b.match - a.match)[0];
698
+ return {
699
+ member,
700
+ reasons: [
701
+ named.has(member.character.id) ? tr("named in the move") : "",
702
+ here ? tr("in the scene") : "",
703
+ (goal?.match ?? 0) >= 2 ? tr("own goal: {goal}", { goal: goal.intent.name }) : "",
704
+ (factionGoal?.match ?? 0) >= 2 ? tr("faction pressure: {goal}", { goal: factionGoal.intent.name }) : "",
705
+ relation !== void 0 && relation.tension >= .5 ? tr("high tension toward the player") : "",
706
+ relation !== void 0 && relation.trust <= -.4 ? tr("distrusts the player") : "",
707
+ relation !== void 0 && Math.abs(relation.affinity) >= .4 ? relation.affinity > 0 ? tr("cares about the player") : tr("dislikes the player") : ""
708
+ ].filter((reason) => reason !== ""),
709
+ 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
710
+ };
711
+ }).filter((entry) => entry.score > 0).sort((a, b) => b.score - a.score || a.member.key.localeCompare(b.member.key)).slice(0, 5);
712
+ if (candidates.length === 0) return "";
713
+ 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")}`;
714
+ }
715
+ function said(entry, tr) {
716
+ return entry.utterance === void 0 ? tr("- {name} intended: {intent} ({result}) {summary}", {
717
+ name: entry.name,
718
+ intent: entry.intent,
719
+ result: entry.result,
720
+ summary: entry.summary
721
+ }) : tr("- {name} said \"{utterance}\" and intended: {intent} ({result}) {summary}", {
722
+ name: entry.name,
723
+ utterance: entry.utterance,
724
+ intent: entry.intent,
725
+ result: entry.result,
726
+ summary: entry.summary
727
+ });
728
+ }
729
+ function age(at, now, tr) {
730
+ if (at === void 0 || now === void 0) return tr("some time ago");
731
+ const seconds = Math.max(0, Math.floor((now - at) / 1e3));
732
+ if (seconds < 60) return tr("just now");
733
+ const amount = Math.floor(seconds / (seconds >= 86400 ? 86400 : seconds >= 3600 ? 3600 : 60));
734
+ if (seconds >= 86400) return amount === 1 ? tr("1 day ago") : tr("{amount} days ago", { amount });
735
+ if (seconds >= 3600) return amount === 1 ? tr("1 hour ago") : tr("{amount} hours ago", { amount });
736
+ return amount === 1 ? tr("1 minute ago") : tr("{amount} minutes ago", { amount });
737
+ }
738
+ /** 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. */
739
+ function remembered(memories, tr, now) {
740
+ return memories.map((memory) => {
741
+ const clarity = memory.clarity === "clear" ? [] : [memory.clarity === "faded" ? tr("the details are fuzzy") : tr("you barely remember")];
742
+ const sure = memory.confidence === "sure" ? [tr("you are sure of it")] : memory.confidence === "doubtful" ? [tr("you doubt it")] : [];
743
+ const against = memory.disputed === true ? [tr("something you have seen since speaks against it")] : [];
744
+ return `- (${[
745
+ age(memory.at, now, tr),
746
+ ...clarity,
747
+ ...sure,
748
+ ...against,
749
+ ...memory.linked === true ? [tr("it comes to mind with the rest")] : []
750
+ ].join(tr(", "))}) ${memory.text}`;
751
+ }).join("\n");
752
+ }
753
+ /** Every character is told the same thing about the scene, plus who it is and what it remembers. */
754
+ const sharedContext = { brief(request) {
755
+ const { member, cast, situation, attempt, earlier, reaction, previous, memories, place, relationships, knowledge, affiliations, carrying, time, agenda } = request;
756
+ const language = languageOf(request.language);
757
+ const tr = translator(language);
758
+ const list = (entries) => entries.join(tr("; "));
759
+ const company = place === void 0 ? cast : place.here;
760
+ const sections = [
761
+ `${tr("Situation:")}\n${situation}`,
762
+ ...time === void 0 ? [] : [tr("Now: {time}.", { time: describeTime(time, language) })],
763
+ ...place === void 0 ? [] : [`${tr("Where you are:")}\n${describePlace(place, { withKeys: false }, tr).join("\n")}`],
764
+ `${tr("Present:")}\n${present(company, member.key, tr)}`
765
+ ];
766
+ 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")}`);
767
+ if (request.cues !== void 0 && request.cues.length > 0) sections.push(`${tr("Just now you notice:")}\n${request.cues.map((cue) => `- ${cue}`).join("\n")}`);
768
+ if (request.tracked !== void 0 && request.tracked.self !== "") sections.push(`${tr("How you are (what you can tell of yourself):")}\n${request.tracked.self}`);
769
+ 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")}`);
770
+ const day = agenda === void 0 || time === void 0 ? [] : describeAgenda(agenda, time.now, tr, language);
771
+ 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")}`);
772
+ if (carrying !== void 0 && carrying.length > 0) sections.push(`${tr("What you have on you:")}\n${describeItems(carrying, { withKeys: false }, tr)}`);
773
+ 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) => {
774
+ const attitude = describeAttitude(relation, tr);
775
+ return `- ${relation.name}${relation.present ? tr(" (here)") : tr(" (not here)")} — ${relation.label}${relation.summary === "" ? "" : `${tr(": ")}${relation.summary}`}${attitude === "" ? "" : ` [${attitude}]`}`;
776
+ }).join("\n")}`);
777
+ if (affiliations !== void 0 && affiliations.length > 0) sections.push(`${tr("Your affiliations (their goals are pressures and commitments, not commands):")}\n${affiliations.map((entry) => {
778
+ const position = [entry.role, entry.rank].filter(Boolean).join(tr(", ")) || tr("member");
779
+ const goals = entry.goals.length === 0 ? "" : tr(" Goals: {goals}.", { goals: list(entry.goals) });
780
+ const state = entry.publicState === "" ? "" : ` ${entry.publicState}`;
781
+ const attitude = entry.relationship === void 0 ? "" : describeAttitude(entry.relationship, tr);
782
+ return tr("- {name}: {position}; {status}; commitment {commitment}.", {
783
+ name: entry.name,
784
+ position,
785
+ status: entry.status,
786
+ commitment: entry.commitment.toFixed(2)
787
+ }) + `${state}${goals}${attitude === "" ? "" : tr(" Your view: {attitude}.", { attitude })}`;
788
+ }).join("\n")}`);
789
+ if (knowledge !== void 0) {
790
+ const shown = (entries) => list(entries.slice(0, 30)) + (entries.length > 30 ? tr("; and {count} more you can recall if needed", { count: entries.length - 30 }) : "");
791
+ const lines = [
792
+ knowledge.characters.length === 0 ? void 0 : `${tr("People: ")}${shown(knowledge.characters)}`,
793
+ knowledge.factions.length === 0 ? void 0 : `${tr("Factions: ")}${shown(knowledge.factions)}`,
794
+ knowledge.locations.length === 0 ? void 0 : `${tr("Places: ")}${shown(knowledge.locations)}`,
795
+ knowledge.routes.length === 0 ? void 0 : `${tr("Routes: ")}${shown(knowledge.routes)}`,
796
+ knowledge.items.length === 0 ? void 0 : `${tr("Things: ")}${shown(knowledge.items)}`
797
+ ].filter((line) => line !== void 0);
798
+ 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")}`);
799
+ }
800
+ 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)}`);
801
+ else if (memories !== void 0) sections.splice(1, 0, tr("What you remember that bears on this: nothing comes to mind."));
802
+ 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")}`);
803
+ if (attempt === 2 && reaction !== void 0) {
804
+ sections.push(`${tr("What just happened, and what you are reacting to:")}\n${reaction.map((entry) => said(entry, tr)).join("\n")}`);
805
+ 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 }));
806
+ }
807
+ return {
808
+ persona: [
809
+ describe(member.character, tr),
810
+ request.text("roleplay/character-rules", { name: member.character.name }),
811
+ request.text("roleplay/character-style", { name: member.character.name }),
812
+ ...request.lookup ? [request.text("roleplay/character-lookup")] : [],
813
+ request.text("roleplay/character-decide", {
814
+ name: member.character.name,
815
+ ...limitVariables(request.language ?? "en")
816
+ })
817
+ ].join("\n\n"),
818
+ prompt: sections.join("\n\n")
819
+ };
820
+ } };
821
+ /**
822
+ * 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
823
+ * 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
824
+ * another place can be asked when the moment reaches it.)
825
+ */
826
+ const everyoneActs = { plan({ cast, requested }) {
827
+ const placed = cast.some((member) => member.place !== void 0);
828
+ const available = cast.filter((member) => member.character.control === "agent");
829
+ const here = cast.find((member) => member.character.control === "player")?.place?.location.id;
830
+ const inScene = (member) => !placed || member.place !== void 0;
831
+ 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);
832
+ const unknown = requested.filter((key) => !available.some((member) => member.key === key));
833
+ 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(", ")})`);
834
+ const nowhere = [...new Set(requested)].map((key) => available.find((member) => member.key === key)).filter((member) => !inScene(member));
835
+ 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`);
836
+ return [...new Set(requested)];
837
+ } };
838
+ const acceptsAnyIntent = { validate: ({ intent }) => intent.trim() === "" ? {
839
+ ok: false,
840
+ reason: "the intent is empty"
841
+ } : { ok: true } };
842
+ /** A character whose intent failed and who is highly committed tries once more. */
843
+ const persistentRetry = { select({ reports, outcomes }) {
844
+ return reports.filter((report) => report.commitment === "high" && outcomes.some((outcome) => outcome.character === report.character && outcome.result === "failed")).map((report) => report.character);
845
+ } };
846
+ const acceptsAnyInput = { validate: () => ({ ok: true }) };
847
+ /** The game master narrates. */
848
+ const gameMasterNarrates = { narrate: () => Promise.resolve(void 0) };
849
+ /** Compares what was said, ignoring the quotes around it and the way whitespace is laid out. */
850
+ const WRAPPING_QUOTES = /^["“”„«»'‘’]+|["“”„«»'‘’]+$/g;
851
+ function sameWords(a, b) {
852
+ const plain = (text) => text.trim().replace(WRAPPING_QUOTES, "").replace(/\s+/g, " ").trim();
853
+ return plain(a) === plain(b);
854
+ }
855
+ /** How many earlier events the game master is reminded of at most. */
856
+ const REMINDED_EVENTS = 5;
857
+ /**
858
+ * The state of the scene, what is still open in the story, and the earlier events that the
859
+ * player's move brings to mind (by the session's search of words and meaning, and by who is named):
860
+ * those already folded out of the conversation into the summaries, whose detail the summaries may have lost.
861
+ */
862
+ /** Where the player is and what is there, who is with them, and who is elsewhere. */
863
+ function placedScene(cast, player, story, describeMember, tr, things) {
864
+ const here = player?.place?.location;
865
+ const sections = [];
866
+ if (here !== void 0) {
867
+ const view = {
868
+ key: locationKey(here),
869
+ location: here,
870
+ here: cast.filter((member) => member.place?.location.id === here.id),
871
+ ...things === void 0 ? {} : { items: things.at(here.id) },
872
+ exits: story.locations.exitsFrom(here.id).flatMap((exit) => {
873
+ const to = story.locations.get(exit.toId);
874
+ return to === void 0 ? [] : [{
875
+ key: locationKey(to),
876
+ name: to.name,
877
+ exit
878
+ }];
879
+ })
880
+ };
881
+ sections.push(tr("The player's character is in {place}", { place: describePlace(view, { withKeys: true }, tr).join("\n") }));
882
+ sections.push(`${tr("Characters here:")}\n${view.here.map(describeMember).join("\n")}`);
883
+ }
884
+ const elsewhere = cast.filter((member) => member.place !== void 0 && member.place.location.id !== here?.id);
885
+ 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})", {
886
+ member: describeMember(member),
887
+ place: member.place.location.name,
888
+ key: locationKey(member.place.location)
889
+ })).join("\n")}`);
890
+ const nowhere = cast.filter((member) => member.place === void 0);
891
+ 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")}`);
892
+ return sections.join("\n\n");
893
+ }
894
+ const castSummary = { scene({ tracked, time, world, cast, turn, input, queryVector, story, items, language: code }) {
895
+ const language = languageOf(code);
896
+ const tr = translator(language);
897
+ const join = (entries) => entries.join(tr("; "));
898
+ const describeMember = (member) => {
899
+ const { key, character, state } = member;
900
+ const role = character.control === "player" ? tr("the player's character, \"{key}\"", { key }) : tr("acts through \"{key}\"", { key });
901
+ const seen = [state?.publicState, state?.activity].filter((text) => text !== void 0 && text.trim() !== "");
902
+ const where = whereIs(member, tr);
903
+ return `- ${referent(character)} (${role})${where === "" ? "" : ` [${where}]`}${character.summary === "" ? "" : `${tr(": ")}${character.summary}`}${seen.length > 0 ? ` ${tr("Currently: {state}", { state: join(seen) })}` : ""}`;
904
+ };
905
+ const player = cast.find((member) => member.character.control === "player");
906
+ const days = time?.agenda === void 0 ? "" : describeSceneAgenda(time.agenda, time.now.now, tr, language);
907
+ const scene = cast.some((member) => member.place !== void 0) ? placedScene(cast, player, story, describeMember, tr, items) : cast.map(describeMember).join("\n");
908
+ const parts = [
909
+ ...time === void 0 ? [] : [timeNotice(time, language, tr)],
910
+ ...days === "" ? [] : [days],
911
+ `${tr("Scene before turn {turn}:", { turn })}\n${scene}`
912
+ ];
913
+ const activation = describeActivationCandidates(cast, input, story, tr);
914
+ if (activation !== "") parts.push(activation);
915
+ if (items !== void 0) {
916
+ const carried = cast.flatMap((member) => {
917
+ const mine = items.carried(member.character.id);
918
+ return mine.length === 0 ? [] : [`- ${member.character.name} (${member.key}): ${describeItems(mine, { withKeys: true }, tr)}`];
919
+ });
920
+ if (carried.length > 0) parts.push(`${tr("What characters have on them:")}\n${carried.join("\n")}`);
921
+ }
922
+ 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")}`);
923
+ 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")}`);
924
+ 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")}`);
925
+ 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")}`);
926
+ const threads = story.threads.list("open");
927
+ if (threads.length > 0) parts.push(`${tr("Still open in the story:")}\n${threads.map((thread) => `- ${thread.text}`).join("\n")}`);
928
+ const folded = story.summaries.list().reduce((latest, summary) => Math.max(latest, summary.toTurn), 0);
929
+ if (folded > 0) {
930
+ const mentionedIds = mentioned(input, cast.map(({ character }) => character));
931
+ const cues = tokens(input);
932
+ const names = new Map(cast.map(({ character }) => [character.id, character.name]));
933
+ const byMeaning = story.searchEvents({
934
+ text: input,
935
+ ...queryVector === void 0 ? {} : { vector: queryVector },
936
+ toTurn: folded,
937
+ limit: REMINDED_EVENTS
938
+ });
939
+ const byCues = story.events.list({ toTurn: folded }).filter((event) => !byMeaning.some((found) => found.id === event.id)).map((event) => ({
940
+ event,
941
+ score: 3 * event.involves.filter((id) => mentionedIds.has(id)).length + overlap(cues, event.text, event.tags)
942
+ })).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);
943
+ const relevant = [...byMeaning, ...byCues].slice(0, REMINDED_EVENTS).sort((a, b) => a.turn - b.turn).map((event) => ({ event }));
944
+ 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 }) => {
945
+ const who = event.involves.map((id) => names.get(id)).filter((name) => name !== void 0).join(tr(", "));
946
+ return `- (${tr("turn {turn}", { turn: event.turn })}) ${event.text}${who === "" ? "" : ` [${who}]`}`;
947
+ }).join("\n")}`);
948
+ }
949
+ return parts.join("\n\n");
950
+ } };
951
+ const sameCharacter = (utterance, character) => utterance.character === character || utterance.name === character;
952
+ /** Every utterance appears once, exactly as given and in the order spoken, and no one speaks who did not. */
953
+ const exactUtterances = {
954
+ check(segments, required) {
955
+ const problems = [];
956
+ const used = /* @__PURE__ */ new Set();
957
+ let latest = 0;
958
+ segments.forEach((segment, index) => {
959
+ const at = `segment ${index + 1}`;
960
+ if (segment.type === "narration") {
961
+ if (segment.text.trim() === "") problems.push(`${at}: the narration is empty`);
962
+ return;
963
+ }
964
+ const own = required.flatMap((utterance, position) => sameCharacter(utterance, segment.character) ? [position] : []);
965
+ const free = own.filter((position) => !used.has(position));
966
+ const exact = free.find((position) => sameWords(segment.text, required[position].text));
967
+ if (exact !== void 0) {
968
+ used.add(exact);
969
+ const spoken = required[exact];
970
+ 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`);
971
+ latest = Math.max(latest, spoken.round);
972
+ } else if (free.length > 0) {
973
+ used.add(free[0]);
974
+ problems.push(`${at}: the utterance of ${required[free[0]].name} was changed; it must be exactly "${required[free[0]].text}"`);
975
+ } 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`);
976
+ else problems.push(`${at}: ${segment.character} has nothing to say this turn, so this utterance is invented; remove it`);
977
+ });
978
+ required.forEach((utterance, position) => {
979
+ 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}"`);
980
+ });
981
+ return problems;
982
+ },
983
+ repair(segments, required) {
984
+ const used = /* @__PURE__ */ new Set();
985
+ const kept = [];
986
+ for (const segment of segments) {
987
+ if (segment.type === "narration") {
988
+ if (segment.text.trim() !== "") kept.push({
989
+ segment,
990
+ round: void 0
991
+ });
992
+ continue;
993
+ }
994
+ const free = required.flatMap((utterance, position) => sameCharacter(utterance, segment.character) && !used.has(position) ? [position] : []);
995
+ const position = free.find((candidate) => sameWords(segment.text, required[candidate].text)) ?? free[0];
996
+ if (position === void 0) continue;
997
+ used.add(position);
998
+ const spoken = required[position];
999
+ kept.push({
1000
+ segment: {
1001
+ type: "utterance",
1002
+ character: spoken.character,
1003
+ name: spoken.name,
1004
+ text: spoken.text
1005
+ },
1006
+ round: spoken.round
1007
+ });
1008
+ }
1009
+ required.forEach((utterance, position) => {
1010
+ if (used.has(position)) return;
1011
+ const restored = {
1012
+ type: "utterance",
1013
+ character: utterance.character,
1014
+ name: utterance.name,
1015
+ text: utterance.text
1016
+ };
1017
+ const later = kept.findIndex((entry) => entry.round !== void 0 && entry.round > utterance.round);
1018
+ kept.splice(later < 0 ? kept.length : later, 0, {
1019
+ segment: restored,
1020
+ round: utterance.round
1021
+ });
1022
+ });
1023
+ return kept.map((entry) => entry.segment);
1024
+ }
1025
+ };
1026
+ /** 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. */
1027
+ const recordsRecall = { recall: ({ member, situation, turn, policy, queryVector, explain }, story, signal) => story.recallRanked({
1028
+ characterId: member.character.id,
1029
+ situation,
1030
+ turn,
1031
+ policy,
1032
+ ...explain === true ? { explain } : {},
1033
+ ...member.place === void 0 ? {} : { locationId: member.place.location.id }
1034
+ }, signal, queryVector === void 0 ? {} : { queryVector }) };
1035
+ /**
1036
+ * Writes no memory. What the game master decided about each character is applied when the round is
1037
+ * recorded, so without a memory keeper the story keeps its states and no events.
1038
+ */
1039
+ const writesNothing = { commit: () => Promise.resolve({
1040
+ writes: 0,
1041
+ notes: ""
1042
+ }) };
1043
+ /** Makes up nothing, and has nothing to fit in: without a world author the world stays as it was written. */
1044
+ const declinesToAuthor = {
1045
+ create: () => Promise.resolve({
1046
+ created: [],
1047
+ declined: "no world author is installed, so the world cannot grow"
1048
+ }),
1049
+ consolidate: () => Promise.resolve({
1050
+ resolved: 0,
1051
+ notes: ""
1052
+ })
1053
+ };
1054
+ /** Lets no organisation act: without a strategist factions change only through what the story records. */
1055
+ const factionsStayPut = { strategize: () => Promise.resolve({ acted: [] }) };
1056
+ /** Reflects on nothing: without a reflector what characters believe changes only through what the story records. */
1057
+ const reflectsOnNothing = { reflect: () => Promise.resolve({ characters: [] }) };
1058
+ /** Judges nothing: without a judge a trigger that waits on a statement never sees it hold. */
1059
+ const judgesNothing = { judge: () => Promise.resolve({ judged: 0 }) };
1060
+ /** Offers nothing: without a suggester the player writes their own move. */
1061
+ const offersNothing = { suggest: () => Promise.resolve([]) };
1062
+ function defaultBoundaries() {
1063
+ return {
1064
+ planner: everyoneActs,
1065
+ characterContext: sharedContext,
1066
+ outputValidator: acceptsAnyIntent,
1067
+ retryPolicy: persistentRetry,
1068
+ inputValidator: acceptsAnyInput,
1069
+ narrator: gameMasterNarrates,
1070
+ narrationChecker: exactUtterances,
1071
+ committer: writesNothing,
1072
+ author: declinesToAuthor,
1073
+ strategist: factionsStayPut,
1074
+ reflector: reflectsOnNothing,
1075
+ judge: judgesNothing,
1076
+ suggester: offersNothing,
1077
+ recaller: recordsRecall,
1078
+ sceneContext: castSummary
1079
+ };
1080
+ }
1081
+ //#endregion
1082
+ //#region src/shared/timeline.ts
1083
+ const emptyTimeline = () => ({
1084
+ version: 1,
1085
+ head: null,
1086
+ next: 1,
1087
+ nodes: []
1088
+ });
1089
+ /** The turns from the first to `id`, in order; none for the start. */
1090
+ function pathTo(timeline, id) {
1091
+ const byId = new Map(timeline.nodes.map((node) => [node.id, node]));
1092
+ const path = [];
1093
+ 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);
1094
+ return path;
1095
+ }
1096
+ /** The turns that follow `parent`, in the order they were played. */
1097
+ const childrenOf = (timeline, parent) => timeline.nodes.filter((node) => node.parent === parent);
1098
+ /** The snapshot that holds the state before any turn. */
1099
+ const START_SNAPSHOT = "start";
1100
+ /** The snapshot that holds the state after a turn. */
1101
+ const snapshotOf = (id) => `after-${id}`;
1102
+ /** Builds what the client shows from the timeline. */
1103
+ function viewOf(timeline) {
1104
+ const turn = (node) => ({
1105
+ id: node.id,
1106
+ turn: node.turn,
1107
+ player: node.player,
1108
+ ...node.endSeq === void 0 ? {} : { endSeq: node.endSeq },
1109
+ ...node.output === void 0 ? {} : { output: node.output },
1110
+ restorable: node.snapshot !== void 0,
1111
+ alternatives: childrenOf(timeline, node.parent).map((sibling) => sibling.id)
1112
+ });
1113
+ const on = new Set(pathTo(timeline, timeline.head).map((node) => node.id));
1114
+ const withdrawn = timeline.nodes.filter((node) => !on.has(node.id) && node.userSeq >= 0).map((node) => ({
1115
+ from: Math.min(node.startSeq ?? node.userSeq, node.userSeq),
1116
+ to: node.endSeq ?? Number.MAX_SAFE_INTEGER
1117
+ }));
1118
+ return {
1119
+ head: timeline.head,
1120
+ path: pathTo(timeline, timeline.head).map(turn),
1121
+ forward: childrenOf(timeline, timeline.head).map(turn),
1122
+ canStart: true,
1123
+ withdrawn
1124
+ };
1125
+ }
1126
+ /** 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. */
1127
+ function noticeText(node) {
1128
+ 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");
1129
+ const ooc = node.output?.ooc;
1130
+ 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}`;
1131
+ return `The story, as it went earlier (restored):\nThe player said: ${node.player}${ruling}\nIt was told to the player:\n${told}`;
1132
+ }
1133
+ //#endregion
1134
+ //#region src/host/timeline/file.ts
1135
+ const TIMELINE_FILE = "timeline.json";
1136
+ function isNode(value) {
1137
+ if (typeof value !== "object" || value === null) return false;
1138
+ const node = value;
1139
+ 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";
1140
+ }
1141
+ /**
1142
+ * The timeline of a session, or an empty one when it has none yet.
1143
+ * @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.
1144
+ */
1145
+ function readTimeline(folder) {
1146
+ let text;
1147
+ try {
1148
+ text = readFileSync(join(folder, TIMELINE_FILE), "utf8");
1149
+ } catch (error) {
1150
+ if (error.code === "ENOENT") return emptyTimeline();
1151
+ throw error;
1152
+ }
1153
+ const value = JSON.parse(text);
1154
+ 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`);
1155
+ return value;
1156
+ }
1157
+ /** Writes it aside and renames it, so a crash leaves the timeline as it was. */
1158
+ function writeTimeline(folder, timeline) {
1159
+ const target = join(folder, TIMELINE_FILE);
1160
+ const aside = `${target}.writing`;
1161
+ writeFileSync(aside, JSON.stringify(timeline, null, 2));
1162
+ renameSync(aside, target);
1163
+ }
1164
+ //#endregion
1165
+ //#region src/host/timeline/branch.ts
1166
+ var BranchError = class extends Error {};
1167
+ /**
1168
+ * 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
1169
+ * that ended last, and the state of the story after that turn.
1170
+ * @param boundary - the seq of the last event the branch inherits.
1171
+ * @param snapshots - the names of the snapshots the story has.
1172
+ * @throws {BranchError} when the state at that point was not kept.
1173
+ */
1174
+ function branchTimeline(timeline, boundary, snapshots) {
1175
+ const nodes = timeline.nodes.filter((node) => node.endSeq !== void 0 && node.endSeq <= boundary).map((node) => ({ ...node }));
1176
+ for (const node of nodes) if (node.noticeSeq !== void 0 && node.noticeSeq > boundary) delete node.noticeSeq;
1177
+ const last = nodes.reduce((found, node) => found === void 0 || node.endSeq > found.endSeq ? node : found, void 0);
1178
+ const available = new Set(snapshots);
1179
+ for (const node of nodes) if (node.snapshot !== void 0 && !available.has(node.snapshot)) delete node.snapshot;
1180
+ const keep = [...nodes.flatMap((node) => node.snapshot === void 0 ? [] : [node.snapshot]), ...available.has("start") ? [START_SNAPSHOT] : []];
1181
+ const branch = {
1182
+ version: 1,
1183
+ head: last?.id ?? null,
1184
+ next: timeline.next,
1185
+ nodes
1186
+ };
1187
+ if (last === void 0) {
1188
+ if (!available.has("start")) throw new BranchError("the state at the start of the story was not kept, so it cannot be branched");
1189
+ return {
1190
+ timeline: branch,
1191
+ from: { snapshot: START_SNAPSHOT },
1192
+ keep
1193
+ };
1194
+ }
1195
+ if (last.snapshot !== void 0) return {
1196
+ timeline: branch,
1197
+ from: { snapshot: last.snapshot },
1198
+ keep
1199
+ };
1200
+ if (timeline.head === last.id) return {
1201
+ timeline: branch,
1202
+ from: { live: true },
1203
+ keep
1204
+ };
1205
+ throw new BranchError(`the state of the story after its turn ${last.turn} was not kept, so it cannot be branched there`);
1206
+ }
1207
+ /** The name of a branch: the story's name with its trailing number counted up, or a 2 added. */
1208
+ function branchName(name) {
1209
+ const numbered = /^(.*?)(\d+)\s*$/.exec(name);
1210
+ const next = numbered === null ? `${name} 2` : `${numbered[1]}${Number(numbered[2]) + 1}`;
1211
+ return next.length > 200 ? `${[...name].slice(0, 190).join("").trimEnd()} 2` : next;
1212
+ }
1213
+ //#endregion
1214
+ //#region src/host/timeline/plan.ts
1215
+ /**
1216
+ * Where the model's conversation has to be changed so that it carries the turns from the first to `target`, and no others.
1217
+ * 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
1218
+ * 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.
1219
+ * @param surface - the seqs of the model's conversation, in order.
1220
+ */
1221
+ function planMove(timeline, target, surface) {
1222
+ const onSurface = new Set(surface);
1223
+ const path = pathTo(timeline, target);
1224
+ let keptCount = 0;
1225
+ let last = -1;
1226
+ for (const node of path) {
1227
+ const at = surface.indexOf(node.userSeq);
1228
+ if (at <= last) break;
1229
+ last = at;
1230
+ keptCount += 1;
1231
+ }
1232
+ const kept = path.slice(0, keptCount);
1233
+ const keptIds = new Set(kept.map((node) => node.id));
1234
+ const byStart = [...timeline.nodes].sort((a, b) => a.userSeq - b.userSeq);
1235
+ const seqs = /* @__PURE__ */ new Set();
1236
+ byStart.forEach((node, index) => {
1237
+ if (keptIds.has(node.id)) return;
1238
+ if (node.noticeSeq !== void 0 && onSurface.has(node.noticeSeq)) seqs.add(node.noticeSeq);
1239
+ if (!onSurface.has(node.userSeq)) return;
1240
+ const end = node.endSeq ?? (byStart[index + 1]?.userSeq === void 0 ? Infinity : byStart[index + 1].userSeq - 1);
1241
+ for (const seq of surface) if (seq >= node.userSeq && seq <= end) seqs.add(seq);
1242
+ });
1243
+ const shadow = [];
1244
+ let run = [];
1245
+ let previous = -2;
1246
+ surface.forEach((seq, index) => {
1247
+ if (!seqs.has(seq)) return;
1248
+ if (index !== previous + 1 && run.length > 0) {
1249
+ shadow.push({
1250
+ startSeq: run[0],
1251
+ endSeq: run.at(-1),
1252
+ seqs: run
1253
+ });
1254
+ run = [];
1255
+ }
1256
+ run.push(seq);
1257
+ previous = index;
1258
+ });
1259
+ if (run.length > 0) shadow.push({
1260
+ startSeq: run[0],
1261
+ endSeq: run.at(-1),
1262
+ seqs: run
1263
+ });
1264
+ return {
1265
+ shadow,
1266
+ kept: kept.map((node) => node.id),
1267
+ inject: path.slice(keptCount)
1268
+ };
1269
+ }
1270
+ //#endregion
1271
+ //#region src/host/timeline/service.ts
1272
+ /** The text of the marker that stands for the turns it replaces: never empty, as a model service may refuse an empty message. */
1273
+ const MARKER_TEXT = "(empty message)";
1274
+ /** A turn that has not ended does not know yet where its own message is in the log. */
1275
+ const UNKNOWN_SEQ = -1;
1276
+ var TimelineError = class extends Error {};
1277
+ /**
1278
+ * What the story's turns are, and taking the story back to one of them (or forward again). The conversation with the model is
1279
+ * only ever added to: the turns that no longer belong are replaced by a marker, which DSH keeps out of the next request, and
1280
+ * 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.
1281
+ * Everything here is one at a time per chat.
1282
+ */
1283
+ var Timelines = class {
1284
+ deps;
1285
+ queues = /* @__PURE__ */ new Map();
1286
+ constructor(deps) {
1287
+ this.deps = deps;
1288
+ }
1289
+ serial(chat, job) {
1290
+ const run = (this.queues.get(chat) ?? Promise.resolve()).then(job, job);
1291
+ this.queues.set(chat, run.catch(() => void 0));
1292
+ return run;
1293
+ }
1294
+ idOf(chat) {
1295
+ const id = roleplaySessionOf(chat);
1296
+ if (id === void 0) throw new TimelineError(`${chat} is not a roleplay chat`);
1297
+ return id;
1298
+ }
1299
+ folder(id) {
1300
+ return sessionFolder(this.deps.sessionsDir(), id);
1301
+ }
1302
+ read(id) {
1303
+ return readTimeline(this.folder(id));
1304
+ }
1305
+ view(id) {
1306
+ return viewOf(this.read(id));
1307
+ }
1308
+ /**
1309
+ * 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,
1310
+ * with the records still waiting for the keeper in it (they are in the database, so a restored state carries them).
1311
+ */
1312
+ begin(chat, turn, player) {
1313
+ return this.serial(chat, async () => {
1314
+ this.deps.cancel?.(chat);
1315
+ const id = this.idOf(chat);
1316
+ const timeline = this.read(id);
1317
+ this.keep(id, timeline, timeline.head);
1318
+ const node = {
1319
+ id: `n${timeline.next}`,
1320
+ parent: timeline.head,
1321
+ turn,
1322
+ userSeq: UNKNOWN_SEQ,
1323
+ player,
1324
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
1325
+ };
1326
+ timeline.nodes.push(node);
1327
+ timeline.next += 1;
1328
+ timeline.head = node.id;
1329
+ writeTimeline(this.folder(id), timeline);
1330
+ this.prune(id, timeline);
1331
+ return node;
1332
+ });
1333
+ }
1334
+ /** What the turn delivered; and, once nothing writes to the story any more, its state is kept. */
1335
+ delivered(chat, output) {
1336
+ const id = this.idOf(chat);
1337
+ const timeline = this.read(id);
1338
+ const node = timeline.nodes.find((candidate) => candidate.id === timeline.head);
1339
+ if (node === void 0) return void 0;
1340
+ node.output = output;
1341
+ writeTimeline(this.folder(id), timeline);
1342
+ this.deps.engine.quiesce(chat).then(() => this.serial(chat, () => {
1343
+ const current = this.read(id);
1344
+ if (current.head === node.id) this.keep(id, current, node.id);
1345
+ return Promise.resolve();
1346
+ })).catch(() => void 0);
1347
+ return node.id;
1348
+ }
1349
+ /**
1350
+ * 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
1351
+ * (it is not in the log yet when the turn begins).
1352
+ */
1353
+ ended(chat, session, seq) {
1354
+ const id = this.idOf(chat);
1355
+ const timeline = this.read(id);
1356
+ const node = timeline.nodes.find((candidate) => candidate.id === timeline.head);
1357
+ if (node === void 0 || node.endSeq !== void 0) return;
1358
+ const after = Math.max(-1, ...timeline.nodes.filter((other) => other.id !== node.id).map((other) => other.endSeq ?? other.userSeq));
1359
+ const human = session.snapshotEvents().find((event) => event.seq > after && event.type === "user/message" && event.data.source.kind === "user");
1360
+ if (human === void 0) throw new TimelineError(`turn ${node.turn} has no message of the player in the log`);
1361
+ node.userSeq = human.seq;
1362
+ node.endSeq = seq;
1363
+ const began = session.snapshotEvents().find((event) => event.type === "turn/start" && event.data.turn === node.turn);
1364
+ node.startSeq = Math.min(began?.seq ?? human.seq, human.seq);
1365
+ writeTimeline(this.folder(id), timeline);
1366
+ }
1367
+ /** Keeps the state as it is under the name of the turn it follows from, when that is not done yet. */
1368
+ keep(id, timeline, at) {
1369
+ if (this.deps.keepSnapshots(id) === 0) return;
1370
+ const node = at === null ? void 0 : timeline.nodes.find((candidate) => candidate.id === at);
1371
+ const name = node === void 0 ? START_SNAPSHOT : snapshotOf(node.id);
1372
+ if (node !== void 0 && node.snapshot !== void 0) return;
1373
+ if (node === void 0 && this.deps.state.snapshots(this.deps.sessionsDir(), id).includes("start")) return;
1374
+ this.deps.state.snapshot(this.deps.sessionsDir(), id, name);
1375
+ if (node !== void 0) {
1376
+ node.snapshot = name;
1377
+ writeTimeline(this.folder(id), timeline);
1378
+ }
1379
+ }
1380
+ /** Lets the oldest snapshots go: only the turns most recently played keep theirs, and the one that holds the start stays. */
1381
+ prune(id, timeline) {
1382
+ const keep = this.deps.keepSnapshots(id);
1383
+ const kept = timeline.nodes.filter((node) => node.snapshot !== void 0);
1384
+ const dropped = kept.slice(0, Math.max(0, kept.length - keep));
1385
+ if (dropped.length === 0) return;
1386
+ for (const node of dropped) {
1387
+ this.deps.state.removeSnapshot(this.deps.sessionsDir(), id, node.snapshot);
1388
+ delete node.snapshot;
1389
+ }
1390
+ writeTimeline(this.folder(id), timeline);
1391
+ }
1392
+ /**
1393
+ * 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,
1394
+ * 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.
1395
+ * @returns what the player said in the first turn that was left, to put back in the input; nothing when the story went forward.
1396
+ * @throws {TimelineError} when there is no such turn, its state was not kept, or the chat is not loaded.
1397
+ */
1398
+ move(chat, target) {
1399
+ return this.serial(chat, async () => {
1400
+ const id = this.idOf(chat);
1401
+ const timeline = this.read(id);
1402
+ const to = target === null ? void 0 : timeline.nodes.find((node) => node.id === target);
1403
+ if (target !== null && to === void 0) throw new TimelineError(`there is no turn "${target}"`);
1404
+ const snapshot = target === null ? START_SNAPSHOT : to.snapshot;
1405
+ 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");
1406
+ const agent = await this.deps.agentOf(chat);
1407
+ if (agent === void 0) throw new TimelineError(`the chat ${chat} is not loaded`);
1408
+ if (agent.status !== "idle") {
1409
+ agent.cancel({ kind: "user" }, { keepInbox: true });
1410
+ await agent.whenIdle();
1411
+ }
1412
+ this.deps.cancel?.(chat);
1413
+ this.deps.engine.stop(chat);
1414
+ await this.deps.engine.quiesce(chat);
1415
+ this.deps.engine.forget(chat);
1416
+ const was = pathTo(timeline, timeline.head);
1417
+ const plan = planMove(timeline, target, [...agent.session.surface.nodes]);
1418
+ this.deps.state.restore(this.deps.sessionsDir(), id, snapshot);
1419
+ this.reconcile(agent, plan);
1420
+ timeline.head = target;
1421
+ writeTimeline(this.folder(id), timeline);
1422
+ const left = was.find((node) => !pathTo(timeline, target).some((kept) => kept.id === node.id));
1423
+ return left === void 0 ? {} : { draft: left.player };
1424
+ });
1425
+ }
1426
+ /** 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. */
1427
+ reconcile(agent, plan) {
1428
+ for (const run of plan.shadow) agent.session.append("user/message", createUserMessage({
1429
+ content: [{
1430
+ type: "text",
1431
+ text: MARKER_TEXT
1432
+ }],
1433
+ source: { kind: "roleplay" }
1434
+ }), {
1435
+ surfaceOp: {
1436
+ op: "replace",
1437
+ startSeq: run.startSeq,
1438
+ endSeq: run.endSeq
1439
+ },
1440
+ sourceEventSeqs: run.seqs
1441
+ });
1442
+ for (const node of plan.inject) node.noticeSeq = agent.session.append("user/message", createUserMessage({
1443
+ content: [{
1444
+ type: "text",
1445
+ text: noticeText(node)
1446
+ }],
1447
+ source: { kind: "roleplay" }
1448
+ }), { surfaceOp: "append" }).seq;
1449
+ }
1450
+ /**
1451
+ * 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
1452
+ * 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
1453
+ * 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.
1454
+ * @param cut - the seq of the last event of the log the branch inherits.
1455
+ * @returns whether a session was made.
1456
+ * @throws {BranchError} when the state at the cut was not kept; the branch is then not made.
1457
+ */
1458
+ adopt(chat, parent, cut, agent) {
1459
+ return this.serial(parent, async () => {
1460
+ const id = this.idOf(chat);
1461
+ const from = this.idOf(parent);
1462
+ const directory = this.deps.sessionsDir();
1463
+ if (existsSync(sessionDatabase(directory, id)) || !existsSync(sessionDatabase(directory, from))) return false;
1464
+ const branch = branchTimeline(this.read(from), cut, this.deps.state.snapshots(directory, from));
1465
+ if ("live" in branch.from) await this.deps.engine.quiesce(parent);
1466
+ const name = branchName(this.deps.state.openSession(directory, from).metadata.get().name);
1467
+ this.deps.state.fork(directory, from, id, branch.from, {
1468
+ name,
1469
+ keep: branch.keep
1470
+ });
1471
+ try {
1472
+ await inheritImages(this.folder(from), this.folder(id), branch.timeline.nodes.map((node) => node.id));
1473
+ inheritPrompts(this.folder(from), this.folder(id));
1474
+ inheritPacks(this.folder(from), this.folder(id));
1475
+ const plan = planMove(branch.timeline, branch.timeline.head, [...agent.session.surface.nodes]);
1476
+ this.reconcile(agent, plan);
1477
+ writeTimeline(this.folder(id), branch.timeline);
1478
+ } catch (error) {
1479
+ this.deps.state.deleteSession(directory, id);
1480
+ throw error;
1481
+ }
1482
+ return true;
1483
+ });
1484
+ }
1485
+ /** The turns that follow a turn, for the choices the story can be taken to. */
1486
+ forward(id) {
1487
+ const timeline = this.read(id);
1488
+ return childrenOf(timeline, timeline.head);
1489
+ }
1490
+ };
1491
+ //#endregion
1492
+ //#region src/host/orchestration/observation.ts
1493
+ /** What a character takes in where it stands and of what it carries: the place, the ways out and what they lead to, what lies in the open, what it holds. */
1494
+ function observeSurroundings(session, characterId, turn) {
1495
+ const placement = session.placements.get("character", characterId);
1496
+ if (placement !== void 0) {
1497
+ session.knowledge.learn(characterId, "location", placement.locationId, turn, true);
1498
+ for (const exit of session.locations.exitsFrom(placement.locationId)) {
1499
+ session.knowledge.learn(characterId, "exit", exit.id, turn, true);
1500
+ session.knowledge.learn(characterId, "location", exit.toId, turn);
1501
+ }
1502
+ for (const { item } of session.items.contents({
1503
+ kind: "location",
1504
+ id: placement.locationId
1505
+ })) if (!item.hidden) session.knowledge.learn(characterId, "item", item.id, turn, true);
1506
+ }
1507
+ for (const { item } of session.items.contents({
1508
+ kind: "character",
1509
+ id: characterId
1510
+ })) session.knowledge.learn(characterId, "item", item.id, turn, true);
1511
+ }
1512
+ /**
1513
+ * The player's character is never asked to act, so nothing else shows it its surroundings: it takes them in when a turn begins, which is
1514
+ * how it comes to know the way back from where it went.
1515
+ */
1516
+ function observeAsPlayer(session, turn) {
1517
+ const player = session.characters.list().find((character) => character.control === "player");
1518
+ if (player !== void 0) observeSurroundings(session, player.id, turn);
1519
+ }
1520
+ //#endregion
1521
+ //#region src/shared/notes.ts
1522
+ const NOTE_KINDS = [
1523
+ "suggestions",
1524
+ "away",
1525
+ "world"
1526
+ ];
1527
+ //#endregion
1528
+ //#region src/host/sessions/notes.ts
1529
+ const KEY$2 = "notes";
1530
+ const isNote = (value) => {
1531
+ if (typeof value !== "object" || value === null) return false;
1532
+ const note = value;
1533
+ return NOTE_KINDS.includes(note["kind"]) && typeof note["turn"] === "number" && Array.isArray(note["lines"]) && note["lines"].every((line) => typeof line === "string");
1534
+ };
1535
+ /** The notes of a session, at most one per kind. */
1536
+ function readNotes(session) {
1537
+ const stored = session.metadata.getValue(KEY$2);
1538
+ return Array.isArray(stored) ? stored.filter(isNote) : [];
1539
+ }
1540
+ /** Replaces the note of the same kind. */
1541
+ function putNote(session, note) {
1542
+ session.metadata.setValue(KEY$2, [...readNotes(session).filter((existing) => existing.kind !== note.kind), note]);
1543
+ }
1544
+ /** The most lines one note keeps: what is past it is not told. */
1545
+ const MAX_NOTE_LINES = 8;
1546
+ /** Adds lines to the note of the kind when it is of the same turn, else starts it. */
1547
+ function addToNote(session, kind, turn, lines) {
1548
+ if (lines.length === 0) return;
1549
+ putNote(session, {
1550
+ kind,
1551
+ turn,
1552
+ lines: [...readNotes(session).find((note) => note.kind === kind && note.turn === turn)?.lines ?? [], ...lines].slice(0, MAX_NOTE_LINES)
1553
+ });
1554
+ }
1555
+ /** Removes every note: they belong to the turn that made them. */
1556
+ function clearNotes(session) {
1557
+ if (readNotes(session).length > 0) session.metadata.setValue(KEY$2, []);
1558
+ }
1559
+ /**
1560
+ * The notes of a session, for the player's screen.
1561
+ * @throws {SessionNotFoundError} when the id names no session.
1562
+ */
1563
+ function notesOfSession(deps, id) {
1564
+ if (!isSessionId(id) || !existsSync(sessionDatabase(deps.sessionsDir(), id))) throw new SessionNotFoundError(`no session "${id}"`);
1565
+ return readNotes(deps.open(id));
1566
+ }
1567
+ //#endregion
1568
+ //#region src/host/pacing/director.ts
1569
+ const PLOTS_METADATA_KEY = "roleplay.pacing.plots";
1570
+ function populatePlots(metadata, plots) {
1571
+ const progress = plots.map((plot) => ({
1572
+ plot,
1573
+ status: plot.start,
1574
+ introduced: [],
1575
+ rejected: [],
1576
+ lastNudgeTurn: 0
1577
+ }));
1578
+ metadata.setValue(PLOTS_METADATA_KEY, progress);
1579
+ }
1580
+ function addSessionPlot(store, plot) {
1581
+ const plots = progressOf(store);
1582
+ if (plots.some((entry) => entry.plot.id === plot.id)) throw new Error(`there is already a plot "${plot.id}"`);
1583
+ plots.push({
1584
+ plot,
1585
+ status: plot.start,
1586
+ introduced: [],
1587
+ rejected: [],
1588
+ lastNudgeTurn: 0
1589
+ });
1590
+ store.story.metadata.setValue(PLOTS_METADATA_KEY, plots);
1591
+ }
1592
+ function plotAuthorNeeded(store, turn) {
1593
+ if (progressOf(store).length > 0 || turn < 5) return false;
1594
+ return store.story.events.list({
1595
+ fromTurn: Math.max(1, turn - 2),
1596
+ toTurn: turn - 1
1597
+ }).length === 0 && store.story.threads.list("open").length === 0;
1598
+ }
1599
+ function plotProgressOf(metadata) {
1600
+ const value = metadata.getValue(PLOTS_METADATA_KEY);
1601
+ return Array.isArray(value) ? value : [];
1602
+ }
1603
+ function progressOf(store) {
1604
+ return plotProgressOf(store.story.metadata);
1605
+ }
1606
+ /** Select one uncommitted possibility when the story has genuinely gone quiet; selection never makes it happen. */
1607
+ function pacingAdvice(store, turn) {
1608
+ const plots = progressOf(store);
1609
+ if (plots.length === 0) return void 0;
1610
+ const now = store.story.clock.get()?.now;
1611
+ const recent = store.story.events.list({
1612
+ fromTurn: Math.max(1, turn - 2),
1613
+ toTurn: turn - 1
1614
+ });
1615
+ const openThreads = store.story.threads.list("open");
1616
+ for (const progress of plots) {
1617
+ if (![
1618
+ "available",
1619
+ "engaged",
1620
+ "cooling"
1621
+ ].includes(progress.status)) continue;
1622
+ const quietTurns = progress.plot.pacing.quietTurns + (openThreads.length === 0 ? 0 : 2);
1623
+ if (recent.length > 0 || turn <= quietTurns) continue;
1624
+ if (turn - progress.lastNudgeTurn < progress.plot.pacing.cooldownTurns) continue;
1625
+ if (now !== void 0 && progress.lastNudgeAt !== void 0 && now - progress.lastNudgeAt < progress.plot.pacing.cooldownDays * 864e5) continue;
1626
+ const step = [...progress.plot.hooks, ...progress.plot.developments].filter((step) => !progress.introduced.includes(step.id) && !progress.rejected.includes(step.id) && step.prerequisites.every((id) => progress.introduced.includes(id)))[0];
1627
+ if (step === void 0) continue;
1628
+ const quietFor = turn - progress.lastNudgeTurn;
1629
+ progress.lastNudgeTurn = turn;
1630
+ if (now !== void 0) progress.lastNudgeAt = now;
1631
+ progress.status = progress.status === "available" ? "engaged" : progress.status;
1632
+ store.story.metadata.setValue(PLOTS_METADATA_KEY, plots);
1633
+ return {
1634
+ need: quietFor > progress.plot.pacing.quietTurns * 2 ? "clear" : "gentle",
1635
+ reason: openThreads.length === 0 ? "no recorded development or immediate thread has guided the last few turns" : "the open threads have remained without recorded development for several turns",
1636
+ plot: progress.plot.id,
1637
+ plotName: progress.plot.name,
1638
+ development: step.id,
1639
+ mode: step.mode,
1640
+ guidance: step.guidance || step.text,
1641
+ avoid: step.avoid
1642
+ };
1643
+ }
1644
+ }
1645
+ function describePacingAdvice(advice) {
1646
+ return `Pacing opportunity (${advice.need}; advice only, not an event): ${advice.plotName} [plot ${advice.plot}] / development ${advice.development}\nWhy now: ${advice.reason}.\nPossible nudge (${advice.mode}): ${advice.guidance}${advice.avoid.length === 0 ? "" : `\nDo not: ${advice.avoid.join("; ")}.`}\nUse it only if it fits the present scene. Do not make the player accept it, do not make a character act without activate_characters, and do not mark the development complete merely because it was offered.`;
1647
+ }
1648
+ function updatePlotProgress(store, plotId, developmentId, action) {
1649
+ const plots = progressOf(store);
1650
+ const progress = plots.find((entry) => entry.plot.id === plotId);
1651
+ if (progress === void 0) throw new Error(`there is no plot "${plotId}"`);
1652
+ if (action === "resolved" || action === "abandoned") progress.status = action;
1653
+ else {
1654
+ if (developmentId === void 0) throw new Error(`${action} needs a development`);
1655
+ if (![...progress.plot.hooks, ...progress.plot.developments].some((step) => step.id === developmentId)) throw new Error(`plot "${plotId}" has no development "${developmentId}"`);
1656
+ const target = action === "introduced" ? progress.introduced : progress.rejected;
1657
+ if (!target.includes(developmentId)) target.push(developmentId);
1658
+ if (action === "introduced") progress.status = "engaged";
1659
+ }
1660
+ store.story.metadata.setValue(PLOTS_METADATA_KEY, plots);
1661
+ return progress;
1662
+ }
1663
+ //#endregion
1664
+ //#region src/host/orchestration/whereabouts.ts
1665
+ const within = (inner, outer, places) => {
1666
+ const byId = new Map(places.map((place) => [place.id, place]));
1667
+ const seen = /* @__PURE__ */ new Set();
1668
+ for (let at = inner; at !== void 0 && !seen.has(at.id); at = at.parentId === void 0 ? void 0 : byId.get(at.parentId)) {
1669
+ if (at.id === outer.id) return true;
1670
+ seen.add(at.id);
1671
+ }
1672
+ return false;
1673
+ };
1674
+ /** Whether two places are one scene: the same place, or one inside the other (a room and its building). */
1675
+ const sameScene = (a, b, places) => within(a, b, places) || within(b, a, places);
1676
+ /**
1677
+ * 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
1678
+ * 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.
1679
+ */
1680
+ function whereabouts(places, here, at) {
1681
+ const target = places.find((place) => locationKey(place) === at);
1682
+ if (target === void 0) return { kind: "unknown" };
1683
+ if (here === void 0) return { kind: "unplaced" };
1684
+ return within(here, target, places) || within(target, here, places) ? { kind: "here" } : {
1685
+ kind: "elsewhere",
1686
+ target,
1687
+ here
1688
+ };
1689
+ }
1690
+ //#endregion
1691
+ //#region src/host/memory/reflection.ts
1692
+ const LAST_KEY = "reflection.last";
1693
+ const CURSOR_KEY = "reflection.cursor";
1694
+ const ANCHOR_KEY = "reflection.anchor";
1695
+ const ERROR_KEY = "reflection.error";
1696
+ const DAY_MS = 864e5;
1697
+ const MAX_MATERIAL = 40;
1698
+ const MAX_BELIEFS_SHOWN = 40;
1699
+ const MAX_ADDED = 4;
1700
+ const MAX_CHANGES = 10;
1701
+ const MAX_TEXT = 300;
1702
+ /** An event this important is reason enough for a belief on its own. */
1703
+ const DECISIVE_IMPORTANCE = 4;
1704
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1705
+ function readLast(session) {
1706
+ const stored = session.metadata.getValue(LAST_KEY);
1707
+ return isRecord(stored) && typeof stored["turn"] === "number" ? stored : void 0;
1708
+ }
1709
+ function readCursor(session) {
1710
+ const stored = session.metadata.getValue(CURSOR_KEY);
1711
+ return isRecord(stored) ? Object.fromEntries(Object.entries(stored).filter((entry) => typeof entry[1] === "number")) : {};
1712
+ }
1713
+ function readAnchor(session) {
1714
+ const stored = session.metadata.getValue(ANCHOR_KEY);
1715
+ return isRecord(stored) && typeof stored["now"] === "number" ? {
1716
+ now: stored["now"],
1717
+ ...typeof stored["place"] === "number" ? { place: stored["place"] } : {}
1718
+ } : void 0;
1719
+ }
1720
+ function writeAnchor(session, place, now) {
1721
+ session.metadata.setValue(ANCHOR_KEY, {
1722
+ now,
1723
+ ...place === void 0 ? {} : { place: place.id }
1724
+ });
1725
+ }
1726
+ const playerPlace = (store) => store.cast().find((member) => member.character.control === "player")?.place?.location;
1727
+ /** What is known of the story's reflection: whether a pass runs, the latest that finished, and why the latest failed. */
1728
+ function reflectionStatus(session, running) {
1729
+ const last = readLast(session);
1730
+ const failure = session.metadata.getValue(ERROR_KEY);
1731
+ return {
1732
+ running,
1733
+ ...last === void 0 ? {} : { last },
1734
+ ...isRecord(failure) && typeof failure["message"] === "string" && typeof failure["at"] === "string" ? { error: {
1735
+ at: failure["at"],
1736
+ message: failure["message"]
1737
+ } } : {}
1738
+ };
1739
+ }
1740
+ function recordFailure(session, message) {
1741
+ session.metadata.setValue(ERROR_KEY, {
1742
+ at: (/* @__PURE__ */ new Date()).toISOString(),
1743
+ message: message.slice(0, 500)
1744
+ });
1745
+ }
1746
+ /**
1747
+ * Whether the story should reflect after this turn, and why. A pass waits until `minTurns` turns have passed since the last one; then it
1748
+ * comes after `everyTurns` turns, or when the scene has changed since the last pass (the player's character is somewhere that is neither
1749
+ * where it was nor inside or around it, or `sceneDays` of story time have passed). The first look only notes where the story stands.
1750
+ */
1751
+ function dueReflection(store, turn) {
1752
+ const { reflection } = store.settings();
1753
+ if (!reflection.auto) return void 0;
1754
+ const session = store.story;
1755
+ const { now } = store.time(turn);
1756
+ const here = playerPlace(store);
1757
+ const anchor = readAnchor(session);
1758
+ if (anchor === void 0) {
1759
+ writeAnchor(session, here, now);
1760
+ return;
1761
+ }
1762
+ const since = turn - (readLast(session)?.turn ?? 0);
1763
+ if (since < reflection.minTurns) return void 0;
1764
+ if (reflection.everyTurns > 0 && since >= reflection.everyTurns) return "turns";
1765
+ if (!reflection.onSceneChange) return void 0;
1766
+ const places = session.locations.list();
1767
+ const before = places.find((place) => place.id === anchor.place);
1768
+ if (here !== void 0 && before !== void 0 && !sameScene(here, before, places)) return "scene";
1769
+ if (reflection.sceneDays > 0 && now - anchor.now >= reflection.sceneDays * DAY_MS) return "scene";
1770
+ }
1771
+ /**
1772
+ * 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
1773
+ * still a draft, so that nothing is passed over that is sealed later.
1774
+ */
1775
+ function materialOf(session, minNew) {
1776
+ const cursor = readCursor(session);
1777
+ const found = [];
1778
+ for (const character of session.characters.list()) {
1779
+ if (character.control !== "agent" || character.kind !== "person" || character.tier === "background") continue;
1780
+ const taken = session.events.perceivedBy(character.id);
1781
+ const draft = taken.filter((entry) => !entry.event.sealed).map((entry) => entry.perception.id);
1782
+ const ceiling = draft.length === 0 ? Infinity : Math.min(...draft) - 1;
1783
+ 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);
1784
+ if (fresh.length < minNew) continue;
1785
+ const beliefs = session.memories.list(character.id).sort((a, b) => b.importance - a.importance || a.id - b.id).slice(0, MAX_BELIEFS_SHOWN);
1786
+ found.push({
1787
+ character,
1788
+ fresh,
1789
+ beliefs
1790
+ });
1791
+ }
1792
+ return found.sort((a, b) => b.fresh.length - a.fresh.length);
1793
+ }
1794
+ const idList = {
1795
+ type: "array",
1796
+ items: { type: "integer" }
1797
+ };
1798
+ const RESULT = {
1799
+ type: "object",
1800
+ properties: {
1801
+ add: {
1802
+ type: "array",
1803
+ description: "New beliefs, at most four. Leave empty when nothing new can be firmly said.",
1804
+ items: {
1805
+ type: "object",
1806
+ properties: {
1807
+ kind: {
1808
+ type: "string",
1809
+ enum: [...MEMORY_KINDS],
1810
+ description: "belief: what it holds true or suspects; relationship: how it stands with someone; knowledge: something it knows."
1811
+ },
1812
+ text: {
1813
+ type: "string",
1814
+ 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."
1815
+ },
1816
+ about: {
1817
+ type: "array",
1818
+ items: { type: "string" },
1819
+ description: "The names of the characters it is about."
1820
+ },
1821
+ importance: {
1822
+ type: "integer",
1823
+ description: `From 1 (passing) to 5 (it shapes how they act).`
1824
+ },
1825
+ confidence: {
1826
+ type: "string",
1827
+ enum: [...MEMORY_CONFIDENCES],
1828
+ description: "How sure they are: doubtful, likely (when you leave it out) or sure, which needs things from at least two different turns."
1829
+ },
1830
+ perceptions: {
1831
+ ...idList,
1832
+ description: "The numbers of the things it took in that this rests on."
1833
+ },
1834
+ beliefs: {
1835
+ ...idList,
1836
+ description: "The numbers of the beliefs it generalises or builds on, if any."
1837
+ }
1838
+ },
1839
+ required: [
1840
+ "kind",
1841
+ "text",
1842
+ "importance",
1843
+ "perceptions"
1844
+ ],
1845
+ additionalProperties: false
1846
+ }
1847
+ },
1848
+ revise: {
1849
+ type: "array",
1850
+ description: "Beliefs to firm up, doubt or correct in the light of what came after them.",
1851
+ items: {
1852
+ type: "object",
1853
+ properties: {
1854
+ id: {
1855
+ type: "integer",
1856
+ description: "The number of the belief, as listed."
1857
+ },
1858
+ text: {
1859
+ type: "string",
1860
+ description: "The belief as it should read now."
1861
+ },
1862
+ importance: {
1863
+ type: "integer",
1864
+ description: `From 1 to 5.`
1865
+ },
1866
+ confidence: {
1867
+ type: "string",
1868
+ enum: [...MEMORY_CONFIDENCES],
1869
+ description: "How sure they are now. Raise it only for what supports the belief; lower it only together with contradicted_by."
1870
+ },
1871
+ perceptions: {
1872
+ ...idList,
1873
+ description: "The numbers of the things it took in since that support the belief or bear on it."
1874
+ },
1875
+ contradicted_by: {
1876
+ ...idList,
1877
+ 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."
1878
+ }
1879
+ },
1880
+ required: ["id"],
1881
+ additionalProperties: false
1882
+ }
1883
+ },
1884
+ drop: {
1885
+ type: "array",
1886
+ description: "Beliefs to let go: settled or overturned by what came after, or merged into another.",
1887
+ items: {
1888
+ type: "object",
1889
+ properties: {
1890
+ id: { type: "integer" },
1891
+ perceptions: {
1892
+ ...idList,
1893
+ description: "What it took in since that settles or overturns it."
1894
+ },
1895
+ merged_into: {
1896
+ type: "integer",
1897
+ description: "The number of the belief that now says the same, instead of a reason from what it took in."
1898
+ }
1899
+ },
1900
+ required: ["id"],
1901
+ additionalProperties: false
1902
+ }
1903
+ }
1904
+ },
1905
+ required: [
1906
+ "add",
1907
+ "revise",
1908
+ "drop"
1909
+ ],
1910
+ additionalProperties: false
1911
+ };
1912
+ function shownOf(session, material) {
1913
+ const turnOf = (perceptionId) => {
1914
+ const seen = session.events.getPerception(perceptionId);
1915
+ return seen === void 0 ? void 0 : session.events.get(seen.eventId)?.turn;
1916
+ };
1917
+ return {
1918
+ perceptions: new Map(material.fresh.map((entry) => [entry.perception.id, entry])),
1919
+ beliefs: new Map(material.beliefs.map((belief) => [belief.id, belief])),
1920
+ 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) ?? []))]))
1921
+ };
1922
+ }
1923
+ const rankOf = (confidence) => MEMORY_CONFIDENCES.indexOf(confidence);
1924
+ /**
1925
+ * 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
1926
+ * 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
1927
+ * into another. Nothing is judged about whether the belief is wise; only whether it is grounded in what the character was given.
1928
+ */
1929
+ function proposalProblems(proposal, shown, resolveName, tr = translator("en")) {
1930
+ const problems = [];
1931
+ const add = proposal.add ?? [];
1932
+ const revise = proposal.revise ?? [];
1933
+ const drop = proposal.drop ?? [];
1934
+ if (add.length > MAX_ADDED) problems.push(tr("add: at most {max} new beliefs in one pass; merge or choose", { max: MAX_ADDED }));
1935
+ if (add.length + revise.length + drop.length > MAX_CHANGES) problems.push(tr("at most {max} changes in one pass", { max: MAX_CHANGES }));
1936
+ const cited = (ids, where) => (ids ?? []).flatMap((id) => {
1937
+ const entry = shown.perceptions.get(id);
1938
+ if (entry === void 0) problems.push(tr("{where}: there is no thing it took in numbered {id}", {
1939
+ where,
1940
+ id
1941
+ }));
1942
+ return entry === void 0 ? [] : [entry];
1943
+ });
1944
+ const known = (value, where) => {
1945
+ const fine = value === void 0 || MEMORY_CONFIDENCES.includes(value);
1946
+ if (!fine) problems.push(tr("{where}: confidence is one of {options}", {
1947
+ where,
1948
+ options: MEMORY_CONFIDENCES.join(", ")
1949
+ }));
1950
+ return fine;
1951
+ };
1952
+ add.forEach((belief, index) => {
1953
+ const where = `add[${index}]`;
1954
+ if (!MEMORY_KINDS.includes(belief.kind)) problems.push(tr("{where}: unknown kind \"{kind}\"", {
1955
+ where,
1956
+ kind: belief.kind
1957
+ }));
1958
+ if (belief.text.trim() === "") problems.push(tr("{where}: say what it believes", { where }));
1959
+ else if (belief.text.trim().length > MAX_TEXT) problems.push(tr("{where}: at most {max} characters; say it shorter", {
1960
+ where,
1961
+ max: MAX_TEXT
1962
+ }));
1963
+ if (!Number.isInteger(belief.importance) || belief.importance < 1 || belief.importance > 5) problems.push(tr("{where}: importance runs from {min} to {max}", {
1964
+ where,
1965
+ min: 1,
1966
+ max: 5
1967
+ }));
1968
+ const sure = known(belief.confidence, where) && belief.confidence === "sure";
1969
+ const events = cited(belief.perceptions, where);
1970
+ const built = (belief.beliefs ?? []).flatMap((id) => {
1971
+ const found = shown.beliefs.get(id);
1972
+ if (found === void 0) problems.push(tr("{where}: there is no belief numbered {id}", {
1973
+ where,
1974
+ id
1975
+ }));
1976
+ return found === void 0 ? [] : [found];
1977
+ });
1978
+ const turns = /* @__PURE__ */ new Set([...events.map((entry) => entry.event.turn), ...built.map((found) => found.turn)]);
1979
+ 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 }));
1980
+ 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 }));
1981
+ 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", {
1982
+ where,
1983
+ name
1984
+ }));
1985
+ });
1986
+ const touched = /* @__PURE__ */ new Set();
1987
+ const touch = (id, where) => {
1988
+ if (touched.has(id)) problems.push(tr("{where}: belief {id} is already changed in this pass", {
1989
+ where,
1990
+ id
1991
+ }));
1992
+ touched.add(id);
1993
+ };
1994
+ const fresh = (events, belief, where) => {
1995
+ if (events.length === 0) problems.push(tr("{where}: say what it took in since that bears on it", { where }));
1996
+ 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", {
1997
+ where,
1998
+ id: entry.perception.id
1999
+ }));
2000
+ };
2001
+ revise.forEach((change, index) => {
2002
+ const where = `revise[${index}]`;
2003
+ const belief = shown.beliefs.get(change.id);
2004
+ if (belief === void 0) {
2005
+ problems.push(tr("{where}: there is no belief numbered {id}", {
2006
+ where,
2007
+ id: change.id
2008
+ }));
2009
+ return;
2010
+ }
2011
+ touch(change.id, where);
2012
+ const supports = cited(change.perceptions, where);
2013
+ const against = cited(change.contradicted_by, where);
2014
+ if (change.text === void 0 && change.importance === void 0 && change.confidence === void 0 && against.length === 0) problems.push(tr("{where}: say what changes", { where }));
2015
+ 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", {
2016
+ where,
2017
+ max: MAX_TEXT
2018
+ }));
2019
+ 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}", {
2020
+ where,
2021
+ min: 1,
2022
+ max: 5
2023
+ }));
2024
+ fresh([...supports, ...against], belief, where);
2025
+ if (!known(change.confidence, where) || change.confidence === void 0) {
2026
+ if (against.length > 0) problems.push(tr("{where}: a belief that something contradicts must be doubted: lower its confidence", { where }));
2027
+ return;
2028
+ }
2029
+ 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 }));
2030
+ 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 }));
2031
+ if (change.confidence === "sure" && belief.confidence !== "sure") {
2032
+ 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 }));
2033
+ }
2034
+ });
2035
+ const dropped = new Set(drop.map((entry) => entry.id));
2036
+ drop.forEach((change, index) => {
2037
+ const where = `drop[${index}]`;
2038
+ const belief = shown.beliefs.get(change.id);
2039
+ if (belief === void 0) {
2040
+ problems.push(tr("{where}: there is no belief numbered {id}", {
2041
+ where,
2042
+ id: change.id
2043
+ }));
2044
+ return;
2045
+ }
2046
+ touch(change.id, where);
2047
+ if (change.merged_into !== void 0) {
2048
+ 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 }));
2049
+ return;
2050
+ }
2051
+ fresh(cited(change.perceptions, where), belief, where);
2052
+ });
2053
+ return problems;
2054
+ }
2055
+ const keysOf = (names, resolveName) => (names ?? []).flatMap((name) => {
2056
+ const key = resolveName(name);
2057
+ return key === void 0 ? [] : [key];
2058
+ });
2059
+ /** The edit that writes a proposal that passed. */
2060
+ function editOf(turn, character, proposal, resolveName) {
2061
+ const who = characterKey(character);
2062
+ return {
2063
+ turn,
2064
+ beliefs: (proposal.add ?? []).map((belief) => ({
2065
+ character: who,
2066
+ kind: belief.kind,
2067
+ text: belief.text.trim(),
2068
+ about: keysOf(belief.about, resolveName),
2069
+ importance: belief.importance,
2070
+ ...belief.confidence === void 0 ? {} : { confidence: belief.confidence },
2071
+ evidenceFor: belief.perceptions ?? []
2072
+ })),
2073
+ beliefEdits: (proposal.revise ?? []).map((change) => ({
2074
+ id: change.id,
2075
+ ...change.text === void 0 ? {} : { text: change.text.trim() },
2076
+ ...change.importance === void 0 ? {} : { importance: change.importance },
2077
+ ...change.confidence === void 0 ? {} : { confidence: change.confidence },
2078
+ evidenceFor: change.perceptions ?? [],
2079
+ evidenceAgainst: change.contradicted_by ?? []
2080
+ })),
2081
+ beliefRetractions: (proposal.drop ?? []).map((change) => change.id)
2082
+ };
2083
+ }
2084
+ function brief(session, material, now, zone, time, tr) {
2085
+ const { character, fresh, beliefs } = material;
2086
+ const named = (id) => session.characters.get(id)?.name ?? String(id);
2087
+ const { disputed } = session.memories.evidenceIndex(character.id);
2088
+ const believed = beliefs.map((belief) => {
2089
+ const about = belief.about.length === 0 ? "" : tr(", about {names}", { names: belief.about.map(named).join(tr(" and ")) });
2090
+ const dispute = disputed.has(belief.id) ? tr(", something taken in since speaks against it") : "";
2091
+ return `- b${belief.id} (${tr("{kind}, importance {importance}, {confidence}{about}{dispute}", {
2092
+ kind: belief.kind,
2093
+ importance: belief.importance,
2094
+ confidence: tr(belief.confidence),
2095
+ about,
2096
+ dispute
2097
+ })}): ${belief.text}`;
2098
+ });
2099
+ const taken = fresh.map((entry) => {
2100
+ const at = time(entry.event.turn, entry.event.round);
2101
+ return `- p${entry.perception.id}${at === void 0 ? "" : ` (${describeWhen(at, now, zone)})`}: ${entry.perception.content}`;
2102
+ });
2103
+ return [
2104
+ tr("Character: {name}{summary}", {
2105
+ name: referent(character),
2106
+ summary: character.summary === "" ? "" : ` - ${character.summary}`
2107
+ }),
2108
+ tr("What they believe now:"),
2109
+ ...believed.length === 0 ? [tr("(nothing yet)")] : believed,
2110
+ tr("What they have taken in since:"),
2111
+ ...taken,
2112
+ tr("Sort their memory.")
2113
+ ].join("\n");
2114
+ }
2115
+ /**
2116
+ * 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
2117
+ * 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
2118
+ * and leaves the characters not yet done as they were.
2119
+ */
2120
+ function memoryReflector(deps) {
2121
+ return { async reflect(job, signal) {
2122
+ const parent = deps.agentOf(job.chat);
2123
+ if (parent === void 0) throw new Error(`no agent for chat ${job.chat}`);
2124
+ const { store } = job;
2125
+ const session = store.story;
2126
+ const settings = store.settings();
2127
+ const { now, zone } = store.time(job.turn);
2128
+ const due = materialOf(session, job.reason === "manual" ? 1 : settings.reflection.minNew);
2129
+ const taken = job.reason === "manual" ? due : due.slice(0, settings.reflection.perRun);
2130
+ const resolveName = (name) => {
2131
+ const found = session.characters.findByName(name.trim());
2132
+ return found.length === 1 ? characterKey(found[0]) : void 0;
2133
+ };
2134
+ const tr = translator(languageOf(settings.prompts.language));
2135
+ const characters = [];
2136
+ for (const material of taken) {
2137
+ const shown = shownOf(session, material);
2138
+ const proposal = await runChild({
2139
+ parent,
2140
+ signal,
2141
+ reasoningEffort: settings.reasoning.children,
2142
+ sampling: childSampling(settings, "records"),
2143
+ ...childModel(settings, "records"),
2144
+ trace: childTrace(store, "records", `reflection ${material.character.name}`),
2145
+ persona: promptFor(parent, "roleplay/reflection", settings.prompts.language),
2146
+ prompt: brief(session, material, now, zone, (turn, round) => session.clock.at(turn, round), tr),
2147
+ result: RESULT,
2148
+ beforeSubmit: (value) => {
2149
+ const given = value;
2150
+ const problems = [...proposalProblems(given, shown, resolveName, tr), ...[wrongLanguage(settings.prompts.language, { beliefs: [...given.add ?? [], ...given.revise ?? []].map((belief) => belief.text ?? "").join(" ") })].flatMap((problem) => problem === void 0 ? [] : [problem])];
2151
+ return problems.length === 0 ? void 0 : tr("not acceptable: {problems}", { problems: problems.join("; ") });
2152
+ },
2153
+ maxCalls: 3
2154
+ });
2155
+ const reached = Math.max(...material.fresh.map((entry) => entry.perception.id));
2156
+ session.transaction(() => {
2157
+ session.edit(editOf(job.turn, material.character, proposal, resolveName));
2158
+ session.metadata.setValue(CURSOR_KEY, {
2159
+ ...readCursor(session),
2160
+ [characterKey(material.character)]: reached
2161
+ });
2162
+ });
2163
+ characters.push({
2164
+ name: material.character.name,
2165
+ added: proposal.add?.length ?? 0,
2166
+ revised: proposal.revise?.length ?? 0,
2167
+ dropped: proposal.drop?.length ?? 0
2168
+ });
2169
+ }
2170
+ session.metadata.setValue(LAST_KEY, {
2171
+ turn: job.turn,
2172
+ at: (/* @__PURE__ */ new Date()).toISOString(),
2173
+ reason: job.reason,
2174
+ characters
2175
+ });
2176
+ writeAnchor(session, playerPlace(store), now);
2177
+ session.metadata.deleteValue(ERROR_KEY);
2178
+ return { characters };
2179
+ } };
2180
+ }
2181
+ //#endregion
2182
+ //#region src/host/sessions/activity.ts
2183
+ const KEY$1 = "activity";
2184
+ const isEntry = (value) => {
2185
+ if (typeof value !== "object" || value === null) return false;
2186
+ const entry = value;
2187
+ return typeof entry["at"] === "number" && typeof entry["label"] === "string" && typeof entry["model"] === "string" && typeof entry["ms"] === "number" && typeof entry["calls"] === "number" && (entry["error"] === void 0 || typeof entry["error"] === "string");
2188
+ };
2189
+ /** The recorded runs, oldest first. */
2190
+ function readActivity(session) {
2191
+ const stored = session.metadata.getValue(KEY$1);
2192
+ return Array.isArray(stored) ? stored.filter(isEntry) : [];
2193
+ }
2194
+ /** Files the run and returns the runs that fell off the end of the record to make room. */
2195
+ function recordActivity(session, entry) {
2196
+ const all = [...readActivity(session), entry];
2197
+ session.metadata.setValue(KEY$1, all.slice(-60));
2198
+ return all.slice(0, -60);
2199
+ }
2200
+ const RUN_FOLDER = "activity";
2201
+ const RUN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
2202
+ const runFile = (folder, run) => {
2203
+ if (!RUN_ID.test(run)) throw new RangeError(`"${run}" is not a run`);
2204
+ return join(folder, RUN_FOLDER, `${run}.json`);
2205
+ };
2206
+ /** Stores what a helper was told and did, beside the session's database: it is bulky, and only read to find out what went wrong. */
2207
+ function keepRunDetail(folder, run, detail) {
2208
+ const file = runFile(folder, run);
2209
+ mkdirSync(join(folder, RUN_FOLDER), { recursive: true });
2210
+ writeFileSync(`${file}.tmp`, JSON.stringify(detail));
2211
+ renameSync(`${file}.tmp`, file);
2212
+ }
2213
+ /** The stored detail of a run, or nothing when it was not kept or has been dropped. */
2214
+ function readRunDetail(folder, run) {
2215
+ try {
2216
+ return JSON.parse(readFileSync(runFile(folder, run), "utf8"));
2217
+ } catch (error) {
2218
+ if (error.code === "ENOENT") return void 0;
2219
+ throw error;
2220
+ }
2221
+ }
2222
+ function forgetRunDetails(folder, dropped) {
2223
+ for (const entry of dropped) if (entry.run !== void 0) rmSync(runFile(folder, entry.run), { force: true });
2224
+ }
2225
+ //#endregion
2226
+ //#region src/host/triggers/deliver.ts
2227
+ const KEY = "triggers.withdrawn";
2228
+ /** Why a note was withdrawn instead of told, by the number of the note. */
2229
+ function readWithdrawn(session) {
2230
+ const stored = session.metadata.getValue(KEY);
2231
+ if (!Array.isArray(stored)) return {};
2232
+ return Object.fromEntries(stored.flatMap((entry) => {
2233
+ const { note, reason } = entry ?? {};
2234
+ return typeof note === "number" && typeof reason === "string" ? [[note, reason]] : [];
2235
+ }));
2236
+ }
2237
+ /**
2238
+ * Tells these notes as the story stands now: each is written from the story at this moment, and one that no longer applies is let go and the
2239
+ * reason kept (`readWithdrawn`). @returns what is to be told, with the number of its note.
2240
+ */
2241
+ function deliverNow(session, notes, clock) {
2242
+ const { shown, withdrawn } = session.deliverNotes(notes, clock);
2243
+ if (withdrawn.length > 0) session.transaction(() => {
2244
+ for (const { note } of withdrawn) session.triggers.resolveNote(note.id, "lapsed");
2245
+ const before = Object.entries(readWithdrawn(session)).map(([note, reason]) => ({
2246
+ note: Number(note),
2247
+ reason
2248
+ }));
2249
+ session.metadata.setValue(KEY, [...before, ...withdrawn.map(({ note, reason }) => ({
2250
+ note: note.id,
2251
+ reason
2252
+ }))].slice(-100));
2253
+ });
2254
+ return shown.map(({ note, text }) => ({
2255
+ id: note.id,
2256
+ text
2257
+ }));
2258
+ }
2259
+ //#endregion
2260
+ export { readTimeline as A, skipTime as B, notesOfSession as C, observeSurroundings as D, observeAsPlayer as E, beginTurn as F, RESULTS as G, referent as H, describeTime as I, languageOf as J, answerEstimate as K, describeWhen as L, defaultBoundaries as M, sameWords as N, TimelineError as O, ClockError as P, endRound as R, clearNotes as S, readNotes as T, AWAY_ACTION_SCHEMA as U, zoneOf as V, CHARACTER_ACTION_SCHEMA as W, translator as Y, plotAuthorNeeded as _, readActivity as a, updatePlotProgress as b, dueReflection as c, reflectionStatus as d, whereabouts as f, pacingAdvice as g, describePacingAdvice as h, keepRunDetail as i, pathTo as j, Timelines as k, memoryReflector as l, addSessionPlot as m, readWithdrawn as n, readRunDetail as o, PLOTS_METADATA_KEY as p, parseCharacterAction as q, forgetRunDetails as r, recordActivity as s, deliverNow as t, recordFailure as u, plotProgressOf as v, putNote as w, addToNote as x, populatePlots as y, readTime as z };
2261
+
2262
+ //# sourceMappingURL=deliver-BDW5WZvc.js.map