@dsh-agentic-roleplay/core 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/lib/authoring.js +13 -2
  2. package/lib/child-lPncV1ps.js +380 -0
  3. package/lib/client.js +1526 -356
  4. package/lib/client.js.map +1 -1
  5. package/lib/compaction.js +1 -1
  6. package/lib/deliver-De62a8i9.js +1929 -0
  7. package/lib/doctor-chat-ByDfCMeo.js +17 -0
  8. package/lib/doctor.js +95 -0
  9. package/lib/{documents-DtlY2IRt.js → documents-Do4lz4SB.js} +549 -64
  10. package/lib/{gallery-DACG5eh2.js → gallery-CtFDL22W.js} +2 -2
  11. package/lib/{generator-DGYcLMp7.js → generator-B6FxlKOV.js} +2 -378
  12. package/lib/hooks-Ka22sFNy.js +1019 -0
  13. package/lib/images.js +3 -3
  14. package/lib/index.js +303 -190
  15. package/lib/language-DWVwi1R7.js +520 -0
  16. package/lib/narration-DK2kiIjE.js +141 -0
  17. package/lib/orchestration.js +777 -2542
  18. package/lib/{packs-CkRZDCsV.js → packs-BYjrAen6.js} +4 -518
  19. package/lib/{presenter-agent-PK9JYExk.js → presenter-agent-Dt21K96b.js} +4 -3
  20. package/lib/{deliver-BDW5WZvc.js → reflection-md7BCYCl.js} +350 -769
  21. package/lib/{narration-5ig7Dg28.js → settings-CA6icLL_.js} +156 -141
  22. package/package.json +3 -2
  23. package/prompts/en/doctor/persona.md +1 -0
  24. package/prompts/en/doctor/procedure.md +5 -0
  25. package/prompts/en/doctor/welcome.md +1 -0
  26. package/prompts/en/import/character.md +1 -0
  27. package/prompts/en/roleplay/dice.md +7 -0
  28. package/prompts/en/roleplay/game-master.md +2 -0
  29. package/prompts/en/roleplay/reflection-check.md +5 -0
  30. package/prompts/en/roleplay/reflection.md +5 -1
  31. package/prompts/zh/doctor/persona.md +1 -0
  32. package/prompts/zh/doctor/procedure.md +5 -0
  33. package/prompts/zh/doctor/welcome.md +1 -0
  34. package/prompts/zh/import/character.md +1 -0
  35. package/prompts/zh/roleplay/dice.md +7 -0
  36. package/prompts/zh/roleplay/game-master.md +2 -0
  37. package/prompts/zh/roleplay/reflection-check.md +5 -0
  38. package/prompts/zh/roleplay/reflection.md +5 -1
  39. package/lib/src-CWTNeL6Y.js +0 -128
@@ -1,11 +1,14 @@
1
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";
2
+ import { i as inheritPacks } from "./packs-BYjrAen6.js";
3
+ import "./settings-CA6icLL_.js";
4
+ import { _ as inheritPrompts, a as wrongLanguage } from "./language-DWVwi1R7.js";
5
+ import { B as languageOf, M as describeTime, N as describeWhen, V as translator, z as answerLimits } from "./deliver-De62a8i9.js";
6
+ import { a as runChild, i as childTrace, n as childSampling, o as estimateAnswer, t as childModel } from "./child-lPncV1ps.js";
7
+ import { u as inheritImages } from "./generator-B6FxlKOV.js";
5
8
  import { join } from "node:path";
6
- import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
9
+ import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
7
10
  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";
11
+ import { MINUTE, characterKey, describeDuration, locationKey, mentioned, overlap, sessionDatabase, sessionFolder, tokens } from "@dsh-agentic-roleplay/state";
9
12
  //#region ../dsh-roleplay-model/src/memory.ts
10
13
  const MEMORY_KINDS = [
11
14
  "belief",
@@ -19,350 +22,6 @@ const MEMORY_CONFIDENCES = [
19
22
  "sure"
20
23
  ];
21
24
  //#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
25
  //#region src/host/orchestration/referent.ts
367
26
  /**
368
27
  * How a person is named wherever the text may go on to say what they do: the name with the pronouns the world gave them, or the gender when only that is given.
@@ -373,154 +32,6 @@ function referent(character) {
373
32
  return mark === void 0 ? character.name : `${character.name} (${mark})`;
374
33
  }
375
34
  //#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
35
  //#region src/host/orchestration/defaults.ts
525
36
  const ENGLISH = translator("en");
526
37
  /** What the instructions say about how long each part of a character's answer may run. */
@@ -1489,178 +1000,6 @@ var Timelines = class {
1489
1000
  }
1490
1001
  };
