@dsh-agentic-roleplay/core 0.3.0 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/authoring.js +18 -223
- package/lib/client.js +1838 -489
- package/lib/client.js.map +1 -1
- package/lib/compaction.js +1 -1
- package/lib/deliver-BSsDtF6X.js +3443 -0
- package/lib/{documents-7GMc5NnW.js → documents-B5XAdfo2.js} +992 -14
- package/lib/{gallery-DUeBMHQX.js → gallery-DS5-qH9F.js} +2 -2
- package/lib/{generator-HPifO3Kk.js → generator-BzeepLd2.js} +3 -3
- package/lib/images.js +3 -3
- package/lib/index.js +351 -13
- package/lib/narration-DK2kiIjE.js +141 -0
- package/lib/orchestration.js +867 -1547
- package/lib/{packs-alJTiDM2.js → packs-BCGK9KZV.js} +51 -7
- package/lib/{presenter-agent-PX1WVaJB.js → presenter-agent-Cp-J0onD.js} +3 -3
- package/lib/{narration-CKZTk5UE.js → settings-CA6icLL_.js} +158 -142
- package/package.json +4 -4
- package/packs/scene/strip.js +1 -1
- package/prompts/en/roleplay/character-decide.md +1 -1
- package/prompts/en/roleplay/character-rules.md +1 -1
- package/prompts/en/roleplay/chronicler.md +1 -1
- package/prompts/en/roleplay/dice.md +7 -0
- package/prompts/en/roleplay/game-master.md +3 -1
- package/prompts/en/roleplay/reflection.md +4 -2
- package/prompts/en/roleplay/style.md +1 -1
- package/prompts/en/roleplay/suggester.md +1 -1
- package/prompts/en/translate/document.md +6 -0
- package/prompts/en/translate/glossary.md +5 -0
- package/prompts/en/translate/notice.md +2 -0
- package/prompts/zh/roleplay/character-decide.md +1 -1
- package/prompts/zh/roleplay/character-rules.md +1 -1
- package/prompts/zh/roleplay/chronicler.md +1 -1
- package/prompts/zh/roleplay/dice.md +7 -0
- package/prompts/zh/roleplay/game-master.md +3 -1
- package/prompts/zh/roleplay/reflection.md +4 -2
- package/prompts/zh/roleplay/style.md +1 -1
- package/prompts/zh/roleplay/suggester.md +1 -1
- package/prompts/zh/translate/document.md +6 -0
- package/prompts/zh/translate/glossary.md +5 -0
- package/prompts/zh/translate/notice.md +2 -0
- package/lib/deliver--uMhC6oO.js +0 -1878
- package/lib/src-CWTNeL6Y.js +0 -128
|
@@ -0,0 +1,3443 @@
|
|
|
1
|
+
import { r as roleplaySessionOf, t as promptFor } from "./access-EbNdZFbk.js";
|
|
2
|
+
import { K as SessionNotFoundError, P as inheritPrompts, S as wrongLanguage, T as parsePlotsFile, i as inheritPacks } from "./packs-BCGK9KZV.js";
|
|
3
|
+
import "./settings-CA6icLL_.js";
|
|
4
|
+
import { n as encodeOutput, r as encodePreview } from "./narration-DK2kiIjE.js";
|
|
5
|
+
import { A as runChild, D as childSampling, E as childModel, j as estimateAnswer, k as childTrace, u as inheritImages } from "./generator-BzeepLd2.js";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { createUserMessage } from "@deepseek-ai/dsh-llm";
|
|
9
|
+
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
10
|
+
import { DAY, ITEM_ACTIONS, MINUTE, SECOND, addLocalDays, characterKey, clockTime, createCharacterTools, createDiceTools, createTools, dayPart, describeDuration, describeInstant, holidaysOn, isSessionId, localTime, locationKey, mentioned, nextTimeOfDay, overlap, readCalendar, seasonOf, sessionDatabase, sessionFolder, tokens } from "@dsh-agentic-roleplay/state";
|
|
11
|
+
//#region ../dsh-roleplay-model/src/memory.ts
|
|
12
|
+
const MEMORY_KINDS = [
|
|
13
|
+
"belief",
|
|
14
|
+
"relationship",
|
|
15
|
+
"knowledge"
|
|
16
|
+
];
|
|
17
|
+
/** How sure a character is of what it believes, from least to most. */
|
|
18
|
+
const MEMORY_CONFIDENCES = [
|
|
19
|
+
"doubtful",
|
|
20
|
+
"likely",
|
|
21
|
+
"sure"
|
|
22
|
+
];
|
|
23
|
+
//#endregion
|
|
24
|
+
//#region ../dsh-roleplay-model/src/messages-zh.ts
|
|
25
|
+
/** 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. */
|
|
26
|
+
const ZH = {
|
|
27
|
+
", ": ",",
|
|
28
|
+
"; ": ";",
|
|
29
|
+
": ": ":",
|
|
30
|
+
".": "。",
|
|
31
|
+
" and ": "和",
|
|
32
|
+
"doubtful": "存疑",
|
|
33
|
+
"likely": "较有把握",
|
|
34
|
+
"sure": "确信",
|
|
35
|
+
"open": "畅通",
|
|
36
|
+
"locked": "已上锁",
|
|
37
|
+
"blocked": "被堵住",
|
|
38
|
+
"night": "夜里",
|
|
39
|
+
"morning": "上午",
|
|
40
|
+
"afternoon": "下午",
|
|
41
|
+
"evening": "傍晚",
|
|
42
|
+
"spring": "春季",
|
|
43
|
+
"summer": "夏季",
|
|
44
|
+
"autumn": "秋季",
|
|
45
|
+
"winter": "冬季",
|
|
46
|
+
"today is {holidays}": "今天是{holidays}",
|
|
47
|
+
"Summary": "概述",
|
|
48
|
+
"Personality": "性格",
|
|
49
|
+
"Background": "背景",
|
|
50
|
+
"Appearance": "外貌",
|
|
51
|
+
"How you speak": "说话方式",
|
|
52
|
+
"You are {name}.": "你是{name}。",
|
|
53
|
+
"You are also called {names}.": "你也被称作{names}。",
|
|
54
|
+
"age: {value}": "年龄:{value}",
|
|
55
|
+
"gender: {value}": "性别:{value}",
|
|
56
|
+
"pronouns: {value}": "代词:{value}",
|
|
57
|
+
"- {key} ({name}): {use}": "- {key}({name}):{use}",
|
|
58
|
+
"Rolls {dice}.": "掷 {dice}。",
|
|
59
|
+
"Give a target: the difficulty, the number to meet or beat; set it by how hard the attempt is.": "需给出 target:难度,即要达到或超过的数字;按这次尝试的难易来定。",
|
|
60
|
+
"Give a target: the number to stay under; set it by how hard the attempt is.": "需给出 target:要低于的数字;按这次尝试的难易来定。",
|
|
61
|
+
"It adds the character's {variable}.": "它会加上该角色的 {variable}。",
|
|
62
|
+
"Counts the dice that show {hit} or more.": "统计显示 {hit} 或更高的骰子数。",
|
|
63
|
+
"the player's roll": "玩家的掷骰",
|
|
64
|
+
"The player rolled {dice} ({reason}) and got {total}: dice {faces}. This is a fact, decided by the dice: take it into account when you judge the attempt and decide what happens.": "玩家掷了 {dice}({reason}),得到 {total}:骰面 {faces}。这是由骰子决定的事实:在你判断这次尝试、决定发生什么时把它考虑进去。",
|
|
65
|
+
"The checks of this story:": "本故事的检定:",
|
|
66
|
+
"No checks are defined: use roll_dice only.": "没有定义检定:只用 roll_dice。",
|
|
67
|
+
"Situation:": "当前情形:",
|
|
68
|
+
"Now: {time}.": "现在是:{time}。",
|
|
69
|
+
"Where you are:": "你所在之处:",
|
|
70
|
+
"Present:": "在场的人:",
|
|
71
|
+
" (you)": "(你)",
|
|
72
|
+
"What you know is coming:": "你知道即将发生的事:",
|
|
73
|
+
"Just now you notice:": "此刻你注意到:",
|
|
74
|
+
"How you are (what you can tell of yourself):": "你的状态(你自己能感觉到的):",
|
|
75
|
+
"What you can tell of the others here:": "你能看出在场其他人的情况:",
|
|
76
|
+
"What you have on you:": "你身上带着:",
|
|
77
|
+
"Things here: ": "这里有:",
|
|
78
|
+
"Ways out: ": "出路:",
|
|
79
|
+
"Lying about: ": "散落在周围的:",
|
|
80
|
+
"hidden": "隐蔽",
|
|
81
|
+
" holding {things}": ",里面有{things}",
|
|
82
|
+
"; and {count} more": ";另有{count}项",
|
|
83
|
+
"at {feature}": "在{feature}",
|
|
84
|
+
"; and {count} more you can recall if needed": ";另有{count}项,需要时你可以回想起来",
|
|
85
|
+
"What you know exists (this does not tell you where it is now or what state it is in):": "你知道存在的事物(这并不说明它现在在哪里、处于什么状态):",
|
|
86
|
+
"People: ": "人物:",
|
|
87
|
+
"Factions: ": "组织:",
|
|
88
|
+
"Places: ": "地点:",
|
|
89
|
+
"Routes: ": "路径:",
|
|
90
|
+
"Things: ": "物品:",
|
|
91
|
+
"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):": "你的日程与你想达成的事(只是计划,不是命令:依当下情形和你的性格,可以照做、推迟或放弃):",
|
|
92
|
+
"Your day, now: {activity}{place}, until {until}{note}.": "你此刻的日程:{activity}{place},持续到{until}{note}。",
|
|
93
|
+
"Your day, next: {activity}{place}, from {from}.": "你接下来的日程:{activity}{place},{from}开始。",
|
|
94
|
+
" at {place}": ",在{place}",
|
|
95
|
+
" (not something you would drop lightly)": "(你不会轻易放下)",
|
|
96
|
+
", with {names}": ",与{names}一起",
|
|
97
|
+
"You were to: {title}{place}{with}, at {at}, which has passed and is still open.": "你本应:{title}{place}{with},时间是{at},已经过了,事情仍未了结。",
|
|
98
|
+
"You are due to: {title}{place}{with}, at {at}.": "你约定要:{title}{place}{with},时间是{at}。",
|
|
99
|
+
"What you are after:": "你想达成的事:",
|
|
100
|
+
", by {deadline}, which has passed": ",限期{deadline},已过",
|
|
101
|
+
", by {deadline}": ",限期{deadline}",
|
|
102
|
+
" Next: {plan}.": " 下一步:{plan}。",
|
|
103
|
+
"How you stand with people who bear on this moment (your own view, not objective fact):": "你与和此刻相关的人的关系(是你自己的看法,不是客观事实):",
|
|
104
|
+
" (here)": "(在场)",
|
|
105
|
+
" (not here)": "(不在场)",
|
|
106
|
+
"knows them well": "很了解对方",
|
|
107
|
+
"barely knows them": "几乎不了解对方",
|
|
108
|
+
"trusts them": "信任对方",
|
|
109
|
+
"distrusts them": "不信任对方",
|
|
110
|
+
"is fond of them": "喜欢对方",
|
|
111
|
+
"dislikes them": "不喜欢对方",
|
|
112
|
+
"things are strained between them": "彼此关系紧张",
|
|
113
|
+
"Your affiliations (their goals are pressures and commitments, not commands):": "你的所属组织(其目标是压力和承诺,不是命令):",
|
|
114
|
+
"member": "成员",
|
|
115
|
+
" Goals: {goals}.": " 目标:{goals}。",
|
|
116
|
+
"- {name}: {position}; {status}; commitment {commitment}.": "- {name}:{position};{status};投入程度 {commitment}。",
|
|
117
|
+
" Your view: {attitude}.": " 你的看法:{attitude}。",
|
|
118
|
+
"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):": "你记得的、与此相关的事(只限你自己亲身经历的;不要声称记得更多,模糊的地方要保持不确定):",
|
|
119
|
+
"What you remember that bears on this: nothing comes to mind.": "你记得的、与此相关的事:想不起任何事。",
|
|
120
|
+
"some time ago": "一段时间以前",
|
|
121
|
+
"just now": "刚才",
|
|
122
|
+
"1 day ago": "1天前",
|
|
123
|
+
"{amount} days ago": "{amount}天前",
|
|
124
|
+
"1 hour ago": "1小时前",
|
|
125
|
+
"{amount} hours ago": "{amount}小时前",
|
|
126
|
+
"1 minute ago": "1分钟前",
|
|
127
|
+
"{amount} minutes ago": "{amount}分钟前",
|
|
128
|
+
"the details are fuzzy": "细节已经模糊",
|
|
129
|
+
"you barely remember": "你几乎记不清了",
|
|
130
|
+
"you are sure of it": "你对此确信无疑",
|
|
131
|
+
"you doubt it": "你对此存疑",
|
|
132
|
+
"something you have seen since speaks against it": "此后你所见所闻有与之相悖的地方",
|
|
133
|
+
"it comes to mind with the rest": "它和其余的事一起浮现在脑海",
|
|
134
|
+
"Earlier in this scene, before this moment:": "这一幕此刻之前发生的事:",
|
|
135
|
+
"What just happened, and what you are reacting to:": "刚才发生的事,以及你在回应的是什么:",
|
|
136
|
+
"- {name} intended: {intent} ({result}) {summary}": "- {name}打算:{intent}({result}){summary}",
|
|
137
|
+
"- {name} said \"{utterance}\" and intended: {intent} ({result}) {summary}": "- {name}说了“{utterance}”,并打算:{intent}({result}){summary}",
|
|
138
|
+
"Your earlier intent did not work out: {intent}\nYou are trying again, knowing the above. Decide again what you do now.": "你先前的打算没有成功:{intent}\n你带着上面这些再试一次。重新决定你现在做什么。",
|
|
139
|
+
"Character: {name}{summary}": "角色:{name}{summary}",
|
|
140
|
+
"What they believe now:": "他们现在的看法:",
|
|
141
|
+
"(nothing yet)": "(暂时没有)",
|
|
142
|
+
"What they have taken in since:": "他们此后经历的事:",
|
|
143
|
+
"Sort their memory.": "请整理他们的记忆。",
|
|
144
|
+
"not acceptable: {problems}": "不可接受:{problems}",
|
|
145
|
+
"{kind}, importance {importance}, {confidence}{about}{dispute}": "{kind},重要性 {importance},{confidence}{about}{dispute}",
|
|
146
|
+
", about {names}": ",关于{names}",
|
|
147
|
+
", something taken in since speaks against it": ",此后经历的事与之相悖",
|
|
148
|
+
"add: at most {max} new beliefs in one pass; merge or choose": "add:一次最多 {max} 条新看法;请合并或取舍",
|
|
149
|
+
"at most {max} changes in one pass": "一次最多 {max} 处修改",
|
|
150
|
+
"{where}: there is no thing it took in numbered {id}": "{where}:没有编号为 {id} 的经历",
|
|
151
|
+
"{where}: confidence is one of {options}": "{where}:confidence 须为 {options} 之一",
|
|
152
|
+
"{where}: unknown kind \"{kind}\"": "{where}:未知的 kind “{kind}”",
|
|
153
|
+
"{where}: say what it believes": "{where}:请写出它相信什么",
|
|
154
|
+
"{where}: at most {max} characters; say it shorter": "{where}:最多 {max} 个字符;请写得更短",
|
|
155
|
+
"{where}: importance runs from {min} to {max}": "{where}:importance 取值为 {min} 到 {max}",
|
|
156
|
+
"{where}: there is no belief numbered {id}": "{where}:没有编号为 {id} 的看法",
|
|
157
|
+
"{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}:一个转瞬即逝的瞬间还不是看法;请以至少两个不同回合的经历为依据,或以一件扭转了故事的事件为依据",
|
|
158
|
+
"{where}: to be sure of something it must rest on things from at least two different turns": "{where}:要对某事确信,必须以至少两个不同回合的经历为依据",
|
|
159
|
+
"{where}: \"{name}\" is not a character; name them as they are named": "{where}:“{name}”不是角色;请使用他们的名字",
|
|
160
|
+
"{where}: belief {id} is already changed in this pass": "{where}:看法 {id} 在这一轮中已经修改过",
|
|
161
|
+
"{where}: say what it took in since that bears on it": "{where}:请写出此后与之相关的经历",
|
|
162
|
+
"{where}: thing {id} came before the belief was formed; cite what came after": "{where}:经历 {id} 发生在看法形成之前;请引用之后发生的事",
|
|
163
|
+
"{where}: say what changes": "{where}:请写出有何改变",
|
|
164
|
+
"{where}: the text must be there and at most {max} characters; leave it out to keep the belief as it is": "{where}:文字不能为空,且最多 {max} 个字符;想保持信念原样就不要写这一项",
|
|
165
|
+
"{where}: the confidence, the importance and the numbers are fields of their own, not part of the text": "{where}:把握程度、重要性和编号是各自独立的字段,不属于文字",
|
|
166
|
+
"{where}: name what speaks against the belief in contradicted_by": "{where}:在 contradicted_by 里写出与该信念相悖的内容的编号",
|
|
167
|
+
"{where}: a belief that something contradicts must be doubted: lower its confidence": "{where}:被事实相悖的看法必须存疑:请降低其 confidence",
|
|
168
|
+
"{where}: to doubt a belief, name what contradicts it in contradicted_by": "{where}:要对看法存疑,请在 contradicted_by 中写明与之相悖的经历",
|
|
169
|
+
"{where}: merge into a belief that stays": "{where}:请合并到保留的看法中",
|
|
170
|
+
"Time: {time}.": "时间:{time}。",
|
|
171
|
+
"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 可以跳过一段时间。",
|
|
172
|
+
"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}的真实时间,其间故事仍在继续:角色们各忙各的事,除非记录另有说明,不要假定任何人还在玩家离开时的位置或状态。",
|
|
173
|
+
"The story's time follows the real clock: it cannot be skipped, and each round takes as long as it really took.": "故事时间跟随真实时钟:无法跳过,每一轮耗时就是它实际花费的时间。",
|
|
174
|
+
"By their routines since you last looked: {moves}.": "按各自的日程,自你上次查看以来:{moves}。",
|
|
175
|
+
"{name} went to {place} ({activity})": "{name}去了{place}({activity})",
|
|
176
|
+
"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}。是否照日程行事由角色自己决定;当下的情形也可能拖住他们。",
|
|
177
|
+
", at {place}": ",在{place}",
|
|
178
|
+
"\"{title}\" ({with}{place}) was due {when} and is still open": "“{title}”({with}{place})原定{when},仍未了结",
|
|
179
|
+
"\"{title}\" ({with}{place}) is due {when}": "“{title}”({with}{place})定于{when}",
|
|
180
|
+
"Commitments due soon or overdue: {entries}.": "即将到期或已逾期的约定:{entries}。",
|
|
181
|
+
"named in the move": "被这一步行动点到",
|
|
182
|
+
"in the scene": "在场",
|
|
183
|
+
"own goal: {goal}": "自身目标:{goal}",
|
|
184
|
+
"faction pressure: {goal}": "组织压力:{goal}",
|
|
185
|
+
"high tension toward the player": "对玩家高度紧张",
|
|
186
|
+
"distrusts the player": "不信任玩家",
|
|
187
|
+
"cares about the player": "在意玩家",
|
|
188
|
+
"dislikes the player": "不喜欢玩家",
|
|
189
|
+
"Likely characters to activate, in priority order (advice only; activate only whoever the moment actually reaches):": "可能需要启动的角色,按优先级排列(仅供参考;只启动当下真正牵涉到的人):",
|
|
190
|
+
"socially implicated": "社交上被牵涉",
|
|
191
|
+
"The player's character is in {place}": "玩家角色在{place}",
|
|
192
|
+
"Characters here:": "在这里的角色:",
|
|
193
|
+
"Characters elsewhere (they perceive nothing here unless the moment reaches them):": "在别处的角色(除非当下波及他们,否则感知不到这里的事):",
|
|
194
|
+
"{member} - in {place} ({key})": "{member} - 在{place}({key})",
|
|
195
|
+
"Characters with no place (not part of this scene; they cannot be asked to act):": "没有所在地点的角色(不属于这一幕;不能让他们行动):",
|
|
196
|
+
"the player's character, \"{key}\"": "玩家角色,“{key}”",
|
|
197
|
+
"acts through \"{key}\"": "通过“{key}”行动",
|
|
198
|
+
"Currently: {state}": "目前:{state}",
|
|
199
|
+
"Scene before turn {turn}:": "第 {turn} 回合之前的场景:",
|
|
200
|
+
"What characters have on them:": "角色们身上带着:",
|
|
201
|
+
"The world acted since the last turn, by itself:": "自上一回合以来,世界自行发生的事:",
|
|
202
|
+
"Known beforehand, still to come (who knows of it; it will happen by itself when its time comes):": "事先已知、尚未发生的事(谁知道;时候到了会自行发生):",
|
|
203
|
+
"[known to {who}]": "[知情者:{who}]",
|
|
204
|
+
"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 中说明已处理(每条会保留几个回合,之后放弃):",
|
|
205
|
+
"What the story keeps track of (change it with variable_changes in an outcome when what happened calls for it):": "故事追踪的内容(发生的事需要时,在结果中用 variable_changes 修改):",
|
|
206
|
+
"Still open in the story:": "故事中仍未了结的事:",
|
|
207
|
+
"Earlier events that bear on what the player just did (from the records of the story):": "与玩家刚才的行动相关的早先事件(来自故事记录):",
|
|
208
|
+
"turn {turn}": "第 {turn} 回合",
|
|
209
|
+
"You were to {title}, at {when}": "你本应{title},时间是{when}",
|
|
210
|
+
"You were to {title} at {place}, at {when}": "你本应在{place}:{title},时间是{when}",
|
|
211
|
+
" ({note})": "({note})",
|
|
212
|
+
"It is {now} now and the time has passed.": "现在是{now},时间已经过了。",
|
|
213
|
+
"It is {now} now.": "现在是{now}。",
|
|
214
|
+
"It was with: {who}.": "同你一起的有:{who}。",
|
|
215
|
+
"You are not with the player's character, and nothing of this happens in front of anyone: decide what you do about it.": "你不和玩家的角色在一起,这件事也不会发生在任何人面前:决定你要怎么处理。",
|
|
216
|
+
"The time you had for \"{goal}\" has passed ({when}; it is {now} now)": "你为“{goal}”预留的时间已过({when};现在是{now})",
|
|
217
|
+
"You are not with the player's character and nothing of this happens in front of anyone: decide what you do about it.": "你不和玩家的角色在一起,这件事也不会发生在任何人面前:决定你要怎么处理。",
|
|
218
|
+
"{names} noticed: {text}": "{names}注意到:{text}",
|
|
219
|
+
"{name} went to {place}.": "{name}去了{place}。",
|
|
220
|
+
"## MCP resource servers\n\nUse {tools} with the server argument naming an MCP server.": "## MCP 资源服务器\n\n使用 {tools},server 参数填 MCP 服务器的名称。",
|
|
221
|
+
"## MCP resource servers\n\nUse {tools} with one of these names as the server argument: {servers}.": "## MCP 资源服务器\n\n使用 {tools},server 参数填下列名称之一:{servers}。"
|
|
222
|
+
};
|
|
223
|
+
//#endregion
|
|
224
|
+
//#region ../dsh-roleplay-model/src/messages.ts
|
|
225
|
+
/** The language a setting such as `zh-CN` or `en` stands for; English when it is none that is known. */
|
|
226
|
+
function languageOf(code) {
|
|
227
|
+
return (code ?? "").trim().toLowerCase().startsWith("zh") ? "zh" : "en";
|
|
228
|
+
}
|
|
229
|
+
const fill = (template, values) => values === void 0 ? template : template.replace(/\{(\w+)\}/g, (whole, name) => name in values ? String(values[name]) : whole);
|
|
230
|
+
const CATALOGUES = { zh: ZH };
|
|
231
|
+
/**
|
|
232
|
+
* 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
|
|
233
|
+
* the others; a text a language lacks is told in English, and a test keeps that from happening.
|
|
234
|
+
*/
|
|
235
|
+
function translator(language) {
|
|
236
|
+
const catalogue = language === "en" ? void 0 : CATALOGUES[language];
|
|
237
|
+
return (text, values) => fill(catalogue?.[text] ?? text, values);
|
|
238
|
+
}
|
|
239
|
+
//#endregion
|
|
240
|
+
//#region src/host/orchestration/protocol.ts
|
|
241
|
+
const COMMITMENTS = [
|
|
242
|
+
"low",
|
|
243
|
+
"medium",
|
|
244
|
+
"high"
|
|
245
|
+
];
|
|
246
|
+
const RESULTS = [
|
|
247
|
+
"succeeded",
|
|
248
|
+
"partial",
|
|
249
|
+
"failed"
|
|
250
|
+
];
|
|
251
|
+
const MAX_ACCOUNT = 300;
|
|
252
|
+
/**
|
|
253
|
+
* 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.
|
|
254
|
+
* A character of a script written without spaces says more in fewer.
|
|
255
|
+
*/
|
|
256
|
+
const ANSWER_LIMITS = {
|
|
257
|
+
en: {
|
|
258
|
+
thought: 240,
|
|
259
|
+
intent: 300,
|
|
260
|
+
utterance: 600,
|
|
261
|
+
account: MAX_ACCOUNT
|
|
262
|
+
},
|
|
263
|
+
zh: {
|
|
264
|
+
thought: 100,
|
|
265
|
+
intent: 120,
|
|
266
|
+
utterance: 240,
|
|
267
|
+
account: 120
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
const answerLimits = (language) => language.toLowerCase().startsWith("zh") ? ANSWER_LIMITS.zh : ANSWER_LIMITS.en;
|
|
271
|
+
/** What the answer of a character comes to at most, in tokens (an answer about what happened out of sight has its account too). */
|
|
272
|
+
function answerEstimate(language, away) {
|
|
273
|
+
const limits = answerLimits(language);
|
|
274
|
+
return estimateAnswer([
|
|
275
|
+
limits.thought,
|
|
276
|
+
limits.intent,
|
|
277
|
+
limits.utterance,
|
|
278
|
+
...away ? [limits.account] : []
|
|
279
|
+
], language);
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* 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
|
|
283
|
+
* 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).
|
|
284
|
+
*/
|
|
285
|
+
const CHARACTER_ACTION_SCHEMA = {
|
|
286
|
+
type: "object",
|
|
287
|
+
properties: {
|
|
288
|
+
thought: {
|
|
289
|
+
type: "string",
|
|
290
|
+
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."
|
|
291
|
+
},
|
|
292
|
+
intent: {
|
|
293
|
+
type: "string",
|
|
294
|
+
description: "What the character does, or tries to do, now, as an action in one or two sentences, without any speech."
|
|
295
|
+
},
|
|
296
|
+
utterance: {
|
|
297
|
+
type: "string",
|
|
298
|
+
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."
|
|
299
|
+
},
|
|
300
|
+
commitment: {
|
|
301
|
+
type: "string",
|
|
302
|
+
enum: [...COMMITMENTS],
|
|
303
|
+
description: "How hard the character will keep trying if this does not work out: low gives up at once, high persists."
|
|
304
|
+
}
|
|
305
|
+
},
|
|
306
|
+
required: [
|
|
307
|
+
"thought",
|
|
308
|
+
"intent",
|
|
309
|
+
"commitment"
|
|
310
|
+
],
|
|
311
|
+
additionalProperties: false
|
|
312
|
+
};
|
|
313
|
+
/** 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. */
|
|
314
|
+
const AWAY_ACTION_SCHEMA = {
|
|
315
|
+
...CHARACTER_ACTION_SCHEMA,
|
|
316
|
+
properties: {
|
|
317
|
+
...CHARACTER_ACTION_SCHEMA.properties,
|
|
318
|
+
account: {
|
|
319
|
+
type: "string",
|
|
320
|
+
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."
|
|
321
|
+
}
|
|
322
|
+
},
|
|
323
|
+
required: [
|
|
324
|
+
"thought",
|
|
325
|
+
"intent",
|
|
326
|
+
"commitment",
|
|
327
|
+
"account"
|
|
328
|
+
]
|
|
329
|
+
};
|
|
330
|
+
/** @throws {Error} when the value is not a character action. */
|
|
331
|
+
const QUOTE_PAIRS = [
|
|
332
|
+
["\"", "\""],
|
|
333
|
+
["“", "”"],
|
|
334
|
+
["「", "」"],
|
|
335
|
+
["『", "』"],
|
|
336
|
+
["«", "»"],
|
|
337
|
+
["‘", "’"]
|
|
338
|
+
];
|
|
339
|
+
/** Words said aloud, without the quotation marks a model puts around them: the output puts its own. */
|
|
340
|
+
function unquoted(text) {
|
|
341
|
+
let words = text.trim();
|
|
342
|
+
for (let again = true; again;) {
|
|
343
|
+
again = false;
|
|
344
|
+
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)) {
|
|
345
|
+
words = words.slice(open.length, words.length - close.length).trim();
|
|
346
|
+
again = true;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
return words;
|
|
350
|
+
}
|
|
351
|
+
const LEAKED_FIELD = /<\/?(?:intent|parameter(?:=\w+)?)>/g;
|
|
352
|
+
/** A model that writes the markup of its call into a field puts the next field's text inside this one. */
|
|
353
|
+
function splitLeakedFields(intent) {
|
|
354
|
+
const at = intent.search(/<parameter=utterance>/);
|
|
355
|
+
if (at === -1) return { intent: intent.replace(LEAKED_FIELD, " ") };
|
|
356
|
+
const spoken = intent.slice(at).replace(LEAKED_FIELD, " ").trim();
|
|
357
|
+
return {
|
|
358
|
+
intent: intent.slice(0, at).replace(LEAKED_FIELD, " "),
|
|
359
|
+
...spoken === "" ? {} : { utterance: spoken }
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
function parseCharacterAction(value) {
|
|
363
|
+
if (typeof value !== "object" || value === null) throw new Error("the character did not answer with an object");
|
|
364
|
+
const { intent: rawIntent, utterance: rawUtterance, commitment, account } = value;
|
|
365
|
+
const { intent, utterance } = typeof rawIntent === "string" && rawUtterance === void 0 ? splitLeakedFields(rawIntent) : {
|
|
366
|
+
intent: rawIntent,
|
|
367
|
+
utterance: rawUtterance
|
|
368
|
+
};
|
|
369
|
+
if (typeof intent !== "string" || intent.trim() === "") throw new Error("the character gave no intent");
|
|
370
|
+
if (!COMMITMENTS.includes(commitment)) throw new Error(`the character gave an unknown commitment "${String(commitment)}"`);
|
|
371
|
+
if (utterance !== void 0 && typeof utterance !== "string") throw new Error("the character's utterance is not text");
|
|
372
|
+
const spoken = utterance === void 0 ? void 0 : unquoted(utterance);
|
|
373
|
+
const told = typeof account === "string" ? account.trim().slice(0, MAX_ACCOUNT) : "";
|
|
374
|
+
return {
|
|
375
|
+
intent: intent.trim(),
|
|
376
|
+
...spoken === void 0 || spoken === "" ? {} : { utterance: spoken },
|
|
377
|
+
commitment,
|
|
378
|
+
...told === "" ? {} : { account: told }
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
//#endregion
|
|
382
|
+
//#region src/host/orchestration/referent.ts
|
|
383
|
+
/**
|
|
384
|
+
* 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.
|
|
385
|
+
* 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.
|
|
386
|
+
*/
|
|
387
|
+
function referent(character) {
|
|
388
|
+
const mark = [character.pronouns, character.gender].find((text) => text !== void 0 && text.trim() !== "")?.trim();
|
|
389
|
+
return mark === void 0 ? character.name : `${character.name} (${mark})`;
|
|
390
|
+
}
|
|
391
|
+
//#endregion
|
|
392
|
+
//#region src/host/clock/story-clock.ts
|
|
393
|
+
var ClockError = class extends Error {};
|
|
394
|
+
/** 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. */
|
|
395
|
+
function describeWhen(instant, now, zone, language = "en") {
|
|
396
|
+
const a = localTime(instant, zone);
|
|
397
|
+
const b = localTime(now, zone);
|
|
398
|
+
return a.year === b.year && a.month === b.month && a.day === b.day ? clockTime(instant, zone) : describeInstant(instant, zone, language);
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
401
|
+
* 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
|
|
402
|
+
* fall on the day.
|
|
403
|
+
*/
|
|
404
|
+
function describeTime(time, language = "en") {
|
|
405
|
+
const { calendar } = time;
|
|
406
|
+
const tr = translator(language);
|
|
407
|
+
const base = `${describeInstant(time.now, time.zone, language)} (${tr(dayPart(localTime(time.now, time.zone).minuteOfDay))})`;
|
|
408
|
+
if (calendar === void 0 || calendar.holidays.length === 0 && calendar.hemisphere === "north") return base;
|
|
409
|
+
const day = addLocalDays(time.now, time.zone, 0);
|
|
410
|
+
const holidays = holidaysOn(calendar, day).map((holiday) => holiday.name);
|
|
411
|
+
return `${base}${tr(", ")}${tr(seasonOf(day, calendar.hemisphere))}${holidays.length === 0 ? "" : `${tr("; ")}${tr("today is {holidays}", { holidays: holidays.join(tr(", ")) })}`}`;
|
|
412
|
+
}
|
|
413
|
+
/** The time zone the story is read in. */
|
|
414
|
+
const zoneOf = (config) => config.timeZone === "" ? "UTC" : config.timeZone;
|
|
415
|
+
/** 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. */
|
|
416
|
+
function ensure(session, config, turn, wall) {
|
|
417
|
+
const current = session.clock.get();
|
|
418
|
+
if (current === void 0) {
|
|
419
|
+
session.clock.start(config.mode, config.mode === "real" ? wall : Math.floor(wall / MINUTE) * MINUTE);
|
|
420
|
+
return session.clock.get() ?? {
|
|
421
|
+
mode: config.mode,
|
|
422
|
+
now: wall
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
if (current.mode !== "real" || config.mode !== "simulated") return current;
|
|
426
|
+
session.clock.resync("simulated", Math.max(current.now, wall), turn, "the story's time was detached from the real clock");
|
|
427
|
+
return session.clock.get() ?? current;
|
|
428
|
+
}
|
|
429
|
+
function timeOf(session, state, config) {
|
|
430
|
+
const calendar = session.metadata === void 0 ? void 0 : readCalendar(session.metadata);
|
|
431
|
+
return {
|
|
432
|
+
mode: state.mode,
|
|
433
|
+
now: state.now,
|
|
434
|
+
zone: zoneOf(config),
|
|
435
|
+
...calendar === void 0 || calendar.holidays.length === 0 && calendar.hemisphere === "north" ? {} : { calendar }
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
/** What time it is, without letting any pass. */
|
|
439
|
+
function readTime(session, config, turn, wall) {
|
|
440
|
+
return session.transaction(() => timeOf(session, ensure(session, config, turn, wall), config));
|
|
441
|
+
}
|
|
442
|
+
/**
|
|
443
|
+
* The start of a turn. Following the wall clock, the time since the last turn passed outside the story:
|
|
444
|
+
* `away` says how long.
|
|
445
|
+
*/
|
|
446
|
+
function beginTurn(session, config, turn, wall) {
|
|
447
|
+
return session.transaction(() => {
|
|
448
|
+
const state = ensure(session, config, turn, wall);
|
|
449
|
+
if (state.mode === "real" && wall > state.now) {
|
|
450
|
+
session.clock.advance({
|
|
451
|
+
to: wall,
|
|
452
|
+
turn,
|
|
453
|
+
round: 0,
|
|
454
|
+
kind: "real",
|
|
455
|
+
reason: "between turns"
|
|
456
|
+
});
|
|
457
|
+
return {
|
|
458
|
+
time: timeOf(session, {
|
|
459
|
+
mode: "real",
|
|
460
|
+
now: wall
|
|
461
|
+
}, config),
|
|
462
|
+
away: wall - state.now
|
|
463
|
+
};
|
|
464
|
+
}
|
|
465
|
+
return { time: timeOf(session, state, config) };
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* A round passes. Simulated, it takes what the game master said (or the default), and at least as long as the
|
|
470
|
+
* journey the player's character made (`minimum`); following the wall clock, it takes as long as it took.
|
|
471
|
+
*/
|
|
472
|
+
function endRound(session, config, turn, round, wall, stated, minimum) {
|
|
473
|
+
return session.transaction(() => {
|
|
474
|
+
const state = ensure(session, config, turn, wall);
|
|
475
|
+
if (state.mode === "real") {
|
|
476
|
+
const to = Math.max(state.now, wall);
|
|
477
|
+
session.clock.advance({
|
|
478
|
+
to,
|
|
479
|
+
turn,
|
|
480
|
+
round,
|
|
481
|
+
kind: "real"
|
|
482
|
+
});
|
|
483
|
+
return {
|
|
484
|
+
from: state.now,
|
|
485
|
+
to,
|
|
486
|
+
zone: zoneOf(config)
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
const took = Math.max(stated ?? config.roundSeconds, minimum ?? 0) * SECOND;
|
|
490
|
+
session.clock.advance({
|
|
491
|
+
to: state.now + took,
|
|
492
|
+
turn,
|
|
493
|
+
round,
|
|
494
|
+
kind: "elapsed"
|
|
495
|
+
});
|
|
496
|
+
return {
|
|
497
|
+
from: state.now,
|
|
498
|
+
to: state.now + took,
|
|
499
|
+
zone: zoneOf(config)
|
|
500
|
+
};
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
/**
|
|
504
|
+
* Skip ahead in the story's own time.
|
|
505
|
+
* @throws {ClockError} when time follows the wall clock, the request is not one, or it asks for more than the chat allows.
|
|
506
|
+
*/
|
|
507
|
+
function skipTime(session, config, turn, round, wall, request) {
|
|
508
|
+
return session.transaction(() => {
|
|
509
|
+
const state = ensure(session, config, turn, wall);
|
|
510
|
+
if (state.mode === "real") throw new ClockError("the story's time follows the wall clock, so it cannot be skipped");
|
|
511
|
+
const zone = zoneOf(config);
|
|
512
|
+
const reason = request.reason.trim();
|
|
513
|
+
if (reason === "") throw new ClockError("say what happens in the time that passes (reason)");
|
|
514
|
+
let to;
|
|
515
|
+
if ("byMinutes" in request) {
|
|
516
|
+
if (!Number.isInteger(request.byMinutes) || request.byMinutes < 1) throw new ClockError("by_minutes must be a whole number of minutes, at least 1");
|
|
517
|
+
to = state.now + request.byMinutes * MINUTE;
|
|
518
|
+
} else try {
|
|
519
|
+
to = nextTimeOfDay(state.now, zone, request.untilTime, request.daysLater);
|
|
520
|
+
} catch (error) {
|
|
521
|
+
throw new ClockError(error instanceof RangeError ? error.message : String(error));
|
|
522
|
+
}
|
|
523
|
+
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`);
|
|
524
|
+
session.clock.advance({
|
|
525
|
+
to,
|
|
526
|
+
turn,
|
|
527
|
+
round,
|
|
528
|
+
kind: "skip",
|
|
529
|
+
reason
|
|
530
|
+
});
|
|
531
|
+
return {
|
|
532
|
+
from: state.now,
|
|
533
|
+
to,
|
|
534
|
+
zone,
|
|
535
|
+
reason
|
|
536
|
+
};
|
|
537
|
+
});
|
|
538
|
+
}
|
|
539
|
+
//#endregion
|
|
540
|
+
//#region src/host/orchestration/defaults.ts
|
|
541
|
+
const ENGLISH = translator("en");
|
|
542
|
+
/** What the instructions say about how long each part of a character's answer may run. */
|
|
543
|
+
const limitVariables = (language) => {
|
|
544
|
+
const limits = answerLimits(language);
|
|
545
|
+
return {
|
|
546
|
+
thoughtLimit: limits.thought,
|
|
547
|
+
intentLimit: limits.intent,
|
|
548
|
+
utteranceLimit: limits.utterance
|
|
549
|
+
};
|
|
550
|
+
};
|
|
551
|
+
function describe(character, tr) {
|
|
552
|
+
const lines = [tr("You are {name}.", { name: character.name })];
|
|
553
|
+
if (character.aliases.length > 0) lines.push(tr("You are also called {names}.", { names: character.aliases.join(tr(", ")) }));
|
|
554
|
+
const facts = [
|
|
555
|
+
character.age === void 0 ? void 0 : tr("age: {value}", { value: character.age }),
|
|
556
|
+
character.gender === void 0 ? void 0 : tr("gender: {value}", { value: character.gender }),
|
|
557
|
+
character.pronouns === void 0 ? void 0 : tr("pronouns: {value}", { value: character.pronouns })
|
|
558
|
+
].filter((fact) => fact !== void 0);
|
|
559
|
+
if (facts.length > 0) lines.push(facts.join(tr("; ")) + tr("."));
|
|
560
|
+
for (const [label, text] of [
|
|
561
|
+
["Summary", character.summary],
|
|
562
|
+
["Personality", character.personality],
|
|
563
|
+
["Background", character.background],
|
|
564
|
+
["Appearance", character.appearance],
|
|
565
|
+
["How you speak", character.speech.style]
|
|
566
|
+
]) if (text.trim() !== "") lines.push(`${tr(label)}${tr(": ")}${text.trim()}`);
|
|
567
|
+
return lines.join("\n");
|
|
568
|
+
}
|
|
569
|
+
/** At most this many features and ways out of a place are told at once. */
|
|
570
|
+
const SHOWN_FEATURES = 12;
|
|
571
|
+
const SHOWN_EXITS = 12;
|
|
572
|
+
const sentence = (text) => {
|
|
573
|
+
return (/^[^.!?。!?]*[.!?。!?]?/u.exec(text.trim())?.[0] ?? text).trim();
|
|
574
|
+
};
|
|
575
|
+
/** At most this many things are listed at once: the rest are said to be there and left for a closer look. */
|
|
576
|
+
const SHOWN_ITEMS = 12;
|
|
577
|
+
/** One thing in a sentence: how many, what state it is in, where it is. */
|
|
578
|
+
function describeItem(item, { withKeys }, tr = ENGLISH) {
|
|
579
|
+
const name = `${item.quantity > 1 ? `${item.quantity} ` : ""}${item.name}${item.quality === "" ? "" : ` (${item.quality})`}`;
|
|
580
|
+
const extra = [
|
|
581
|
+
item.hidden ? tr("hidden") : "",
|
|
582
|
+
item.state === void 0 ? "" : item.state,
|
|
583
|
+
item.where ?? ""
|
|
584
|
+
].filter((part) => part !== "").join(tr(", "));
|
|
585
|
+
const inside = item.contents === void 0 ? "" : tr(" holding {things}", { things: item.contents.join(tr(", ")) });
|
|
586
|
+
return `${withKeys ? `${item.key}: ` : ""}${name}${extra === "" ? "" : ` [${extra}]`}${inside}`;
|
|
587
|
+
}
|
|
588
|
+
/** A list of things, capped. */
|
|
589
|
+
function describeItems(items, options, tr = ENGLISH) {
|
|
590
|
+
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 }) : ""}`;
|
|
591
|
+
}
|
|
592
|
+
/** What someone in a place is told about it: what it is like, what can be pointed at, and the ways out. */
|
|
593
|
+
function describePlace(view, { withKeys }, tr = ENGLISH) {
|
|
594
|
+
const { location, exits } = view;
|
|
595
|
+
const lines = [`${location.name}${withKeys ? ` (${view.key})` : ""}${location.description === "" ? "" : `: ${location.description}`}`];
|
|
596
|
+
if (location.features.length > 0) {
|
|
597
|
+
const shown = location.features.slice(0, SHOWN_FEATURES).map((feature) => `${withKeys ? `${feature.key}: ` : ""}${feature.name}${feature.description === "" ? "" : ` - ${sentence(feature.description)}`}`);
|
|
598
|
+
lines.push(`${tr("Things here: ")}${shown.join(tr("; "))}${location.features.length > SHOWN_FEATURES ? tr("; and {count} more", { count: location.features.length - SHOWN_FEATURES }) : ""}`);
|
|
599
|
+
}
|
|
600
|
+
if (exits.length > 0) {
|
|
601
|
+
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}`}]`}`);
|
|
602
|
+
lines.push(`${tr("Ways out: ")}${shown.join(tr("; "))}${exits.length > SHOWN_EXITS ? tr("; and {count} more", { count: exits.length - SHOWN_EXITS }) : ""}`);
|
|
603
|
+
}
|
|
604
|
+
if (view.items !== void 0 && view.items.length > 0) lines.push(`${tr("Lying about: ")}${describeItems(view.items, { withKeys }, tr)}`);
|
|
605
|
+
return lines;
|
|
606
|
+
}
|
|
607
|
+
/** How long the player has to have been away for it to be worth telling the game master. */
|
|
608
|
+
const NOTICEABLE_ABSENCE = 5 * MINUTE;
|
|
609
|
+
/** What the game master is told about time at the start of a turn, and how it passes. */
|
|
610
|
+
function timeNotice(time, language, tr) {
|
|
611
|
+
const now = tr("Time: {time}.", { time: describeTime(time.now, language) });
|
|
612
|
+
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.")}`;
|
|
613
|
+
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) })}` : "";
|
|
614
|
+
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}`;
|
|
615
|
+
}
|
|
616
|
+
/** What a character is told of its day, its commitments and what it is after. */
|
|
617
|
+
function describeAgenda(agenda, now, tr = ENGLISH, language = "en") {
|
|
618
|
+
const { zone } = agenda;
|
|
619
|
+
const when = (instant) => describeWhen(instant, now, zone, language);
|
|
620
|
+
const at = (place) => place === void 0 ? "" : tr(" at {place}", { place });
|
|
621
|
+
const lines = [];
|
|
622
|
+
if (agenda.now !== void 0) lines.push(tr("Your day, now: {activity}{place}, until {until}{note}.", {
|
|
623
|
+
activity: agenda.now.activity,
|
|
624
|
+
place: at(agenda.now.place),
|
|
625
|
+
until: when(agenda.now.until),
|
|
626
|
+
note: agenda.now.interruptible ? "" : tr(" (not something you would drop lightly)")
|
|
627
|
+
}));
|
|
628
|
+
if (agenda.next !== void 0) lines.push(tr("Your day, next: {activity}{place}, from {from}.", {
|
|
629
|
+
activity: agenda.next.activity,
|
|
630
|
+
place: at(agenda.next.place),
|
|
631
|
+
from: when(agenda.next.at)
|
|
632
|
+
}));
|
|
633
|
+
for (const engagement of agenda.engagements) {
|
|
634
|
+
const values = {
|
|
635
|
+
title: engagement.title,
|
|
636
|
+
place: at(engagement.place),
|
|
637
|
+
with: engagement.with.length === 0 ? "" : tr(", with {names}", { names: engagement.with.join(tr(", ")) }),
|
|
638
|
+
at: when(engagement.at)
|
|
639
|
+
};
|
|
640
|
+
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));
|
|
641
|
+
}
|
|
642
|
+
if (agenda.goals.length > 0) {
|
|
643
|
+
lines.push(tr("What you are after:"));
|
|
644
|
+
for (const goal of agenda.goals) {
|
|
645
|
+
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) });
|
|
646
|
+
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("; ")) })}`);
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
return lines;
|
|
650
|
+
}
|
|
651
|
+
/** What the game master is told of the characters' days at the start of a turn; nothing when there is nothing to tell. */
|
|
652
|
+
function describeSceneAgenda(agenda, now, tr = ENGLISH, language = "en") {
|
|
653
|
+
const lines = [];
|
|
654
|
+
const join = (entries) => entries.join(tr("; "));
|
|
655
|
+
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})", {
|
|
656
|
+
name: move.name,
|
|
657
|
+
place: move.to,
|
|
658
|
+
activity: move.activity
|
|
659
|
+
}))) }));
|
|
660
|
+
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}`)) }));
|
|
661
|
+
if (agenda.engagements.length > 0) {
|
|
662
|
+
const entries = agenda.engagements.map((engagement) => {
|
|
663
|
+
const values = {
|
|
664
|
+
title: engagement.title,
|
|
665
|
+
with: engagement.with.join(tr(", ")),
|
|
666
|
+
place: engagement.place === void 0 ? "" : tr(", at {place}", { place: engagement.place }),
|
|
667
|
+
when: describeWhen(engagement.at, now, agenda.zone, language)
|
|
668
|
+
};
|
|
669
|
+
return engagement.overdue ? tr("\"{title}\" ({with}{place}) was due {when} and is still open", values) : tr("\"{title}\" ({with}{place}) is due {when}", values);
|
|
670
|
+
});
|
|
671
|
+
lines.push(tr("Commitments due soon or overdue: {entries}.", { entries: join(entries) }));
|
|
672
|
+
}
|
|
673
|
+
return lines.join("\n");
|
|
674
|
+
}
|
|
675
|
+
/** In words, how a character stands with another, from the numbers of its profile; nothing for what is unremarkable. */
|
|
676
|
+
function describeAttitude(relation, tr = ENGLISH) {
|
|
677
|
+
return [
|
|
678
|
+
relation.familiarity >= .7 ? tr("knows them well") : relation.familiarity <= .15 ? tr("barely knows them") : "",
|
|
679
|
+
relation.trust >= .4 ? tr("trusts them") : relation.trust <= -.4 ? tr("distrusts them") : "",
|
|
680
|
+
relation.affinity >= .4 ? tr("is fond of them") : relation.affinity <= -.4 ? tr("dislikes them") : "",
|
|
681
|
+
relation.tension >= .5 ? tr("things are strained between them") : ""
|
|
682
|
+
].filter((part) => part !== "").join(tr(", "));
|
|
683
|
+
}
|
|
684
|
+
function whereIs(member, tr = ENGLISH) {
|
|
685
|
+
const place = member.place;
|
|
686
|
+
if (place === void 0) return "";
|
|
687
|
+
return [place.position, place.feature === void 0 ? "" : tr("at {feature}", { feature: place.feature.name })].filter((part) => part !== "").join(tr(", "));
|
|
688
|
+
}
|
|
689
|
+
function present(cast, self, tr) {
|
|
690
|
+
return cast.map((member) => {
|
|
691
|
+
const { key, character, state } = member;
|
|
692
|
+
const seen = [state?.publicState, state?.activity].filter((text) => text !== void 0 && text.trim() !== "");
|
|
693
|
+
const where = whereIs(member);
|
|
694
|
+
return `- ${key === self ? character.name : referent(character)}${key === self ? tr(" (you)") : ""}${where === "" ? "" : ` (${where})`}${seen.length > 0 ? `${tr(": ")}${seen.join(tr("; "))}` : ""}`;
|
|
695
|
+
}).join("\n");
|
|
696
|
+
}
|
|
697
|
+
/** A bounded, advisory order for who is most likely to need a turn; reachability still governs activation. */
|
|
698
|
+
function describeActivationCandidates(cast, input, story, tr = ENGLISH) {
|
|
699
|
+
const player = cast.find((member) => member.character.control === "player");
|
|
700
|
+
if (player === void 0) return "";
|
|
701
|
+
const named = mentioned(input, cast.map((member) => member.character));
|
|
702
|
+
const cues = tokens(input);
|
|
703
|
+
const candidates = cast.filter((member) => member.character.control === "agent").map((member) => {
|
|
704
|
+
const relation = story.relationships.get(member.character.id, player.character.id);
|
|
705
|
+
const here = member.place === void 0 || player.place === void 0 || member.place.location.id === player.place.location.id;
|
|
706
|
+
const goal = story.intents.list(member.character.id, { status: "active" }).map((intent) => ({
|
|
707
|
+
intent,
|
|
708
|
+
match: overlap(cues, `${intent.name} ${intent.description}`, [])
|
|
709
|
+
})).sort((a, b) => b.match - a.match)[0];
|
|
710
|
+
const factionGoal = story.factionMemberships.ofCharacter(member.character.id, "active").flatMap((membership) => story.factionIntents.list(membership.factionId, { status: "active" }).map((intent) => ({
|
|
711
|
+
intent,
|
|
712
|
+
match: overlap(cues, `${intent.name} ${intent.description}`, []) * membership.commitment
|
|
713
|
+
}))).sort((a, b) => b.match - a.match)[0];
|
|
714
|
+
return {
|
|
715
|
+
member,
|
|
716
|
+
reasons: [
|
|
717
|
+
named.has(member.character.id) ? tr("named in the move") : "",
|
|
718
|
+
here ? tr("in the scene") : "",
|
|
719
|
+
(goal?.match ?? 0) >= 2 ? tr("own goal: {goal}", { goal: goal.intent.name }) : "",
|
|
720
|
+
(factionGoal?.match ?? 0) >= 2 ? tr("faction pressure: {goal}", { goal: factionGoal.intent.name }) : "",
|
|
721
|
+
relation !== void 0 && relation.tension >= .5 ? tr("high tension toward the player") : "",
|
|
722
|
+
relation !== void 0 && relation.trust <= -.4 ? tr("distrusts the player") : "",
|
|
723
|
+
relation !== void 0 && Math.abs(relation.affinity) >= .4 ? relation.affinity > 0 ? tr("cares about the player") : tr("dislikes the player") : ""
|
|
724
|
+
].filter((reason) => reason !== ""),
|
|
725
|
+
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
|
|
726
|
+
};
|
|
727
|
+
}).filter((entry) => entry.score > 0).sort((a, b) => b.score - a.score || a.member.key.localeCompare(b.member.key)).slice(0, 5);
|
|
728
|
+
if (candidates.length === 0) return "";
|
|
729
|
+
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")}`;
|
|
730
|
+
}
|
|
731
|
+
function said(entry, tr) {
|
|
732
|
+
return entry.utterance === void 0 ? tr("- {name} intended: {intent} ({result}) {summary}", {
|
|
733
|
+
name: entry.name,
|
|
734
|
+
intent: entry.intent,
|
|
735
|
+
result: entry.result,
|
|
736
|
+
summary: entry.summary
|
|
737
|
+
}) : tr("- {name} said \"{utterance}\" and intended: {intent} ({result}) {summary}", {
|
|
738
|
+
name: entry.name,
|
|
739
|
+
utterance: entry.utterance,
|
|
740
|
+
intent: entry.intent,
|
|
741
|
+
result: entry.result,
|
|
742
|
+
summary: entry.summary
|
|
743
|
+
});
|
|
744
|
+
}
|
|
745
|
+
function age(at, now, tr) {
|
|
746
|
+
if (at === void 0 || now === void 0) return tr("some time ago");
|
|
747
|
+
const seconds = Math.max(0, Math.floor((now - at) / 1e3));
|
|
748
|
+
if (seconds < 60) return tr("just now");
|
|
749
|
+
const amount = Math.floor(seconds / (seconds >= 86400 ? 86400 : seconds >= 3600 ? 3600 : 60));
|
|
750
|
+
if (seconds >= 86400) return amount === 1 ? tr("1 day ago") : tr("{amount} days ago", { amount });
|
|
751
|
+
if (seconds >= 3600) return amount === 1 ? tr("1 hour ago") : tr("{amount} hours ago", { amount });
|
|
752
|
+
return amount === 1 ? tr("1 minute ago") : tr("{amount} minutes ago", { amount });
|
|
753
|
+
}
|
|
754
|
+
/** 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. */
|
|
755
|
+
function remembered(memories, tr, now) {
|
|
756
|
+
return memories.map((memory) => {
|
|
757
|
+
const clarity = memory.clarity === "clear" ? [] : [memory.clarity === "faded" ? tr("the details are fuzzy") : tr("you barely remember")];
|
|
758
|
+
const sure = memory.confidence === "sure" ? [tr("you are sure of it")] : memory.confidence === "doubtful" ? [tr("you doubt it")] : [];
|
|
759
|
+
const against = memory.disputed === true ? [tr("something you have seen since speaks against it")] : [];
|
|
760
|
+
return `- (${[
|
|
761
|
+
age(memory.at, now, tr),
|
|
762
|
+
...clarity,
|
|
763
|
+
...sure,
|
|
764
|
+
...against,
|
|
765
|
+
...memory.linked === true ? [tr("it comes to mind with the rest")] : []
|
|
766
|
+
].join(tr(", "))}) ${memory.text}`;
|
|
767
|
+
}).join("\n");
|
|
768
|
+
}
|
|
769
|
+
/** Every character is told the same thing about the scene, plus who it is and what it remembers. */
|
|
770
|
+
const sharedContext = { brief(request) {
|
|
771
|
+
const { member, cast, situation, attempt, earlier, reaction, previous, memories, place, relationships, knowledge, affiliations, carrying, time, agenda } = request;
|
|
772
|
+
const language = languageOf(request.language);
|
|
773
|
+
const tr = translator(language);
|
|
774
|
+
const list = (entries) => entries.join(tr("; "));
|
|
775
|
+
const company = place === void 0 ? cast : place.here;
|
|
776
|
+
const sections = [
|
|
777
|
+
`${tr("Situation:")}\n${situation}`,
|
|
778
|
+
...time === void 0 ? [] : [tr("Now: {time}.", { time: describeTime(time, language) })],
|
|
779
|
+
...place === void 0 ? [] : [`${tr("Where you are:")}\n${describePlace(place, { withKeys: false }, tr).join("\n")}`],
|
|
780
|
+
`${tr("Present:")}\n${present(company, member.key, tr)}`
|
|
781
|
+
];
|
|
782
|
+
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")}`);
|
|
783
|
+
if (request.cues !== void 0 && request.cues.length > 0) sections.push(`${tr("Just now you notice:")}\n${request.cues.map((cue) => `- ${cue}`).join("\n")}`);
|
|
784
|
+
if (request.tracked !== void 0 && request.tracked.self !== "") sections.push(`${tr("How you are (what you can tell of yourself):")}\n${request.tracked.self}`);
|
|
785
|
+
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")}`);
|
|
786
|
+
const day = agenda === void 0 || time === void 0 ? [] : describeAgenda(agenda, time.now, tr, language);
|
|
787
|
+
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")}`);
|
|
788
|
+
if (carrying !== void 0 && carrying.length > 0) sections.push(`${tr("What you have on you:")}\n${describeItems(carrying, { withKeys: false }, tr)}`);
|
|
789
|
+
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) => {
|
|
790
|
+
const attitude = describeAttitude(relation, tr);
|
|
791
|
+
return `- ${relation.name}${relation.present ? tr(" (here)") : tr(" (not here)")} — ${relation.label}${relation.summary === "" ? "" : `${tr(": ")}${relation.summary}`}${attitude === "" ? "" : ` [${attitude}]`}`;
|
|
792
|
+
}).join("\n")}`);
|
|
793
|
+
if (affiliations !== void 0 && affiliations.length > 0) sections.push(`${tr("Your affiliations (their goals are pressures and commitments, not commands):")}\n${affiliations.map((entry) => {
|
|
794
|
+
const position = [entry.role, entry.rank].filter(Boolean).join(tr(", ")) || tr("member");
|
|
795
|
+
const goals = entry.goals.length === 0 ? "" : tr(" Goals: {goals}.", { goals: list(entry.goals) });
|
|
796
|
+
const state = entry.publicState === "" ? "" : ` ${entry.publicState}`;
|
|
797
|
+
const attitude = entry.relationship === void 0 ? "" : describeAttitude(entry.relationship, tr);
|
|
798
|
+
return tr("- {name}: {position}; {status}; commitment {commitment}.", {
|
|
799
|
+
name: entry.name,
|
|
800
|
+
position,
|
|
801
|
+
status: entry.status,
|
|
802
|
+
commitment: entry.commitment.toFixed(2)
|
|
803
|
+
}) + `${state}${goals}${attitude === "" ? "" : tr(" Your view: {attitude}.", { attitude })}`;
|
|
804
|
+
}).join("\n")}`);
|
|
805
|
+
if (knowledge !== void 0) {
|
|
806
|
+
const shown = (entries) => list(entries.slice(0, 30)) + (entries.length > 30 ? tr("; and {count} more you can recall if needed", { count: entries.length - 30 }) : "");
|
|
807
|
+
const lines = [
|
|
808
|
+
knowledge.characters.length === 0 ? void 0 : `${tr("People: ")}${shown(knowledge.characters)}`,
|
|
809
|
+
knowledge.factions.length === 0 ? void 0 : `${tr("Factions: ")}${shown(knowledge.factions)}`,
|
|
810
|
+
knowledge.locations.length === 0 ? void 0 : `${tr("Places: ")}${shown(knowledge.locations)}`,
|
|
811
|
+
knowledge.routes.length === 0 ? void 0 : `${tr("Routes: ")}${shown(knowledge.routes)}`,
|
|
812
|
+
knowledge.items.length === 0 ? void 0 : `${tr("Things: ")}${shown(knowledge.items)}`
|
|
813
|
+
].filter((line) => line !== void 0);
|
|
814
|
+
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")}`);
|
|
815
|
+
}
|
|
816
|
+
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)}`);
|
|
817
|
+
else if (memories !== void 0) sections.splice(1, 0, tr("What you remember that bears on this: nothing comes to mind."));
|
|
818
|
+
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")}`);
|
|
819
|
+
if (attempt === 2 && reaction !== void 0) {
|
|
820
|
+
sections.push(`${tr("What just happened, and what you are reacting to:")}\n${reaction.map((entry) => said(entry, tr)).join("\n")}`);
|
|
821
|
+
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 }));
|
|
822
|
+
}
|
|
823
|
+
return {
|
|
824
|
+
persona: [
|
|
825
|
+
describe(member.character, tr),
|
|
826
|
+
request.text("roleplay/character-rules", { name: member.character.name }),
|
|
827
|
+
request.text("roleplay/character-style", { name: member.character.name }),
|
|
828
|
+
...request.lookup ? [request.text("roleplay/character-lookup")] : [],
|
|
829
|
+
request.text("roleplay/character-decide", {
|
|
830
|
+
name: member.character.name,
|
|
831
|
+
...limitVariables(request.language ?? "en")
|
|
832
|
+
})
|
|
833
|
+
].join("\n\n"),
|
|
834
|
+
prompt: sections.join("\n\n")
|
|
835
|
+
};
|
|
836
|
+
} };
|
|
837
|
+
/**
|
|
838
|
+
* 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
|
|
839
|
+
* 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
|
|
840
|
+
* another place can be asked when the moment reaches it.)
|
|
841
|
+
*/
|
|
842
|
+
const everyoneActs = { plan({ cast, requested }) {
|
|
843
|
+
const placed = cast.some((member) => member.place !== void 0);
|
|
844
|
+
const available = cast.filter((member) => member.character.control === "agent");
|
|
845
|
+
const here = cast.find((member) => member.character.control === "player")?.place?.location.id;
|
|
846
|
+
const inScene = (member) => !placed || member.place !== void 0;
|
|
847
|
+
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);
|
|
848
|
+
const unknown = requested.filter((key) => !available.some((member) => member.key === key));
|
|
849
|
+
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(", ")})`);
|
|
850
|
+
const nowhere = [...new Set(requested)].map((key) => available.find((member) => member.key === key)).filter((member) => !inScene(member));
|
|
851
|
+
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`);
|
|
852
|
+
return [...new Set(requested)];
|
|
853
|
+
} };
|
|
854
|
+
const acceptsAnyIntent = { validate: ({ intent }) => intent.trim() === "" ? {
|
|
855
|
+
ok: false,
|
|
856
|
+
reason: "the intent is empty"
|
|
857
|
+
} : { ok: true } };
|
|
858
|
+
/** A character whose intent failed and who is highly committed tries once more. */
|
|
859
|
+
const persistentRetry = { select({ reports, outcomes }) {
|
|
860
|
+
return reports.filter((report) => report.commitment === "high" && outcomes.some((outcome) => outcome.character === report.character && outcome.result === "failed")).map((report) => report.character);
|
|
861
|
+
} };
|
|
862
|
+
const acceptsAnyInput = { validate: () => ({ ok: true }) };
|
|
863
|
+
/** The game master narrates. */
|
|
864
|
+
const gameMasterNarrates = { narrate: () => Promise.resolve(void 0) };
|
|
865
|
+
/** Compares what was said, ignoring the quotes around it and the way whitespace is laid out. */
|
|
866
|
+
const WRAPPING_QUOTES = /^["“”„«»'‘’]+|["“”„«»'‘’]+$/g;
|
|
867
|
+
function sameWords(a, b) {
|
|
868
|
+
const plain = (text) => text.trim().replace(WRAPPING_QUOTES, "").replace(/\s+/g, " ").trim();
|
|
869
|
+
return plain(a) === plain(b);
|
|
870
|
+
}
|
|
871
|
+
/** How many earlier events the game master is reminded of at most. */
|
|
872
|
+
const REMINDED_EVENTS = 5;
|
|
873
|
+
/**
|
|
874
|
+
* The state of the scene, what is still open in the story, and the earlier events that the
|
|
875
|
+
* player's move brings to mind (by the session's search of words and meaning, and by who is named):
|
|
876
|
+
* those already folded out of the conversation into the summaries, whose detail the summaries may have lost.
|
|
877
|
+
*/
|
|
878
|
+
/** Where the player is and what is there, who is with them, and who is elsewhere. */
|
|
879
|
+
function placedScene(cast, player, story, describeMember, tr, things) {
|
|
880
|
+
const here = player?.place?.location;
|
|
881
|
+
const sections = [];
|
|
882
|
+
if (here !== void 0) {
|
|
883
|
+
const view = {
|
|
884
|
+
key: locationKey(here),
|
|
885
|
+
location: here,
|
|
886
|
+
here: cast.filter((member) => member.place?.location.id === here.id),
|
|
887
|
+
...things === void 0 ? {} : { items: things.at(here.id) },
|
|
888
|
+
exits: story.locations.exitsFrom(here.id).flatMap((exit) => {
|
|
889
|
+
const to = story.locations.get(exit.toId);
|
|
890
|
+
return to === void 0 ? [] : [{
|
|
891
|
+
key: locationKey(to),
|
|
892
|
+
name: to.name,
|
|
893
|
+
exit
|
|
894
|
+
}];
|
|
895
|
+
})
|
|
896
|
+
};
|
|
897
|
+
sections.push(tr("The player's character is in {place}", { place: describePlace(view, { withKeys: true }, tr).join("\n") }));
|
|
898
|
+
sections.push(`${tr("Characters here:")}\n${view.here.map(describeMember).join("\n")}`);
|
|
899
|
+
}
|
|
900
|
+
const elsewhere = cast.filter((member) => member.place !== void 0 && member.place.location.id !== here?.id);
|
|
901
|
+
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})", {
|
|
902
|
+
member: describeMember(member),
|
|
903
|
+
place: member.place.location.name,
|
|
904
|
+
key: locationKey(member.place.location)
|
|
905
|
+
})).join("\n")}`);
|
|
906
|
+
const nowhere = cast.filter((member) => member.place === void 0);
|
|
907
|
+
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")}`);
|
|
908
|
+
return sections.join("\n\n");
|
|
909
|
+
}
|
|
910
|
+
const castSummary = { scene({ tracked, time, world, cast, turn, input, queryVector, story, items, language: code }) {
|
|
911
|
+
const language = languageOf(code);
|
|
912
|
+
const tr = translator(language);
|
|
913
|
+
const join = (entries) => entries.join(tr("; "));
|
|
914
|
+
const describeMember = (member) => {
|
|
915
|
+
const { key, character, state } = member;
|
|
916
|
+
const role = character.control === "player" ? tr("the player's character, \"{key}\"", { key }) : tr("acts through \"{key}\"", { key });
|
|
917
|
+
const seen = [state?.publicState, state?.activity].filter((text) => text !== void 0 && text.trim() !== "");
|
|
918
|
+
const where = whereIs(member, tr);
|
|
919
|
+
return `- ${referent(character)} (${role})${where === "" ? "" : ` [${where}]`}${character.summary === "" ? "" : `${tr(": ")}${character.summary}`}${seen.length > 0 ? ` ${tr("Currently: {state}", { state: join(seen) })}` : ""}`;
|
|
920
|
+
};
|
|
921
|
+
const player = cast.find((member) => member.character.control === "player");
|
|
922
|
+
const days = time?.agenda === void 0 ? "" : describeSceneAgenda(time.agenda, time.now.now, tr, language);
|
|
923
|
+
const scene = cast.some((member) => member.place !== void 0) ? placedScene(cast, player, story, describeMember, tr, items) : cast.map(describeMember).join("\n");
|
|
924
|
+
const parts = [
|
|
925
|
+
...time === void 0 ? [] : [timeNotice(time, language, tr)],
|
|
926
|
+
...days === "" ? [] : [days],
|
|
927
|
+
`${tr("Scene before turn {turn}:", { turn })}\n${scene}`
|
|
928
|
+
];
|
|
929
|
+
const activation = describeActivationCandidates(cast, input, story, tr);
|
|
930
|
+
if (activation !== "") parts.push(activation);
|
|
931
|
+
if (items !== void 0) {
|
|
932
|
+
const carried = cast.flatMap((member) => {
|
|
933
|
+
const mine = items.carried(member.character.id);
|
|
934
|
+
return mine.length === 0 ? [] : [`- ${member.character.name} (${member.key}): ${describeItems(mine, { withKeys: true }, tr)}`];
|
|
935
|
+
});
|
|
936
|
+
if (carried.length > 0) parts.push(`${tr("What characters have on them:")}\n${carried.join("\n")}`);
|
|
937
|
+
}
|
|
938
|
+
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")}`);
|
|
939
|
+
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")}`);
|
|
940
|
+
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")}`);
|
|
941
|
+
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")}`);
|
|
942
|
+
const threads = story.threads.list("open");
|
|
943
|
+
if (threads.length > 0) parts.push(`${tr("Still open in the story:")}\n${threads.map((thread) => `- ${thread.text}`).join("\n")}`);
|
|
944
|
+
const folded = story.summaries.list().reduce((latest, summary) => Math.max(latest, summary.toTurn), 0);
|
|
945
|
+
if (folded > 0) {
|
|
946
|
+
const mentionedIds = mentioned(input, cast.map(({ character }) => character));
|
|
947
|
+
const cues = tokens(input);
|
|
948
|
+
const names = new Map(cast.map(({ character }) => [character.id, character.name]));
|
|
949
|
+
const byMeaning = story.searchEvents({
|
|
950
|
+
text: input,
|
|
951
|
+
...queryVector === void 0 ? {} : { vector: queryVector },
|
|
952
|
+
toTurn: folded,
|
|
953
|
+
limit: REMINDED_EVENTS
|
|
954
|
+
});
|
|
955
|
+
const byCues = story.events.list({ toTurn: folded }).filter((event) => !byMeaning.some((found) => found.id === event.id)).map((event) => ({
|
|
956
|
+
event,
|
|
957
|
+
score: 3 * event.involves.filter((id) => mentionedIds.has(id)).length + overlap(cues, event.text, event.tags)
|
|
958
|
+
})).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);
|
|
959
|
+
const relevant = [...byMeaning, ...byCues].slice(0, REMINDED_EVENTS).sort((a, b) => a.turn - b.turn).map((event) => ({ event }));
|
|
960
|
+
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 }) => {
|
|
961
|
+
const who = event.involves.map((id) => names.get(id)).filter((name) => name !== void 0).join(tr(", "));
|
|
962
|
+
return `- (${tr("turn {turn}", { turn: event.turn })}) ${event.text}${who === "" ? "" : ` [${who}]`}`;
|
|
963
|
+
}).join("\n")}`);
|
|
964
|
+
}
|
|
965
|
+
return parts.join("\n\n");
|
|
966
|
+
} };
|
|
967
|
+
const sameCharacter = (utterance, character) => utterance.character === character || utterance.name === character;
|
|
968
|
+
/** Every utterance appears once, exactly as given and in the order spoken, and no one speaks who did not. */
|
|
969
|
+
const exactUtterances = {
|
|
970
|
+
check(segments, required) {
|
|
971
|
+
const problems = [];
|
|
972
|
+
const used = /* @__PURE__ */ new Set();
|
|
973
|
+
let latest = 0;
|
|
974
|
+
segments.forEach((segment, index) => {
|
|
975
|
+
const at = `segment ${index + 1}`;
|
|
976
|
+
if (segment.type === "narration") {
|
|
977
|
+
if (segment.text.trim() === "") problems.push(`${at}: the narration is empty`);
|
|
978
|
+
return;
|
|
979
|
+
}
|
|
980
|
+
const own = required.flatMap((utterance, position) => sameCharacter(utterance, segment.character) ? [position] : []);
|
|
981
|
+
const free = own.filter((position) => !used.has(position));
|
|
982
|
+
const exact = free.find((position) => sameWords(segment.text, required[position].text));
|
|
983
|
+
if (exact !== void 0) {
|
|
984
|
+
used.add(exact);
|
|
985
|
+
const spoken = required[exact];
|
|
986
|
+
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`);
|
|
987
|
+
latest = Math.max(latest, spoken.round);
|
|
988
|
+
} else if (free.length > 0) {
|
|
989
|
+
used.add(free[0]);
|
|
990
|
+
problems.push(`${at}: the utterance of ${required[free[0]].name} was changed; it must be exactly "${required[free[0]].text}"`);
|
|
991
|
+
} 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`);
|
|
992
|
+
else problems.push(`${at}: ${segment.character} has nothing to say this turn, so this utterance is invented; remove it`);
|
|
993
|
+
});
|
|
994
|
+
required.forEach((utterance, position) => {
|
|
995
|
+
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}"`);
|
|
996
|
+
});
|
|
997
|
+
return problems;
|
|
998
|
+
},
|
|
999
|
+
repair(segments, required) {
|
|
1000
|
+
const used = /* @__PURE__ */ new Set();
|
|
1001
|
+
const kept = [];
|
|
1002
|
+
for (const segment of segments) {
|
|
1003
|
+
if (segment.type === "narration") {
|
|
1004
|
+
if (segment.text.trim() !== "") kept.push({
|
|
1005
|
+
segment,
|
|
1006
|
+
round: void 0
|
|
1007
|
+
});
|
|
1008
|
+
continue;
|
|
1009
|
+
}
|
|
1010
|
+
const free = required.flatMap((utterance, position) => sameCharacter(utterance, segment.character) && !used.has(position) ? [position] : []);
|
|
1011
|
+
const position = free.find((candidate) => sameWords(segment.text, required[candidate].text)) ?? free[0];
|
|
1012
|
+
if (position === void 0) continue;
|
|
1013
|
+
used.add(position);
|
|
1014
|
+
const spoken = required[position];
|
|
1015
|
+
kept.push({
|
|
1016
|
+
segment: {
|
|
1017
|
+
type: "utterance",
|
|
1018
|
+
character: spoken.character,
|
|
1019
|
+
name: spoken.name,
|
|
1020
|
+
text: spoken.text
|
|
1021
|
+
},
|
|
1022
|
+
round: spoken.round
|
|
1023
|
+
});
|
|
1024
|
+
}
|
|
1025
|
+
required.forEach((utterance, position) => {
|
|
1026
|
+
if (used.has(position)) return;
|
|
1027
|
+
const restored = {
|
|
1028
|
+
type: "utterance",
|
|
1029
|
+
character: utterance.character,
|
|
1030
|
+
name: utterance.name,
|
|
1031
|
+
text: utterance.text
|
|
1032
|
+
};
|
|
1033
|
+
const later = kept.findIndex((entry) => entry.round !== void 0 && entry.round > utterance.round);
|
|
1034
|
+
kept.splice(later < 0 ? kept.length : later, 0, {
|
|
1035
|
+
segment: restored,
|
|
1036
|
+
round: utterance.round
|
|
1037
|
+
});
|
|
1038
|
+
});
|
|
1039
|
+
return kept.map((entry) => entry.segment);
|
|
1040
|
+
}
|
|
1041
|
+
};
|
|
1042
|
+
/** 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. */
|
|
1043
|
+
const recordsRecall = { recall: ({ member, situation, turn, policy, queryVector, explain }, story, signal) => story.recallRanked({
|
|
1044
|
+
characterId: member.character.id,
|
|
1045
|
+
situation,
|
|
1046
|
+
turn,
|
|
1047
|
+
policy,
|
|
1048
|
+
...explain === true ? { explain } : {},
|
|
1049
|
+
...member.place === void 0 ? {} : { locationId: member.place.location.id }
|
|
1050
|
+
}, signal, queryVector === void 0 ? {} : { queryVector }) };
|
|
1051
|
+
/**
|
|
1052
|
+
* Writes no memory. What the game master decided about each character is applied when the round is
|
|
1053
|
+
* recorded, so without a memory keeper the story keeps its states and no events.
|
|
1054
|
+
*/
|
|
1055
|
+
const writesNothing = { commit: () => Promise.resolve({
|
|
1056
|
+
writes: 0,
|
|
1057
|
+
notes: ""
|
|
1058
|
+
}) };
|
|
1059
|
+
/** Makes up nothing, and has nothing to fit in: without a world author the world stays as it was written. */
|
|
1060
|
+
const declinesToAuthor = {
|
|
1061
|
+
create: () => Promise.resolve({
|
|
1062
|
+
created: [],
|
|
1063
|
+
declined: "no world author is installed, so the world cannot grow"
|
|
1064
|
+
}),
|
|
1065
|
+
consolidate: () => Promise.resolve({
|
|
1066
|
+
resolved: 0,
|
|
1067
|
+
notes: ""
|
|
1068
|
+
})
|
|
1069
|
+
};
|
|
1070
|
+
/** Lets no organisation act: without a strategist factions change only through what the story records. */
|
|
1071
|
+
const factionsStayPut = { strategize: () => Promise.resolve({ acted: [] }) };
|
|
1072
|
+
/** Reflects on nothing: without a reflector what characters believe changes only through what the story records. */
|
|
1073
|
+
const reflectsOnNothing = { reflect: () => Promise.resolve({ characters: [] }) };
|
|
1074
|
+
/** Judges nothing: without a judge a trigger that waits on a statement never sees it hold. */
|
|
1075
|
+
const judgesNothing = { judge: () => Promise.resolve({ judged: 0 }) };
|
|
1076
|
+
/** Offers nothing: without a suggester the player writes their own move. */
|
|
1077
|
+
const offersNothing = { suggest: () => Promise.resolve([]) };
|
|
1078
|
+
function defaultBoundaries() {
|
|
1079
|
+
return {
|
|
1080
|
+
planner: everyoneActs,
|
|
1081
|
+
characterContext: sharedContext,
|
|
1082
|
+
outputValidator: acceptsAnyIntent,
|
|
1083
|
+
retryPolicy: persistentRetry,
|
|
1084
|
+
inputValidator: acceptsAnyInput,
|
|
1085
|
+
narrator: gameMasterNarrates,
|
|
1086
|
+
narrationChecker: exactUtterances,
|
|
1087
|
+
committer: writesNothing,
|
|
1088
|
+
author: declinesToAuthor,
|
|
1089
|
+
strategist: factionsStayPut,
|
|
1090
|
+
reflector: reflectsOnNothing,
|
|
1091
|
+
judge: judgesNothing,
|
|
1092
|
+
suggester: offersNothing,
|
|
1093
|
+
recaller: recordsRecall,
|
|
1094
|
+
sceneContext: castSummary
|
|
1095
|
+
};
|
|
1096
|
+
}
|
|
1097
|
+
//#endregion
|
|
1098
|
+
//#region src/shared/timeline.ts
|
|
1099
|
+
const emptyTimeline = () => ({
|
|
1100
|
+
version: 1,
|
|
1101
|
+
head: null,
|
|
1102
|
+
next: 1,
|
|
1103
|
+
nodes: []
|
|
1104
|
+
});
|
|
1105
|
+
/** The turns from the first to `id`, in order; none for the start. */
|
|
1106
|
+
function pathTo(timeline, id) {
|
|
1107
|
+
const byId = new Map(timeline.nodes.map((node) => [node.id, node]));
|
|
1108
|
+
const path = [];
|
|
1109
|
+
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);
|
|
1110
|
+
return path;
|
|
1111
|
+
}
|
|
1112
|
+
/** The turns that follow `parent`, in the order they were played. */
|
|
1113
|
+
const childrenOf = (timeline, parent) => timeline.nodes.filter((node) => node.parent === parent);
|
|
1114
|
+
/** The snapshot that holds the state before any turn. */
|
|
1115
|
+
const START_SNAPSHOT = "start";
|
|
1116
|
+
/** The snapshot that holds the state after a turn. */
|
|
1117
|
+
const snapshotOf = (id) => `after-${id}`;
|
|
1118
|
+
/** Builds what the client shows from the timeline. */
|
|
1119
|
+
function viewOf(timeline) {
|
|
1120
|
+
const turn = (node) => ({
|
|
1121
|
+
id: node.id,
|
|
1122
|
+
turn: node.turn,
|
|
1123
|
+
player: node.player,
|
|
1124
|
+
...node.endSeq === void 0 ? {} : { endSeq: node.endSeq },
|
|
1125
|
+
...node.output === void 0 ? {} : { output: node.output },
|
|
1126
|
+
restorable: node.snapshot !== void 0,
|
|
1127
|
+
alternatives: childrenOf(timeline, node.parent).map((sibling) => sibling.id)
|
|
1128
|
+
});
|
|
1129
|
+
const on = new Set(pathTo(timeline, timeline.head).map((node) => node.id));
|
|
1130
|
+
const withdrawn = timeline.nodes.filter((node) => !on.has(node.id) && node.userSeq >= 0).map((node) => ({
|
|
1131
|
+
from: Math.min(node.startSeq ?? node.userSeq, node.userSeq),
|
|
1132
|
+
to: node.endSeq ?? Number.MAX_SAFE_INTEGER
|
|
1133
|
+
}));
|
|
1134
|
+
return {
|
|
1135
|
+
head: timeline.head,
|
|
1136
|
+
path: pathTo(timeline, timeline.head).map(turn),
|
|
1137
|
+
forward: childrenOf(timeline, timeline.head).map(turn),
|
|
1138
|
+
canStart: true,
|
|
1139
|
+
withdrawn
|
|
1140
|
+
};
|
|
1141
|
+
}
|
|
1142
|
+
/** 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. */
|
|
1143
|
+
function noticeText(node) {
|
|
1144
|
+
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");
|
|
1145
|
+
const ooc = node.output?.ooc;
|
|
1146
|
+
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}`;
|
|
1147
|
+
return `The story, as it went earlier (restored):\nThe player said: ${node.player}${ruling}\nIt was told to the player:\n${told}`;
|
|
1148
|
+
}
|
|
1149
|
+
//#endregion
|
|
1150
|
+
//#region src/host/timeline/file.ts
|
|
1151
|
+
const TIMELINE_FILE = "timeline.json";
|
|
1152
|
+
function isNode(value) {
|
|
1153
|
+
if (typeof value !== "object" || value === null) return false;
|
|
1154
|
+
const node = value;
|
|
1155
|
+
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";
|
|
1156
|
+
}
|
|
1157
|
+
/**
|
|
1158
|
+
* The timeline of a session, or an empty one when it has none yet.
|
|
1159
|
+
* @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.
|
|
1160
|
+
*/
|
|
1161
|
+
function readTimeline(folder) {
|
|
1162
|
+
let text;
|
|
1163
|
+
try {
|
|
1164
|
+
text = readFileSync(join(folder, TIMELINE_FILE), "utf8");
|
|
1165
|
+
} catch (error) {
|
|
1166
|
+
if (error.code === "ENOENT") return emptyTimeline();
|
|
1167
|
+
throw error;
|
|
1168
|
+
}
|
|
1169
|
+
const value = JSON.parse(text);
|
|
1170
|
+
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`);
|
|
1171
|
+
return value;
|
|
1172
|
+
}
|
|
1173
|
+
/** Writes it aside and renames it, so a crash leaves the timeline as it was. */
|
|
1174
|
+
function writeTimeline(folder, timeline) {
|
|
1175
|
+
const target = join(folder, TIMELINE_FILE);
|
|
1176
|
+
const aside = `${target}.writing`;
|
|
1177
|
+
writeFileSync(aside, JSON.stringify(timeline, null, 2));
|
|
1178
|
+
renameSync(aside, target);
|
|
1179
|
+
}
|
|
1180
|
+
//#endregion
|
|
1181
|
+
//#region src/host/timeline/branch.ts
|
|
1182
|
+
var BranchError = class extends Error {};
|
|
1183
|
+
/**
|
|
1184
|
+
* 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
|
|
1185
|
+
* that ended last, and the state of the story after that turn.
|
|
1186
|
+
* @param boundary - the seq of the last event the branch inherits.
|
|
1187
|
+
* @param snapshots - the names of the snapshots the story has.
|
|
1188
|
+
* @throws {BranchError} when the state at that point was not kept.
|
|
1189
|
+
*/
|
|
1190
|
+
function branchTimeline(timeline, boundary, snapshots) {
|
|
1191
|
+
const nodes = timeline.nodes.filter((node) => node.endSeq !== void 0 && node.endSeq <= boundary).map((node) => ({ ...node }));
|
|
1192
|
+
for (const node of nodes) if (node.noticeSeq !== void 0 && node.noticeSeq > boundary) delete node.noticeSeq;
|
|
1193
|
+
const last = nodes.reduce((found, node) => found === void 0 || node.endSeq > found.endSeq ? node : found, void 0);
|
|
1194
|
+
const available = new Set(snapshots);
|
|
1195
|
+
for (const node of nodes) if (node.snapshot !== void 0 && !available.has(node.snapshot)) delete node.snapshot;
|
|
1196
|
+
const keep = [...nodes.flatMap((node) => node.snapshot === void 0 ? [] : [node.snapshot]), ...available.has("start") ? [START_SNAPSHOT] : []];
|
|
1197
|
+
const branch = {
|
|
1198
|
+
version: 1,
|
|
1199
|
+
head: last?.id ?? null,
|
|
1200
|
+
next: timeline.next,
|
|
1201
|
+
nodes
|
|
1202
|
+
};
|
|
1203
|
+
if (last === void 0) {
|
|
1204
|
+
if (!available.has("start")) throw new BranchError("the state at the start of the story was not kept, so it cannot be branched");
|
|
1205
|
+
return {
|
|
1206
|
+
timeline: branch,
|
|
1207
|
+
from: { snapshot: START_SNAPSHOT },
|
|
1208
|
+
keep
|
|
1209
|
+
};
|
|
1210
|
+
}
|
|
1211
|
+
if (last.snapshot !== void 0) return {
|
|
1212
|
+
timeline: branch,
|
|
1213
|
+
from: { snapshot: last.snapshot },
|
|
1214
|
+
keep
|
|
1215
|
+
};
|
|
1216
|
+
if (timeline.head === last.id) return {
|
|
1217
|
+
timeline: branch,
|
|
1218
|
+
from: { live: true },
|
|
1219
|
+
keep
|
|
1220
|
+
};
|
|
1221
|
+
throw new BranchError(`the state of the story after its turn ${last.turn} was not kept, so it cannot be branched there`);
|
|
1222
|
+
}
|
|
1223
|
+
/** The name of a branch: the story's name with its trailing number counted up, or a 2 added. */
|
|
1224
|
+
function branchName(name) {
|
|
1225
|
+
const numbered = /^(.*?)(\d+)\s*$/.exec(name);
|
|
1226
|
+
const next = numbered === null ? `${name} 2` : `${numbered[1]}${Number(numbered[2]) + 1}`;
|
|
1227
|
+
return next.length > 200 ? `${[...name].slice(0, 190).join("").trimEnd()} 2` : next;
|
|
1228
|
+
}
|
|
1229
|
+
//#endregion
|
|
1230
|
+
//#region src/host/timeline/plan.ts
|
|
1231
|
+
/**
|
|
1232
|
+
* Where the model's conversation has to be changed so that it carries the turns from the first to `target`, and no others.
|
|
1233
|
+
* 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
|
|
1234
|
+
* 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.
|
|
1235
|
+
* @param surface - the seqs of the model's conversation, in order.
|
|
1236
|
+
*/
|
|
1237
|
+
function planMove(timeline, target, surface) {
|
|
1238
|
+
const onSurface = new Set(surface);
|
|
1239
|
+
const path = pathTo(timeline, target);
|
|
1240
|
+
let keptCount = 0;
|
|
1241
|
+
let last = -1;
|
|
1242
|
+
for (const node of path) {
|
|
1243
|
+
const at = surface.indexOf(node.userSeq);
|
|
1244
|
+
if (at <= last) break;
|
|
1245
|
+
last = at;
|
|
1246
|
+
keptCount += 1;
|
|
1247
|
+
}
|
|
1248
|
+
const kept = path.slice(0, keptCount);
|
|
1249
|
+
const keptIds = new Set(kept.map((node) => node.id));
|
|
1250
|
+
const byStart = [...timeline.nodes].sort((a, b) => a.userSeq - b.userSeq);
|
|
1251
|
+
const seqs = /* @__PURE__ */ new Set();
|
|
1252
|
+
byStart.forEach((node, index) => {
|
|
1253
|
+
if (keptIds.has(node.id)) return;
|
|
1254
|
+
if (node.noticeSeq !== void 0 && onSurface.has(node.noticeSeq)) seqs.add(node.noticeSeq);
|
|
1255
|
+
if (!onSurface.has(node.userSeq)) return;
|
|
1256
|
+
const end = node.endSeq ?? (byStart[index + 1]?.userSeq === void 0 ? Infinity : byStart[index + 1].userSeq - 1);
|
|
1257
|
+
for (const seq of surface) if (seq >= node.userSeq && seq <= end) seqs.add(seq);
|
|
1258
|
+
});
|
|
1259
|
+
const shadow = [];
|
|
1260
|
+
let run = [];
|
|
1261
|
+
let previous = -2;
|
|
1262
|
+
surface.forEach((seq, index) => {
|
|
1263
|
+
if (!seqs.has(seq)) return;
|
|
1264
|
+
if (index !== previous + 1 && run.length > 0) {
|
|
1265
|
+
shadow.push({
|
|
1266
|
+
startSeq: run[0],
|
|
1267
|
+
endSeq: run.at(-1),
|
|
1268
|
+
seqs: run
|
|
1269
|
+
});
|
|
1270
|
+
run = [];
|
|
1271
|
+
}
|
|
1272
|
+
run.push(seq);
|
|
1273
|
+
previous = index;
|
|
1274
|
+
});
|
|
1275
|
+
if (run.length > 0) shadow.push({
|
|
1276
|
+
startSeq: run[0],
|
|
1277
|
+
endSeq: run.at(-1),
|
|
1278
|
+
seqs: run
|
|
1279
|
+
});
|
|
1280
|
+
return {
|
|
1281
|
+
shadow,
|
|
1282
|
+
kept: kept.map((node) => node.id),
|
|
1283
|
+
inject: path.slice(keptCount)
|
|
1284
|
+
};
|
|
1285
|
+
}
|
|
1286
|
+
//#endregion
|
|
1287
|
+
//#region src/host/timeline/service.ts
|
|
1288
|
+
/** The text of the marker that stands for the turns it replaces: never empty, as a model service may refuse an empty message. */
|
|
1289
|
+
const MARKER_TEXT = "(empty message)";
|
|
1290
|
+
/** A turn that has not ended does not know yet where its own message is in the log. */
|
|
1291
|
+
const UNKNOWN_SEQ = -1;
|
|
1292
|
+
var TimelineError = class extends Error {};
|
|
1293
|
+
/**
|
|
1294
|
+
* What the story's turns are, and taking the story back to one of them (or forward again). The conversation with the model is
|
|
1295
|
+
* only ever added to: the turns that no longer belong are replaced by a marker, which DSH keeps out of the next request, and
|
|
1296
|
+
* 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.
|
|
1297
|
+
* Everything here is one at a time per chat.
|
|
1298
|
+
*/
|
|
1299
|
+
var Timelines = class {
|
|
1300
|
+
deps;
|
|
1301
|
+
queues = /* @__PURE__ */ new Map();
|
|
1302
|
+
constructor(deps) {
|
|
1303
|
+
this.deps = deps;
|
|
1304
|
+
}
|
|
1305
|
+
serial(chat, job) {
|
|
1306
|
+
const run = (this.queues.get(chat) ?? Promise.resolve()).then(job, job);
|
|
1307
|
+
this.queues.set(chat, run.catch(() => void 0));
|
|
1308
|
+
return run;
|
|
1309
|
+
}
|
|
1310
|
+
idOf(chat) {
|
|
1311
|
+
const id = roleplaySessionOf(chat);
|
|
1312
|
+
if (id === void 0) throw new TimelineError(`${chat} is not a roleplay chat`);
|
|
1313
|
+
return id;
|
|
1314
|
+
}
|
|
1315
|
+
folder(id) {
|
|
1316
|
+
return sessionFolder(this.deps.sessionsDir(), id);
|
|
1317
|
+
}
|
|
1318
|
+
read(id) {
|
|
1319
|
+
return readTimeline(this.folder(id));
|
|
1320
|
+
}
|
|
1321
|
+
view(id) {
|
|
1322
|
+
return viewOf(this.read(id));
|
|
1323
|
+
}
|
|
1324
|
+
/**
|
|
1325
|
+
* 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,
|
|
1326
|
+
* with the records still waiting for the keeper in it (they are in the database, so a restored state carries them).
|
|
1327
|
+
*/
|
|
1328
|
+
begin(chat, turn, player) {
|
|
1329
|
+
return this.serial(chat, async () => {
|
|
1330
|
+
this.deps.cancel?.(chat);
|
|
1331
|
+
const id = this.idOf(chat);
|
|
1332
|
+
const timeline = this.read(id);
|
|
1333
|
+
this.keep(id, timeline, timeline.head);
|
|
1334
|
+
const node = {
|
|
1335
|
+
id: `n${timeline.next}`,
|
|
1336
|
+
parent: timeline.head,
|
|
1337
|
+
turn,
|
|
1338
|
+
userSeq: UNKNOWN_SEQ,
|
|
1339
|
+
player,
|
|
1340
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1341
|
+
};
|
|
1342
|
+
timeline.nodes.push(node);
|
|
1343
|
+
timeline.next += 1;
|
|
1344
|
+
timeline.head = node.id;
|
|
1345
|
+
writeTimeline(this.folder(id), timeline);
|
|
1346
|
+
this.prune(id, timeline);
|
|
1347
|
+
return node;
|
|
1348
|
+
});
|
|
1349
|
+
}
|
|
1350
|
+
/** What the turn delivered; and, once nothing writes to the story any more, its state is kept. */
|
|
1351
|
+
delivered(chat, output) {
|
|
1352
|
+
const id = this.idOf(chat);
|
|
1353
|
+
const timeline = this.read(id);
|
|
1354
|
+
const node = timeline.nodes.find((candidate) => candidate.id === timeline.head);
|
|
1355
|
+
if (node === void 0) return void 0;
|
|
1356
|
+
node.output = output;
|
|
1357
|
+
writeTimeline(this.folder(id), timeline);
|
|
1358
|
+
this.deps.engine.quiesce(chat).then(() => this.serial(chat, () => {
|
|
1359
|
+
const current = this.read(id);
|
|
1360
|
+
if (current.head === node.id) this.keep(id, current, node.id);
|
|
1361
|
+
return Promise.resolve();
|
|
1362
|
+
})).catch(() => void 0);
|
|
1363
|
+
return node.id;
|
|
1364
|
+
}
|
|
1365
|
+
/**
|
|
1366
|
+
* 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
|
|
1367
|
+
* (it is not in the log yet when the turn begins).
|
|
1368
|
+
*/
|
|
1369
|
+
ended(chat, session, seq) {
|
|
1370
|
+
const id = this.idOf(chat);
|
|
1371
|
+
const timeline = this.read(id);
|
|
1372
|
+
const node = timeline.nodes.find((candidate) => candidate.id === timeline.head);
|
|
1373
|
+
if (node === void 0 || node.endSeq !== void 0) return;
|
|
1374
|
+
const after = Math.max(-1, ...timeline.nodes.filter((other) => other.id !== node.id).map((other) => other.endSeq ?? other.userSeq));
|
|
1375
|
+
const human = session.snapshotEvents().find((event) => event.seq > after && event.type === "user/message" && event.data.source.kind === "user");
|
|
1376
|
+
if (human === void 0) throw new TimelineError(`turn ${node.turn} has no message of the player in the log`);
|
|
1377
|
+
node.userSeq = human.seq;
|
|
1378
|
+
node.endSeq = seq;
|
|
1379
|
+
const began = session.snapshotEvents().find((event) => event.type === "turn/start" && event.data.turn === node.turn);
|
|
1380
|
+
node.startSeq = Math.min(began?.seq ?? human.seq, human.seq);
|
|
1381
|
+
writeTimeline(this.folder(id), timeline);
|
|
1382
|
+
}
|
|
1383
|
+
/** Keeps the state as it is under the name of the turn it follows from, when that is not done yet. */
|
|
1384
|
+
keep(id, timeline, at) {
|
|
1385
|
+
if (this.deps.keepSnapshots(id) === 0) return;
|
|
1386
|
+
const node = at === null ? void 0 : timeline.nodes.find((candidate) => candidate.id === at);
|
|
1387
|
+
const name = node === void 0 ? START_SNAPSHOT : snapshotOf(node.id);
|
|
1388
|
+
if (node !== void 0 && node.snapshot !== void 0) return;
|
|
1389
|
+
if (node === void 0 && this.deps.state.snapshots(this.deps.sessionsDir(), id).includes("start")) return;
|
|
1390
|
+
this.deps.state.snapshot(this.deps.sessionsDir(), id, name);
|
|
1391
|
+
if (node !== void 0) {
|
|
1392
|
+
node.snapshot = name;
|
|
1393
|
+
writeTimeline(this.folder(id), timeline);
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
/** Lets the oldest snapshots go: only the turns most recently played keep theirs, and the one that holds the start stays. */
|
|
1397
|
+
prune(id, timeline) {
|
|
1398
|
+
const keep = this.deps.keepSnapshots(id);
|
|
1399
|
+
const kept = timeline.nodes.filter((node) => node.snapshot !== void 0);
|
|
1400
|
+
const dropped = kept.slice(0, Math.max(0, kept.length - keep));
|
|
1401
|
+
if (dropped.length === 0) return;
|
|
1402
|
+
for (const node of dropped) {
|
|
1403
|
+
this.deps.state.removeSnapshot(this.deps.sessionsDir(), id, node.snapshot);
|
|
1404
|
+
delete node.snapshot;
|
|
1405
|
+
}
|
|
1406
|
+
writeTimeline(this.folder(id), timeline);
|
|
1407
|
+
}
|
|
1408
|
+
/**
|
|
1409
|
+
* 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,
|
|
1410
|
+
* 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.
|
|
1411
|
+
* @returns what the player said in the first turn that was left, to put back in the input; nothing when the story went forward.
|
|
1412
|
+
* @throws {TimelineError} when there is no such turn, its state was not kept, or the chat is not loaded.
|
|
1413
|
+
*/
|
|
1414
|
+
move(chat, target) {
|
|
1415
|
+
return this.serial(chat, async () => {
|
|
1416
|
+
const id = this.idOf(chat);
|
|
1417
|
+
const timeline = this.read(id);
|
|
1418
|
+
const to = target === null ? void 0 : timeline.nodes.find((node) => node.id === target);
|
|
1419
|
+
if (target !== null && to === void 0) throw new TimelineError(`there is no turn "${target}"`);
|
|
1420
|
+
const snapshot = target === null ? START_SNAPSHOT : to.snapshot;
|
|
1421
|
+
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");
|
|
1422
|
+
const agent = await this.deps.agentOf(chat);
|
|
1423
|
+
if (agent === void 0) throw new TimelineError(`the chat ${chat} is not loaded`);
|
|
1424
|
+
if (agent.status !== "idle") {
|
|
1425
|
+
agent.cancel({ kind: "user" }, { keepInbox: true });
|
|
1426
|
+
await agent.whenIdle();
|
|
1427
|
+
}
|
|
1428
|
+
this.deps.cancel?.(chat);
|
|
1429
|
+
this.deps.engine.stop(chat);
|
|
1430
|
+
await this.deps.engine.quiesce(chat);
|
|
1431
|
+
this.deps.engine.forget(chat);
|
|
1432
|
+
const was = pathTo(timeline, timeline.head);
|
|
1433
|
+
const plan = planMove(timeline, target, [...agent.session.surface.nodes]);
|
|
1434
|
+
this.deps.state.restore(this.deps.sessionsDir(), id, snapshot);
|
|
1435
|
+
this.reconcile(agent, plan);
|
|
1436
|
+
timeline.head = target;
|
|
1437
|
+
writeTimeline(this.folder(id), timeline);
|
|
1438
|
+
const left = was.find((node) => !pathTo(timeline, target).some((kept) => kept.id === node.id));
|
|
1439
|
+
return left === void 0 ? {} : { draft: left.player };
|
|
1440
|
+
});
|
|
1441
|
+
}
|
|
1442
|
+
/** 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. */
|
|
1443
|
+
reconcile(agent, plan) {
|
|
1444
|
+
for (const run of plan.shadow) agent.session.append("user/message", createUserMessage({
|
|
1445
|
+
content: [{
|
|
1446
|
+
type: "text",
|
|
1447
|
+
text: MARKER_TEXT
|
|
1448
|
+
}],
|
|
1449
|
+
source: { kind: "roleplay" }
|
|
1450
|
+
}), {
|
|
1451
|
+
surfaceOp: {
|
|
1452
|
+
op: "replace",
|
|
1453
|
+
startSeq: run.startSeq,
|
|
1454
|
+
endSeq: run.endSeq
|
|
1455
|
+
},
|
|
1456
|
+
sourceEventSeqs: run.seqs
|
|
1457
|
+
});
|
|
1458
|
+
for (const node of plan.inject) node.noticeSeq = agent.session.append("user/message", createUserMessage({
|
|
1459
|
+
content: [{
|
|
1460
|
+
type: "text",
|
|
1461
|
+
text: noticeText(node)
|
|
1462
|
+
}],
|
|
1463
|
+
source: { kind: "roleplay" }
|
|
1464
|
+
}), { surfaceOp: "append" }).seq;
|
|
1465
|
+
}
|
|
1466
|
+
/**
|
|
1467
|
+
* 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
|
|
1468
|
+
* 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
|
|
1469
|
+
* 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.
|
|
1470
|
+
* @param cut - the seq of the last event of the log the branch inherits.
|
|
1471
|
+
* @returns whether a session was made.
|
|
1472
|
+
* @throws {BranchError} when the state at the cut was not kept; the branch is then not made.
|
|
1473
|
+
*/
|
|
1474
|
+
adopt(chat, parent, cut, agent) {
|
|
1475
|
+
return this.serial(parent, async () => {
|
|
1476
|
+
const id = this.idOf(chat);
|
|
1477
|
+
const from = this.idOf(parent);
|
|
1478
|
+
const directory = this.deps.sessionsDir();
|
|
1479
|
+
if (existsSync(sessionDatabase(directory, id)) || !existsSync(sessionDatabase(directory, from))) return false;
|
|
1480
|
+
const branch = branchTimeline(this.read(from), cut, this.deps.state.snapshots(directory, from));
|
|
1481
|
+
if ("live" in branch.from) await this.deps.engine.quiesce(parent);
|
|
1482
|
+
const name = branchName(this.deps.state.openSession(directory, from).metadata.get().name);
|
|
1483
|
+
this.deps.state.fork(directory, from, id, branch.from, {
|
|
1484
|
+
name,
|
|
1485
|
+
keep: branch.keep
|
|
1486
|
+
});
|
|
1487
|
+
try {
|
|
1488
|
+
await inheritImages(this.folder(from), this.folder(id), branch.timeline.nodes.map((node) => node.id));
|
|
1489
|
+
inheritPrompts(this.folder(from), this.folder(id));
|
|
1490
|
+
inheritPacks(this.folder(from), this.folder(id));
|
|
1491
|
+
const plan = planMove(branch.timeline, branch.timeline.head, [...agent.session.surface.nodes]);
|
|
1492
|
+
this.reconcile(agent, plan);
|
|
1493
|
+
writeTimeline(this.folder(id), branch.timeline);
|
|
1494
|
+
} catch (error) {
|
|
1495
|
+
this.deps.state.deleteSession(directory, id);
|
|
1496
|
+
throw error;
|
|
1497
|
+
}
|
|
1498
|
+
return true;
|
|
1499
|
+
});
|
|
1500
|
+
}
|
|
1501
|
+
/** The turns that follow a turn, for the choices the story can be taken to. */
|
|
1502
|
+
forward(id) {
|
|
1503
|
+
const timeline = this.read(id);
|
|
1504
|
+
return childrenOf(timeline, timeline.head);
|
|
1505
|
+
}
|
|
1506
|
+
};
|
|
1507
|
+
//#endregion
|
|
1508
|
+
//#region src/host/orchestration/observation.ts
|
|
1509
|
+
/** 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. */
|
|
1510
|
+
function observeSurroundings(session, characterId, turn) {
|
|
1511
|
+
const placement = session.placements.get("character", characterId);
|
|
1512
|
+
if (placement !== void 0) {
|
|
1513
|
+
session.knowledge.learn(characterId, "location", placement.locationId, turn, true);
|
|
1514
|
+
for (const exit of session.locations.exitsFrom(placement.locationId)) {
|
|
1515
|
+
session.knowledge.learn(characterId, "exit", exit.id, turn, true);
|
|
1516
|
+
session.knowledge.learn(characterId, "location", exit.toId, turn);
|
|
1517
|
+
}
|
|
1518
|
+
for (const { item } of session.items.contents({
|
|
1519
|
+
kind: "location",
|
|
1520
|
+
id: placement.locationId
|
|
1521
|
+
})) if (!item.hidden) session.knowledge.learn(characterId, "item", item.id, turn, true);
|
|
1522
|
+
}
|
|
1523
|
+
for (const { item } of session.items.contents({
|
|
1524
|
+
kind: "character",
|
|
1525
|
+
id: characterId
|
|
1526
|
+
})) session.knowledge.learn(characterId, "item", item.id, turn, true);
|
|
1527
|
+
}
|
|
1528
|
+
/**
|
|
1529
|
+
* 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
|
|
1530
|
+
* how it comes to know the way back from where it went.
|
|
1531
|
+
*/
|
|
1532
|
+
function observeAsPlayer(session, turn) {
|
|
1533
|
+
const player = session.characters.list().find((character) => character.control === "player");
|
|
1534
|
+
if (player !== void 0) observeSurroundings(session, player.id, turn);
|
|
1535
|
+
}
|
|
1536
|
+
//#endregion
|
|
1537
|
+
//#region src/shared/notes.ts
|
|
1538
|
+
const NOTE_KINDS = [
|
|
1539
|
+
"suggestions",
|
|
1540
|
+
"away",
|
|
1541
|
+
"world"
|
|
1542
|
+
];
|
|
1543
|
+
//#endregion
|
|
1544
|
+
//#region src/host/sessions/notes.ts
|
|
1545
|
+
const KEY$2 = "notes";
|
|
1546
|
+
const isNote = (value) => {
|
|
1547
|
+
if (typeof value !== "object" || value === null) return false;
|
|
1548
|
+
const note = value;
|
|
1549
|
+
return NOTE_KINDS.includes(note["kind"]) && typeof note["turn"] === "number" && Array.isArray(note["lines"]) && note["lines"].every((line) => typeof line === "string");
|
|
1550
|
+
};
|
|
1551
|
+
/** The notes of a session, at most one per kind. */
|
|
1552
|
+
function readNotes(session) {
|
|
1553
|
+
const stored = session.metadata.getValue(KEY$2);
|
|
1554
|
+
return Array.isArray(stored) ? stored.filter(isNote) : [];
|
|
1555
|
+
}
|
|
1556
|
+
/** Replaces the note of the same kind. */
|
|
1557
|
+
function putNote(session, note) {
|
|
1558
|
+
session.metadata.setValue(KEY$2, [...readNotes(session).filter((existing) => existing.kind !== note.kind), note]);
|
|
1559
|
+
}
|
|
1560
|
+
/** The most lines one note keeps: what is past it is not told. */
|
|
1561
|
+
const MAX_NOTE_LINES = 8;
|
|
1562
|
+
/** Adds lines to the note of the kind when it is of the same turn, else starts it. */
|
|
1563
|
+
function addToNote(session, kind, turn, lines) {
|
|
1564
|
+
if (lines.length === 0) return;
|
|
1565
|
+
putNote(session, {
|
|
1566
|
+
kind,
|
|
1567
|
+
turn,
|
|
1568
|
+
lines: [...readNotes(session).find((note) => note.kind === kind && note.turn === turn)?.lines ?? [], ...lines].slice(0, MAX_NOTE_LINES)
|
|
1569
|
+
});
|
|
1570
|
+
}
|
|
1571
|
+
/** Removes every note: they belong to the turn that made them. */
|
|
1572
|
+
function clearNotes(session) {
|
|
1573
|
+
if (readNotes(session).length > 0) session.metadata.setValue(KEY$2, []);
|
|
1574
|
+
}
|
|
1575
|
+
/**
|
|
1576
|
+
* The notes of a session, for the player's screen.
|
|
1577
|
+
* @throws {SessionNotFoundError} when the id names no session.
|
|
1578
|
+
*/
|
|
1579
|
+
function notesOfSession(deps, id) {
|
|
1580
|
+
if (!isSessionId(id) || !existsSync(sessionDatabase(deps.sessionsDir(), id))) throw new SessionNotFoundError(`no session "${id}"`);
|
|
1581
|
+
return readNotes(deps.open(id));
|
|
1582
|
+
}
|
|
1583
|
+
//#endregion
|
|
1584
|
+
//#region src/shared/ooc.ts
|
|
1585
|
+
/** What the player writes to speak to the game master as the author of the story: a command (`/ooc`) or a question (`/ask`), a turn of its own, never mixed with an action of the character. */
|
|
1586
|
+
const OOC_COMMAND = /^\s*\/(ooc|ask)(?=\s|$)\s*([\s\S]*)$/i;
|
|
1587
|
+
/** The command or question in a player's message, or nothing when the message is an ordinary action. The request may be empty. */
|
|
1588
|
+
function parseOoc(text) {
|
|
1589
|
+
const match = OOC_COMMAND.exec(text);
|
|
1590
|
+
return match === null ? void 0 : {
|
|
1591
|
+
request: (match[2] ?? "").trim(),
|
|
1592
|
+
question: match[1].toLowerCase() === "ask"
|
|
1593
|
+
};
|
|
1594
|
+
}
|
|
1595
|
+
/** The longest answer to an out-of-character question. */
|
|
1596
|
+
const MAX_OOC_ANSWER = 1200;
|
|
1597
|
+
//#endregion
|
|
1598
|
+
//#region src/host/orchestration/character-runner.ts
|
|
1599
|
+
/**
|
|
1600
|
+
* Runs each character as a one-shot child of the game master. It is the character and nothing
|
|
1601
|
+
* else: it knows what its brief gives it, and its only tool (when the chat allows it) reaches
|
|
1602
|
+
* the memory of that character alone, so characters acting at the same time cannot see each
|
|
1603
|
+
* other's memories.
|
|
1604
|
+
*/
|
|
1605
|
+
function characterRunner(deps) {
|
|
1606
|
+
return async (request, signal) => {
|
|
1607
|
+
const brief = deps.boundaries().characterContext.brief(request);
|
|
1608
|
+
const tools = request.lookup ? createCharacterTools(() => ({
|
|
1609
|
+
session: deps.store.story,
|
|
1610
|
+
turn: request.turn,
|
|
1611
|
+
policy: deps.store.settings().memory,
|
|
1612
|
+
queryVector: deps.store.queryVector
|
|
1613
|
+
}), request.member.character.id) : [];
|
|
1614
|
+
const settings = deps.store.settings();
|
|
1615
|
+
const external = externalGiven(deps.parent.ctx.tools, settings.tools, "characters");
|
|
1616
|
+
const named = request.member.character.tier === "background" && settings.models.background.trim() !== "" ? settings.models.background : settings.models.characters;
|
|
1617
|
+
return parseCharacterAction(await runChild({
|
|
1618
|
+
parent: deps.parent,
|
|
1619
|
+
signal,
|
|
1620
|
+
sampling: childSampling(settings, "characters", answerEstimate(settings.prompts.language, request.away === true)),
|
|
1621
|
+
...childModel(settings, "characters", named),
|
|
1622
|
+
trace: childTrace(deps.store, "characters", request.member.character.name, recalledOf(request), named),
|
|
1623
|
+
reasoningEffort: deps.store.settings().reasoning.children,
|
|
1624
|
+
persona: brief.persona,
|
|
1625
|
+
prompt: brief.prompt,
|
|
1626
|
+
tools,
|
|
1627
|
+
external,
|
|
1628
|
+
maxCalls: deps.store.settings().memory.lookupCalls + (external.length === 0 ? 0 : EXTERNAL_CALLS),
|
|
1629
|
+
result: request.away === true ? AWAY_ACTION_SCHEMA : CHARACTER_ACTION_SCHEMA,
|
|
1630
|
+
unenforced: ["thought"],
|
|
1631
|
+
beforeSubmit: (value) => spokenIn(settings.prompts.language, value)
|
|
1632
|
+
}));
|
|
1633
|
+
};
|
|
1634
|
+
}
|
|
1635
|
+
/** What a character that was given tools of other plugins may call on top of its memory look-ups. */
|
|
1636
|
+
const EXTERNAL_CALLS = 5;
|
|
1637
|
+
/** A character whose sheet is in another language than the chat's writes in the sheet's: the answer is refused until it is in the chat's. */
|
|
1638
|
+
function spokenIn(language, value) {
|
|
1639
|
+
const given = value;
|
|
1640
|
+
return wrongLanguage(language, {
|
|
1641
|
+
thought: given.thought,
|
|
1642
|
+
intent: given.intent,
|
|
1643
|
+
utterance: given.utterance,
|
|
1644
|
+
account: given.account
|
|
1645
|
+
});
|
|
1646
|
+
}
|
|
1647
|
+
/** What the character was reminded of and why, for the run's record, when the recall said why. */
|
|
1648
|
+
function recalledOf(request) {
|
|
1649
|
+
const explained = (request.memories ?? []).filter((memory) => memory.why !== void 0);
|
|
1650
|
+
return explained.length === 0 ? {} : { recalled: explained.slice(0, 30).map(({ clarity, turn, text, why }) => ({
|
|
1651
|
+
clarity,
|
|
1652
|
+
turn,
|
|
1653
|
+
text,
|
|
1654
|
+
why
|
|
1655
|
+
})) };
|
|
1656
|
+
}
|
|
1657
|
+
const ANSWER_SCHEMA = {
|
|
1658
|
+
type: "object",
|
|
1659
|
+
properties: { answer: {
|
|
1660
|
+
type: "string",
|
|
1661
|
+
description: "The answer to the player, in plain words, in a few sentences."
|
|
1662
|
+
} },
|
|
1663
|
+
required: ["answer"],
|
|
1664
|
+
additionalProperties: false
|
|
1665
|
+
};
|
|
1666
|
+
/**
|
|
1667
|
+
* Answers a player's question as an agent that has only what the player's character is given when it acts: the character sheet is left out and nothing the
|
|
1668
|
+
* game master alone knows is in the prompt, so the answer cannot give away what the character could not know.
|
|
1669
|
+
*/
|
|
1670
|
+
function answerRunner(deps) {
|
|
1671
|
+
return async (request, signal) => {
|
|
1672
|
+
const brief = deps.boundaries().characterContext.brief(request);
|
|
1673
|
+
return (await runChild({
|
|
1674
|
+
parent: deps.parent,
|
|
1675
|
+
signal,
|
|
1676
|
+
sampling: childSampling(deps.store.settings(), "records", estimateAnswer([MAX_OOC_ANSWER], deps.store.settings().prompts.language)),
|
|
1677
|
+
...childModel(deps.store.settings(), "records"),
|
|
1678
|
+
trace: childTrace(deps.store, "records", "answer to the player"),
|
|
1679
|
+
reasoningEffort: deps.store.settings().reasoning.children,
|
|
1680
|
+
persona: request.text("roleplay/ask-answerer", { name: request.member.character.name }),
|
|
1681
|
+
prompt: brief.prompt,
|
|
1682
|
+
tools: [],
|
|
1683
|
+
maxCalls: 3,
|
|
1684
|
+
result: ANSWER_SCHEMA
|
|
1685
|
+
})).answer;
|
|
1686
|
+
};
|
|
1687
|
+
}
|
|
1688
|
+
//#endregion
|
|
1689
|
+
//#region src/host/orchestration/boundaries.ts
|
|
1690
|
+
/** Why the game master may ask for something to be made up: the story genuinely needs it. */
|
|
1691
|
+
const AUTHORING_NEEDS = [
|
|
1692
|
+
"scene_change",
|
|
1693
|
+
"arrival",
|
|
1694
|
+
"introduction",
|
|
1695
|
+
"object",
|
|
1696
|
+
"variable",
|
|
1697
|
+
"trigger"
|
|
1698
|
+
];
|
|
1699
|
+
//#endregion
|
|
1700
|
+
//#region src/host/pacing/director.ts
|
|
1701
|
+
const PLOTS_METADATA_KEY = "roleplay.pacing.plots";
|
|
1702
|
+
function populatePlots(metadata, plots) {
|
|
1703
|
+
const progress = plots.map((plot) => ({
|
|
1704
|
+
plot,
|
|
1705
|
+
status: plot.start,
|
|
1706
|
+
introduced: [],
|
|
1707
|
+
rejected: [],
|
|
1708
|
+
lastNudgeTurn: 0
|
|
1709
|
+
}));
|
|
1710
|
+
metadata.setValue(PLOTS_METADATA_KEY, progress);
|
|
1711
|
+
}
|
|
1712
|
+
function addSessionPlot(store, plot) {
|
|
1713
|
+
const plots = progressOf(store);
|
|
1714
|
+
if (plots.some((entry) => entry.plot.id === plot.id)) throw new Error(`there is already a plot "${plot.id}"`);
|
|
1715
|
+
plots.push({
|
|
1716
|
+
plot,
|
|
1717
|
+
status: plot.start,
|
|
1718
|
+
introduced: [],
|
|
1719
|
+
rejected: [],
|
|
1720
|
+
lastNudgeTurn: 0
|
|
1721
|
+
});
|
|
1722
|
+
store.story.metadata.setValue(PLOTS_METADATA_KEY, plots);
|
|
1723
|
+
}
|
|
1724
|
+
function plotAuthorNeeded(store, turn) {
|
|
1725
|
+
if (progressOf(store).length > 0 || turn < 5) return false;
|
|
1726
|
+
return store.story.events.list({
|
|
1727
|
+
fromTurn: Math.max(1, turn - 2),
|
|
1728
|
+
toTurn: turn - 1
|
|
1729
|
+
}).length === 0 && store.story.threads.list("open").length === 0;
|
|
1730
|
+
}
|
|
1731
|
+
function plotProgressOf(metadata) {
|
|
1732
|
+
const value = metadata.getValue(PLOTS_METADATA_KEY);
|
|
1733
|
+
return Array.isArray(value) ? value : [];
|
|
1734
|
+
}
|
|
1735
|
+
function progressOf(store) {
|
|
1736
|
+
return plotProgressOf(store.story.metadata);
|
|
1737
|
+
}
|
|
1738
|
+
/** Select one uncommitted possibility when the story has genuinely gone quiet; selection never makes it happen. */
|
|
1739
|
+
function pacingAdvice(store, turn) {
|
|
1740
|
+
const plots = progressOf(store);
|
|
1741
|
+
if (plots.length === 0) return void 0;
|
|
1742
|
+
const now = store.story.clock.get()?.now;
|
|
1743
|
+
const recent = store.story.events.list({
|
|
1744
|
+
fromTurn: Math.max(1, turn - 2),
|
|
1745
|
+
toTurn: turn - 1
|
|
1746
|
+
});
|
|
1747
|
+
const openThreads = store.story.threads.list("open");
|
|
1748
|
+
for (const progress of plots) {
|
|
1749
|
+
if (![
|
|
1750
|
+
"available",
|
|
1751
|
+
"engaged",
|
|
1752
|
+
"cooling"
|
|
1753
|
+
].includes(progress.status)) continue;
|
|
1754
|
+
const quietTurns = progress.plot.pacing.quietTurns + (openThreads.length === 0 ? 0 : 2);
|
|
1755
|
+
if (recent.length > 0 || turn <= quietTurns) continue;
|
|
1756
|
+
if (turn - progress.lastNudgeTurn < progress.plot.pacing.cooldownTurns) continue;
|
|
1757
|
+
if (now !== void 0 && progress.lastNudgeAt !== void 0 && now - progress.lastNudgeAt < progress.plot.pacing.cooldownDays * 864e5) continue;
|
|
1758
|
+
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];
|
|
1759
|
+
if (step === void 0) continue;
|
|
1760
|
+
const quietFor = turn - progress.lastNudgeTurn;
|
|
1761
|
+
progress.lastNudgeTurn = turn;
|
|
1762
|
+
if (now !== void 0) progress.lastNudgeAt = now;
|
|
1763
|
+
progress.status = progress.status === "available" ? "engaged" : progress.status;
|
|
1764
|
+
store.story.metadata.setValue(PLOTS_METADATA_KEY, plots);
|
|
1765
|
+
return {
|
|
1766
|
+
need: quietFor > progress.plot.pacing.quietTurns * 2 ? "clear" : "gentle",
|
|
1767
|
+
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",
|
|
1768
|
+
plot: progress.plot.id,
|
|
1769
|
+
plotName: progress.plot.name,
|
|
1770
|
+
development: step.id,
|
|
1771
|
+
mode: step.mode,
|
|
1772
|
+
guidance: step.guidance || step.text,
|
|
1773
|
+
avoid: step.avoid
|
|
1774
|
+
};
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
function describePacingAdvice(advice) {
|
|
1778
|
+
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.`;
|
|
1779
|
+
}
|
|
1780
|
+
function updatePlotProgress(store, plotId, developmentId, action) {
|
|
1781
|
+
const plots = progressOf(store);
|
|
1782
|
+
const progress = plots.find((entry) => entry.plot.id === plotId);
|
|
1783
|
+
if (progress === void 0) throw new Error(`there is no plot "${plotId}"`);
|
|
1784
|
+
if (action === "resolved" || action === "abandoned") progress.status = action;
|
|
1785
|
+
else {
|
|
1786
|
+
if (developmentId === void 0) throw new Error(`${action} needs a development`);
|
|
1787
|
+
if (![...progress.plot.hooks, ...progress.plot.developments].some((step) => step.id === developmentId)) throw new Error(`plot "${plotId}" has no development "${developmentId}"`);
|
|
1788
|
+
const target = action === "introduced" ? progress.introduced : progress.rejected;
|
|
1789
|
+
if (!target.includes(developmentId)) target.push(developmentId);
|
|
1790
|
+
if (action === "introduced") progress.status = "engaged";
|
|
1791
|
+
}
|
|
1792
|
+
store.story.metadata.setValue(PLOTS_METADATA_KEY, plots);
|
|
1793
|
+
return progress;
|
|
1794
|
+
}
|
|
1795
|
+
//#endregion
|
|
1796
|
+
//#region src/host/pacing/author.ts
|
|
1797
|
+
const RESULT$1 = {
|
|
1798
|
+
type: "object",
|
|
1799
|
+
required: [
|
|
1800
|
+
"id",
|
|
1801
|
+
"name",
|
|
1802
|
+
"premise",
|
|
1803
|
+
"themes",
|
|
1804
|
+
"hook",
|
|
1805
|
+
"developments",
|
|
1806
|
+
"stakes",
|
|
1807
|
+
"resolutions",
|
|
1808
|
+
"participants"
|
|
1809
|
+
],
|
|
1810
|
+
additionalProperties: false,
|
|
1811
|
+
properties: {
|
|
1812
|
+
id: { type: "string" },
|
|
1813
|
+
name: { type: "string" },
|
|
1814
|
+
premise: { type: "string" },
|
|
1815
|
+
themes: {
|
|
1816
|
+
type: "array",
|
|
1817
|
+
items: { type: "string" }
|
|
1818
|
+
},
|
|
1819
|
+
hook: {
|
|
1820
|
+
type: "object",
|
|
1821
|
+
required: [
|
|
1822
|
+
"id",
|
|
1823
|
+
"text",
|
|
1824
|
+
"guidance",
|
|
1825
|
+
"avoid"
|
|
1826
|
+
],
|
|
1827
|
+
additionalProperties: false,
|
|
1828
|
+
properties: {
|
|
1829
|
+
id: { type: "string" },
|
|
1830
|
+
text: { type: "string" },
|
|
1831
|
+
guidance: { type: "string" },
|
|
1832
|
+
avoid: {
|
|
1833
|
+
type: "array",
|
|
1834
|
+
items: { type: "string" }
|
|
1835
|
+
}
|
|
1836
|
+
}
|
|
1837
|
+
},
|
|
1838
|
+
developments: {
|
|
1839
|
+
type: "array",
|
|
1840
|
+
items: {
|
|
1841
|
+
type: "object",
|
|
1842
|
+
required: [
|
|
1843
|
+
"id",
|
|
1844
|
+
"text",
|
|
1845
|
+
"mode",
|
|
1846
|
+
"prerequisites",
|
|
1847
|
+
"guidance",
|
|
1848
|
+
"avoid"
|
|
1849
|
+
],
|
|
1850
|
+
additionalProperties: false,
|
|
1851
|
+
properties: {
|
|
1852
|
+
id: { type: "string" },
|
|
1853
|
+
text: { type: "string" },
|
|
1854
|
+
mode: {
|
|
1855
|
+
type: "string",
|
|
1856
|
+
enum: [
|
|
1857
|
+
"opportunity",
|
|
1858
|
+
"reminder",
|
|
1859
|
+
"character",
|
|
1860
|
+
"consequence",
|
|
1861
|
+
"escalation",
|
|
1862
|
+
"breathing_room"
|
|
1863
|
+
]
|
|
1864
|
+
},
|
|
1865
|
+
prerequisites: {
|
|
1866
|
+
type: "array",
|
|
1867
|
+
items: { type: "string" }
|
|
1868
|
+
},
|
|
1869
|
+
guidance: { type: "string" },
|
|
1870
|
+
avoid: {
|
|
1871
|
+
type: "array",
|
|
1872
|
+
items: { type: "string" }
|
|
1873
|
+
}
|
|
1874
|
+
}
|
|
1875
|
+
}
|
|
1876
|
+
},
|
|
1877
|
+
stakes: {
|
|
1878
|
+
type: "array",
|
|
1879
|
+
items: { type: "string" }
|
|
1880
|
+
},
|
|
1881
|
+
resolutions: {
|
|
1882
|
+
type: "array",
|
|
1883
|
+
items: { type: "string" }
|
|
1884
|
+
},
|
|
1885
|
+
participants: {
|
|
1886
|
+
type: "array",
|
|
1887
|
+
items: { type: "string" }
|
|
1888
|
+
}
|
|
1889
|
+
}
|
|
1890
|
+
};
|
|
1891
|
+
/** A scaffold is about two dozen short texts: premise, hook, developments with their guidance, stakes and resolutions. */
|
|
1892
|
+
const PLOT_TEXTS = 24;
|
|
1893
|
+
const PLOT_TEXT_CHARS = 300;
|
|
1894
|
+
async function authorPlot(parent, store, turn, signal) {
|
|
1895
|
+
const cast = store.cast().map((member) => `${member.character.name} (${member.key}): ${member.character.summary}`).join("\n");
|
|
1896
|
+
const factions = store.story.factions.list().map((faction) => `${faction.name} (${faction.sourceId ?? faction.id}): ${faction.summary}`).join("\n");
|
|
1897
|
+
const places = store.story.locations.list().map((place) => `${place.name} (${place.sourceId ?? place.id})`).join(", ");
|
|
1898
|
+
const events = store.story.events.list().slice(-12).map((event) => `- ${event.text}`).join("\n");
|
|
1899
|
+
let checked;
|
|
1900
|
+
const result = await runChild({
|
|
1901
|
+
parent,
|
|
1902
|
+
signal,
|
|
1903
|
+
sampling: childSampling(store.settings(), "authoring", estimateAnswer(Array.from({ length: PLOT_TEXTS }, () => PLOT_TEXT_CHARS), store.settings().prompts.language)),
|
|
1904
|
+
...childModel(store.settings(), "authoring"),
|
|
1905
|
+
trace: childTrace(store, "authoring", "plot author"),
|
|
1906
|
+
persona: promptFor(parent, "roleplay/plot-author", store.settings().prompts.language),
|
|
1907
|
+
reasoningEffort: store.settings().reasoning.children,
|
|
1908
|
+
result: RESULT$1,
|
|
1909
|
+
maxCalls: 3,
|
|
1910
|
+
prompt: `The story has gone quiet by turn ${turn}. Propose one optional plot scaffold that grows from this state.\n\nCharacters:\n${cast || "- none"}\n\nFactions:\n${factions || "- none"}\n\nPlaces: ${places || "none"}\n\nRecent recorded events:\n${events || "- none"}`,
|
|
1911
|
+
beforeSubmit(value) {
|
|
1912
|
+
const authored = value;
|
|
1913
|
+
const candidate = {
|
|
1914
|
+
...authored,
|
|
1915
|
+
hooks: [{
|
|
1916
|
+
...authored.hook,
|
|
1917
|
+
mode: "opportunity",
|
|
1918
|
+
prerequisites: []
|
|
1919
|
+
}],
|
|
1920
|
+
start: "available",
|
|
1921
|
+
pacing: {
|
|
1922
|
+
quietTurns: 3,
|
|
1923
|
+
cooldownTurns: 4,
|
|
1924
|
+
cooldownDays: 1
|
|
1925
|
+
}
|
|
1926
|
+
};
|
|
1927
|
+
const parsed = parsePlotsFile(JSON.stringify([candidate]));
|
|
1928
|
+
if (!parsed.ok) return parsed.issues.map((issue) => `${issue.path}: ${issue.message}`).join("\n");
|
|
1929
|
+
checked = parsed.value[0];
|
|
1930
|
+
}
|
|
1931
|
+
});
|
|
1932
|
+
if (checked === void 0) throw new Error(`the plot author returned an invalid plot: ${result.name}`);
|
|
1933
|
+
addSessionPlot(store, checked);
|
|
1934
|
+
return checked;
|
|
1935
|
+
}
|
|
1936
|
+
//#endregion
|
|
1937
|
+
//#region src/host/orchestration/tools.ts
|
|
1938
|
+
const ACTIVATE_TOOL = "activate_characters";
|
|
1939
|
+
const RESOLVE_TOOL = "resolve_round";
|
|
1940
|
+
const NARRATE_TOOL = "narrate";
|
|
1941
|
+
const RECORD_TOOL = "record_memory";
|
|
1942
|
+
const EXPAND_TOOL = "expand_world";
|
|
1943
|
+
const INTRODUCE_TOOL = "introduce_thing";
|
|
1944
|
+
const TIME_TOOL = "advance_time";
|
|
1945
|
+
const PREVIEW_TOOL = "preview_scene";
|
|
1946
|
+
const RULING_TOOL = "ooc_ruling";
|
|
1947
|
+
const ANSWER_TOOL = "ooc_answer";
|
|
1948
|
+
const JUDGE_TOOL = "judge_action";
|
|
1949
|
+
const PLOT_TOOL = "record_plot_progress";
|
|
1950
|
+
const AUTHOR_PLOT_TOOL = "author_plot";
|
|
1951
|
+
/** The JSON value the tool records; the model reads the rendered text. */
|
|
1952
|
+
function record(value) {
|
|
1953
|
+
return JSON.parse(JSON.stringify(value));
|
|
1954
|
+
}
|
|
1955
|
+
function failures(list) {
|
|
1956
|
+
return list.length === 0 ? [] : [
|
|
1957
|
+
"",
|
|
1958
|
+
"Could not act:",
|
|
1959
|
+
...list.map((failure) => failure.technical === true ? `- ${failure.character} (${failure.name}): no decision came back. That is a fault of the system, not something that happened in the story: nothing is recorded for ${failure.name} this round, so write nothing for them and say nothing about why` : `- ${failure.character} (${failure.name}): ${failure.reason}`)
|
|
1960
|
+
];
|
|
1961
|
+
}
|
|
1962
|
+
function renderAttempt(attempt) {
|
|
1963
|
+
const heading = attempt.attempt === 1 ? "The characters acted. Their intents may conflict with each other; you decide what actually happens." : "These characters failed but were highly committed, so each tried once more, knowing what just happened.";
|
|
1964
|
+
const lines = attempt.reports.map((report) => `- ${report.character} (${report.name}): ${report.utterance === void 0 ? "says nothing" : `says "${report.utterance}"`}; does: ${report.intent} [commitment: ${report.commitment}]`);
|
|
1965
|
+
const next = attempt.reports.length === 0 ? ["", "Nobody could act. Fix the problem or call activate_characters again with a different set."] : attempt.attempt === 1 ? ["", `Now call ${RESOLVE_TOOL} with one outcome for each of: ${attempt.reports.map((report) => report.character).join(", ")}.`] : ["", `Call ${RESOLVE_TOOL} once more with one outcome for each of: ${attempt.reports.map((report) => report.character).join(", ")}. There are no further retries: what you decide now is final.`];
|
|
1966
|
+
return [
|
|
1967
|
+
heading,
|
|
1968
|
+
...lines,
|
|
1969
|
+
...failures(attempt.failures),
|
|
1970
|
+
...next
|
|
1971
|
+
].join("\n");
|
|
1972
|
+
}
|
|
1973
|
+
/** Who went where because their day says so. */
|
|
1974
|
+
const routineLine = (move) => `By their routine, ${move.name} is now at ${move.to} (${move.activity}).`;
|
|
1975
|
+
const OUTPUT_RULES = "Deliver the output with the narrate tool as ordered segments: utterances and narration. Narration may come before, between and after utterances and is yours to write. Utterances are the characters' words: include every one exactly as given, once, in the order they were spoken, and never change, add or remove one.";
|
|
1976
|
+
const listed = (utterances) => utterances.map((utterance) => `- ${utterance.character} (${utterance.name}), round ${utterance.round}: "${utterance.text}"`).join("\n");
|
|
1977
|
+
/** What the world did by itself, as the game master is told: what happened, what characters notice, and what it is to weave in. */
|
|
1978
|
+
function renderWorld(world) {
|
|
1979
|
+
return world.flatMap((entry) => [
|
|
1980
|
+
...entry.events.map((text) => `The world acted (${entry.name}): ${text}`),
|
|
1981
|
+
...entry.cues.map((cue) => `${cue.names.join(" and ")} will notice: ${cue.text}`),
|
|
1982
|
+
...entry.beats.map((beat) => `Weave this into the story, then say you did with addressed: [${beat.id}] in narrate (${beat.text})`)
|
|
1983
|
+
]);
|
|
1984
|
+
}
|
|
1985
|
+
function renderResolution(report) {
|
|
1986
|
+
if (report.next !== void 0) return renderAttempt(report.next);
|
|
1987
|
+
const done = report.done;
|
|
1988
|
+
if (done === void 0) return "";
|
|
1989
|
+
const left = done.limit - done.round;
|
|
1990
|
+
const passed = done.time.to - done.time.from;
|
|
1991
|
+
const lines = [
|
|
1992
|
+
`Round ${done.round} is recorded (${done.updated.join(", ")}).`,
|
|
1993
|
+
`It is now ${describeTime({
|
|
1994
|
+
now: done.time.to,
|
|
1995
|
+
zone: done.time.zone
|
|
1996
|
+
})}${passed > 0 ? `; ${describeDuration(passed)} passed` : ""}.`,
|
|
1997
|
+
...done.moved.map(routineLine),
|
|
1998
|
+
...done.moves.map((move) => `${move.name} is now at ${move.to}${move.via > 0 ? ` (by way of ${move.via} other place${move.via === 1 ? "" : "s"})` : ""}.`),
|
|
1999
|
+
...done.things.map((thing) => `${thing.name}: ${thing.summary}.`),
|
|
2000
|
+
...done.variables.map((line) => `${line}.`),
|
|
2001
|
+
...renderWorld(done.world),
|
|
2002
|
+
...failures(done.retryFailures)
|
|
2003
|
+
];
|
|
2004
|
+
lines.push(done.spoken.length === 0 ? "Nobody has said anything yet this turn." : `Everything said so far this turn, in order; the output must carry all of it exactly:\n${listed(done.spoken)}`);
|
|
2005
|
+
lines.push(left > 0 ? `Now decide. If the story genuinely flows from what just happened (someone is directly answered, a reaction is natural, something is left unresolved that the characters would act on), call activate_characters for the next round: ${left} round(s) are left for this message. Otherwise give control back to the player now.` : "That was the last round allowed for this message: give control back to the player now.");
|
|
2006
|
+
lines.push(done.waiting === 0 ? "Nothing is waiting to be recorded." : `${done.waiting} round${done.waiting === 1 ? " is" : "s are"} waiting to be recorded in the story's memory. Memory is not written after every round: call ${RECORD_TOOL} when the story just moved on (a decision made, a secret or fact revealed, a promise, an injury, a relationship changed, the scene or time moved); skip it for small talk and routine movement, which are kept and recorded together with the next thing that matters.`);
|
|
2007
|
+
lines.push(OUTPUT_RULES);
|
|
2008
|
+
lines.push("Narrate only what the player's character can perceive.");
|
|
2009
|
+
return lines.join("\n");
|
|
2010
|
+
}
|
|
2011
|
+
function renderExpansion(report) {
|
|
2012
|
+
if (report.created.length === 0) return `Nothing was made up: ${(report.declined ?? "the world author found nothing the story needs").replace(/[.\s]+$/, "")}. Work with what exists.`;
|
|
2013
|
+
const lines = report.created.map((entry) => `- ${entry.kind} ${entry.key} (${entry.name})`);
|
|
2014
|
+
const characters = report.created.filter((entry) => entry.kind === "character");
|
|
2015
|
+
return [
|
|
2016
|
+
"Made up and fitted into the world:",
|
|
2017
|
+
...lines,
|
|
2018
|
+
...characters.length === 0 ? [] : [`${characters.length === 1 ? "They are" : "They are all"} now in the cast: ask them to act with ${ACTIVATE_TOOL}, by their keys, like anyone else.`],
|
|
2019
|
+
...report.declined === void 0 ? [] : [`Not made: ${report.declined}`]
|
|
2020
|
+
].join("\n");
|
|
2021
|
+
}
|
|
2022
|
+
/** The tools the game master plays a turn with. */
|
|
2023
|
+
function createTools$1(deps) {
|
|
2024
|
+
const ownerOf = (agent) => {
|
|
2025
|
+
if (agent === void 0) throw new Error("the roleplay tools can only be called by an agent");
|
|
2026
|
+
return {
|
|
2027
|
+
agent,
|
|
2028
|
+
owner: {
|
|
2029
|
+
chat: agent.session.id,
|
|
2030
|
+
turn: deps.turnOf(agent)
|
|
2031
|
+
}
|
|
2032
|
+
};
|
|
2033
|
+
};
|
|
2034
|
+
const storeOf = (chat) => {
|
|
2035
|
+
const store = deps.stores(chat);
|
|
2036
|
+
if (store === void 0) throw new Error("this chat is not a roleplay session");
|
|
2037
|
+
return store;
|
|
2038
|
+
};
|
|
2039
|
+
const activate = defineTool({
|
|
2040
|
+
name: ACTIVATE_TOOL,
|
|
2041
|
+
description: "Let the characters act: one round of the turn. Each character asked is asked, separately and at the same time, what it intends to do and say in the situation you describe and how committed it is. Call it after reading what the player did, and again for a later round only when the story genuinely needs the characters to react to what just happened; the number of rounds for one player message is limited.",
|
|
2042
|
+
parameters: {
|
|
2043
|
+
characters: {
|
|
2044
|
+
type: "array",
|
|
2045
|
+
required: true,
|
|
2046
|
+
items: { type: "string" },
|
|
2047
|
+
description: "Keys of the characters to ask, chosen by you from the scene (where each is, what each is doing). Ask only those the moment reaches: those in the same place, and those elsewhere who can plainly see, hear or are summoned; a character elsewhere perceives nothing by itself. Never the whole cast. In a later round ask only those the moment calls for."
|
|
2048
|
+
},
|
|
2049
|
+
situation: {
|
|
2050
|
+
type: "string",
|
|
2051
|
+
required: true,
|
|
2052
|
+
description: "An objective description of the moment: in the first round what the player's character just did or said; in a later round what is happening now, following from the rounds before (they are told those too). Every character is told this and nothing more, so leave out anyone's private thoughts."
|
|
2053
|
+
}
|
|
2054
|
+
},
|
|
2055
|
+
output: {
|
|
2056
|
+
schema: { type: "json" },
|
|
2057
|
+
render: (_args, value) => [{
|
|
2058
|
+
type: "text",
|
|
2059
|
+
text: renderAttempt(value)
|
|
2060
|
+
}]
|
|
2061
|
+
},
|
|
2062
|
+
isConcurrencySafe: () => false,
|
|
2063
|
+
async execute(args, exec) {
|
|
2064
|
+
const { agent, owner } = ownerOf(exec.agent);
|
|
2065
|
+
await deps.engine.settle(owner.chat, owner.turn);
|
|
2066
|
+
const run = characterRunner({
|
|
2067
|
+
parent: agent,
|
|
2068
|
+
boundaries: deps.boundaries,
|
|
2069
|
+
store: storeOf(owner.chat)
|
|
2070
|
+
});
|
|
2071
|
+
return record(await deps.engine.activate(owner, {
|
|
2072
|
+
situation: args.situation,
|
|
2073
|
+
characters: args.characters
|
|
2074
|
+
}, run, exec.signal));
|
|
2075
|
+
}
|
|
2076
|
+
});
|
|
2077
|
+
const resolve = defineTool({
|
|
2078
|
+
name: RESOLVE_TOOL,
|
|
2079
|
+
description: "Decide what actually happens to each character that acted in the current round, from their intents and the scene only. Intents can conflict; settle them consistently. A character whose intent fails and who was highly committed gets one more chance, and you resolve that attempt too. The player's character is not asked to act, but you may include an outcome for it (its key is in the scene) when what the player did moves it somewhere or has it handle things; when nobody else needs to react (the player just walks somewhere, picks something up), call this with only that outcome, without activate_characters. When nobody retries, the round is recorded and you decide whether another round is needed or the turn goes back to the player.",
|
|
2080
|
+
parameters: {
|
|
2081
|
+
outcomes: {
|
|
2082
|
+
type: "array",
|
|
2083
|
+
required: true,
|
|
2084
|
+
items: {
|
|
2085
|
+
type: "object",
|
|
2086
|
+
additionalProperties: false,
|
|
2087
|
+
properties: {
|
|
2088
|
+
character: {
|
|
2089
|
+
type: "string",
|
|
2090
|
+
required: true,
|
|
2091
|
+
description: "The character's key; for the player's character, only when it moves or handles things; in an out-of-character command, any character of the story."
|
|
2092
|
+
},
|
|
2093
|
+
result: {
|
|
2094
|
+
type: "string",
|
|
2095
|
+
required: true,
|
|
2096
|
+
enum: RESULTS,
|
|
2097
|
+
description: "Whether the character's intent went through."
|
|
2098
|
+
},
|
|
2099
|
+
summary: {
|
|
2100
|
+
type: "string",
|
|
2101
|
+
required: true,
|
|
2102
|
+
description: "What concretely happens to the character, in a sentence. It becomes what the character is doing."
|
|
2103
|
+
},
|
|
2104
|
+
roll: {
|
|
2105
|
+
type: "integer",
|
|
2106
|
+
description: "The id of the dice roll that decided this outcome (the id roll_check gave), when you rolled for it: the result you give must be the roll's."
|
|
2107
|
+
},
|
|
2108
|
+
spoken: {
|
|
2109
|
+
type: "boolean",
|
|
2110
|
+
description: "Whether the character gets to say its utterance. It does unless something prevents it, such as being silenced or knocked out first."
|
|
2111
|
+
},
|
|
2112
|
+
public_state: {
|
|
2113
|
+
type: "string",
|
|
2114
|
+
description: "What anyone present can now see or infer about the character, when that changed."
|
|
2115
|
+
},
|
|
2116
|
+
item_changes: {
|
|
2117
|
+
type: "array",
|
|
2118
|
+
description: "What the character does with things as a result, in order, when it does: leave out when it handles nothing. Each is checked, and you are told why when it cannot be done. Not for a character whose intent failed.",
|
|
2119
|
+
items: {
|
|
2120
|
+
type: "object",
|
|
2121
|
+
additionalProperties: false,
|
|
2122
|
+
properties: {
|
|
2123
|
+
item: {
|
|
2124
|
+
type: "string",
|
|
2125
|
+
required: true,
|
|
2126
|
+
description: "The key of the item, as the scene lists it. Leave a way's lock to exit."
|
|
2127
|
+
},
|
|
2128
|
+
action: {
|
|
2129
|
+
type: "string",
|
|
2130
|
+
required: true,
|
|
2131
|
+
enum: ITEM_ACTIONS,
|
|
2132
|
+
description: "take (pick up what is here or take it out of a container it carries), drop (leave it here), give (to someone present), put (into an open container), wear, remove (what is worn), open, close, lock, unlock, reveal (find what was hidden)."
|
|
2133
|
+
},
|
|
2134
|
+
to: {
|
|
2135
|
+
type: "string",
|
|
2136
|
+
description: "For give: who gets it. For put: the container."
|
|
2137
|
+
},
|
|
2138
|
+
quantity: {
|
|
2139
|
+
type: "integer",
|
|
2140
|
+
description: "How many, of a pile; all when left out."
|
|
2141
|
+
},
|
|
2142
|
+
position: {
|
|
2143
|
+
type: "string",
|
|
2144
|
+
description: "Where, in words, for drop and put."
|
|
2145
|
+
},
|
|
2146
|
+
feature: {
|
|
2147
|
+
type: "string",
|
|
2148
|
+
description: "For drop: the feature of the place it is left at."
|
|
2149
|
+
},
|
|
2150
|
+
with: {
|
|
2151
|
+
type: "string",
|
|
2152
|
+
description: "For lock and unlock: the key item used. It has to be in hand and fit the lock."
|
|
2153
|
+
},
|
|
2154
|
+
exit: {
|
|
2155
|
+
type: "string",
|
|
2156
|
+
description: "For lock and unlock of a way instead of an item: the key of the place it leads to."
|
|
2157
|
+
},
|
|
2158
|
+
forced: {
|
|
2159
|
+
type: "boolean",
|
|
2160
|
+
description: "Only when the story breaks the lock (picked, smashed): no key is needed."
|
|
2161
|
+
}
|
|
2162
|
+
}
|
|
2163
|
+
}
|
|
2164
|
+
},
|
|
2165
|
+
variable_changes: {
|
|
2166
|
+
type: "array",
|
|
2167
|
+
description: "What this changes of what the story keeps track of (the scene lists it; list_variables shows what exists): a feeling, an injury, a flag, a debt. Only what the outcome establishes; to is the new value (a number, true or false, or one of the words of a choice), by is an amount a number goes up or down (it stops at its bounds).",
|
|
2168
|
+
items: {
|
|
2169
|
+
type: "object",
|
|
2170
|
+
additionalProperties: false,
|
|
2171
|
+
properties: {
|
|
2172
|
+
variable: {
|
|
2173
|
+
type: "string",
|
|
2174
|
+
required: true,
|
|
2175
|
+
description: "The key of the variable."
|
|
2176
|
+
},
|
|
2177
|
+
subject: {
|
|
2178
|
+
type: "string",
|
|
2179
|
+
required: true,
|
|
2180
|
+
description: "The key of the character, item or place it is about; world for the whole story."
|
|
2181
|
+
},
|
|
2182
|
+
to: {
|
|
2183
|
+
oneOf: [
|
|
2184
|
+
{ type: "number" },
|
|
2185
|
+
{ type: "boolean" },
|
|
2186
|
+
{ type: "string" }
|
|
2187
|
+
],
|
|
2188
|
+
description: "The new value."
|
|
2189
|
+
},
|
|
2190
|
+
by: {
|
|
2191
|
+
type: "number",
|
|
2192
|
+
description: "How much a number goes up (positive) or down (negative)."
|
|
2193
|
+
},
|
|
2194
|
+
baseline: {
|
|
2195
|
+
oneOf: [
|
|
2196
|
+
{ type: "number" },
|
|
2197
|
+
{ type: "boolean" },
|
|
2198
|
+
{ type: "string" }
|
|
2199
|
+
],
|
|
2200
|
+
description: "For a variable with a temperament (feelings): the new baseline, when what happened changes it lastingly."
|
|
2201
|
+
}
|
|
2202
|
+
}
|
|
2203
|
+
}
|
|
2204
|
+
},
|
|
2205
|
+
moves_to: {
|
|
2206
|
+
type: "object",
|
|
2207
|
+
additionalProperties: false,
|
|
2208
|
+
description: "Where the character ends up if it goes somewhere as a result: leave out when it stays. It must be possible (a way over open exits); you are told why if it is not. Not for a character whose intent failed. A journey takes at least as long as the ways on it say, whatever elapsed_seconds you give.",
|
|
2209
|
+
properties: {
|
|
2210
|
+
location: {
|
|
2211
|
+
type: "string",
|
|
2212
|
+
required: true,
|
|
2213
|
+
description: "The key of the place, as the scene lists it."
|
|
2214
|
+
},
|
|
2215
|
+
position: {
|
|
2216
|
+
type: "string",
|
|
2217
|
+
description: "Where in the place, in words: \"by the window\"."
|
|
2218
|
+
},
|
|
2219
|
+
feature: {
|
|
2220
|
+
type: "string",
|
|
2221
|
+
description: "The key of a feature of that place it is at."
|
|
2222
|
+
},
|
|
2223
|
+
ignore_exits: {
|
|
2224
|
+
type: "boolean",
|
|
2225
|
+
description: "Only when the story itself carries it (carried off, teleported, falls): the exits do not matter."
|
|
2226
|
+
}
|
|
2227
|
+
}
|
|
2228
|
+
}
|
|
2229
|
+
}
|
|
2230
|
+
}
|
|
2231
|
+
},
|
|
2232
|
+
elapsed_seconds: {
|
|
2233
|
+
type: "integer",
|
|
2234
|
+
description: "How long this round took in the story, in seconds:: a few seconds for a remark, a minute or two for a conversation, longer for work or a journey. Left out, the chat's default applies. Not when the story's time follows the wall clock."
|
|
2235
|
+
}
|
|
2236
|
+
},
|
|
2237
|
+
output: {
|
|
2238
|
+
schema: { type: "json" },
|
|
2239
|
+
render: (_args, value) => [{
|
|
2240
|
+
type: "text",
|
|
2241
|
+
text: renderResolution(value)
|
|
2242
|
+
}]
|
|
2243
|
+
},
|
|
2244
|
+
isConcurrencySafe: () => false,
|
|
2245
|
+
async execute(args, exec) {
|
|
2246
|
+
const { agent, owner } = ownerOf(exec.agent);
|
|
2247
|
+
await deps.engine.settle(owner.chat, owner.turn);
|
|
2248
|
+
const run = characterRunner({
|
|
2249
|
+
parent: agent,
|
|
2250
|
+
boundaries: deps.boundaries,
|
|
2251
|
+
store: storeOf(owner.chat)
|
|
2252
|
+
});
|
|
2253
|
+
const outcomes = args.outcomes.map((outcome) => ({
|
|
2254
|
+
character: outcome.character,
|
|
2255
|
+
result: outcome.result,
|
|
2256
|
+
summary: outcome.summary,
|
|
2257
|
+
...outcome.public_state === void 0 ? {} : { publicState: outcome.public_state },
|
|
2258
|
+
...outcome.spoken === void 0 ? {} : { spoken: outcome.spoken },
|
|
2259
|
+
...outcome.roll === void 0 ? {} : { roll: outcome.roll },
|
|
2260
|
+
...outcome.item_changes === void 0 || outcome.item_changes.length === 0 ? {} : { itemChanges: outcome.item_changes.map((change) => ({
|
|
2261
|
+
item: change.item,
|
|
2262
|
+
action: change.action,
|
|
2263
|
+
...change.to === void 0 ? {} : { to: change.to },
|
|
2264
|
+
...change.quantity === void 0 ? {} : { quantity: change.quantity },
|
|
2265
|
+
...change.position === void 0 ? {} : { position: change.position },
|
|
2266
|
+
...change.feature === void 0 ? {} : { feature: change.feature },
|
|
2267
|
+
...change.with === void 0 ? {} : { with: change.with },
|
|
2268
|
+
...change.exit === void 0 ? {} : { exit: change.exit },
|
|
2269
|
+
...change.forced === true ? { forced: true } : {}
|
|
2270
|
+
})) },
|
|
2271
|
+
...outcome.variable_changes === void 0 || outcome.variable_changes.length === 0 ? {} : { variableChanges: outcome.variable_changes.map((change) => ({
|
|
2272
|
+
variable: change.variable,
|
|
2273
|
+
subject: change.subject,
|
|
2274
|
+
...change.to === void 0 ? {} : { to: change.to },
|
|
2275
|
+
...change.by === void 0 ? {} : { by: change.by },
|
|
2276
|
+
...change.baseline === void 0 ? {} : { baseline: change.baseline }
|
|
2277
|
+
})) },
|
|
2278
|
+
...outcome.moves_to === void 0 ? {} : { moveTo: {
|
|
2279
|
+
location: outcome.moves_to.location,
|
|
2280
|
+
...outcome.moves_to.position === void 0 ? {} : { position: outcome.moves_to.position },
|
|
2281
|
+
...outcome.moves_to.feature === void 0 ? {} : { feature: outcome.moves_to.feature },
|
|
2282
|
+
...outcome.moves_to.ignore_exits === true ? { ignoreExits: true } : {}
|
|
2283
|
+
} }
|
|
2284
|
+
}));
|
|
2285
|
+
return record(await deps.engine.resolve(owner, outcomes, run, exec.signal, args.elapsed_seconds));
|
|
2286
|
+
}
|
|
2287
|
+
});
|
|
2288
|
+
const narrate = defineTool({
|
|
2289
|
+
name: NARRATE_TOOL,
|
|
2290
|
+
description: "Deliver the output of the turn to the player and give control back to them, once at least one round is recorded: the characters' utterances from all the rounds and your narration, as ordered segments. Every utterance a character gave must appear exactly once, exactly as given and in the order spoken; narration is free. An output that changes, drops, invents or reorders an utterance is refused with what is wrong.",
|
|
2291
|
+
parameters: {
|
|
2292
|
+
segments: {
|
|
2293
|
+
type: "array",
|
|
2294
|
+
description: "The output in order. Leave out only when a narrator other than you writes the output.",
|
|
2295
|
+
items: {
|
|
2296
|
+
type: "object",
|
|
2297
|
+
additionalProperties: false,
|
|
2298
|
+
properties: {
|
|
2299
|
+
type: {
|
|
2300
|
+
type: "string",
|
|
2301
|
+
required: true,
|
|
2302
|
+
enum: ["utterance", "narration"]
|
|
2303
|
+
},
|
|
2304
|
+
character: {
|
|
2305
|
+
type: "string",
|
|
2306
|
+
description: "For an utterance: the key of the character who says it."
|
|
2307
|
+
},
|
|
2308
|
+
text: {
|
|
2309
|
+
type: "string",
|
|
2310
|
+
required: true,
|
|
2311
|
+
description: "For an utterance: the words exactly as the character gave them, without quotation marks. For narration: what the player reads."
|
|
2312
|
+
}
|
|
2313
|
+
}
|
|
2314
|
+
}
|
|
2315
|
+
},
|
|
2316
|
+
addressed: {
|
|
2317
|
+
type: "array",
|
|
2318
|
+
items: { type: "integer" },
|
|
2319
|
+
description: "The ids of the beats you were told to weave in that this output does. Beats you do not address are told again, then let go."
|
|
2320
|
+
}
|
|
2321
|
+
},
|
|
2322
|
+
output: {
|
|
2323
|
+
schema: { type: "json" },
|
|
2324
|
+
render: (_args, value) => {
|
|
2325
|
+
const output = value;
|
|
2326
|
+
return [{
|
|
2327
|
+
type: "text",
|
|
2328
|
+
text: `${output.repaired ? "The output was corrected so that every utterance appears exactly as the characters gave it, and has been delivered to the player. The turn ends here." : "The output has been delivered to the player. The turn ends here."}\n${encodeOutput(output)}`
|
|
2329
|
+
}];
|
|
2330
|
+
}
|
|
2331
|
+
},
|
|
2332
|
+
isConcurrencySafe: () => false,
|
|
2333
|
+
async execute(args, exec) {
|
|
2334
|
+
const { agent, owner } = ownerOf(exec.agent);
|
|
2335
|
+
await deps.engine.settle(owner.chat, owner.turn);
|
|
2336
|
+
const segments = (args.segments ?? []).map((segment) => ({
|
|
2337
|
+
type: segment.type,
|
|
2338
|
+
text: segment.text,
|
|
2339
|
+
...segment.character === void 0 ? {} : { character: segment.character }
|
|
2340
|
+
}));
|
|
2341
|
+
const output = await deps.engine.narrate(owner, segments, characterRunner({
|
|
2342
|
+
parent: agent,
|
|
2343
|
+
boundaries: deps.boundaries,
|
|
2344
|
+
store: storeOf(owner.chat)
|
|
2345
|
+
}), args.addressed ?? []);
|
|
2346
|
+
const timelineNode = deps.delivered?.(owner.chat, output);
|
|
2347
|
+
const delivered = timelineNode === void 0 ? output : {
|
|
2348
|
+
...output,
|
|
2349
|
+
timelineNode
|
|
2350
|
+
};
|
|
2351
|
+
exec.concludeTurn();
|
|
2352
|
+
return record(delivered);
|
|
2353
|
+
}
|
|
2354
|
+
});
|
|
2355
|
+
const remember = defineTool({
|
|
2356
|
+
name: RECORD_TOOL,
|
|
2357
|
+
description: "Have the memory keeper write what happened since the last record into the story's lasting memory: the events, what each character took in of them, what they now believe, and the threads left open. It works in the background and covers every round still waiting, from this turn and earlier ones. Call it when the story changes phase, not after every round; rounds you do not record are kept and recorded together later.",
|
|
2358
|
+
parameters: { focus: {
|
|
2359
|
+
type: "string",
|
|
2360
|
+
description: "What is worth keeping, in a sentence: the decision, revelation or change that matters. The keeper writes it first and may leave out incidental detail."
|
|
2361
|
+
} },
|
|
2362
|
+
output: {
|
|
2363
|
+
schema: { type: "json" },
|
|
2364
|
+
render: (_args, value) => [{
|
|
2365
|
+
type: "text",
|
|
2366
|
+
text: `The memory keeper is writing ${value.rounds} round${value.rounds === 1 ? "" : "s"} into the story's memory.`
|
|
2367
|
+
}]
|
|
2368
|
+
},
|
|
2369
|
+
isConcurrencySafe: () => false,
|
|
2370
|
+
execute(args, exec) {
|
|
2371
|
+
const { owner } = ownerOf(exec.agent);
|
|
2372
|
+
return Promise.resolve(record({ rounds: deps.engine.record(owner, args.focus) }));
|
|
2373
|
+
}
|
|
2374
|
+
});
|
|
2375
|
+
const plot = defineTool({
|
|
2376
|
+
name: PLOT_TOOL,
|
|
2377
|
+
description: "Record only what play has already established about an optional plot. introduced means the named opportunity actually became perceptible in the resolved round, not merely that the pacing note suggested it. rejected means the player clearly declined that specific hook. resolved or abandoned applies to the plot as a whole. This records pacing state; it creates no event and makes nothing happen.",
|
|
2378
|
+
parameters: {
|
|
2379
|
+
plot: {
|
|
2380
|
+
type: "string",
|
|
2381
|
+
required: true,
|
|
2382
|
+
description: "The plot id from the pacing opportunity."
|
|
2383
|
+
},
|
|
2384
|
+
development: {
|
|
2385
|
+
type: "string",
|
|
2386
|
+
description: "The development id; required for introduced or rejected."
|
|
2387
|
+
},
|
|
2388
|
+
action: {
|
|
2389
|
+
type: "string",
|
|
2390
|
+
required: true,
|
|
2391
|
+
enum: [
|
|
2392
|
+
"introduced",
|
|
2393
|
+
"rejected",
|
|
2394
|
+
"resolved",
|
|
2395
|
+
"abandoned"
|
|
2396
|
+
]
|
|
2397
|
+
}
|
|
2398
|
+
},
|
|
2399
|
+
output: {
|
|
2400
|
+
schema: { type: "json" },
|
|
2401
|
+
render: (_args, value) => [{
|
|
2402
|
+
type: "text",
|
|
2403
|
+
text: `Plot pacing recorded: ${value.plot.name} is ${value.status}.`
|
|
2404
|
+
}]
|
|
2405
|
+
},
|
|
2406
|
+
isConcurrencySafe: () => false,
|
|
2407
|
+
execute(args, exec) {
|
|
2408
|
+
const { owner } = ownerOf(exec.agent);
|
|
2409
|
+
return Promise.resolve(record(updatePlotProgress(storeOf(owner.chat), args.plot, args.development, args.action)));
|
|
2410
|
+
}
|
|
2411
|
+
});
|
|
2412
|
+
const makePlot = defineTool({
|
|
2413
|
+
name: AUTHOR_PLOT_TOOL,
|
|
2414
|
+
description: "Ask a plot author for one optional, branching dramatic scaffold grounded in the current session. Use only when the scene explicitly says the quiet story has no plot scaffold and a reusable tension would help. It creates possibilities, not events, actions or obligations; do not introduce any part until a later pacing opportunity fits.",
|
|
2415
|
+
parameters: {},
|
|
2416
|
+
output: {
|
|
2417
|
+
schema: { type: "json" },
|
|
2418
|
+
render: (_args, value) => {
|
|
2419
|
+
const made = value;
|
|
2420
|
+
return [{
|
|
2421
|
+
type: "text",
|
|
2422
|
+
text: `Authored optional plot ${made.name} [${made.id}]: ${made.premise}. Nothing in it has happened. Continue this turn normally; a later pacing opportunity may offer a hook.`
|
|
2423
|
+
}];
|
|
2424
|
+
}
|
|
2425
|
+
},
|
|
2426
|
+
isConcurrencySafe: () => false,
|
|
2427
|
+
async execute(_args, exec) {
|
|
2428
|
+
const { agent, owner } = ownerOf(exec.agent);
|
|
2429
|
+
const store = storeOf(owner.chat);
|
|
2430
|
+
if (!plotAuthorNeeded(store, owner.turn)) throw new Error("the story does not currently need a plot author; continue with its existing plots, threads and character goals");
|
|
2431
|
+
return record(await authorPlot(agent, store, owner.turn, exec.signal));
|
|
2432
|
+
}
|
|
2433
|
+
});
|
|
2434
|
+
const expand = defineTool({
|
|
2435
|
+
name: EXPAND_TOOL,
|
|
2436
|
+
description: "Have a new character or place made up and fitted into the world, only when the story genuinely needs it. Valid reasons: scene_change (the story has actually gone somewhere that no known place covers, even as part of one), arrival (someone new has actually arrived or been brought into the scene), introduction (a specific person who has not appeared is needed by what is happening now and the story has established who they are), object (a thing so important or so complex that it needs inventing, such as an artifact with properties or a vehicle; or a place on the body that the world has no slot for; ordinary things the story uses are yours to bring in with introduce_thing), trigger (the story set up a moment that is bound to come, such as a deadline given, a promised arrival or a trap laid, that can be stated as a condition: a time, someone in a place, a thing held, a variable, an event), variable (a quantity, state or choice the story established matters from here on and nothing tracked fits: a debt, a health, a reputation). Not valid: colour, atmosphere, filling a quiet scene, something mentioned in passing, a passer-by or a crowd, scenery, or anything an existing character, place or thing can serve; use those. Ordinary things go through introduce_thing. A world author decides, and may decline and say what exists that can serve. A few things at most per turn.",
|
|
2437
|
+
parameters: {
|
|
2438
|
+
need: {
|
|
2439
|
+
type: "string",
|
|
2440
|
+
required: true,
|
|
2441
|
+
enum: AUTHORING_NEEDS,
|
|
2442
|
+
description: "Why: scene_change, arrival, introduction, object, variable or trigger."
|
|
2443
|
+
},
|
|
2444
|
+
what: {
|
|
2445
|
+
type: "string",
|
|
2446
|
+
required: true,
|
|
2447
|
+
description: "What is needed, from what the story has established: who or where (a name when it was given), their role, what happened to make it needed now, and where it is in relation to what exists."
|
|
2448
|
+
}
|
|
2449
|
+
},
|
|
2450
|
+
output: {
|
|
2451
|
+
schema: { type: "json" },
|
|
2452
|
+
render: (_args, value) => [{
|
|
2453
|
+
type: "text",
|
|
2454
|
+
text: renderExpansion(value)
|
|
2455
|
+
}]
|
|
2456
|
+
},
|
|
2457
|
+
isConcurrencySafe: () => false,
|
|
2458
|
+
async execute(args, exec) {
|
|
2459
|
+
const { owner } = ownerOf(exec.agent);
|
|
2460
|
+
await deps.engine.settle(owner.chat, owner.turn);
|
|
2461
|
+
return record(await deps.engine.expand(owner, {
|
|
2462
|
+
need: args.need,
|
|
2463
|
+
what: args.what
|
|
2464
|
+
}, exec.signal));
|
|
2465
|
+
}
|
|
2466
|
+
});
|
|
2467
|
+
const introduce = defineTool({
|
|
2468
|
+
name: INTRODUCE_TOOL,
|
|
2469
|
+
description: "Bring a thing into the story as a table's game master would: something the story is about to use or that the player can find, take or handle (a barricade, a tool, a note, a bottle, a key) and that does not exist yet. It is made at once, where you say: at a place (at, a place key; the player's place when you say nothing), in someone's hands (held_by, a character key) or inside a thing (inside, an item key). Afterwards it is a thing like any other: use its key in item_changes. Not for scenery nobody will touch (that is just part of the place), not for something important and complex enough to need a world author (use expand_world, reason object), and never for what exists already (list_items). A few things at most per turn.",
|
|
2470
|
+
parameters: {
|
|
2471
|
+
name: {
|
|
2472
|
+
type: "string",
|
|
2473
|
+
required: true,
|
|
2474
|
+
description: "What it is called, as the story names it."
|
|
2475
|
+
},
|
|
2476
|
+
description: {
|
|
2477
|
+
type: "string",
|
|
2478
|
+
description: "One or two sentences: what it looks like, what it is made of, what state it is in."
|
|
2479
|
+
},
|
|
2480
|
+
quantity: {
|
|
2481
|
+
type: "integer",
|
|
2482
|
+
description: "How many, when it is a number of the same thing (default 1)."
|
|
2483
|
+
},
|
|
2484
|
+
quality: {
|
|
2485
|
+
type: "string",
|
|
2486
|
+
description: "Its condition in a word or two (rusty, new), when that matters."
|
|
2487
|
+
},
|
|
2488
|
+
notable: {
|
|
2489
|
+
type: "boolean",
|
|
2490
|
+
description: "Whether the characters present would notice it at once."
|
|
2491
|
+
},
|
|
2492
|
+
hidden: {
|
|
2493
|
+
type: "boolean",
|
|
2494
|
+
description: "Whether it starts out of sight (until a round reveals it)."
|
|
2495
|
+
},
|
|
2496
|
+
at: {
|
|
2497
|
+
type: "string",
|
|
2498
|
+
description: "The key of the place it lies in."
|
|
2499
|
+
},
|
|
2500
|
+
held_by: {
|
|
2501
|
+
type: "string",
|
|
2502
|
+
description: "The key of the character who holds it."
|
|
2503
|
+
},
|
|
2504
|
+
inside: {
|
|
2505
|
+
type: "string",
|
|
2506
|
+
description: "The key of the container it is in."
|
|
2507
|
+
}
|
|
2508
|
+
},
|
|
2509
|
+
output: {
|
|
2510
|
+
schema: { type: "json" },
|
|
2511
|
+
render: (_args, value) => {
|
|
2512
|
+
const made = value;
|
|
2513
|
+
return [{
|
|
2514
|
+
type: "text",
|
|
2515
|
+
text: `Introduced ${made.name} [${made.key}], ${made.where}. Use the key in item_changes; nobody has taken it up yet.`
|
|
2516
|
+
}];
|
|
2517
|
+
}
|
|
2518
|
+
},
|
|
2519
|
+
isConcurrencySafe: () => false,
|
|
2520
|
+
async execute(args, exec) {
|
|
2521
|
+
const { owner } = ownerOf(exec.agent);
|
|
2522
|
+
await deps.engine.settle(owner.chat, owner.turn);
|
|
2523
|
+
return record(deps.engine.introduce(owner, {
|
|
2524
|
+
name: args.name,
|
|
2525
|
+
...args.description === void 0 ? {} : { description: args.description },
|
|
2526
|
+
...args.quantity === void 0 ? {} : { quantity: args.quantity },
|
|
2527
|
+
...args.quality === void 0 ? {} : { quality: args.quality },
|
|
2528
|
+
...args.notable === void 0 ? {} : { notable: args.notable },
|
|
2529
|
+
...args.hidden === void 0 ? {} : { hidden: args.hidden },
|
|
2530
|
+
...args.at === void 0 ? {} : { at: args.at },
|
|
2531
|
+
...args.held_by === void 0 ? {} : { heldBy: args.held_by },
|
|
2532
|
+
...args.inside === void 0 ? {} : { inside: args.inside }
|
|
2533
|
+
}));
|
|
2534
|
+
}
|
|
2535
|
+
});
|
|
2536
|
+
const skip = defineTool({
|
|
2537
|
+
name: TIME_TOOL,
|
|
2538
|
+
description: "Skip ahead in the story's time, between rounds: the player's character sleeps till morning, waits, or travels for days. Say either how long (by_minutes) or until when (until_time, and days_later for a later day). Time does not otherwise pass faster than the rounds take; use this only for a stretch that is summarised rather than played. Nothing else changes: if the skip changes what characters are doing or where they are, run a round for them afterwards. Not available when the story's time follows the wall clock.",
|
|
2539
|
+
parameters: {
|
|
2540
|
+
reason: {
|
|
2541
|
+
type: "string",
|
|
2542
|
+
required: true,
|
|
2543
|
+
description: "What happens in the time that passes, in a sentence (\"they sleep\", \"the ferry crosses\")."
|
|
2544
|
+
},
|
|
2545
|
+
by_minutes: {
|
|
2546
|
+
type: "integer",
|
|
2547
|
+
description: "How many minutes to skip."
|
|
2548
|
+
},
|
|
2549
|
+
until_time: {
|
|
2550
|
+
type: "string",
|
|
2551
|
+
description: "The time of day to skip to, 24-hour HH:MM: the next time the clock reads it, or the day given by days_later."
|
|
2552
|
+
},
|
|
2553
|
+
days_later: {
|
|
2554
|
+
type: "integer",
|
|
2555
|
+
description: "With until_time: that many days after today (0 is later today, 1 is tomorrow)."
|
|
2556
|
+
}
|
|
2557
|
+
},
|
|
2558
|
+
output: {
|
|
2559
|
+
schema: { type: "json" },
|
|
2560
|
+
render: (_args, value) => {
|
|
2561
|
+
const done = value;
|
|
2562
|
+
return [{
|
|
2563
|
+
type: "text",
|
|
2564
|
+
text: `${describeDuration(done.to - done.from)} pass. It is now ${describeTime({
|
|
2565
|
+
now: done.to,
|
|
2566
|
+
zone: done.zone
|
|
2567
|
+
})}.${done.moved.length === 0 ? "" : ` ${done.moved.map(routineLine).join(" ")}`} Nothing else changed: characters with you are still doing what they were, where they were; run a round for them if the time that passed changes that.${done.world.length === 0 ? "" : `\n${renderWorld(done.world).join("\n")}`}`
|
|
2568
|
+
}];
|
|
2569
|
+
}
|
|
2570
|
+
},
|
|
2571
|
+
isConcurrencySafe: () => false,
|
|
2572
|
+
async execute(args, exec) {
|
|
2573
|
+
const { owner } = ownerOf(exec.agent);
|
|
2574
|
+
await deps.engine.settle(owner.chat, owner.turn);
|
|
2575
|
+
if ([args.by_minutes !== void 0, args.until_time !== void 0].filter(Boolean).length !== 1) throw new Error("give exactly one of by_minutes and until_time");
|
|
2576
|
+
if (args.days_later !== void 0 && args.until_time === void 0) throw new Error("days_later goes with until_time");
|
|
2577
|
+
const request = args.by_minutes !== void 0 ? {
|
|
2578
|
+
byMinutes: args.by_minutes,
|
|
2579
|
+
reason: args.reason
|
|
2580
|
+
} : {
|
|
2581
|
+
untilTime: args.until_time ?? "",
|
|
2582
|
+
...args.days_later === void 0 ? {} : { daysLater: args.days_later },
|
|
2583
|
+
reason: args.reason
|
|
2584
|
+
};
|
|
2585
|
+
return record(deps.engine.advanceTime(owner, request));
|
|
2586
|
+
}
|
|
2587
|
+
});
|
|
2588
|
+
const preview = defineTool({
|
|
2589
|
+
name: PREVIEW_TOOL,
|
|
2590
|
+
description: "Show the player how the scene opens, as your very first action of a turn, before you ask any character: two or three sentences that set the mood and what the player's character perceives, ending on the open question of the moment. It is on screen at once, while the characters are still being asked, and is replaced in the player's view by the output you deliver with narrate, which may use it, change it or start over. Describe only what the scene and the player's own action establish: never what any other character does, says, decides or thinks, and nothing the player's character cannot perceive. Once per message.",
|
|
2591
|
+
parameters: { text: {
|
|
2592
|
+
type: "string",
|
|
2593
|
+
required: true,
|
|
2594
|
+
description: "The opening, plain prose in the narration voice."
|
|
2595
|
+
} },
|
|
2596
|
+
output: {
|
|
2597
|
+
schema: { type: "json" },
|
|
2598
|
+
render: (_args, value) => [{
|
|
2599
|
+
type: "text",
|
|
2600
|
+
text: `${encodePreview(value.text)}\nShown to the player. Now call activate_characters.`
|
|
2601
|
+
}]
|
|
2602
|
+
},
|
|
2603
|
+
isConcurrencySafe: () => false,
|
|
2604
|
+
execute(args, exec) {
|
|
2605
|
+
const { owner } = ownerOf(exec.agent);
|
|
2606
|
+
return Promise.resolve(record({ text: deps.engine.preview(owner, args.text) }));
|
|
2607
|
+
}
|
|
2608
|
+
});
|
|
2609
|
+
const ruling = defineTool({
|
|
2610
|
+
name: RULING_TOOL,
|
|
2611
|
+
description: "Rule on the player's out-of-character command, as the very first thing of an out-of-character turn: legal is false only when the command breaks the rules of the world or the player's own rules (the scene lists them); what is merely strange, impossible for the characters, or hard on them is legal, because the player may change the story itself. The reason is shown to the player, so write it plainly to them. Only a legal ruling lets you change anything.",
|
|
2612
|
+
parameters: {
|
|
2613
|
+
rule_check: {
|
|
2614
|
+
type: "string",
|
|
2615
|
+
required: true,
|
|
2616
|
+
description: "First, go through every rule the scene lists, one by one, in a few words each: does the command need what the rule excludes (the rules are literal: a rule against magic is broken by anything magical, however the command words it, and strange is not the same as against a rule)? Write \"no rules listed\" when there are none."
|
|
2617
|
+
},
|
|
2618
|
+
legal: {
|
|
2619
|
+
type: "boolean",
|
|
2620
|
+
required: true,
|
|
2621
|
+
description: "Whether the command is allowed: false when any listed rule is broken."
|
|
2622
|
+
},
|
|
2623
|
+
reason: {
|
|
2624
|
+
type: "string",
|
|
2625
|
+
required: true,
|
|
2626
|
+
description: "To the player, in plain words and briefly: what you will do, or which rule it breaks."
|
|
2627
|
+
}
|
|
2628
|
+
},
|
|
2629
|
+
output: {
|
|
2630
|
+
schema: { type: "json" },
|
|
2631
|
+
render: (_args, value) => [{
|
|
2632
|
+
type: "text",
|
|
2633
|
+
text: value.legal ? `Ruled legal. Now make it happen: ${RESOLVE_TOOL} (outcomes for any characters, asked or not, with their moves and things), ${EXPAND_TOOL} (for what does not exist yet), ${TIME_TOOL}; do only what the command says. Then call ${NARRATE_TOOL} with narration only, of what the player can perceive.` : `Ruled illegal; nothing changes. Call ${NARRATE_TOOL} with no segments: the player is told why.`
|
|
2634
|
+
}]
|
|
2635
|
+
},
|
|
2636
|
+
isConcurrencySafe: () => false,
|
|
2637
|
+
execute(args, exec) {
|
|
2638
|
+
const { owner } = ownerOf(exec.agent);
|
|
2639
|
+
return Promise.resolve(record(deps.engine.rule(owner, args.legal, args.reason)));
|
|
2640
|
+
}
|
|
2641
|
+
});
|
|
2642
|
+
const answer = defineTool({
|
|
2643
|
+
name: ANSWER_TOOL,
|
|
2644
|
+
description: "Have the player's out-of-character question answered, as the very first thing of a question turn. You do not write the answer: it is written from what the player's character knows (what it remembers, knows to exist, carries and sees where it is), so that nothing hidden is given away. Nothing in the story changes, nobody is asked to act and time does not pass.",
|
|
2645
|
+
parameters: {},
|
|
2646
|
+
output: {
|
|
2647
|
+
schema: { type: "json" },
|
|
2648
|
+
render: () => [{
|
|
2649
|
+
type: "text",
|
|
2650
|
+
text: `The player is shown the answer. Now call ${NARRATE_TOOL} with no segments.`
|
|
2651
|
+
}]
|
|
2652
|
+
},
|
|
2653
|
+
isConcurrencySafe: () => false,
|
|
2654
|
+
async execute(_args, exec) {
|
|
2655
|
+
const { agent, owner } = ownerOf(exec.agent);
|
|
2656
|
+
return record(await deps.engine.answer(owner, answerRunner({
|
|
2657
|
+
parent: agent,
|
|
2658
|
+
boundaries: deps.boundaries,
|
|
2659
|
+
store: storeOf(owner.chat)
|
|
2660
|
+
}), exec.signal));
|
|
2661
|
+
}
|
|
2662
|
+
});
|
|
2663
|
+
return [
|
|
2664
|
+
defineTool({
|
|
2665
|
+
name: JUDGE_TOOL,
|
|
2666
|
+
description: "Judge what the player's character tries, as the very first thing of an ordinary turn (nothing else is accepted before it): allowed is false when it is not viable (what it needs is out of reach, is not there, or the character cannot do it or does not have it) or when it breaks a rule of the world or of the player (the scene lists them and they are absolute: no magic means no spell works). The player's claim of an effect is not a fact. What merely looks strange, rash or foolish is allowed. When it is not allowed the attempt is played as a failure for the player's character, and nobody is asked to act on it.",
|
|
2667
|
+
parameters: {
|
|
2668
|
+
rule_check: {
|
|
2669
|
+
type: "string",
|
|
2670
|
+
required: true,
|
|
2671
|
+
description: "First, go through every rule the scene lists, one by one, in a few words each: does what the character tries need what the rule excludes? The rules are literal. Then whether it is viable here. Write \"no rules listed\" when there are none."
|
|
2672
|
+
},
|
|
2673
|
+
at: {
|
|
2674
|
+
type: "string",
|
|
2675
|
+
description: "The key of the place where the action happens, only when the player says it happens at a particular place (talking to the baker in the market, searching the cellar) rather than where the character is. If the character is somewhere else the action cannot work: it has to go there first. Leave it out when the action happens where the character is, and when the player is going somewhere (the journey is its own action)."
|
|
2676
|
+
},
|
|
2677
|
+
allowed: {
|
|
2678
|
+
type: "boolean",
|
|
2679
|
+
required: true,
|
|
2680
|
+
description: "Whether what the character tries can work: false when any listed rule is broken or it is not viable."
|
|
2681
|
+
},
|
|
2682
|
+
uncertain: {
|
|
2683
|
+
type: "boolean",
|
|
2684
|
+
required: true,
|
|
2685
|
+
description: "Always answer, when it can work: true when it can plainly go either way and the result matters to the story, such as talking round someone wary or hostile, a hard lock, a stealthy approach past someone watching, a climb, a leap, a chase, a fight, a hurried search; false for what plainly succeeds (walking, opening an unlocked door, asking a friendly question) or has nothing at stake. When it is true and you have dice tools, you roll for it before anyone is asked to act and the dice decide; without dice tools it changes nothing."
|
|
2686
|
+
},
|
|
2687
|
+
reason: {
|
|
2688
|
+
type: "string",
|
|
2689
|
+
required: true,
|
|
2690
|
+
description: "What the character tries, and the rule or the fact that decides it, in a sentence."
|
|
2691
|
+
}
|
|
2692
|
+
},
|
|
2693
|
+
output: {
|
|
2694
|
+
schema: { type: "json" },
|
|
2695
|
+
render: (_args, value) => [{
|
|
2696
|
+
type: "text",
|
|
2697
|
+
text: value.allowed ? `Judged: it can work${value.roll === true ? " but it is uncertain: roll for it now with roll_check (list_checks shows the checks), naming the character it is for; nobody is asked to act before the dice are rolled. Then" : ". Now"} call ${PREVIEW_TOOL} (when the scene asks for it) and ${ACTIVATE_TOOL}, describing only what the character does.` : `Judged: it cannot work${value.elsewhere === true ? ` (${value.reason})` : ""}. Play the failed attempt: ${RESOLVE_TOOL} with one outcome for the player's character (result failed, one sentence: what it does, what comes of it, why not) and nothing else, then ${NARRATE_TOOL}. Narrate what a witness would see of the attempt, never the effect the player claimed.`
|
|
2698
|
+
}]
|
|
2699
|
+
},
|
|
2700
|
+
isConcurrencySafe: () => false,
|
|
2701
|
+
execute(args, exec) {
|
|
2702
|
+
const { owner } = ownerOf(exec.agent);
|
|
2703
|
+
return Promise.resolve(record(deps.engine.judge(owner, args.allowed, args.reason, args.at, args.uncertain)));
|
|
2704
|
+
}
|
|
2705
|
+
}),
|
|
2706
|
+
preview,
|
|
2707
|
+
ruling,
|
|
2708
|
+
answer,
|
|
2709
|
+
activate,
|
|
2710
|
+
resolve,
|
|
2711
|
+
skip,
|
|
2712
|
+
remember,
|
|
2713
|
+
expand,
|
|
2714
|
+
introduce,
|
|
2715
|
+
makePlot,
|
|
2716
|
+
plot,
|
|
2717
|
+
narrate
|
|
2718
|
+
];
|
|
2719
|
+
}
|
|
2720
|
+
//#endregion
|
|
2721
|
+
//#region src/shared/tools.ts
|
|
2722
|
+
/** What this version can offer. A name in a settings file or a world that is not here is kept and ignored. */
|
|
2723
|
+
const OPTIONAL_TOOLS = [
|
|
2724
|
+
{
|
|
2725
|
+
id: "roll_check",
|
|
2726
|
+
agent: "gameMaster",
|
|
2727
|
+
default: true
|
|
2728
|
+
},
|
|
2729
|
+
{
|
|
2730
|
+
id: "roll_dice",
|
|
2731
|
+
agent: "gameMaster",
|
|
2732
|
+
default: true
|
|
2733
|
+
},
|
|
2734
|
+
{
|
|
2735
|
+
id: "list_checks",
|
|
2736
|
+
agent: "gameMaster",
|
|
2737
|
+
default: true
|
|
2738
|
+
}
|
|
2739
|
+
];
|
|
2740
|
+
/** Whether an agent of this kind has a tool, by what the switches say and, failing that, by default. A tool this version does not offer is never on. */
|
|
2741
|
+
function toolEnabled(board, agent, id) {
|
|
2742
|
+
const offered = OPTIONAL_TOOLS.find((tool) => tool.agent === agent && tool.id === id);
|
|
2743
|
+
if (offered === void 0) return false;
|
|
2744
|
+
return board[agent]?.[id] ?? offered.default;
|
|
2745
|
+
}
|
|
2746
|
+
/**
|
|
2747
|
+
* Whether an agent of this kind has a tool that is not one of this plugin's own: only when it was switched on. Such tools are off by default, because
|
|
2748
|
+
* they reach beyond the story (files, a shell, the web), and a name that no plugin registers now has no effect.
|
|
2749
|
+
*/
|
|
2750
|
+
function externalEnabled(board, agent, name) {
|
|
2751
|
+
return board[agent]?.[name] === true;
|
|
2752
|
+
}
|
|
2753
|
+
//#endregion
|
|
2754
|
+
//#region src/host/tools/external.ts
|
|
2755
|
+
/** The reserved transport DSH presents tools through; it is never a tool of its own to switch. */
|
|
2756
|
+
const RESERVED = /* @__PURE__ */ new Set(["run_code"]);
|
|
2757
|
+
let own;
|
|
2758
|
+
/** The names of every tool this plugin and the state plugin register themselves: the story's own, which are not for switching here. */
|
|
2759
|
+
function ownToolNames() {
|
|
2760
|
+
own ??= /* @__PURE__ */ new Set([
|
|
2761
|
+
...createTools(() => void 0, {
|
|
2762
|
+
write: true,
|
|
2763
|
+
authoring: true
|
|
2764
|
+
}).map((tool) => tool.name),
|
|
2765
|
+
...createDiceTools(() => void 0).map((tool) => tool.name),
|
|
2766
|
+
...createTools$1({}).map((tool) => tool.name)
|
|
2767
|
+
]);
|
|
2768
|
+
return own;
|
|
2769
|
+
}
|
|
2770
|
+
/** The tools other plugins registered for everyone (a file or shell tool, an MCP server's tools), which a story can give to an agent. */
|
|
2771
|
+
function externalTools(registry) {
|
|
2772
|
+
const mine = ownToolNames();
|
|
2773
|
+
return registry.schemas().filter((tool) => !mine.has(tool.name) && !RESERVED.has(tool.name)).map((tool) => ({
|
|
2774
|
+
name: tool.name,
|
|
2775
|
+
description: tool.description
|
|
2776
|
+
})).sort((a, b) => a.name.localeCompare(b.name));
|
|
2777
|
+
}
|
|
2778
|
+
/** The external tools that are registered now and that an agent of this kind has been given. */
|
|
2779
|
+
function externalGiven(registry, board, agent) {
|
|
2780
|
+
return externalTools(registry).map((tool) => tool.name).filter((name) => externalEnabled(board, agent, name));
|
|
2781
|
+
}
|
|
2782
|
+
/** The external tools that are registered now and that an agent of this kind has not been given: they are taken away from it. */
|
|
2783
|
+
function externalWithheld(registry, board, agent) {
|
|
2784
|
+
return externalTools(registry).map((tool) => tool.name).filter((name) => !externalEnabled(board, agent, name));
|
|
2785
|
+
}
|
|
2786
|
+
//#endregion
|
|
2787
|
+
//#region src/host/orchestration/whereabouts.ts
|
|
2788
|
+
const within = (inner, outer, places) => {
|
|
2789
|
+
const byId = new Map(places.map((place) => [place.id, place]));
|
|
2790
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2791
|
+
for (let at = inner; at !== void 0 && !seen.has(at.id); at = at.parentId === void 0 ? void 0 : byId.get(at.parentId)) {
|
|
2792
|
+
if (at.id === outer.id) return true;
|
|
2793
|
+
seen.add(at.id);
|
|
2794
|
+
}
|
|
2795
|
+
return false;
|
|
2796
|
+
};
|
|
2797
|
+
/** Whether two places are one scene: the same place, or one inside the other (a room and its building). */
|
|
2798
|
+
const sameScene = (a, b, places) => within(a, b, places) || within(b, a, places);
|
|
2799
|
+
/**
|
|
2800
|
+
* 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
|
|
2801
|
+
* 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.
|
|
2802
|
+
*/
|
|
2803
|
+
function whereabouts(places, here, at) {
|
|
2804
|
+
const target = places.find((place) => locationKey(place) === at);
|
|
2805
|
+
if (target === void 0) return { kind: "unknown" };
|
|
2806
|
+
if (here === void 0) return { kind: "unplaced" };
|
|
2807
|
+
return within(here, target, places) || within(target, here, places) ? { kind: "here" } : {
|
|
2808
|
+
kind: "elsewhere",
|
|
2809
|
+
target,
|
|
2810
|
+
here
|
|
2811
|
+
};
|
|
2812
|
+
}
|
|
2813
|
+
//#endregion
|
|
2814
|
+
//#region src/host/memory/reflection.ts
|
|
2815
|
+
const LAST_KEY = "reflection.last";
|
|
2816
|
+
const CURSOR_KEY = "reflection.cursor";
|
|
2817
|
+
const ANCHOR_KEY = "reflection.anchor";
|
|
2818
|
+
const ERROR_KEY = "reflection.error";
|
|
2819
|
+
const DAY_MS = 864e5;
|
|
2820
|
+
const MAX_MATERIAL = 40;
|
|
2821
|
+
const MAX_BELIEFS_SHOWN = 40;
|
|
2822
|
+
const MAX_ADDED = 4;
|
|
2823
|
+
const MAX_CHANGES = 10;
|
|
2824
|
+
const MAX_TEXT = 300;
|
|
2825
|
+
/** An event this important is reason enough for a belief on its own. */
|
|
2826
|
+
const DECISIVE_IMPORTANCE = 4;
|
|
2827
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2828
|
+
function readLast(session) {
|
|
2829
|
+
const stored = session.metadata.getValue(LAST_KEY);
|
|
2830
|
+
return isRecord(stored) && typeof stored["turn"] === "number" ? stored : void 0;
|
|
2831
|
+
}
|
|
2832
|
+
function readCursor(session) {
|
|
2833
|
+
const stored = session.metadata.getValue(CURSOR_KEY);
|
|
2834
|
+
return isRecord(stored) ? Object.fromEntries(Object.entries(stored).filter((entry) => typeof entry[1] === "number")) : {};
|
|
2835
|
+
}
|
|
2836
|
+
function readAnchor(session) {
|
|
2837
|
+
const stored = session.metadata.getValue(ANCHOR_KEY);
|
|
2838
|
+
return isRecord(stored) && typeof stored["now"] === "number" ? {
|
|
2839
|
+
now: stored["now"],
|
|
2840
|
+
...typeof stored["place"] === "number" ? { place: stored["place"] } : {}
|
|
2841
|
+
} : void 0;
|
|
2842
|
+
}
|
|
2843
|
+
function writeAnchor(session, place, now) {
|
|
2844
|
+
session.metadata.setValue(ANCHOR_KEY, {
|
|
2845
|
+
now,
|
|
2846
|
+
...place === void 0 ? {} : { place: place.id }
|
|
2847
|
+
});
|
|
2848
|
+
}
|
|
2849
|
+
const playerPlace = (store) => store.cast().find((member) => member.character.control === "player")?.place?.location;
|
|
2850
|
+
/** What is known of the story's reflection: whether a pass runs, the latest that finished, and why the latest failed. */
|
|
2851
|
+
function reflectionStatus(session, running) {
|
|
2852
|
+
const last = readLast(session);
|
|
2853
|
+
const failure = session.metadata.getValue(ERROR_KEY);
|
|
2854
|
+
return {
|
|
2855
|
+
running,
|
|
2856
|
+
...last === void 0 ? {} : { last },
|
|
2857
|
+
...isRecord(failure) && typeof failure["message"] === "string" && typeof failure["at"] === "string" ? { error: {
|
|
2858
|
+
at: failure["at"],
|
|
2859
|
+
message: failure["message"]
|
|
2860
|
+
} } : {}
|
|
2861
|
+
};
|
|
2862
|
+
}
|
|
2863
|
+
function recordFailure(session, message) {
|
|
2864
|
+
session.metadata.setValue(ERROR_KEY, {
|
|
2865
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2866
|
+
message: message.slice(0, 500)
|
|
2867
|
+
});
|
|
2868
|
+
}
|
|
2869
|
+
/**
|
|
2870
|
+
* Whether the story should reflect after this turn, and why. A pass waits until `minTurns` turns have passed since the last one; then it
|
|
2871
|
+
* comes after `everyTurns` turns, or when the scene has changed since the last pass (the player's character is somewhere that is neither
|
|
2872
|
+
* where it was nor inside or around it, or `sceneDays` of story time have passed). The first look only notes where the story stands.
|
|
2873
|
+
*/
|
|
2874
|
+
function dueReflection(store, turn) {
|
|
2875
|
+
const { reflection } = store.settings();
|
|
2876
|
+
if (!reflection.auto) return void 0;
|
|
2877
|
+
const session = store.story;
|
|
2878
|
+
const { now } = store.time(turn);
|
|
2879
|
+
const here = playerPlace(store);
|
|
2880
|
+
const anchor = readAnchor(session);
|
|
2881
|
+
if (anchor === void 0) {
|
|
2882
|
+
writeAnchor(session, here, now);
|
|
2883
|
+
return;
|
|
2884
|
+
}
|
|
2885
|
+
const since = turn - (readLast(session)?.turn ?? 0);
|
|
2886
|
+
if (since < reflection.minTurns) return void 0;
|
|
2887
|
+
if (reflection.everyTurns > 0 && since >= reflection.everyTurns) return "turns";
|
|
2888
|
+
if (!reflection.onSceneChange) return void 0;
|
|
2889
|
+
const places = session.locations.list();
|
|
2890
|
+
const before = places.find((place) => place.id === anchor.place);
|
|
2891
|
+
if (here !== void 0 && before !== void 0 && !sameScene(here, before, places)) return "scene";
|
|
2892
|
+
if (reflection.sceneDays > 0 && now - anchor.now >= reflection.sceneDays * DAY_MS) return "scene";
|
|
2893
|
+
}
|
|
2894
|
+
/**
|
|
2895
|
+
* 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
|
|
2896
|
+
* still a draft, so that nothing is passed over that is sealed later.
|
|
2897
|
+
*/
|
|
2898
|
+
function materialOf(session, minNew) {
|
|
2899
|
+
const cursor = readCursor(session);
|
|
2900
|
+
const found = [];
|
|
2901
|
+
for (const character of session.characters.list()) {
|
|
2902
|
+
if (character.control !== "agent" || character.kind !== "person" || character.tier === "background") continue;
|
|
2903
|
+
const taken = session.events.perceivedBy(character.id);
|
|
2904
|
+
const draft = taken.filter((entry) => !entry.event.sealed).map((entry) => entry.perception.id);
|
|
2905
|
+
const ceiling = draft.length === 0 ? Infinity : Math.min(...draft) - 1;
|
|
2906
|
+
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);
|
|
2907
|
+
if (fresh.length < minNew) continue;
|
|
2908
|
+
const beliefs = session.memories.list(character.id).sort((a, b) => b.importance - a.importance || a.id - b.id).slice(0, MAX_BELIEFS_SHOWN);
|
|
2909
|
+
found.push({
|
|
2910
|
+
character,
|
|
2911
|
+
fresh,
|
|
2912
|
+
beliefs
|
|
2913
|
+
});
|
|
2914
|
+
}
|
|
2915
|
+
return found.sort((a, b) => b.fresh.length - a.fresh.length);
|
|
2916
|
+
}
|
|
2917
|
+
const idList = {
|
|
2918
|
+
type: "array",
|
|
2919
|
+
items: { type: "integer" }
|
|
2920
|
+
};
|
|
2921
|
+
const RESULT = {
|
|
2922
|
+
type: "object",
|
|
2923
|
+
properties: {
|
|
2924
|
+
add: {
|
|
2925
|
+
type: "array",
|
|
2926
|
+
description: "New beliefs, at most four. Leave empty when nothing new can be firmly said.",
|
|
2927
|
+
items: {
|
|
2928
|
+
type: "object",
|
|
2929
|
+
properties: {
|
|
2930
|
+
kind: {
|
|
2931
|
+
type: "string",
|
|
2932
|
+
enum: [...MEMORY_KINDS],
|
|
2933
|
+
description: "belief: what it holds true or suspects; relationship: how it stands with someone; knowledge: something it knows."
|
|
2934
|
+
},
|
|
2935
|
+
text: {
|
|
2936
|
+
type: "string",
|
|
2937
|
+
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."
|
|
2938
|
+
},
|
|
2939
|
+
about: {
|
|
2940
|
+
type: "array",
|
|
2941
|
+
items: { type: "string" },
|
|
2942
|
+
description: "The names of the characters it is about."
|
|
2943
|
+
},
|
|
2944
|
+
importance: {
|
|
2945
|
+
type: "integer",
|
|
2946
|
+
description: `From 1 (passing) to 5 (it shapes how they act).`
|
|
2947
|
+
},
|
|
2948
|
+
confidence: {
|
|
2949
|
+
type: "string",
|
|
2950
|
+
enum: [...MEMORY_CONFIDENCES],
|
|
2951
|
+
description: "How sure they are: doubtful, likely (when you leave it out) or sure, which needs things from at least two different turns."
|
|
2952
|
+
},
|
|
2953
|
+
perceptions: {
|
|
2954
|
+
...idList,
|
|
2955
|
+
description: "The numbers of the things it took in that this rests on."
|
|
2956
|
+
},
|
|
2957
|
+
beliefs: {
|
|
2958
|
+
...idList,
|
|
2959
|
+
description: "The numbers of the beliefs it generalises or builds on, if any."
|
|
2960
|
+
}
|
|
2961
|
+
},
|
|
2962
|
+
required: [
|
|
2963
|
+
"kind",
|
|
2964
|
+
"text",
|
|
2965
|
+
"importance",
|
|
2966
|
+
"perceptions"
|
|
2967
|
+
],
|
|
2968
|
+
additionalProperties: false
|
|
2969
|
+
}
|
|
2970
|
+
},
|
|
2971
|
+
revise: {
|
|
2972
|
+
type: "array",
|
|
2973
|
+
description: "Beliefs to firm up, doubt or correct in the light of what came after them.",
|
|
2974
|
+
items: {
|
|
2975
|
+
type: "object",
|
|
2976
|
+
properties: {
|
|
2977
|
+
id: {
|
|
2978
|
+
type: "integer",
|
|
2979
|
+
description: "The number of the belief, as listed."
|
|
2980
|
+
},
|
|
2981
|
+
text: {
|
|
2982
|
+
type: "string",
|
|
2983
|
+
description: "The belief as it should read now."
|
|
2984
|
+
},
|
|
2985
|
+
importance: {
|
|
2986
|
+
type: "integer",
|
|
2987
|
+
description: `From 1 to 5.`
|
|
2988
|
+
},
|
|
2989
|
+
confidence: {
|
|
2990
|
+
type: "string",
|
|
2991
|
+
enum: [...MEMORY_CONFIDENCES],
|
|
2992
|
+
description: "How sure they are now. Raise it only for what supports the belief; lower it only together with contradicted_by."
|
|
2993
|
+
},
|
|
2994
|
+
perceptions: {
|
|
2995
|
+
...idList,
|
|
2996
|
+
description: "The numbers of the things it took in since that support the belief or bear on it."
|
|
2997
|
+
},
|
|
2998
|
+
contradicted_by: {
|
|
2999
|
+
...idList,
|
|
3000
|
+
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."
|
|
3001
|
+
}
|
|
3002
|
+
},
|
|
3003
|
+
required: ["id"],
|
|
3004
|
+
additionalProperties: false
|
|
3005
|
+
}
|
|
3006
|
+
},
|
|
3007
|
+
doubt: {
|
|
3008
|
+
type: "array",
|
|
3009
|
+
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.",
|
|
3010
|
+
items: {
|
|
3011
|
+
type: "object",
|
|
3012
|
+
properties: {
|
|
3013
|
+
id: {
|
|
3014
|
+
type: "integer",
|
|
3015
|
+
description: "The number of the belief, as listed."
|
|
3016
|
+
},
|
|
3017
|
+
contradicted_by: {
|
|
3018
|
+
...idList,
|
|
3019
|
+
description: "The numbers of the things it took in since that speak against the belief."
|
|
3020
|
+
},
|
|
3021
|
+
text: {
|
|
3022
|
+
type: "string",
|
|
3023
|
+
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."
|
|
3024
|
+
}
|
|
3025
|
+
},
|
|
3026
|
+
required: ["id", "contradicted_by"],
|
|
3027
|
+
additionalProperties: false
|
|
3028
|
+
}
|
|
3029
|
+
},
|
|
3030
|
+
drop: {
|
|
3031
|
+
type: "array",
|
|
3032
|
+
description: "Beliefs to let go: settled or overturned by what came after, or merged into another.",
|
|
3033
|
+
items: {
|
|
3034
|
+
type: "object",
|
|
3035
|
+
properties: {
|
|
3036
|
+
id: { type: "integer" },
|
|
3037
|
+
perceptions: {
|
|
3038
|
+
...idList,
|
|
3039
|
+
description: "What it took in since that settles or overturns it."
|
|
3040
|
+
},
|
|
3041
|
+
merged_into: {
|
|
3042
|
+
type: "integer",
|
|
3043
|
+
description: "The number of the belief that now says the same, instead of a reason from what it took in."
|
|
3044
|
+
}
|
|
3045
|
+
},
|
|
3046
|
+
required: ["id"],
|
|
3047
|
+
additionalProperties: false
|
|
3048
|
+
}
|
|
3049
|
+
}
|
|
3050
|
+
},
|
|
3051
|
+
required: [
|
|
3052
|
+
"add",
|
|
3053
|
+
"revise",
|
|
3054
|
+
"drop"
|
|
3055
|
+
],
|
|
3056
|
+
additionalProperties: false
|
|
3057
|
+
};
|
|
3058
|
+
function shownOf(session, material) {
|
|
3059
|
+
const turnOf = (perceptionId) => {
|
|
3060
|
+
const seen = session.events.getPerception(perceptionId);
|
|
3061
|
+
return seen === void 0 ? void 0 : session.events.get(seen.eventId)?.turn;
|
|
3062
|
+
};
|
|
3063
|
+
return {
|
|
3064
|
+
perceptions: new Map(material.fresh.map((entry) => [entry.perception.id, entry])),
|
|
3065
|
+
beliefs: new Map(material.beliefs.map((belief) => [belief.id, belief])),
|
|
3066
|
+
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) ?? []))]))
|
|
3067
|
+
};
|
|
3068
|
+
}
|
|
3069
|
+
const rankOf = (confidence) => MEMORY_CONFIDENCES.indexOf(confidence);
|
|
3070
|
+
/** 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. */
|
|
3071
|
+
const MIXED_IN = /\((?:[^)]*\b(?:doubtful|likely|sure|importance)\b[^)]*|[^)]*\bperceptions?\s*\[?\d[^)]*)\)|\bperceptions?\s*\[\d/i;
|
|
3072
|
+
/** One step less sure, and no less than doubtful. */
|
|
3073
|
+
const lowered = (confidence) => MEMORY_CONFIDENCES[Math.max(0, rankOf(confidence) - 1)];
|
|
3074
|
+
/**
|
|
3075
|
+
* 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
|
|
3076
|
+
* 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
|
|
3077
|
+
* into another. Nothing is judged about whether the belief is wise; only whether it is grounded in what the character was given.
|
|
3078
|
+
*/
|
|
3079
|
+
function proposalProblems(proposal, shown, resolveName, tr = translator("en")) {
|
|
3080
|
+
const problems = [];
|
|
3081
|
+
const add = proposal.add ?? [];
|
|
3082
|
+
const revise = proposal.revise ?? [];
|
|
3083
|
+
const drop = proposal.drop ?? [];
|
|
3084
|
+
const doubt = proposal.doubt ?? [];
|
|
3085
|
+
if (add.length > MAX_ADDED) problems.push(tr("add: at most {max} new beliefs in one pass; merge or choose", { max: MAX_ADDED }));
|
|
3086
|
+
if (add.length + revise.length + drop.length + doubt.length > MAX_CHANGES) problems.push(tr("at most {max} changes in one pass", { max: MAX_CHANGES }));
|
|
3087
|
+
const cited = (ids, where) => (ids ?? []).flatMap((id) => {
|
|
3088
|
+
const entry = shown.perceptions.get(id);
|
|
3089
|
+
if (entry === void 0) problems.push(tr("{where}: there is no thing it took in numbered {id}", {
|
|
3090
|
+
where,
|
|
3091
|
+
id
|
|
3092
|
+
}));
|
|
3093
|
+
return entry === void 0 ? [] : [entry];
|
|
3094
|
+
});
|
|
3095
|
+
const known = (value, where) => {
|
|
3096
|
+
const fine = value === void 0 || MEMORY_CONFIDENCES.includes(value);
|
|
3097
|
+
if (!fine) problems.push(tr("{where}: confidence is one of {options}", {
|
|
3098
|
+
where,
|
|
3099
|
+
options: MEMORY_CONFIDENCES.join(", ")
|
|
3100
|
+
}));
|
|
3101
|
+
return fine;
|
|
3102
|
+
};
|
|
3103
|
+
add.forEach((belief, index) => {
|
|
3104
|
+
const where = `add[${index}]`;
|
|
3105
|
+
if (!MEMORY_KINDS.includes(belief.kind)) problems.push(tr("{where}: unknown kind \"{kind}\"", {
|
|
3106
|
+
where,
|
|
3107
|
+
kind: belief.kind
|
|
3108
|
+
}));
|
|
3109
|
+
if (belief.text.trim() === "") problems.push(tr("{where}: say what it believes", { where }));
|
|
3110
|
+
else if (belief.text.trim().length > MAX_TEXT) problems.push(tr("{where}: at most {max} characters; say it shorter", {
|
|
3111
|
+
where,
|
|
3112
|
+
max: MAX_TEXT
|
|
3113
|
+
}));
|
|
3114
|
+
if (!Number.isInteger(belief.importance) || belief.importance < 1 || belief.importance > 5) problems.push(tr("{where}: importance runs from {min} to {max}", {
|
|
3115
|
+
where,
|
|
3116
|
+
min: 1,
|
|
3117
|
+
max: 5
|
|
3118
|
+
}));
|
|
3119
|
+
const sure = known(belief.confidence, where) && belief.confidence === "sure";
|
|
3120
|
+
const events = cited(belief.perceptions, where);
|
|
3121
|
+
const built = (belief.beliefs ?? []).flatMap((id) => {
|
|
3122
|
+
const found = shown.beliefs.get(id);
|
|
3123
|
+
if (found === void 0) problems.push(tr("{where}: there is no belief numbered {id}", {
|
|
3124
|
+
where,
|
|
3125
|
+
id
|
|
3126
|
+
}));
|
|
3127
|
+
return found === void 0 ? [] : [found];
|
|
3128
|
+
});
|
|
3129
|
+
const turns = /* @__PURE__ */ new Set([...events.map((entry) => entry.event.turn), ...built.map((found) => found.turn)]);
|
|
3130
|
+
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 }));
|
|
3131
|
+
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 }));
|
|
3132
|
+
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", {
|
|
3133
|
+
where,
|
|
3134
|
+
name
|
|
3135
|
+
}));
|
|
3136
|
+
});
|
|
3137
|
+
const touched = /* @__PURE__ */ new Set();
|
|
3138
|
+
const touch = (id, where) => {
|
|
3139
|
+
if (touched.has(id)) problems.push(tr("{where}: belief {id} is already changed in this pass", {
|
|
3140
|
+
where,
|
|
3141
|
+
id
|
|
3142
|
+
}));
|
|
3143
|
+
touched.add(id);
|
|
3144
|
+
};
|
|
3145
|
+
const fresh = (events, belief, where) => {
|
|
3146
|
+
if (events.length === 0) problems.push(tr("{where}: say what it took in since that bears on it", { where }));
|
|
3147
|
+
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", {
|
|
3148
|
+
where,
|
|
3149
|
+
id: entry.perception.id
|
|
3150
|
+
}));
|
|
3151
|
+
};
|
|
3152
|
+
revise.forEach((change, index) => {
|
|
3153
|
+
const where = `revise[${index}]`;
|
|
3154
|
+
const belief = shown.beliefs.get(change.id);
|
|
3155
|
+
if (belief === void 0) {
|
|
3156
|
+
problems.push(tr("{where}: there is no belief numbered {id}", {
|
|
3157
|
+
where,
|
|
3158
|
+
id: change.id
|
|
3159
|
+
}));
|
|
3160
|
+
return;
|
|
3161
|
+
}
|
|
3162
|
+
touch(change.id, where);
|
|
3163
|
+
const supports = cited(change.perceptions, where);
|
|
3164
|
+
const against = cited(change.contradicted_by, where);
|
|
3165
|
+
if (change.text === void 0 && change.importance === void 0 && change.confidence === void 0 && against.length === 0) problems.push(tr("{where}: say what changes", { where }));
|
|
3166
|
+
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", {
|
|
3167
|
+
where,
|
|
3168
|
+
max: MAX_TEXT
|
|
3169
|
+
}));
|
|
3170
|
+
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 }));
|
|
3171
|
+
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}", {
|
|
3172
|
+
where,
|
|
3173
|
+
min: 1,
|
|
3174
|
+
max: 5
|
|
3175
|
+
}));
|
|
3176
|
+
fresh([...supports, ...against], belief, where);
|
|
3177
|
+
if (!known(change.confidence, where) || change.confidence === void 0) {
|
|
3178
|
+
if (against.length > 0) problems.push(tr("{where}: a belief that something contradicts must be doubted: lower its confidence", { where }));
|
|
3179
|
+
return;
|
|
3180
|
+
}
|
|
3181
|
+
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 }));
|
|
3182
|
+
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 }));
|
|
3183
|
+
if (change.confidence === "sure" && belief.confidence !== "sure") {
|
|
3184
|
+
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 }));
|
|
3185
|
+
}
|
|
3186
|
+
});
|
|
3187
|
+
doubt.forEach((change, index) => {
|
|
3188
|
+
const where = `doubt[${index}]`;
|
|
3189
|
+
const belief = shown.beliefs.get(change.id);
|
|
3190
|
+
if (belief === void 0) {
|
|
3191
|
+
problems.push(tr("{where}: there is no belief numbered {id}", {
|
|
3192
|
+
where,
|
|
3193
|
+
id: change.id
|
|
3194
|
+
}));
|
|
3195
|
+
return;
|
|
3196
|
+
}
|
|
3197
|
+
touch(change.id, where);
|
|
3198
|
+
const against = cited(change.contradicted_by, where);
|
|
3199
|
+
if (against.length === 0) problems.push(tr("{where}: name what speaks against the belief in contradicted_by", { where }));
|
|
3200
|
+
fresh(against, belief, where);
|
|
3201
|
+
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", {
|
|
3202
|
+
where,
|
|
3203
|
+
max: MAX_TEXT
|
|
3204
|
+
}));
|
|
3205
|
+
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 }));
|
|
3206
|
+
});
|
|
3207
|
+
const dropped = new Set(drop.map((entry) => entry.id));
|
|
3208
|
+
drop.forEach((change, index) => {
|
|
3209
|
+
const where = `drop[${index}]`;
|
|
3210
|
+
const belief = shown.beliefs.get(change.id);
|
|
3211
|
+
if (belief === void 0) {
|
|
3212
|
+
problems.push(tr("{where}: there is no belief numbered {id}", {
|
|
3213
|
+
where,
|
|
3214
|
+
id: change.id
|
|
3215
|
+
}));
|
|
3216
|
+
return;
|
|
3217
|
+
}
|
|
3218
|
+
touch(change.id, where);
|
|
3219
|
+
if (change.merged_into !== void 0) {
|
|
3220
|
+
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 }));
|
|
3221
|
+
return;
|
|
3222
|
+
}
|
|
3223
|
+
fresh(cited(change.perceptions, where), belief, where);
|
|
3224
|
+
});
|
|
3225
|
+
return problems;
|
|
3226
|
+
}
|
|
3227
|
+
const keysOf = (names, resolveName) => (names ?? []).flatMap((name) => {
|
|
3228
|
+
const key = resolveName(name);
|
|
3229
|
+
return key === void 0 ? [] : [key];
|
|
3230
|
+
});
|
|
3231
|
+
/** The edit that writes a proposal that passed. */
|
|
3232
|
+
function editOf(turn, character, proposal, resolveName, confidenceOf = () => void 0) {
|
|
3233
|
+
const who = characterKey(character);
|
|
3234
|
+
return {
|
|
3235
|
+
turn,
|
|
3236
|
+
beliefs: (proposal.add ?? []).map((belief) => ({
|
|
3237
|
+
character: who,
|
|
3238
|
+
kind: belief.kind,
|
|
3239
|
+
text: belief.text.trim(),
|
|
3240
|
+
about: keysOf(belief.about, resolveName),
|
|
3241
|
+
importance: belief.importance,
|
|
3242
|
+
...belief.confidence === void 0 ? {} : { confidence: belief.confidence },
|
|
3243
|
+
evidenceFor: belief.perceptions ?? []
|
|
3244
|
+
})),
|
|
3245
|
+
beliefEdits: [...proposal.revise ?? [], ...(proposal.doubt ?? []).map((change) => ({
|
|
3246
|
+
id: change.id,
|
|
3247
|
+
...change.text === void 0 ? {} : { text: change.text },
|
|
3248
|
+
confidence: lowered(confidenceOf(change.id) ?? "likely"),
|
|
3249
|
+
contradicted_by: change.contradicted_by
|
|
3250
|
+
}))].map((change) => ({
|
|
3251
|
+
id: change.id,
|
|
3252
|
+
...change.text === void 0 ? {} : { text: change.text.trim() },
|
|
3253
|
+
..."importance" in change && change.importance !== void 0 ? { importance: change.importance } : {},
|
|
3254
|
+
...change.confidence === void 0 ? {} : { confidence: change.confidence },
|
|
3255
|
+
evidenceFor: "perceptions" in change ? change.perceptions ?? [] : [],
|
|
3256
|
+
evidenceAgainst: change.contradicted_by ?? []
|
|
3257
|
+
})),
|
|
3258
|
+
beliefRetractions: (proposal.drop ?? []).map((change) => change.id)
|
|
3259
|
+
};
|
|
3260
|
+
}
|
|
3261
|
+
function brief(session, material, now, zone, time, tr) {
|
|
3262
|
+
const { character, fresh, beliefs } = material;
|
|
3263
|
+
const named = (id) => session.characters.get(id)?.name ?? String(id);
|
|
3264
|
+
const { disputed } = session.memories.evidenceIndex(character.id);
|
|
3265
|
+
const believed = beliefs.map((belief) => {
|
|
3266
|
+
const about = belief.about.length === 0 ? "" : tr(", about {names}", { names: belief.about.map(named).join(tr(" and ")) });
|
|
3267
|
+
const dispute = disputed.has(belief.id) ? tr(", something taken in since speaks against it") : "";
|
|
3268
|
+
return `- b${belief.id} (${tr("{kind}, importance {importance}, {confidence}{about}{dispute}", {
|
|
3269
|
+
kind: belief.kind,
|
|
3270
|
+
importance: belief.importance,
|
|
3271
|
+
confidence: tr(belief.confidence),
|
|
3272
|
+
about,
|
|
3273
|
+
dispute
|
|
3274
|
+
})}): ${belief.text}`;
|
|
3275
|
+
});
|
|
3276
|
+
const taken = fresh.map((entry) => {
|
|
3277
|
+
const at = time(entry.event.turn, entry.event.round);
|
|
3278
|
+
return `- p${entry.perception.id}${at === void 0 ? "" : ` (${describeWhen(at, now, zone)})`}: ${entry.perception.content}`;
|
|
3279
|
+
});
|
|
3280
|
+
return [
|
|
3281
|
+
tr("Character: {name}{summary}", {
|
|
3282
|
+
name: referent(character),
|
|
3283
|
+
summary: character.summary === "" ? "" : ` - ${character.summary}`
|
|
3284
|
+
}),
|
|
3285
|
+
tr("What they believe now:"),
|
|
3286
|
+
...believed.length === 0 ? [tr("(nothing yet)")] : believed,
|
|
3287
|
+
tr("What they have taken in since:"),
|
|
3288
|
+
...taken,
|
|
3289
|
+
tr("Sort their memory.")
|
|
3290
|
+
].join("\n");
|
|
3291
|
+
}
|
|
3292
|
+
/**
|
|
3293
|
+
* 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
|
|
3294
|
+
* 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
|
|
3295
|
+
* and leaves the characters not yet done as they were.
|
|
3296
|
+
*/
|
|
3297
|
+
function memoryReflector(deps) {
|
|
3298
|
+
return { async reflect(job, signal) {
|
|
3299
|
+
const parent = deps.agentOf(job.chat);
|
|
3300
|
+
if (parent === void 0) throw new Error(`no agent for chat ${job.chat}`);
|
|
3301
|
+
const { store } = job;
|
|
3302
|
+
const session = store.story;
|
|
3303
|
+
const settings = store.settings();
|
|
3304
|
+
const { now, zone } = store.time(job.turn);
|
|
3305
|
+
const due = materialOf(session, job.reason === "manual" ? 1 : settings.reflection.minNew);
|
|
3306
|
+
const taken = job.reason === "manual" ? due : due.slice(0, settings.reflection.perRun);
|
|
3307
|
+
const resolveName = (name) => {
|
|
3308
|
+
const found = session.characters.findByName(name.trim());
|
|
3309
|
+
return found.length === 1 ? characterKey(found[0]) : void 0;
|
|
3310
|
+
};
|
|
3311
|
+
const tr = translator(languageOf(settings.prompts.language));
|
|
3312
|
+
const characters = [];
|
|
3313
|
+
for (const material of taken) {
|
|
3314
|
+
const shown = shownOf(session, material);
|
|
3315
|
+
const proposal = await runChild({
|
|
3316
|
+
parent,
|
|
3317
|
+
signal,
|
|
3318
|
+
reasoningEffort: settings.reasoning.children,
|
|
3319
|
+
sampling: childSampling(settings, "records"),
|
|
3320
|
+
...childModel(settings, "records"),
|
|
3321
|
+
trace: childTrace(store, "records", `reflection ${material.character.name}`),
|
|
3322
|
+
persona: promptFor(parent, "roleplay/reflection", settings.prompts.language),
|
|
3323
|
+
prompt: brief(session, material, now, zone, (turn, round) => session.clock.at(turn, round), tr),
|
|
3324
|
+
result: RESULT,
|
|
3325
|
+
beforeSubmit: (value) => {
|
|
3326
|
+
const given = value;
|
|
3327
|
+
const problems = [...proposalProblems(given, shown, resolveName, tr), ...[wrongLanguage(settings.prompts.language, { beliefs: [
|
|
3328
|
+
...given.add ?? [],
|
|
3329
|
+
...given.revise ?? [],
|
|
3330
|
+
...given.doubt ?? []
|
|
3331
|
+
].map((belief) => belief.text ?? "").join(" ") })].flatMap((problem) => problem === void 0 ? [] : [problem])];
|
|
3332
|
+
return problems.length === 0 ? void 0 : tr("not acceptable: {problems}", { problems: problems.join("; ") });
|
|
3333
|
+
},
|
|
3334
|
+
maxCalls: 3
|
|
3335
|
+
});
|
|
3336
|
+
const reached = Math.max(...material.fresh.map((entry) => entry.perception.id));
|
|
3337
|
+
session.transaction(() => {
|
|
3338
|
+
session.edit(editOf(job.turn, material.character, proposal, resolveName, (belief) => shown.beliefs.get(belief)?.confidence));
|
|
3339
|
+
session.metadata.setValue(CURSOR_KEY, {
|
|
3340
|
+
...readCursor(session),
|
|
3341
|
+
[characterKey(material.character)]: reached
|
|
3342
|
+
});
|
|
3343
|
+
});
|
|
3344
|
+
characters.push({
|
|
3345
|
+
name: material.character.name,
|
|
3346
|
+
added: proposal.add?.length ?? 0,
|
|
3347
|
+
revised: (proposal.revise?.length ?? 0) + (proposal.doubt?.length ?? 0),
|
|
3348
|
+
dropped: proposal.drop?.length ?? 0
|
|
3349
|
+
});
|
|
3350
|
+
}
|
|
3351
|
+
session.metadata.setValue(LAST_KEY, {
|
|
3352
|
+
turn: job.turn,
|
|
3353
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3354
|
+
reason: job.reason,
|
|
3355
|
+
characters
|
|
3356
|
+
});
|
|
3357
|
+
writeAnchor(session, playerPlace(store), now);
|
|
3358
|
+
session.metadata.deleteValue(ERROR_KEY);
|
|
3359
|
+
return { characters };
|
|
3360
|
+
} };
|
|
3361
|
+
}
|
|
3362
|
+
//#endregion
|
|
3363
|
+
//#region src/host/sessions/activity.ts
|
|
3364
|
+
const KEY$1 = "activity";
|
|
3365
|
+
const isEntry = (value) => {
|
|
3366
|
+
if (typeof value !== "object" || value === null) return false;
|
|
3367
|
+
const entry = value;
|
|
3368
|
+
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");
|
|
3369
|
+
};
|
|
3370
|
+
/** The recorded runs, oldest first. */
|
|
3371
|
+
function readActivity(session) {
|
|
3372
|
+
const stored = session.metadata.getValue(KEY$1);
|
|
3373
|
+
return Array.isArray(stored) ? stored.filter(isEntry) : [];
|
|
3374
|
+
}
|
|
3375
|
+
/** Files the run and returns the runs that fell off the end of the record to make room. */
|
|
3376
|
+
function recordActivity(session, entry) {
|
|
3377
|
+
const all = [...readActivity(session), entry];
|
|
3378
|
+
session.metadata.setValue(KEY$1, all.slice(-60));
|
|
3379
|
+
return all.slice(0, -60);
|
|
3380
|
+
}
|
|
3381
|
+
const RUN_FOLDER = "activity";
|
|
3382
|
+
const RUN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
3383
|
+
const runFile = (folder, run) => {
|
|
3384
|
+
if (!RUN_ID.test(run)) throw new RangeError(`"${run}" is not a run`);
|
|
3385
|
+
return join(folder, RUN_FOLDER, `${run}.json`);
|
|
3386
|
+
};
|
|
3387
|
+
/** 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. */
|
|
3388
|
+
function keepRunDetail(folder, run, detail) {
|
|
3389
|
+
const file = runFile(folder, run);
|
|
3390
|
+
mkdirSync(join(folder, RUN_FOLDER), { recursive: true });
|
|
3391
|
+
writeFileSync(`${file}.tmp`, JSON.stringify(detail));
|
|
3392
|
+
renameSync(`${file}.tmp`, file);
|
|
3393
|
+
}
|
|
3394
|
+
/** The stored detail of a run, or nothing when it was not kept or has been dropped. */
|
|
3395
|
+
function readRunDetail(folder, run) {
|
|
3396
|
+
try {
|
|
3397
|
+
return JSON.parse(readFileSync(runFile(folder, run), "utf8"));
|
|
3398
|
+
} catch (error) {
|
|
3399
|
+
if (error.code === "ENOENT") return void 0;
|
|
3400
|
+
throw error;
|
|
3401
|
+
}
|
|
3402
|
+
}
|
|
3403
|
+
function forgetRunDetails(folder, dropped) {
|
|
3404
|
+
for (const entry of dropped) if (entry.run !== void 0) rmSync(runFile(folder, entry.run), { force: true });
|
|
3405
|
+
}
|
|
3406
|
+
//#endregion
|
|
3407
|
+
//#region src/host/triggers/deliver.ts
|
|
3408
|
+
const KEY = "triggers.withdrawn";
|
|
3409
|
+
/** Why a note was withdrawn instead of told, by the number of the note. */
|
|
3410
|
+
function readWithdrawn(session) {
|
|
3411
|
+
const stored = session.metadata.getValue(KEY);
|
|
3412
|
+
if (!Array.isArray(stored)) return {};
|
|
3413
|
+
return Object.fromEntries(stored.flatMap((entry) => {
|
|
3414
|
+
const { note, reason } = entry ?? {};
|
|
3415
|
+
return typeof note === "number" && typeof reason === "string" ? [[note, reason]] : [];
|
|
3416
|
+
}));
|
|
3417
|
+
}
|
|
3418
|
+
/**
|
|
3419
|
+
* 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
|
|
3420
|
+
* reason kept (`readWithdrawn`). @returns what is to be told, with the number of its note.
|
|
3421
|
+
*/
|
|
3422
|
+
function deliverNow(session, notes, clock) {
|
|
3423
|
+
const { shown, withdrawn } = session.deliverNotes(notes, clock);
|
|
3424
|
+
if (withdrawn.length > 0) session.transaction(() => {
|
|
3425
|
+
for (const { note } of withdrawn) session.triggers.resolveNote(note.id, "lapsed");
|
|
3426
|
+
const before = Object.entries(readWithdrawn(session)).map(([note, reason]) => ({
|
|
3427
|
+
note: Number(note),
|
|
3428
|
+
reason
|
|
3429
|
+
}));
|
|
3430
|
+
session.metadata.setValue(KEY, [...before, ...withdrawn.map(({ note, reason }) => ({
|
|
3431
|
+
note: note.id,
|
|
3432
|
+
reason
|
|
3433
|
+
}))].slice(-100));
|
|
3434
|
+
});
|
|
3435
|
+
return shown.map(({ note, text }) => ({
|
|
3436
|
+
id: note.id,
|
|
3437
|
+
text
|
|
3438
|
+
}));
|
|
3439
|
+
}
|
|
3440
|
+
//#endregion
|
|
3441
|
+
export { notesOfSession as A, sameWords as B, plotProgressOf as C, parseOoc as D, MAX_OOC_ANSWER as E, TimelineError as F, readTime as G, beginTurn as H, Timelines as I, referent as J, skipTime as K, readTimeline as L, readNotes as M, observeAsPlayer as N, addToNote as O, observeSurroundings as P, pathTo as R, plotAuthorNeeded as S, AUTHORING_NEEDS as T, describeWhen as U, ClockError as V, endRound as W, languageOf as X, RESULTS as Y, translator as Z, PREVIEW_TOOL as _, readActivity as a, describePacingAdvice as b, dueReflection as c, reflectionStatus as d, whereabouts as f, toolEnabled as g, externalWithheld as h, keepRunDetail as i, putNote as j, clearNotes as k, memoryReflector as l, externalTools as m, readWithdrawn as n, readRunDetail as o, externalGiven as p, zoneOf as q, forgetRunDetails as r, recordActivity as s, deliverNow as t, recordFailure as u, createTools$1 as v, populatePlots as w, pacingAdvice as x, PLOTS_METADATA_KEY as y, defaultBoundaries as z };
|
|
3442
|
+
|
|
3443
|
+
//# sourceMappingURL=deliver-BSsDtF6X.js.map
|