1491
1002
  //#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
1003
  //#region src/host/orchestration/whereabouts.ts
1665
1004
  const within = (inner, outer, places) => {
1666
1005
  const byId = new Map(places.map((place) => [place.id, place]));
@@ -1881,6 +1220,29 @@ const RESULT = {
1881
1220
  additionalProperties: false
1882
1221
  }
1883
1222
  },
1223
+ doubt: {
1224
+ type: "array",
1225
+ description: "Beliefs that something the character took in since speaks against, which it still holds but with more doubt: name the belief and the numbers of what speaks against it, and its confidence is lowered for you. This is the way to answer a belief that a later event contradicts, instead of revising or dropping it.",
1226
+ items: {
1227
+ type: "object",
1228
+ properties: {
1229
+ id: {
1230
+ type: "integer",
1231
+ description: "The number of the belief, as listed."
1232
+ },
1233
+ contradicted_by: {
1234
+ ...idList,
1235
+ description: "The numbers of the things it took in since that speak against the belief."
1236
+ },
1237
+ text: {
1238
+ type: "string",
1239
+ description: "The belief reworded to say what is now in doubt, when its words need it; one or two sentences, and nothing but the belief: its confidence and the numbers are not part of the text."
1240
+ }
1241
+ },
1242
+ required: ["id", "contradicted_by"],
1243
+ additionalProperties: false
1244
+ }
1245
+ },
1884
1246
  drop: {
1885
1247
  type: "array",
1886
1248
  description: "Beliefs to let go: settled or overturned by what came after, or merged into another.",
@@ -1921,6 +1283,10 @@ function shownOf(session, material) {
1921
1283
  };
1922
1284
  }
1923
1285
  const rankOf = (confidence) => MEMORY_CONFIDENCES.indexOf(confidence);
1286
+ /** What a model writes into a belief's text when it has not put it in the fields: its confidence, importance or the numbers it rests on. */
1287
+ const MIXED_IN = /\((?:[^)]*\b(?:doubtful|likely|sure|importance)\b[^)]*|[^)]*\bperceptions?\s*\[?\d[^)]*)\)|\bperceptions?\s*\[\d/i;
1288
+ /** One step less sure, and no less than doubtful. */
1289
+ const lowered = (confidence) => MEMORY_CONFIDENCES[Math.max(0, rankOf(confidence) - 1)];
1924
1290
  /**
1925
1291
  * Why a proposal cannot be written, or nothing when it can. A belief must rest on what the character took in: on things from at least two
1926
1292
  * different turns, or on one event that turned the story; a belief is changed or let go only for what came after it, or for being merged
@@ -1931,8 +1297,9 @@ function proposalProblems(proposal, shown, resolveName, tr = translator("en")) {
1931
1297
  const add = proposal.add ?? [];
1932
1298
  const revise = proposal.revise ?? [];
1933
1299
  const drop = proposal.drop ?? [];
1300
+ const doubt = proposal.doubt ?? [];
1934
1301
  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 }));
1302
+ if (add.length + revise.length + drop.length + doubt.length > MAX_CHANGES) problems.push(tr("at most {max} changes in one pass", { max: MAX_CHANGES }));
1936
1303
  const cited = (ids, where) => (ids ?? []).flatMap((id) => {
1937
1304
  const entry = shown.perceptions.get(id);
1938
1305
  if (entry === void 0) problems.push(tr("{where}: there is no thing it took in numbered {id}", {
@@ -2012,10 +1379,15 @@ function proposalProblems(proposal, shown, resolveName, tr = translator("en")) {
2012
1379
  const supports = cited(change.perceptions, where);
2013
1380
  const against = cited(change.contradicted_by, where);
2014
1381
  if (change.text === void 0 && change.importance === void 0 && change.confidence === void 0 && against.length === 0) problems.push(tr("{where}: say what changes", { where }));
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", {
1382
+ if (change.text !== void 0 && change.text.trim().length > MAX_TEXT) problems.push(tr("{where}: the text is longer than {max} characters. A belief is not rewritten to hold what speaks against it: leave the text out and list the belief under doubt with the numbers of what speaks against it, and put what was learned as a new belief of its own", {
2016
1383
  where,
2017
1384
  max: MAX_TEXT
2018
1385
  }));
1386
+ else if (change.text !== void 0 && change.text.trim() === "") problems.push(tr("{where}: the text must be there and at most {max} characters; leave it out to keep the belief as it is", {
1387
+ where,
1388
+ max: MAX_TEXT
1389
+ }));
1390
+ if (change.text !== void 0 && MIXED_IN.test(change.text)) problems.push(tr("{where}: the confidence, the importance and the numbers are fields of their own, not part of the text", { where }));
2019
1391
  if (change.importance !== void 0 && (!Number.isInteger(change.importance) || change.importance < 1 || change.importance > 5)) problems.push(tr("{where}: importance runs from {min} to {max}", {
2020
1392
  where,
2021
1393
  min: 1,
@@ -2032,6 +1404,26 @@ function proposalProblems(proposal, shown, resolveName, tr = translator("en")) {
2032
1404
  if ((/* @__PURE__ */ new Set([...shown.supportTurns?.get(belief.id) ?? [], ...supports.map((entry) => entry.event.turn)])).size < 2) problems.push(tr("{where}: to be sure of something it must rest on things from at least two different turns", { where }));
2033
1405
  }
2034
1406
  });
1407
+ doubt.forEach((change, index) => {
1408
+ const where = `doubt[${index}]`;
1409
+ const belief = shown.beliefs.get(change.id);
1410
+ if (belief === void 0) {
1411
+ problems.push(tr("{where}: there is no belief numbered {id}", {
1412
+ where,
1413
+ id: change.id
1414
+ }));
1415
+ return;
1416
+ }
1417
+ touch(change.id, where);
1418
+ const against = cited(change.contradicted_by, where);
1419
+ if (against.length === 0) problems.push(tr("{where}: name what speaks against the belief in contradicted_by", { where }));
1420
+ fresh(against, belief, where);
1421
+ if (change.text !== void 0 && (change.text.trim() === "" || change.text.trim().length > MAX_TEXT)) problems.push(tr("{where}: the text must be there and at most {max} characters; leave it out to keep the belief as it is", {
1422
+ where,
1423
+ max: MAX_TEXT
1424
+ }));
1425
+ if (change.text !== void 0 && MIXED_IN.test(change.text)) problems.push(tr("{where}: the confidence, the importance and the numbers are fields of their own, not part of the text", { where }));
1426
+ });
2035
1427
  const dropped = new Set(drop.map((entry) => entry.id));
2036
1428
  drop.forEach((change, index) => {
2037
1429
  const where = `drop[${index}]`;
@@ -2052,12 +1444,135 @@ function proposalProblems(proposal, shown, resolveName, tr = translator("en")) {
2052
1444
  });
2053
1445
  return problems;
2054
1446
  }
1447
+ /**
1448
+ * The proposal with its mechanical mistakes mended instead of refused: things cited that were not shown, beliefs that do not exist, names that are
1449
+ * not characters, confidence the evidence cannot carry, changes that name a belief twice, and new beliefs that rest on one passing moment. A model
1450
+ * that is refused such a thing sends it again, five times, and the pass is lost; mended, the proposal is what the refusal would have asked for.
1451
+ * What needs the model's judgment (the words of a belief, what it rests on when nothing valid is left) is still refused by `proposalProblems`.
1452
+ */
1453
+ /** A text cut to the limit at the end of a sentence, or failing that at a word. */
1454
+ function shortened(text) {
1455
+ const trimmed = text.trim();
1456
+ if (trimmed.length <= MAX_TEXT) return trimmed;
1457
+ const head = trimmed.slice(0, MAX_TEXT);
1458
+ const sentence = Math.max(head.lastIndexOf(". "), head.lastIndexOf("! "), head.lastIndexOf("? "), head.lastIndexOf("。"), head.lastIndexOf("!"), head.lastIndexOf("?"));
1459
+ if (sentence >= MAX_TEXT / 3) return head.slice(0, sentence + 1).trim();
1460
+ const word = head.lastIndexOf(" ");
1461
+ return (word >= MAX_TEXT / 2 ? head.slice(0, word) : head.slice(0, 299)).trim() + "…";
1462
+ }
1463
+ /** What a rewrite of an existing belief keeps of its text: nothing when it is too long, because a belief is doubted for what speaks against it, not rewritten. */
1464
+ const keptText = (text) => text === void 0 || text.trim() === "" || text.trim().length > MAX_TEXT ? {} : { text };
1465
+ function settleProposal(proposal, shown, resolveName) {
1466
+ const known = (ids) => [...new Set(ids ?? [])].filter((id) => shown.perceptions.has(id));
1467
+ const after = (ids, belief) => known(ids).filter((id) => shown.perceptions.get(id).event.turn >= belief.turn);
1468
+ const turnsOf = (ids, built) => /* @__PURE__ */ new Set([...ids.map((id) => shown.perceptions.get(id).event.turn), ...built.map((found) => found.turn)]);
1469
+ const decisive = (ids) => ids.some((id) => shown.perceptions.get(id).event.importance >= DECISIVE_IMPORTANCE);
1470
+ const clamp = (importance) => Math.min(5, Math.max(1, Math.round(importance)));
1471
+ const add = (proposal.add ?? []).flatMap((belief) => {
1472
+ if (typeof belief.text !== "string" || belief.text.trim() === "") return [];
1473
+ const perceptions = known(belief.perceptions);
1474
+ const built = [...new Set(belief.beliefs ?? [])].flatMap((id) => shown.beliefs.get(id) ?? []);
1475
+ const turns = turnsOf(perceptions, built);
1476
+ if (turns.size < 2 && !decisive(perceptions)) return [];
1477
+ const about = (belief.about ?? []).filter((name) => resolveName(name) !== void 0);
1478
+ const { confidence: _confidence, ...rest } = belief;
1479
+ const confidence = belief.confidence === "sure" && turns.size < 2 ? "likely" : belief.confidence;
1480
+ return [{
1481
+ ...rest,
1482
+ text: shortened(belief.text),
1483
+ kind: MEMORY_KINDS.includes(belief.kind) ? belief.kind : "belief",
1484
+ importance: clamp(belief.importance),
1485
+ perceptions,
1486
+ beliefs: built.map((found) => found.id),
1487
+ about,
1488
+ ...confidence === void 0 ? {} : { confidence }
1489
+ }];
1490
+ }).slice(0, MAX_ADDED);
1491
+ const taken = /* @__PURE__ */ new Set();
1492
+ const fresh = (changes, mend) => (changes ?? []).flatMap((change) => {
1493
+ const belief = shown.beliefs.get(change.id);
1494
+ if (belief === void 0 || taken.has(change.id)) return [];
1495
+ const mended = mend(change, belief);
1496
+ if (mended !== void 0) taken.add(change.id);
1497
+ return mended === void 0 ? [] : [mended];
1498
+ });
1499
+ const doubt = fresh(proposal.doubt, (change, belief) => {
1500
+ const against = after(change.contradicted_by, belief);
1501
+ const { text: _text, ...rest } = change;
1502
+ return against.length === 0 ? void 0 : {
1503
+ ...rest,
1504
+ ...keptText(change.text),
1505
+ contradicted_by: against
1506
+ };
1507
+ });
1508
+ const revise = fresh(proposal.revise, (change, belief) => {
1509
+ const supports = after(change.perceptions, belief);
1510
+ const against = after(change.contradicted_by, belief);
1511
+ const { confidence, text: _text, ...rest } = change;
1512
+ let mended = confidence;
1513
+ if (confidence !== void 0 && !MEMORY_CONFIDENCES.includes(confidence)) mended = void 0;
1514
+ else if (confidence !== void 0 && against.length > 0 && rankOf(confidence) >= rankOf(belief.confidence)) mended = lowered(belief.confidence);
1515
+ else if (confidence !== void 0 && against.length === 0 && rankOf(confidence) < rankOf(belief.confidence)) mended = void 0;
1516
+ else if (confidence === "sure" && belief.confidence !== "sure" && (/* @__PURE__ */ new Set([...shown.supportTurns?.get(belief.id) ?? [], ...supports.map((id) => shown.perceptions.get(id).event.turn)])).size < 2) mended = void 0;
1517
+ const result = {
1518
+ ...rest,
1519
+ ...keptText(change.text),
1520
+ perceptions: supports,
1521
+ contradicted_by: against,
1522
+ ...mended === void 0 ? {} : { confidence: mended },
1523
+ ...change.importance === void 0 ? {} : { importance: clamp(change.importance) }
1524
+ };
1525
+ return result.text === void 0 && result.importance === void 0 && result.confidence === void 0 && against.length === 0 ? void 0 : result;
1526
+ });
1527
+ const drop = fresh(proposal.drop, (change, belief) => {
1528
+ if (change.merged_into !== void 0 && change.merged_into !== change.id && shown.beliefs.has(change.merged_into) && !(proposal.drop ?? []).some((other) => other.id === change.merged_into)) return {
1529
+ id: change.id,
1530
+ merged_into: change.merged_into
1531
+ };
1532
+ const settled = after(change.perceptions, belief);
1533
+ return settled.length === 0 ? void 0 : {
1534
+ id: change.id,
1535
+ perceptions: settled
1536
+ };
1537
+ });
1538
+ const room = Math.max(0, MAX_CHANGES - add.length);
1539
+ const changes = [
1540
+ ...revise.map((change) => ["revise", change]),
1541
+ ...doubt.map((change) => ["doubt", change]),
1542
+ ...drop.map((change) => ["drop", change])
1543
+ ].slice(0, room);
1544
+ const only = (kind) => changes.filter((entry) => entry[0] === kind).map((entry) => entry[1]);
1545
+ return {
1546
+ add,
1547
+ revise: only("revise"),
1548
+ doubt: only("doubt"),
1549
+ drop: only("drop")
1550
+ };
1551
+ }
1552
+ /**
1553
+ * The proposal with every contradiction the checks found doubted. What the proposal itself does to such a belief (revise, doubt or drop it) is replaced by
1554
+ * the doubt: a belief that something contradicts is not rewritten or let go in the same pass, and what was learned stays in the new beliefs it adds.
1555
+ */
1556
+ function withDoubts(proposal, found) {
1557
+ if (found.length === 0) return proposal;
1558
+ const doubted = new Set(found.map((entry) => entry.belief));
1559
+ const kept = (changes) => (changes ?? []).filter((change) => !doubted.has(change.id));
1560
+ return {
1561
+ ...proposal,
1562
+ revise: kept(proposal.revise),
1563
+ drop: kept(proposal.drop),
1564
+ doubt: [...kept(proposal.doubt), ...found.map((entry) => ({
1565
+ id: entry.belief,
1566
+ contradicted_by: entry.things
1567
+ }))]
1568
+ };
1569
+ }
2055
1570
  const keysOf = (names, resolveName) => (names ?? []).flatMap((name) => {
2056
1571
  const key = resolveName(name);
2057
1572
  return key === void 0 ? [] : [key];
2058
1573
  });
2059
1574
  /** The edit that writes a proposal that passed. */
2060
- function editOf(turn, character, proposal, resolveName) {
1575
+ function editOf(turn, character, proposal, resolveName, confidenceOf = () => void 0) {
2061
1576
  const who = characterKey(character);
2062
1577
  return {
2063
1578
  turn,
@@ -2070,24 +1585,107 @@ function editOf(turn, character, proposal, resolveName) {
2070
1585
  ...belief.confidence === void 0 ? {} : { confidence: belief.confidence },
2071
1586
  evidenceFor: belief.perceptions ?? []
2072
1587
  })),
2073
- beliefEdits: (proposal.revise ?? []).map((change) => ({
1588
+ beliefEdits: [...proposal.revise ?? [], ...(proposal.doubt ?? []).map((change) => ({
1589
+ id: change.id,
1590
+ ...change.text === void 0 ? {} : { text: change.text },
1591
+ confidence: lowered(confidenceOf(change.id) ?? "likely"),
1592
+ contradicted_by: change.contradicted_by
1593
+ }))].map((change) => ({
2074
1594
  id: change.id,
2075
1595
  ...change.text === void 0 ? {} : { text: change.text.trim() },
2076
- ...change.importance === void 0 ? {} : { importance: change.importance },
1596
+ ..."importance" in change && change.importance !== void 0 ? { importance: change.importance } : {},
2077
1597
  ...change.confidence === void 0 ? {} : { confidence: change.confidence },
2078
- evidenceFor: change.perceptions ?? [],
1598
+ evidenceFor: "perceptions" in change ? change.perceptions ?? [] : [],
2079
1599
  evidenceAgainst: change.contradicted_by ?? []
2080
1600
  })),
2081
1601
  beliefRetractions: (proposal.drop ?? []).map((change) => change.id)
2082
1602
  };
2083
1603
  }
2084
- function brief(session, material, now, zone, time, tr) {
1604
+ /** The most things a belief is pointed at: the model checks a few against it, not everything. */
1605
+ const MAX_BEARING = 4;
1606
+ /** How many words, besides these, a belief and a thing taken in must share for one to be pointed at the other. */
1607
+ const SHARED_WORDS = 2;
1608
+ const FUNCTION_WORDS = new Set("the and that with have has had from which they them their this these those were was been being are for not but you your our his her its who whom what when where why how into onto about after before over under then than there here would could should will just also only some any all out too very can may might must did does done doing got get".split(" "));
1609
+ /**
1610
+ * What the character took in since that bears on a belief, which is where a contradiction is found: a model told only to look for one rationalises, but
1611
+ * one pointed at the few things about the same subject compares them. A thing bears on a belief when its event involves the people the belief is about,
1612
+ * or when it shares words with the belief (beliefs are often about a subject and no one in particular).
1613
+ */
1614
+ function bearingOn(belief, fresh) {
1615
+ const people = fresh.filter((entry) => belief.about.length > 0 && entry.event.involves.some((id) => belief.about.includes(id))).slice(-4);
1616
+ const own = [...tokens(belief.text)].filter((token) => !FUNCTION_WORDS.has(token));
1617
+ const chosen = new Set(people.map((entry) => entry.perception.id));
1618
+ const alike = fresh.map((entry) => {
1619
+ const words = tokens(entry.perception.content);
1620
+ return {
1621
+ id: entry.perception.id,
1622
+ shared: own.filter((token) => words.has(token)).length
1623
+ };
1624
+ }).filter((entry) => entry.shared >= SHARED_WORDS && !chosen.has(entry.id)).sort((a, b) => b.shared - a.shared || b.id - a.id).slice(0, MAX_BEARING - chosen.size);
1625
+ return [...chosen, ...alike.map((entry) => entry.id)].sort((x, y) => x - y);
1626
+ }
1627
+ /** The most beliefs of one character checked against what bears on them in one pass: each is a request of its own. */
1628
+ const MAX_CHECKS = 6;
1629
+ /** The fewest things taken in that a failed sorting is tried again with half of. */
1630
+ const MIN_TO_HALVE = 8;
1631
+ const CHECK_RESULT = {
1632
+ type: "object",
1633
+ properties: {
1634
+ reason: {
1635
+ type: "string",
1636
+ description: "One short sentence, written first, without quotation marks: what the belief claims and what the things say, side by side, and whether they can all be true together."
1637
+ },
1638
+ things: {
1639
+ ...idList,
1640
+ description: "The numbers of the things that cannot be true together with the belief; none when they all can be."
1641
+ },
1642
+ verdict: {
1643
+ type: "string",
1644
+ enum: ["consistent", "contradicted"],
1645
+ description: "consistent: the belief and every one of the things can be true together; contradicted: at least one thing cannot be true if the belief is."
1646
+ }
1647
+ },
1648
+ required: [
1649
+ "reason",
1650
+ "things",
1651
+ "verdict"
1652
+ ],
1653
+ additionalProperties: false
1654
+ };
1655
+ /** Why an answer to the check of one belief cannot be taken, or nothing when it can. */
1656
+ function checkProblem(answer, belief, shown, near, tr = translator("en")) {
1657
+ if ((answer.reason ?? "").trim() === "") return tr("say in a sentence what the belief claims and what the things say, before the verdict");
1658
+ if (answer.verdict !== "consistent" && answer.verdict !== "contradicted") return tr("the verdict is consistent or contradicted");
1659
+ const things = answer.things ?? [];
1660
+ if (answer.verdict === "consistent") return things.length === 0 ? void 0 : tr("a belief that can be true together with all of them names none of them");
1661
+ if (things.length === 0) return tr("name the things that cannot be true together with the belief");
1662
+ for (const id of things) {
1663
+ const entry = shown.perceptions.get(id);
1664
+ if (!near.has(id) || entry === void 0) return tr("there is no thing listed numbered {id}", { id });
1665
+ if (entry.event.turn < belief.turn) return tr("thing {id} came before the belief was formed", { id });
1666
+ }
1667
+ }
1668
+ function checkBrief(character, belief, things, now, zone, time, tr) {
1669
+ return [
1670
+ tr("A belief held by {name}: {text}", {
1671
+ name: referent(character),
1672
+ text: belief.text
1673
+ }),
1674
+ tr("What they took in since that bears on it:"),
1675
+ ...things.map((entry) => {
1676
+ const at = time(entry.event.turn, entry.event.round);
1677
+ return `- p${entry.perception.id}${at === void 0 ? "" : ` (${describeWhen(at, now, zone)})`}: ${entry.perception.content}`;
1678
+ }),
1679
+ tr("Can the belief and each of these be true together? Name the ones that cannot be.")
1680
+ ].join("\n");
1681
+ }
1682
+ function brief(session, material, doubted, now, zone, time, tr) {
2085
1683
  const { character, fresh, beliefs } = material;
2086
1684
  const named = (id) => session.characters.get(id)?.name ?? String(id);
2087
1685
  const { disputed } = session.memories.evidenceIndex(character.id);
2088
1686
  const believed = beliefs.map((belief) => {
2089
1687
  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") : "";
1688
+ const dispute = disputed.has(belief.id) || doubted.has(belief.id) ? tr(", something taken in since speaks against it") : "";
2091
1689
  return `- b${belief.id} (${tr("{kind}, importance {importance}, {confidence}{about}{dispute}", {
2092
1690
  kind: belief.kind,
2093
1691
  importance: belief.importance,
@@ -2133,40 +1731,97 @@ function memoryReflector(deps) {
2133
1731
  };
2134
1732
  const tr = translator(languageOf(settings.prompts.language));
2135
1733
  const characters = [];
2136
- for (const material of taken) {
1734
+ const failures = [];
1735
+ const sort = async (material) => {
2137
1736
  const shown = shownOf(session, material);
2138
- const proposal = await runChild({
1737
+ const found = [];
1738
+ let checked = 0;
1739
+ for (const belief of material.beliefs) {
1740
+ const near = bearingOn(belief, material.fresh);
1741
+ if (near.length === 0 || checked >= MAX_CHECKS) continue;
1742
+ checked += 1;
1743
+ const things = near.flatMap((id) => shown.perceptions.get(id) ?? []);
1744
+ let verdict;
1745
+ try {
1746
+ verdict = await runChild({
1747
+ parent,
1748
+ signal,
1749
+ reasoningEffort: settings.reasoning.children,
1750
+ sampling: childSampling(settings, "records", estimateAnswer([MAX_TEXT * 2, 100], settings.prompts.language)),
1751
+ ...childModel(settings, "records"),
1752
+ trace: childTrace(store, "records", `reflection check ${material.character.name} b${belief.id}`),
1753
+ persona: promptFor(parent, "roleplay/reflection-check", settings.prompts.language),
1754
+ prompt: checkBrief(material.character, belief, things, now, zone, (turn, round) => session.clock.at(turn, round), tr),
1755
+ result: CHECK_RESULT,
1756
+ beforeSubmit: (value) => {
1757
+ const problem = checkProblem(value, belief, shown, new Set(near), tr);
1758
+ return problem === void 0 ? void 0 : tr("not acceptable: {problems}", { problems: problem });
1759
+ },
1760
+ maxCalls: 2
1761
+ });
1762
+ } catch (error) {
1763
+ if (signal.aborted) throw error;
1764
+ }
1765
+ if (verdict?.verdict === "contradicted") found.push({
1766
+ belief: belief.id,
1767
+ things: verdict.things
1768
+ });
1769
+ }
1770
+ const doubted = new Set(found.map((entry) => entry.belief));
1771
+ const proposal = withDoubts(settleProposal(await runChild({
2139
1772
  parent,
2140
1773
  signal,
2141
1774
  reasoningEffort: settings.reasoning.children,
2142
- sampling: childSampling(settings, "records"),
1775
+ sampling: childSampling(settings, "records", estimateAnswer(Array.from({ length: 14 }, () => MAX_TEXT), settings.prompts.language)),
2143
1776
  ...childModel(settings, "records"),
2144
1777
  trace: childTrace(store, "records", `reflection ${material.character.name}`),
2145
1778
  persona: promptFor(parent, "roleplay/reflection", settings.prompts.language),
2146
- prompt: brief(session, material, now, zone, (turn, round) => session.clock.at(turn, round), tr),
1779
+ prompt: brief(session, material, doubted, now, zone, (turn, round) => session.clock.at(turn, round), tr),
2147
1780
  result: RESULT,
2148
1781
  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])];
1782
+ const given = settleProposal(value, shown, resolveName);
1783
+ const problems = [...proposalProblems(given, shown, resolveName, tr), ...[wrongLanguage(settings.prompts.language, { beliefs: [
1784
+ ...given.add ?? [],
1785
+ ...given.revise ?? [],
1786
+ ...given.doubt ?? []
1787
+ ].map((belief) => belief.text ?? "").join(" ") })].flatMap((problem) => problem === void 0 ? [] : [problem])];
2151
1788
  return problems.length === 0 ? void 0 : tr("not acceptable: {problems}", { problems: problems.join("; ") });
2152
1789
  },
2153
1790
  maxCalls: 3
2154
- });
1791
+ }), shown, resolveName), found);
2155
1792
  const reached = Math.max(...material.fresh.map((entry) => entry.perception.id));
2156
1793
  session.transaction(() => {
2157
- session.edit(editOf(job.turn, material.character, proposal, resolveName));
1794
+ session.edit(editOf(job.turn, material.character, proposal, resolveName, (belief) => shown.beliefs.get(belief)?.confidence));
2158
1795
  session.metadata.setValue(CURSOR_KEY, {
2159
1796
  ...readCursor(session),
2160
1797
  [characterKey(material.character)]: reached
2161
1798
  });
2162
1799
  });
2163
- characters.push({
1800
+ return {
2164
1801
  name: material.character.name,
2165
1802
  added: proposal.add?.length ?? 0,
2166
- revised: proposal.revise?.length ?? 0,
1803
+ revised: (proposal.revise?.length ?? 0) + (proposal.doubt?.length ?? 0),
2167
1804
  dropped: proposal.drop?.length ?? 0
2168
- });
1805
+ };
1806
+ };
1807
+ const sortWithRetry = async (material) => {
1808
+ try {
1809
+ return await sort(material);
1810
+ } catch (error) {
1811
+ if (signal.aborted || material.fresh.length < MIN_TO_HALVE) throw error;
1812
+ return await sort({
1813
+ ...material,
1814
+ fresh: material.fresh.slice(0, Math.ceil(material.fresh.length / 2))
1815
+ });
1816
+ }
1817
+ };
1818
+ for (const material of taken) try {
1819
+ characters.push(await sortWithRetry(material));
1820
+ } catch (error) {
1821
+ if (signal.aborted) throw error;
1822
+ failures.push(`${material.character.name}: ${error instanceof Error ? error.message : String(error)}`);
2169
1823
  }
1824
+ if (failures.length > 0 && characters.length === 0) throw new Error(failures.join("; "));
2170
1825
  session.metadata.setValue(LAST_KEY, {
2171
1826
  turn: job.turn,
2172
1827
  at: (/* @__PURE__ */ new Date()).toISOString(),
@@ -2174,89 +1829,15 @@ function memoryReflector(deps) {
2174
1829
  characters
2175
1830
  });
2176
1831
  writeAnchor(session, playerPlace(store), now);
2177
- session.metadata.deleteValue(ERROR_KEY);
1832
+ if (failures.length > 0) recordFailure(session, tr("{names} could not be sorted this time and will be tried again: {reason}", {
1833
+ names: failures.map((entry) => entry.split(":")[0]).join(", "),
1834
+ reason: failures[0].slice(failures[0].indexOf(":") + 2)
1835
+ }));
1836
+ else session.metadata.deleteValue(ERROR_KEY);
2178
1837
  return { characters };
2179
1838
  } };
2180
1839
  }
2181
1840
  //#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 };
1841
+ export { whereabouts as a, readTimeline as c, sameWords as d, referent as f, reflectionStatus as i, pathTo as l, memoryReflector as n, TimelineError as o, recordFailure as r, Timelines as s, dueReflection as t, defaultBoundaries as u };
2261
1842
 
2262
- //# sourceMappingURL=deliver-BDW5WZvc.js.map
1843
+ //# sourceMappingURL=reflection-md7BCYCl.js.map