@dsh-agentic-roleplay/core 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/lib/authoring.js +13 -2
  2. package/lib/child-lPncV1ps.js +380 -0
  3. package/lib/client.js +1526 -356
  4. package/lib/client.js.map +1 -1
  5. package/lib/compaction.js +1 -1
  6. package/lib/deliver-De62a8i9.js +1929 -0
  7. package/lib/doctor-chat-ByDfCMeo.js +17 -0
  8. package/lib/doctor.js +95 -0
  9. package/lib/{documents-DtlY2IRt.js → documents-Do4lz4SB.js} +549 -64
  10. package/lib/{gallery-DACG5eh2.js → gallery-CtFDL22W.js} +2 -2
  11. package/lib/{generator-DGYcLMp7.js → generator-B6FxlKOV.js} +2 -378
  12. package/lib/hooks-Ka22sFNy.js +1019 -0
  13. package/lib/images.js +3 -3
  14. package/lib/index.js +303 -190
  15. package/lib/language-DWVwi1R7.js +520 -0
  16. package/lib/narration-DK2kiIjE.js +141 -0
  17. package/lib/orchestration.js +777 -2542
  18. package/lib/{packs-CkRZDCsV.js → packs-BYjrAen6.js} +4 -518
  19. package/lib/{presenter-agent-PK9JYExk.js → presenter-agent-Dt21K96b.js} +4 -3
  20. package/lib/{deliver-BDW5WZvc.js → reflection-md7BCYCl.js} +350 -769
  21. package/lib/{narration-5ig7Dg28.js → settings-CA6icLL_.js} +156 -141
  22. package/package.json +3 -2
  23. package/prompts/en/doctor/persona.md +1 -0
  24. package/prompts/en/doctor/procedure.md +5 -0
  25. package/prompts/en/doctor/welcome.md +1 -0
  26. package/prompts/en/import/character.md +1 -0
  27. package/prompts/en/roleplay/dice.md +7 -0
  28. package/prompts/en/roleplay/game-master.md +2 -0
  29. package/prompts/en/roleplay/reflection-check.md +5 -0
  30. package/prompts/en/roleplay/reflection.md +5 -1
  31. package/prompts/zh/doctor/persona.md +1 -0
  32. package/prompts/zh/doctor/procedure.md +5 -0
  33. package/prompts/zh/doctor/welcome.md +1 -0
  34. package/prompts/zh/import/character.md +1 -0
  35. package/prompts/zh/roleplay/dice.md +7 -0
  36. package/prompts/zh/roleplay/game-master.md +2 -0
  37. package/prompts/zh/roleplay/reflection-check.md +5 -0
  38. package/prompts/zh/roleplay/reflection.md +5 -1
  39. package/lib/src-CWTNeL6Y.js +0 -128
@@ -0,0 +1,1929 @@
1
+ import { t as promptFor } from "./access-EbNdZFbk.js";
2
+ import "./settings-CA6icLL_.js";
3
+ import { a as wrongLanguage, c as parsePlotsFile, k as SessionNotFoundError } from "./language-DWVwi1R7.js";
4
+ import { n as encodeOutput, r as encodePreview } from "./narration-DK2kiIjE.js";
5
+ import { a as runChild, i as childTrace, n as childSampling, o as estimateAnswer, t as childModel } from "./child-lPncV1ps.js";
6
+ import { join } from "node:path";
7
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
8
+ import { defineTool } from "@deepseek-ai/dsh-tools";
9
+ import { DAY, ITEM_ACTIONS, MINUTE, SECOND, addLocalDays, clockTime, createCharacterTools, createDiceTools, createTools, dayPart, describeDuration, describeInstant, holidaysOn, isSessionId, localTime, nextTimeOfDay, readCalendar, seasonOf, sessionDatabase } from "@dsh-agentic-roleplay/state";
10
+ //#region ../dsh-roleplay-model/src/messages-zh.ts
11
+ /** 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. */
12
+ const ZH = {
13
+ ", ": ",",
14
+ "; ": ";",
15
+ ": ": ":",
16
+ ".": "。",
17
+ " and ": "和",
18
+ "doubtful": "存疑",
19
+ "likely": "较有把握",
20
+ "sure": "确信",
21
+ "open": "畅通",
22
+ "locked": "已上锁",
23
+ "blocked": "被堵住",
24
+ "night": "夜里",
25
+ "morning": "上午",
26
+ "afternoon": "下午",
27
+ "evening": "傍晚",
28
+ "spring": "春季",
29
+ "summer": "夏季",
30
+ "autumn": "秋季",
31
+ "winter": "冬季",
32
+ "today is {holidays}": "今天是{holidays}",
33
+ "Summary": "概述",
34
+ "Personality": "性格",
35
+ "Background": "背景",
36
+ "Appearance": "外貌",
37
+ "How you speak": "说话方式",
38
+ "You are {name}.": "你是{name}。",
39
+ "You are also called {names}.": "你也被称作{names}。",
40
+ "age: {value}": "年龄:{value}",
41
+ "gender: {value}": "性别:{value}",
42
+ "pronouns: {value}": "代词:{value}",
43
+ "- {key} ({name}): {use}": "- {key}({name}):{use}",
44
+ "Rolls {dice}.": "掷 {dice}。",
45
+ "Give a target: the difficulty, the number to meet or beat; set it by how hard the attempt is.": "需给出 target:难度,即要达到或超过的数字;按这次尝试的难易来定。",
46
+ "Give a target: the number to stay under; set it by how hard the attempt is.": "需给出 target:要低于的数字;按这次尝试的难易来定。",
47
+ "It adds the character's {variable}.": "它会加上该角色的 {variable}。",
48
+ "Counts the dice that show {hit} or more.": "统计显示 {hit} 或更高的骰子数。",
49
+ "the player's roll": "玩家的掷骰",
50
+ "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}。这是由骰子决定的事实:在你判断这次尝试、决定发生什么时把它考虑进去。",
51
+ "The checks of this story:": "本故事的检定:",
52
+ "No checks are defined: use roll_dice only.": "没有定义检定:只用 roll_dice。",
53
+ "Situation:": "当前情形:",
54
+ "Now: {time}.": "现在是:{time}。",
55
+ "Where you are:": "你所在之处:",
56
+ "Present:": "在场的人:",
57
+ " (you)": "(你)",
58
+ "What you know is coming:": "你知道即将发生的事:",
59
+ "Just now you notice:": "此刻你注意到:",
60
+ "How you are (what you can tell of yourself):": "你的状态(你自己能感觉到的):",
61
+ "What you can tell of the others here:": "你能看出在场其他人的情况:",
62
+ "What you have on you:": "你身上带着:",
63
+ "Things here: ": "这里有:",
64
+ "Ways out: ": "出路:",
65
+ "Lying about: ": "散落在周围的:",
66
+ "hidden": "隐蔽",
67
+ " holding {things}": ",里面有{things}",
68
+ "; and {count} more": ";另有{count}项",
69
+ "at {feature}": "在{feature}",
70
+ "; and {count} more you can recall if needed": ";另有{count}项,需要时你可以回想起来",
71
+ "What you know exists (this does not tell you where it is now or what state it is in):": "你知道存在的事物(这并不说明它现在在哪里、处于什么状态):",
72
+ "People: ": "人物:",
73
+ "Factions: ": "组织:",
74
+ "Places: ": "地点:",
75
+ "Routes: ": "路径:",
76
+ "Things: ": "物品:",
77
+ "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):": "你的日程与你想达成的事(只是计划,不是命令:依当下情形和你的性格,可以照做、推迟或放弃):",
78
+ "Your day, now: {activity}{place}, until {until}{note}.": "你此刻的日程:{activity}{place},持续到{until}{note}。",
79
+ "Your day, next: {activity}{place}, from {from}.": "你接下来的日程:{activity}{place},{from}开始。",
80
+ " at {place}": ",在{place}",
81
+ " (not something you would drop lightly)": "(你不会轻易放下)",
82
+ ", with {names}": ",与{names}一起",
83
+ "You were to: {title}{place}{with}, at {at}, which has passed and is still open.": "你本应:{title}{place}{with},时间是{at},已经过了,事情仍未了结。",
84
+ "You are due to: {title}{place}{with}, at {at}.": "你约定要:{title}{place}{with},时间是{at}。",
85
+ "What you are after:": "你想达成的事:",
86
+ ", by {deadline}, which has passed": ",限期{deadline},已过",
87
+ ", by {deadline}": ",限期{deadline}",
88
+ " Next: {plan}.": " 下一步:{plan}。",
89
+ "How you stand with people who bear on this moment (your own view, not objective fact):": "你与和此刻相关的人的关系(是你自己的看法,不是客观事实):",
90
+ " (here)": "(在场)",
91
+ " (not here)": "(不在场)",
92
+ "knows them well": "很了解对方",
93
+ "barely knows them": "几乎不了解对方",
94
+ "trusts them": "信任对方",
95
+ "distrusts them": "不信任对方",
96
+ "is fond of them": "喜欢对方",
97
+ "dislikes them": "不喜欢对方",
98
+ "things are strained between them": "彼此关系紧张",
99
+ "Your affiliations (their goals are pressures and commitments, not commands):": "你的所属组织(其目标是压力和承诺,不是命令):",
100
+ "member": "成员",
101
+ " Goals: {goals}.": " 目标:{goals}。",
102
+ "- {name}: {position}; {status}; commitment {commitment}.": "- {name}:{position};{status};投入程度 {commitment}。",
103
+ " Your view: {attitude}.": " 你的看法:{attitude}。",
104
+ "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):": "你记得的、与此相关的事(只限你自己亲身经历的;不要声称记得更多,模糊的地方要保持不确定):",
105
+ "What you remember that bears on this: nothing comes to mind.": "你记得的、与此相关的事:想不起任何事。",
106
+ "some time ago": "一段时间以前",
107
+ "just now": "刚才",
108
+ "1 day ago": "1天前",
109
+ "{amount} days ago": "{amount}天前",
110
+ "1 hour ago": "1小时前",
111
+ "{amount} hours ago": "{amount}小时前",
112
+ "1 minute ago": "1分钟前",
113
+ "{amount} minutes ago": "{amount}分钟前",
114
+ "the details are fuzzy": "细节已经模糊",
115
+ "you barely remember": "你几乎记不清了",
116
+ "you are sure of it": "你对此确信无疑",
117
+ "you doubt it": "你对此存疑",
118
+ "something you have seen since speaks against it": "此后你所见所闻有与之相悖的地方",
119
+ "it comes to mind with the rest": "它和其余的事一起浮现在脑海",
120
+ "Earlier in this scene, before this moment:": "这一幕此刻之前发生的事:",
121
+ "What just happened, and what you are reacting to:": "刚才发生的事,以及你在回应的是什么:",
122
+ "- {name} intended: {intent} ({result}) {summary}": "- {name}打算:{intent}({result}){summary}",
123
+ "- {name} said \"{utterance}\" and intended: {intent} ({result}) {summary}": "- {name}说了“{utterance}”,并打算:{intent}({result}){summary}",
124
+ "Your earlier intent did not work out: {intent}\nYou are trying again, knowing the above. Decide again what you do now.": "你先前的打算没有成功:{intent}\n你带着上面这些再试一次。重新决定你现在做什么。",
125
+ "Character: {name}{summary}": "角色:{name}{summary}",
126
+ "What they believe now:": "他们现在的看法:",
127
+ "(nothing yet)": "(暂时没有)",
128
+ "What they have taken in since:": "他们此后经历的事:",
129
+ "Sort their memory.": "请整理他们的记忆。",
130
+ "not acceptable: {problems}": "不可接受:{problems}",
131
+ "{kind}, importance {importance}, {confidence}{about}{dispute}": "{kind},重要性 {importance},{confidence}{about}{dispute}",
132
+ ", about {names}": ",关于{names}",
133
+ ", something taken in since speaks against it": ",此后经历的事与之相悖",
134
+ "add: at most {max} new beliefs in one pass; merge or choose": "add:一次最多 {max} 条新看法;请合并或取舍",
135
+ "at most {max} changes in one pass": "一次最多 {max} 处修改",
136
+ "{where}: there is no thing it took in numbered {id}": "{where}:没有编号为 {id} 的经历",
137
+ "{where}: confidence is one of {options}": "{where}:confidence 须为 {options} 之一",
138
+ "{where}: unknown kind \"{kind}\"": "{where}:未知的 kind “{kind}”",
139
+ "{where}: say what it believes": "{where}:请写出它相信什么",
140
+ "{where}: at most {max} characters; say it shorter": "{where}:最多 {max} 个字符;请写得更短",
141
+ "{where}: importance runs from {min} to {max}": "{where}:importance 取值为 {min} 到 {max}",
142
+ "{where}: there is no belief numbered {id}": "{where}:没有编号为 {id} 的看法",
143
+ "{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}:一个转瞬即逝的瞬间还不是看法;请以至少两个不同回合的经历为依据,或以一件扭转了故事的事件为依据",
144
+ "{where}: to be sure of something it must rest on things from at least two different turns": "{where}:要对某事确信,必须以至少两个不同回合的经历为依据",
145
+ "{where}: \"{name}\" is not a character; name them as they are named": "{where}:“{name}”不是角色;请使用他们的名字",
146
+ "say in a sentence what the belief claims and what the things say, before the verdict": "先用一句话说明这个看法主张什么、这些内容说了什么,再给出判断",
147
+ "the verdict is consistent or contradicted": "判断是 consistent 或 contradicted",
148
+ "a belief that can be true together with all of them names none of them": "与它们全都可以同时成立的看法,不应列出其中任何一条",
149
+ "name the things that cannot be true together with the belief": "写出与这个看法不可能同时成立的内容",
150
+ "there is no thing listed numbered {id}": "列出的内容里没有编号为 {id} 的",
151
+ "thing {id} came before the belief was formed": "内容 {id} 出现在这个看法形成之前",
152
+ "A belief held by {name}: {text}": "{name} 持有的一个看法:{text}",
153
+ "What they took in since that bears on it:": "此后他们接收到的、与之有关的内容:",
154
+ "Can the belief and each of these be true together? Name the ones that cannot be.": "这个看法与其中每一件事能否同时成立?指出不能同时成立的。",
155
+ "{names} could not be sorted this time and will be tried again: {reason}": "{names} 这一次没能整理,下次会再试:{reason}",
156
+ "{where}: belief {id} is already changed in this pass": "{where}:看法 {id} 在这一轮中已经修改过",
157
+ "{where}: say what it took in since that bears on it": "{where}:请写出此后与之相关的经历",
158
+ "{where}: thing {id} came before the belief was formed; cite what came after": "{where}:经历 {id} 发生在看法形成之前;请引用之后发生的事",
159
+ "{where}: say what changes": "{where}:请写出有何改变",
160
+ "{where}: the text must be there and at most {max} characters; leave it out to keep the belief as it is": "{where}:文字不能为空,且最多 {max} 个字符;想保持信念原样就不要写这一项",
161
+ "{where}: the confidence, the importance and the numbers are fields of their own, not part of the text": "{where}:把握程度、重要性和编号是各自独立的字段,不属于文字",
162
+ "{where}: name what speaks against the belief in contradicted_by": "{where}:在 contradicted_by 里写出与该信念相悖的内容的编号",
163
+ "{where}: a belief that something contradicts must be doubted: lower its confidence": "{where}:被事实相悖的看法必须存疑:请降低其 confidence",
164
+ "{where}: to doubt a belief, name what contradicts it in contradicted_by": "{where}:要对看法存疑,请在 contradicted_by 中写明与之相悖的经历",
165
+ "{where}: merge into a belief that stays": "{where}:请合并到保留的看法中",
166
+ "Time: {time}.": "时间:{time}。",
167
+ "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 可以跳过一段时间。",
168
+ "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}的真实时间,其间故事仍在继续:角色们各忙各的事,除非记录另有说明,不要假定任何人还在玩家离开时的位置或状态。",
169
+ "The story's time follows the real clock: it cannot be skipped, and each round takes as long as it really took.": "故事时间跟随真实时钟:无法跳过,每一轮耗时就是它实际花费的时间。",
170
+ "By their routines since you last looked: {moves}.": "按各自的日程,自你上次查看以来:{moves}。",
171
+ "{name} went to {place} ({activity})": "{name}去了{place}({activity})",
172
+ "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}。是否照日程行事由角色自己决定;当下的情形也可能拖住他们。",
173
+ ", at {place}": ",在{place}",
174
+ "\"{title}\" ({with}{place}) was due {when} and is still open": "“{title}”({with}{place})原定{when},仍未了结",
175
+ "\"{title}\" ({with}{place}) is due {when}": "“{title}”({with}{place})定于{when}",
176
+ "Commitments due soon or overdue: {entries}.": "即将到期或已逾期的约定:{entries}。",
177
+ "named in the move": "被这一步行动点到",
178
+ "in the scene": "在场",
179
+ "own goal: {goal}": "自身目标:{goal}",
180
+ "faction pressure: {goal}": "组织压力:{goal}",
181
+ "high tension toward the player": "对玩家高度紧张",
182
+ "distrusts the player": "不信任玩家",
183
+ "cares about the player": "在意玩家",
184
+ "dislikes the player": "不喜欢玩家",
185
+ "Likely characters to activate, in priority order (advice only; activate only whoever the moment actually reaches):": "可能需要启动的角色,按优先级排列(仅供参考;只启动当下真正牵涉到的人):",
186
+ "socially implicated": "社交上被牵涉",
187
+ "The player's character is in {place}": "玩家角色在{place}",
188
+ "Characters here:": "在这里的角色:",
189
+ "Characters elsewhere (they perceive nothing here unless the moment reaches them):": "在别处的角色(除非当下波及他们,否则感知不到这里的事):",
190
+ "{member} - in {place} ({key})": "{member} - 在{place}({key})",
191
+ "Characters with no place (not part of this scene; they cannot be asked to act):": "没有所在地点的角色(不属于这一幕;不能让他们行动):",
192
+ "the player's character, \"{key}\"": "玩家角色,“{key}”",
193
+ "acts through \"{key}\"": "通过“{key}”行动",
194
+ "Currently: {state}": "目前:{state}",
195
+ "Scene before turn {turn}:": "第 {turn} 回合之前的场景:",
196
+ "What characters have on them:": "角色们身上带着:",
197
+ "The world acted since the last turn, by itself:": "自上一回合以来,世界自行发生的事:",
198
+ "Known beforehand, still to come (who knows of it; it will happen by itself when its time comes):": "事先已知、尚未发生的事(谁知道;时候到了会自行发生):",
199
+ "[known to {who}]": "[知情者:{who}]",
200
+ "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 中说明已处理(每条会保留几个回合,之后放弃):",
201
+ "What the story keeps track of (change it with variable_changes in an outcome when what happened calls for it):": "故事追踪的内容(发生的事需要时,在结果中用 variable_changes 修改):",
202
+ "Still open in the story:": "故事中仍未了结的事:",
203
+ "Earlier events that bear on what the player just did (from the records of the story):": "与玩家刚才的行动相关的早先事件(来自故事记录):",
204
+ "turn {turn}": "第 {turn} 回合",
205
+ "You were to {title}, at {when}": "你本应{title},时间是{when}",
206
+ "You were to {title} at {place}, at {when}": "你本应在{place}:{title},时间是{when}",
207
+ " ({note})": "({note})",
208
+ "It is {now} now and the time has passed.": "现在是{now},时间已经过了。",
209
+ "It is {now} now.": "现在是{now}。",
210
+ "It was with: {who}.": "同你一起的有:{who}。",
211
+ "You are not with the player's character, and nothing of this happens in front of anyone: decide what you do about it.": "你不和玩家的角色在一起,这件事也不会发生在任何人面前:决定你要怎么处理。",
212
+ "The time you had for \"{goal}\" has passed ({when}; it is {now} now)": "你为“{goal}”预留的时间已过({when};现在是{now})",
213
+ "You are not with the player's character and nothing of this happens in front of anyone: decide what you do about it.": "你不和玩家的角色在一起,这件事也不会发生在任何人面前:决定你要怎么处理。",
214
+ "{names} noticed: {text}": "{names}注意到:{text}",
215
+ "{name} went to {place}.": "{name}去了{place}。",
216
+ "## MCP resource servers\n\nUse {tools} with the server argument naming an MCP server.": "## MCP 资源服务器\n\n使用 {tools},server 参数填 MCP 服务器的名称。",
217
+ "## MCP resource servers\n\nUse {tools} with one of these names as the server argument: {servers}.": "## MCP 资源服务器\n\n使用 {tools},server 参数填下列名称之一:{servers}。",
218
+ "{where}: the text is longer than {max} characters. A belief is not rewritten to hold what speaks against it: leave the text out and list the belief under doubt with the numbers of what speaks against it, and put what was learned as a new belief of its own": "{where}:文字超过 {max} 个字符。不要通过改写信念来容纳与之相悖的事:不要写文字,把这条信念列入 doubt 并给出与之相悖的编号;新了解到的内容另写成一条新信念"
219
+ };
220
+ //#endregion
221
+ //#region ../dsh-roleplay-model/src/messages.ts
222
+ /** The language a setting such as `zh-CN` or `en` stands for; English when it is none that is known. */
223
+ function languageOf(code) {
224
+ return (code ?? "").trim().toLowerCase().startsWith("zh") ? "zh" : "en";
225
+ }
226
+ const fill = (template, values) => values === void 0 ? template : template.replace(/\{(\w+)\}/g, (whole, name) => name in values ? String(values[name]) : whole);
227
+ const CATALOGUES = { zh: ZH };
228
+ /**
229
+ * 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
230
+ * the others; a text a language lacks is told in English, and a test keeps that from happening.
231
+ */
232
+ function translator(language) {
233
+ const catalogue = language === "en" ? void 0 : CATALOGUES[language];
234
+ return (text, values) => fill(catalogue?.[text] ?? text, values);
235
+ }
236
+ //#endregion
237
+ //#region src/host/orchestration/protocol.ts
238
+ const COMMITMENTS = [
239
+ "low",
240
+ "medium",
241
+ "high"
242
+ ];
243
+ const RESULTS = [
244
+ "succeeded",
245
+ "partial",
246
+ "failed"
247
+ ];
248
+ const MAX_ACCOUNT = 300;
249
+ /**
250
+ * 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.
251
+ * A character of a script written without spaces says more in fewer.
252
+ */
253
+ const ANSWER_LIMITS = {
254
+ en: {
255
+ thought: 240,
256
+ intent: 300,
257
+ utterance: 600,
258
+ account: MAX_ACCOUNT
259
+ },
260
+ zh: {
261
+ thought: 100,
262
+ intent: 120,
263
+ utterance: 240,
264
+ account: 120
265
+ }
266
+ };
267
+ const answerLimits = (language) => language.toLowerCase().startsWith("zh") ? ANSWER_LIMITS.zh : ANSWER_LIMITS.en;
268
+ /** What the answer of a character comes to at most, in tokens (an answer about what happened out of sight has its account too). */
269
+ function answerEstimate(language, away) {
270
+ const limits = answerLimits(language);
271
+ return estimateAnswer([
272
+ limits.thought,
273
+ limits.intent,
274
+ limits.utterance,
275
+ ...away ? [limits.account] : []
276
+ ], language);
277
+ }
278
+ /**
279
+ * 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
280
+ * 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).
281
+ */
282
+ const CHARACTER_ACTION_SCHEMA = {
283
+ type: "object",
284
+ properties: {
285
+ thought: {
286
+ type: "string",
287
+ 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."
288
+ },
289
+ intent: {
290
+ type: "string",
291
+ description: "What the character does, or tries to do, now, as an action in one or two sentences, without any speech."
292
+ },
293
+ utterance: {
294
+ type: "string",
295
+ 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."
296
+ },
297
+ commitment: {
298
+ type: "string",
299
+ enum: [...COMMITMENTS],
300
+ description: "How hard the character will keep trying if this does not work out: low gives up at once, high persists."
301
+ }
302
+ },
303
+ required: [
304
+ "thought",
305
+ "intent",
306
+ "commitment"
307
+ ],
308
+ additionalProperties: false
309
+ };
310
+ /** 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. */
311
+ const AWAY_ACTION_SCHEMA = {
312
+ ...CHARACTER_ACTION_SCHEMA,
313
+ properties: {
314
+ ...CHARACTER_ACTION_SCHEMA.properties,
315
+ account: {
316
+ type: "string",
317
+ 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."
318
+ }
319
+ },
320
+ required: [
321
+ "thought",
322
+ "intent",
323
+ "commitment",
324
+ "account"
325
+ ]
326
+ };
327
+ /** @throws {Error} when the value is not a character action. */
328
+ const QUOTE_PAIRS = [
329
+ ["\"", "\""],
330
+ ["“", "”"],
331
+ ["「", "」"],
332
+ ["『", "』"],
333
+ ["«", "»"],
334
+ ["‘", "’"]
335
+ ];
336
+ /** Words said aloud, without the quotation marks a model puts around them: the output puts its own. */
337
+ function unquoted(text) {
338
+ let words = text.trim();
339
+ for (let again = true; again;) {
340
+ again = false;
341
+ 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)) {
342
+ words = words.slice(open.length, words.length - close.length).trim();
343
+ again = true;
344
+ }
345
+ }
346
+ return words;
347
+ }
348
+ const LEAKED_FIELD = /<\/?(?:intent|parameter(?:=\w+)?)>/g;
349
+ /** A model that writes the markup of its call into a field puts the next field's text inside this one. */
350
+ function splitLeakedFields(intent) {
351
+ const at = intent.search(/<parameter=utterance>/);
352
+ if (at === -1) return { intent: intent.replace(LEAKED_FIELD, " ") };
353
+ const spoken = intent.slice(at).replace(LEAKED_FIELD, " ").trim();
354
+ return {
355
+ intent: intent.slice(0, at).replace(LEAKED_FIELD, " "),
356
+ ...spoken === "" ? {} : { utterance: spoken }
357
+ };
358
+ }
359
+ function parseCharacterAction(value) {
360
+ if (typeof value !== "object" || value === null) throw new Error("the character did not answer with an object");
361
+ const { intent: rawIntent, utterance: rawUtterance, commitment, account } = value;
362
+ const { intent, utterance } = typeof rawIntent === "string" && rawUtterance === void 0 ? splitLeakedFields(rawIntent) : {
363
+ intent: rawIntent,
364
+ utterance: rawUtterance
365
+ };
366
+ if (typeof intent !== "string" || intent.trim() === "") throw new Error("the character gave no intent");
367
+ if (!COMMITMENTS.includes(commitment)) throw new Error(`the character gave an unknown commitment "${String(commitment)}"`);
368
+ if (utterance !== void 0 && typeof utterance !== "string") throw new Error("the character's utterance is not text");
369
+ const spoken = utterance === void 0 ? void 0 : unquoted(utterance);
370
+ const told = typeof account === "string" ? account.trim().slice(0, MAX_ACCOUNT) : "";
371
+ return {
372
+ intent: intent.trim(),
373
+ ...spoken === void 0 || spoken === "" ? {} : { utterance: spoken },
374
+ commitment,
375
+ ...told === "" ? {} : { account: told }
376
+ };
377
+ }
378
+ //#endregion
379
+ //#region src/host/clock/story-clock.ts
380
+ var ClockError = class extends Error {};
381
+ /** 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. */
382
+ function describeWhen(instant, now, zone, language = "en") {
383
+ const a = localTime(instant, zone);
384
+ const b = localTime(now, zone);
385
+ return a.year === b.year && a.month === b.month && a.day === b.day ? clockTime(instant, zone) : describeInstant(instant, zone, language);
386
+ }
387
+ /**
388
+ * 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
389
+ * fall on the day.
390
+ */
391
+ function describeTime(time, language = "en") {
392
+ const { calendar } = time;
393
+ const tr = translator(language);
394
+ const base = `${describeInstant(time.now, time.zone, language)} (${tr(dayPart(localTime(time.now, time.zone).minuteOfDay))})`;
395
+ if (calendar === void 0 || calendar.holidays.length === 0 && calendar.hemisphere === "north") return base;
396
+ const day = addLocalDays(time.now, time.zone, 0);
397
+ const holidays = holidaysOn(calendar, day).map((holiday) => holiday.name);
398
+ return `${base}${tr(", ")}${tr(seasonOf(day, calendar.hemisphere))}${holidays.length === 0 ? "" : `${tr("; ")}${tr("today is {holidays}", { holidays: holidays.join(tr(", ")) })}`}`;
399
+ }
400
+ /** The time zone the story is read in. */
401
+ const zoneOf = (config) => config.timeZone === "" ? "UTC" : config.timeZone;
402
+ /** 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. */
403
+ function ensure(session, config, turn, wall) {
404
+ const current = session.clock.get();
405
+ if (current === void 0) {
406
+ session.clock.start(config.mode, config.mode === "real" ? wall : Math.floor(wall / MINUTE) * MINUTE);
407
+ return session.clock.get() ?? {
408
+ mode: config.mode,
409
+ now: wall
410
+ };
411
+ }
412
+ if (current.mode !== "real" || config.mode !== "simulated") return current;
413
+ session.clock.resync("simulated", Math.max(current.now, wall), turn, "the story's time was detached from the real clock");
414
+ return session.clock.get() ?? current;
415
+ }
416
+ function timeOf(session, state, config) {
417
+ const calendar = session.metadata === void 0 ? void 0 : readCalendar(session.metadata);
418
+ return {
419
+ mode: state.mode,
420
+ now: state.now,
421
+ zone: zoneOf(config),
422
+ ...calendar === void 0 || calendar.holidays.length === 0 && calendar.hemisphere === "north" ? {} : { calendar }
423
+ };
424
+ }
425
+ /** What time it is, without letting any pass. */
426
+ function readTime(session, config, turn, wall) {
427
+ return session.transaction(() => timeOf(session, ensure(session, config, turn, wall), config));
428
+ }
429
+ /**
430
+ * The start of a turn. Following the wall clock, the time since the last turn passed outside the story:
431
+ * `away` says how long.
432
+ */
433
+ function beginTurn(session, config, turn, wall) {
434
+ return session.transaction(() => {
435
+ const state = ensure(session, config, turn, wall);
436
+ if (state.mode === "real" && wall > state.now) {
437
+ session.clock.advance({
438
+ to: wall,
439
+ turn,
440
+ round: 0,
441
+ kind: "real",
442
+ reason: "between turns"
443
+ });
444
+ return {
445
+ time: timeOf(session, {
446
+ mode: "real",
447
+ now: wall
448
+ }, config),
449
+ away: wall - state.now
450
+ };
451
+ }
452
+ return { time: timeOf(session, state, config) };
453
+ });
454
+ }
455
+ /**
456
+ * A round passes. Simulated, it takes what the game master said (or the default), and at least as long as the
457
+ * journey the player's character made (`minimum`); following the wall clock, it takes as long as it took.
458
+ */
459
+ function endRound(session, config, turn, round, wall, stated, minimum) {
460
+ return session.transaction(() => {
461
+ const state = ensure(session, config, turn, wall);
462
+ if (state.mode === "real") {
463
+ const to = Math.max(state.now, wall);
464
+ session.clock.advance({
465
+ to,
466
+ turn,
467
+ round,
468
+ kind: "real"
469
+ });
470
+ return {
471
+ from: state.now,
472
+ to,
473
+ zone: zoneOf(config)
474
+ };
475
+ }
476
+ const took = Math.max(stated ?? config.roundSeconds, minimum ?? 0) * SECOND;
477
+ session.clock.advance({
478
+ to: state.now + took,
479
+ turn,
480
+ round,
481
+ kind: "elapsed"
482
+ });
483
+ return {
484
+ from: state.now,
485
+ to: state.now + took,
486
+ zone: zoneOf(config)
487
+ };
488
+ });
489
+ }
490
+ /**
491
+ * Skip ahead in the story's own time.
492
+ * @throws {ClockError} when time follows the wall clock, the request is not one, or it asks for more than the chat allows.
493
+ */
494
+ function skipTime(session, config, turn, round, wall, request) {
495
+ return session.transaction(() => {
496
+ const state = ensure(session, config, turn, wall);
497
+ if (state.mode === "real") throw new ClockError("the story's time follows the wall clock, so it cannot be skipped");
498
+ const zone = zoneOf(config);
499
+ const reason = request.reason.trim();
500
+ if (reason === "") throw new ClockError("say what happens in the time that passes (reason)");
501
+ let to;
502
+ if ("byMinutes" in request) {
503
+ if (!Number.isInteger(request.byMinutes) || request.byMinutes < 1) throw new ClockError("by_minutes must be a whole number of minutes, at least 1");
504
+ to = state.now + request.byMinutes * MINUTE;
505
+ } else try {
506
+ to = nextTimeOfDay(state.now, zone, request.untilTime, request.daysLater);
507
+ } catch (error) {
508
+ throw new ClockError(error instanceof RangeError ? error.message : String(error));
509
+ }
510
+ 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`);
511
+ session.clock.advance({
512
+ to,
513
+ turn,
514
+ round,
515
+ kind: "skip",
516
+ reason
517
+ });
518
+ return {
519
+ from: state.now,
520
+ to,
521
+ zone,
522
+ reason
523
+ };
524
+ });
525
+ }
526
+ //#endregion
527
+ //#region src/host/orchestration/observation.ts
528
+ /** 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. */
529
+ function observeSurroundings(session, characterId, turn) {
530
+ const placement = session.placements.get("character", characterId);
531
+ if (placement !== void 0) {
532
+ session.knowledge.learn(characterId, "location", placement.locationId, turn, true);
533
+ for (const exit of session.locations.exitsFrom(placement.locationId)) {
534
+ session.knowledge.learn(characterId, "exit", exit.id, turn, true);
535
+ session.knowledge.learn(characterId, "location", exit.toId, turn);
536
+ }
537
+ for (const { item } of session.items.contents({
538
+ kind: "location",
539
+ id: placement.locationId
540
+ })) if (!item.hidden) session.knowledge.learn(characterId, "item", item.id, turn, true);
541
+ }
542
+ for (const { item } of session.items.contents({
543
+ kind: "character",
544
+ id: characterId
545
+ })) session.knowledge.learn(characterId, "item", item.id, turn, true);
546
+ }
547
+ /**
548
+ * 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
549
+ * how it comes to know the way back from where it went.
550
+ */
551
+ function observeAsPlayer(session, turn) {
552
+ const player = session.characters.list().find((character) => character.control === "player");
553
+ if (player !== void 0) observeSurroundings(session, player.id, turn);
554
+ }
555
+ //#endregion
556
+ //#region src/shared/notes.ts
557
+ /** The kinds the host stores; `unwritten` is made when the notes are read, from the rounds still waiting for the record keeper. */
558
+ const NOTE_KINDS = [
559
+ "suggestions",
560
+ "away",
561
+ "world"
562
+ ];
563
+ //#endregion
564
+ //#region src/host/sessions/notes.ts
565
+ const KEY$2 = "notes";
566
+ const isNote = (value) => {
567
+ if (typeof value !== "object" || value === null) return false;
568
+ const note = value;
569
+ return NOTE_KINDS.includes(note["kind"]) && typeof note["turn"] === "number" && Array.isArray(note["lines"]) && note["lines"].every((line) => typeof line === "string");
570
+ };
571
+ /** The notes of a session, at most one per kind. */
572
+ function readNotes(session) {
573
+ const stored = session.metadata.getValue(KEY$2);
574
+ return Array.isArray(stored) ? stored.filter(isNote) : [];
575
+ }
576
+ /** Replaces the note of the same kind. */
577
+ function putNote(session, note) {
578
+ session.metadata.setValue(KEY$2, [...readNotes(session).filter((existing) => existing.kind !== note.kind), note]);
579
+ }
580
+ /** The most lines one note keeps: what is past it is not told. */
581
+ const MAX_NOTE_LINES = 8;
582
+ /** Adds lines to the note of the kind when it is of the same turn, else starts it. */
583
+ function addToNote(session, kind, turn, lines) {
584
+ if (lines.length === 0) return;
585
+ putNote(session, {
586
+ kind,
587
+ turn,
588
+ lines: [...readNotes(session).find((note) => note.kind === kind && note.turn === turn)?.lines ?? [], ...lines].slice(0, MAX_NOTE_LINES)
589
+ });
590
+ }
591
+ /** Removes every note: they belong to the turn that made them. */
592
+ function clearNotes(session) {
593
+ if (readNotes(session).length > 0) session.metadata.setValue(KEY$2, []);
594
+ }
595
+ /**
596
+ * The notes of a session, for the player's screen.
597
+ * @throws {SessionNotFoundError} when the id names no session.
598
+ */
599
+ function notesOfSession(deps, id) {
600
+ if (!isSessionId(id) || !existsSync(sessionDatabase(deps.sessionsDir(), id))) throw new SessionNotFoundError(`no session "${id}"`);
601
+ const session = deps.open(id);
602
+ const waiting = session.pendingCommits?.list().length ?? 0;
603
+ return waiting === 0 ? readNotes(session) : [...readNotes(session), {
604
+ kind: "unwritten",
605
+ turn: 0,
606
+ lines: [],
607
+ count: waiting
608
+ }];
609
+ }
610
+ //#endregion
611
+ //#region src/shared/tools.ts
612
+ /** What this version can offer. A name in a settings file or a world that is not here is kept and ignored. */
613
+ const OPTIONAL_TOOLS = [
614
+ {
615
+ id: "roll_check",
616
+ agent: "gameMaster",
617
+ default: true
618
+ },
619
+ {
620
+ id: "roll_dice",
621
+ agent: "gameMaster",
622
+ default: true
623
+ },
624
+ {
625
+ id: "list_checks",
626
+ agent: "gameMaster",
627
+ default: true
628
+ },
629
+ {
630
+ id: "recall_my_memories",
631
+ agent: "characters",
632
+ default: true
633
+ },
634
+ {
635
+ id: "recall_my_known_entities",
636
+ agent: "characters",
637
+ default: true
638
+ },
639
+ {
640
+ id: "recall_my_lore",
641
+ agent: "characters",
642
+ default: true
643
+ },
644
+ {
645
+ id: "search_events",
646
+ agent: "records",
647
+ default: true
648
+ },
649
+ {
650
+ id: "list_threads",
651
+ agent: "records",
652
+ default: true
653
+ },
654
+ {
655
+ id: "list_relationships",
656
+ agent: "records",
657
+ default: true
658
+ },
659
+ {
660
+ id: "list_items",
661
+ agent: "records",
662
+ default: true
663
+ }
664
+ ];
665
+ /** 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. */
666
+ function toolEnabled(board, agent, id) {
667
+ const offered = OPTIONAL_TOOLS.find((tool) => tool.agent === agent && tool.id === id);
668
+ if (offered === void 0) return false;
669
+ return board[agent]?.[id] ?? offered.default;
670
+ }
671
+ /**
672
+ * 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
673
+ * they reach beyond the story (files, a shell, the web), and a name that no plugin registers now has no effect.
674
+ */
675
+ function externalEnabled(board, agent, name) {
676
+ return board[agent]?.[name] === true;
677
+ }
678
+ //#endregion
679
+ //#region src/shared/ooc.ts
680
+ /** 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. */
681
+ const OOC_COMMAND = /^\s*\/(ooc|ask)(?=\s|$)\s*([\s\S]*)$/i;
682
+ /** The command or question in a player's message, or nothing when the message is an ordinary action. The request may be empty. */
683
+ function parseOoc(text) {
684
+ const match = OOC_COMMAND.exec(text);
685
+ return match === null ? void 0 : {
686
+ request: (match[2] ?? "").trim(),
687
+ question: match[1].toLowerCase() === "ask"
688
+ };
689
+ }
690
+ /** The longest answer to an out-of-character question. */
691
+ const MAX_OOC_ANSWER = 1200;
692
+ //#endregion
693
+ //#region src/host/orchestration/character-runner.ts
694
+ /**
695
+ * Runs each character as a one-shot child of the game master. It is the character and nothing
696
+ * else: it knows what its brief gives it, and its only tool (when the chat allows it) reaches
697
+ * the memory of that character alone, so characters acting at the same time cannot see each
698
+ * other's memories.
699
+ */
700
+ function characterRunner(deps) {
701
+ return async (request, signal) => {
702
+ const brief = deps.boundaries().characterContext.brief(request);
703
+ const settings = deps.store.settings();
704
+ const tools = settings.memory.lookup ? createCharacterTools(() => ({
705
+ session: deps.store.story,
706
+ turn: request.turn,
707
+ policy: settings.memory,
708
+ queryVector: deps.store.queryVector
709
+ }), request.member.character.id).filter((tool) => toolEnabled(settings.tools, "characters", tool.name)) : [];
710
+ const external = externalGiven(deps.parent.ctx.tools, settings.tools, "characters");
711
+ const named = request.member.character.tier === "background" && settings.models.background.trim() !== "" ? settings.models.background : settings.models.characters;
712
+ return parseCharacterAction(await runChild({
713
+ parent: deps.parent,
714
+ signal,
715
+ sampling: childSampling(settings, "characters", answerEstimate(settings.prompts.language, request.away === true)),
716
+ ...childModel(settings, "characters", named),
717
+ trace: childTrace(deps.store, "characters", request.member.character.name, recalledOf(request), named),
718
+ reasoningEffort: deps.store.settings().reasoning.children,
719
+ persona: brief.persona,
720
+ prompt: brief.prompt,
721
+ tools,
722
+ external,
723
+ maxCalls: deps.store.settings().memory.lookupCalls + (external.length === 0 ? 0 : EXTERNAL_CALLS),
724
+ result: request.away === true ? AWAY_ACTION_SCHEMA : CHARACTER_ACTION_SCHEMA,
725
+ unenforced: ["thought"],
726
+ beforeSubmit: (value) => spokenIn(settings.prompts.language, value)
727
+ }));
728
+ };
729
+ }
730
+ /** What a character that was given tools of other plugins may call on top of its memory look-ups. */
731
+ const EXTERNAL_CALLS = 5;
732
+ /** 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. */
733
+ function spokenIn(language, value) {
734
+ const given = value;
735
+ return wrongLanguage(language, {
736
+ thought: given.thought,
737
+ intent: given.intent,
738
+ utterance: given.utterance,
739
+ account: given.account
740
+ });
741
+ }
742
+ /** What the character was reminded of and why, for the run's record, when the recall said why. */
743
+ function recalledOf(request) {
744
+ const explained = (request.memories ?? []).filter((memory) => memory.why !== void 0);
745
+ return explained.length === 0 ? {} : { recalled: explained.slice(0, 30).map(({ clarity, turn, text, why }) => ({
746
+ clarity,
747
+ turn,
748
+ text,
749
+ why
750
+ })) };
751
+ }
752
+ const ANSWER_SCHEMA = {
753
+ type: "object",
754
+ properties: { answer: {
755
+ type: "string",
756
+ description: "The answer to the player, in plain words, in a few sentences."
757
+ } },
758
+ required: ["answer"],
759
+ additionalProperties: false
760
+ };
761
+ /**
762
+ * 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
763
+ * game master alone knows is in the prompt, so the answer cannot give away what the character could not know.
764
+ */
765
+ function answerRunner(deps) {
766
+ return async (request, signal) => {
767
+ const brief = deps.boundaries().characterContext.brief(request);
768
+ return (await runChild({
769
+ parent: deps.parent,
770
+ signal,
771
+ sampling: childSampling(deps.store.settings(), "records", estimateAnswer([MAX_OOC_ANSWER], deps.store.settings().prompts.language)),
772
+ ...childModel(deps.store.settings(), "records"),
773
+ trace: childTrace(deps.store, "records", "answer to the player"),
774
+ reasoningEffort: deps.store.settings().reasoning.children,
775
+ persona: request.text("roleplay/ask-answerer", { name: request.member.character.name }),
776
+ prompt: brief.prompt,
777
+ tools: [],
778
+ maxCalls: 3,
779
+ result: ANSWER_SCHEMA
780
+ })).answer;
781
+ };
782
+ }
783
+ //#endregion
784
+ //#region src/host/orchestration/boundaries.ts
785
+ /** Why the game master may ask for something to be made up: the story genuinely needs it. */
786
+ const AUTHORING_NEEDS = [
787
+ "scene_change",
788
+ "arrival",
789
+ "introduction",
790
+ "object",
791
+ "variable",
792
+ "trigger"
793
+ ];
794
+ //#endregion
795
+ //#region src/host/pacing/director.ts
796
+ const PLOTS_METADATA_KEY = "roleplay.pacing.plots";
797
+ function populatePlots(metadata, plots) {
798
+ const progress = plots.map((plot) => ({
799
+ plot,
800
+ status: plot.start,
801
+ introduced: [],
802
+ rejected: [],
803
+ lastNudgeTurn: 0
804
+ }));
805
+ metadata.setValue(PLOTS_METADATA_KEY, progress);
806
+ }
807
+ function addSessionPlot(store, plot) {
808
+ const plots = progressOf(store);
809
+ if (plots.some((entry) => entry.plot.id === plot.id)) throw new Error(`there is already a plot "${plot.id}"`);
810
+ plots.push({
811
+ plot,
812
+ status: plot.start,
813
+ introduced: [],
814
+ rejected: [],
815
+ lastNudgeTurn: 0
816
+ });
817
+ store.story.metadata.setValue(PLOTS_METADATA_KEY, plots);
818
+ }
819
+ function plotAuthorNeeded(store, turn) {
820
+ if (progressOf(store).length > 0 || turn < 5) return false;
821
+ return store.story.events.list({
822
+ fromTurn: Math.max(1, turn - 2),
823
+ toTurn: turn - 1
824
+ }).length === 0 && store.story.threads.list("open").length === 0;
825
+ }
826
+ function plotProgressOf(metadata) {
827
+ const value = metadata.getValue(PLOTS_METADATA_KEY);
828
+ return Array.isArray(value) ? value : [];
829
+ }
830
+ function progressOf(store) {
831
+ return plotProgressOf(store.story.metadata);
832
+ }
833
+ /** Select one uncommitted possibility when the story has genuinely gone quiet; selection never makes it happen. */
834
+ function pacingAdvice(store, turn) {
835
+ const plots = progressOf(store);
836
+ if (plots.length === 0) return void 0;
837
+ const now = store.story.clock.get()?.now;
838
+ const recent = store.story.events.list({
839
+ fromTurn: Math.max(1, turn - 2),
840
+ toTurn: turn - 1
841
+ });
842
+ const openThreads = store.story.threads.list("open");
843
+ for (const progress of plots) {
844
+ if (![
845
+ "available",
846
+ "engaged",
847
+ "cooling"
848
+ ].includes(progress.status)) continue;
849
+ const quietTurns = progress.plot.pacing.quietTurns + (openThreads.length === 0 ? 0 : 2);
850
+ if (recent.length > 0 || turn <= quietTurns) continue;
851
+ if (turn - progress.lastNudgeTurn < progress.plot.pacing.cooldownTurns) continue;
852
+ if (now !== void 0 && progress.lastNudgeAt !== void 0 && now - progress.lastNudgeAt < progress.plot.pacing.cooldownDays * 864e5) continue;
853
+ 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];
854
+ if (step === void 0) continue;
855
+ const quietFor = turn - progress.lastNudgeTurn;
856
+ progress.lastNudgeTurn = turn;
857
+ if (now !== void 0) progress.lastNudgeAt = now;
858
+ progress.status = progress.status === "available" ? "engaged" : progress.status;
859
+ store.story.metadata.setValue(PLOTS_METADATA_KEY, plots);
860
+ return {
861
+ need: quietFor > progress.plot.pacing.quietTurns * 2 ? "clear" : "gentle",
862
+ 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",
863
+ plot: progress.plot.id,
864
+ plotName: progress.plot.name,
865
+ development: step.id,
866
+ mode: step.mode,
867
+ guidance: step.guidance || step.text,
868
+ avoid: step.avoid
869
+ };
870
+ }
871
+ }
872
+ function describePacingAdvice(advice) {
873
+ 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.`;
874
+ }
875
+ function updatePlotProgress(store, plotId, developmentId, action) {
876
+ const plots = progressOf(store);
877
+ const progress = plots.find((entry) => entry.plot.id === plotId);
878
+ if (progress === void 0) throw new Error(`there is no plot "${plotId}"`);
879
+ if (action === "resolved" || action === "abandoned") progress.status = action;
880
+ else {
881
+ if (developmentId === void 0) throw new Error(`${action} needs a development`);
882
+ if (![...progress.plot.hooks, ...progress.plot.developments].some((step) => step.id === developmentId)) throw new Error(`plot "${plotId}" has no development "${developmentId}"`);
883
+ const target = action === "introduced" ? progress.introduced : progress.rejected;
884
+ if (!target.includes(developmentId)) target.push(developmentId);
885
+ if (action === "introduced") progress.status = "engaged";
886
+ }
887
+ store.story.metadata.setValue(PLOTS_METADATA_KEY, plots);
888
+ return progress;
889
+ }
890
+ //#endregion
891
+ //#region src/host/pacing/author.ts
892
+ const RESULT = {
893
+ type: "object",
894
+ required: [
895
+ "id",
896
+ "name",
897
+ "premise",
898
+ "themes",
899
+ "hook",
900
+ "developments",
901
+ "stakes",
902
+ "resolutions",
903
+ "participants"
904
+ ],
905
+ additionalProperties: false,
906
+ properties: {
907
+ id: { type: "string" },
908
+ name: { type: "string" },
909
+ premise: { type: "string" },
910
+ themes: {
911
+ type: "array",
912
+ items: { type: "string" }
913
+ },
914
+ hook: {
915
+ type: "object",
916
+ required: [
917
+ "id",
918
+ "text",
919
+ "guidance",
920
+ "avoid"
921
+ ],
922
+ additionalProperties: false,
923
+ properties: {
924
+ id: { type: "string" },
925
+ text: { type: "string" },
926
+ guidance: { type: "string" },
927
+ avoid: {
928
+ type: "array",
929
+ items: { type: "string" }
930
+ }
931
+ }
932
+ },
933
+ developments: {
934
+ type: "array",
935
+ items: {
936
+ type: "object",
937
+ required: [
938
+ "id",
939
+ "text",
940
+ "mode",
941
+ "prerequisites",
942
+ "guidance",
943
+ "avoid"
944
+ ],
945
+ additionalProperties: false,
946
+ properties: {
947
+ id: { type: "string" },
948
+ text: { type: "string" },
949
+ mode: {
950
+ type: "string",
951
+ enum: [
952
+ "opportunity",
953
+ "reminder",
954
+ "character",
955
+ "consequence",
956
+ "escalation",
957
+ "breathing_room"
958
+ ]
959
+ },
960
+ prerequisites: {
961
+ type: "array",
962
+ items: { type: "string" }
963
+ },
964
+ guidance: { type: "string" },
965
+ avoid: {
966
+ type: "array",
967
+ items: { type: "string" }
968
+ }
969
+ }
970
+ }
971
+ },
972
+ stakes: {
973
+ type: "array",
974
+ items: { type: "string" }
975
+ },
976
+ resolutions: {
977
+ type: "array",
978
+ items: { type: "string" }
979
+ },
980
+ participants: {
981
+ type: "array",
982
+ items: { type: "string" }
983
+ }
984
+ }
985
+ };
986
+ /** A scaffold is about two dozen short texts: premise, hook, developments with their guidance, stakes and resolutions. */
987
+ const PLOT_TEXTS = 24;
988
+ const PLOT_TEXT_CHARS = 300;
989
+ async function authorPlot(parent, store, turn, signal) {
990
+ const cast = store.cast().map((member) => `${member.character.name} (${member.key}): ${member.character.summary}`).join("\n");
991
+ const factions = store.story.factions.list().map((faction) => `${faction.name} (${faction.sourceId ?? faction.id}): ${faction.summary}`).join("\n");
992
+ const places = store.story.locations.list().map((place) => `${place.name} (${place.sourceId ?? place.id})`).join(", ");
993
+ const events = store.story.events.list().slice(-12).map((event) => `- ${event.text}`).join("\n");
994
+ let checked;
995
+ const result = await runChild({
996
+ parent,
997
+ signal,
998
+ sampling: childSampling(store.settings(), "authoring", estimateAnswer(Array.from({ length: PLOT_TEXTS }, () => PLOT_TEXT_CHARS), store.settings().prompts.language)),
999
+ ...childModel(store.settings(), "authoring"),
1000
+ trace: childTrace(store, "authoring", "plot author"),
1001
+ persona: promptFor(parent, "roleplay/plot-author", store.settings().prompts.language),
1002
+ reasoningEffort: store.settings().reasoning.children,
1003
+ result: RESULT,
1004
+ maxCalls: 3,
1005
+ 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"}`,
1006
+ beforeSubmit(value) {
1007
+ const authored = value;
1008
+ const candidate = {
1009
+ ...authored,
1010
+ hooks: [{
1011
+ ...authored.hook,
1012
+ mode: "opportunity",
1013
+ prerequisites: []
1014
+ }],
1015
+ start: "available",
1016
+ pacing: {
1017
+ quietTurns: 3,
1018
+ cooldownTurns: 4,
1019
+ cooldownDays: 1
1020
+ }
1021
+ };
1022
+ const parsed = parsePlotsFile(JSON.stringify([candidate]));
1023
+ if (!parsed.ok) return parsed.issues.map((issue) => `${issue.path}: ${issue.message}`).join("\n");
1024
+ checked = parsed.value[0];
1025
+ }
1026
+ });
1027
+ if (checked === void 0) throw new Error(`the plot author returned an invalid plot: ${result.name}`);
1028
+ addSessionPlot(store, checked);
1029
+ return checked;
1030
+ }
1031
+ //#endregion
1032
+ //#region src/host/orchestration/tools.ts
1033
+ const ACTIVATE_TOOL = "activate_characters";
1034
+ const RESOLVE_TOOL = "resolve_round";
1035
+ const NARRATE_TOOL = "narrate";
1036
+ const RECORD_TOOL = "record_memory";
1037
+ const EXPAND_TOOL = "expand_world";
1038
+ const INTRODUCE_TOOL = "introduce_thing";
1039
+ const TIME_TOOL = "advance_time";
1040
+ const PREVIEW_TOOL = "preview_scene";
1041
+ const RULING_TOOL = "ooc_ruling";
1042
+ const ANSWER_TOOL = "ooc_answer";
1043
+ const JUDGE_TOOL = "judge_action";
1044
+ const PLOT_TOOL = "record_plot_progress";
1045
+ const AUTHOR_PLOT_TOOL = "author_plot";
1046
+ /** The JSON value the tool records; the model reads the rendered text. */
1047
+ function record(value) {
1048
+ return JSON.parse(JSON.stringify(value));
1049
+ }
1050
+ function failures(list) {
1051
+ return list.length === 0 ? [] : [
1052
+ "",
1053
+ "Could not act:",
1054
+ ...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}`)
1055
+ ];
1056
+ }
1057
+ function renderAttempt(attempt) {
1058
+ 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.";
1059
+ 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}]`);
1060
+ 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.`];
1061
+ return [
1062
+ heading,
1063
+ ...lines,
1064
+ ...failures(attempt.failures),
1065
+ ...next
1066
+ ].join("\n");
1067
+ }
1068
+ /** Who went where because their day says so. */
1069
+ const routineLine = (move) => `By their routine, ${move.name} is now at ${move.to} (${move.activity}).`;
1070
+ 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.";
1071
+ const listed = (utterances) => utterances.map((utterance) => `- ${utterance.character} (${utterance.name}), round ${utterance.round}: "${utterance.text}"`).join("\n");
1072
+ /** What the world did by itself, as the game master is told: what happened, what characters notice, and what it is to weave in. */
1073
+ function renderWorld(world) {
1074
+ return world.flatMap((entry) => [
1075
+ ...entry.events.map((text) => `The world acted (${entry.name}): ${text}`),
1076
+ ...entry.cues.map((cue) => `${cue.names.join(" and ")} will notice: ${cue.text}`),
1077
+ ...entry.beats.map((beat) => `Weave this into the story, then say you did with addressed: [${beat.id}] in narrate (${beat.text})`)
1078
+ ]);
1079
+ }
1080
+ function renderResolution(report) {
1081
+ if (report.next !== void 0) return renderAttempt(report.next);
1082
+ const done = report.done;
1083
+ if (done === void 0) return "";
1084
+ const left = done.limit - done.round;
1085
+ const passed = done.time.to - done.time.from;
1086
+ const lines = [
1087
+ `Round ${done.round} is recorded (${done.updated.join(", ")}).`,
1088
+ `It is now ${describeTime({
1089
+ now: done.time.to,
1090
+ zone: done.time.zone
1091
+ })}${passed > 0 ? `; ${describeDuration(passed)} passed` : ""}.`,
1092
+ ...done.moved.map(routineLine),
1093
+ ...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"})` : ""}.`),
1094
+ ...done.things.map((thing) => `${thing.name}: ${thing.summary}.`),
1095
+ ...done.variables.map((line) => `${line}.`),
1096
+ ...renderWorld(done.world),
1097
+ ...failures(done.retryFailures)
1098
+ ];
1099
+ 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)}`);
1100
+ 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.");
1101
+ 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.`);
1102
+ lines.push(OUTPUT_RULES);
1103
+ lines.push("Narrate only what the player's character can perceive.");
1104
+ return lines.join("\n");
1105
+ }
1106
+ function renderExpansion(report) {
1107
+ 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.`;
1108
+ const lines = report.created.map((entry) => `- ${entry.kind} ${entry.key} (${entry.name})`);
1109
+ const characters = report.created.filter((entry) => entry.kind === "character");
1110
+ return [
1111
+ "Made up and fitted into the world:",
1112
+ ...lines,
1113
+ ...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.`],
1114
+ ...report.declined === void 0 ? [] : [`Not made: ${report.declined}`]
1115
+ ].join("\n");
1116
+ }
1117
+ /** The tools the game master plays a turn with. */
1118
+ function createTools$1(deps) {
1119
+ const ownerOf = (agent) => {
1120
+ if (agent === void 0) throw new Error("the roleplay tools can only be called by an agent");
1121
+ return {
1122
+ agent,
1123
+ owner: {
1124
+ chat: agent.session.id,
1125
+ turn: deps.turnOf(agent)
1126
+ }
1127
+ };
1128
+ };
1129
+ const storeOf = (chat) => {
1130
+ const store = deps.stores(chat);
1131
+ if (store === void 0) throw new Error("this chat is not a roleplay session");
1132
+ return store;
1133
+ };
1134
+ const activate = defineTool({
1135
+ name: ACTIVATE_TOOL,
1136
+ 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.",
1137
+ parameters: {
1138
+ characters: {
1139
+ type: "array",
1140
+ required: true,
1141
+ items: { type: "string" },
1142
+ 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."
1143
+ },
1144
+ situation: {
1145
+ type: "string",
1146
+ required: true,
1147
+ 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."
1148
+ }
1149
+ },
1150
+ output: {
1151
+ schema: { type: "json" },
1152
+ render: (_args, value) => [{
1153
+ type: "text",
1154
+ text: renderAttempt(value)
1155
+ }]
1156
+ },
1157
+ isConcurrencySafe: () => false,
1158
+ async execute(args, exec) {
1159
+ const { agent, owner } = ownerOf(exec.agent);
1160
+ await deps.engine.settle(owner.chat, owner.turn);
1161
+ const run = characterRunner({
1162
+ parent: agent,
1163
+ boundaries: deps.boundaries,
1164
+ store: storeOf(owner.chat)
1165
+ });
1166
+ return record(await deps.engine.activate(owner, {
1167
+ situation: args.situation,
1168
+ characters: args.characters
1169
+ }, run, exec.signal));
1170
+ }
1171
+ });
1172
+ const resolve = defineTool({
1173
+ name: RESOLVE_TOOL,
1174
+ 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.",
1175
+ parameters: {
1176
+ outcomes: {
1177
+ type: "array",
1178
+ required: true,
1179
+ items: {
1180
+ type: "object",
1181
+ additionalProperties: false,
1182
+ properties: {
1183
+ character: {
1184
+ type: "string",
1185
+ required: true,
1186
+ 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."
1187
+ },
1188
+ result: {
1189
+ type: "string",
1190
+ required: true,
1191
+ enum: RESULTS,
1192
+ description: "Whether the character's intent went through."
1193
+ },
1194
+ summary: {
1195
+ type: "string",
1196
+ required: true,
1197
+ description: "What concretely happens to the character, in a sentence. It becomes what the character is doing."
1198
+ },
1199
+ roll: {
1200
+ type: "integer",
1201
+ 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."
1202
+ },
1203
+ spoken: {
1204
+ type: "boolean",
1205
+ description: "Whether the character gets to say its utterance. It does unless something prevents it, such as being silenced or knocked out first."
1206
+ },
1207
+ public_state: {
1208
+ type: "string",
1209
+ description: "What anyone present can now see or infer about the character, when that changed."
1210
+ },
1211
+ item_changes: {
1212
+ type: "array",
1213
+ 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.",
1214
+ items: {
1215
+ type: "object",
1216
+ additionalProperties: false,
1217
+ properties: {
1218
+ item: {
1219
+ type: "string",
1220
+ required: true,
1221
+ description: "The key of the item, as the scene lists it. Leave a way's lock to exit."
1222
+ },
1223
+ action: {
1224
+ type: "string",
1225
+ required: true,
1226
+ enum: ITEM_ACTIONS,
1227
+ 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)."
1228
+ },
1229
+ to: {
1230
+ type: "string",
1231
+ description: "For give: who gets it. For put: the container."
1232
+ },
1233
+ quantity: {
1234
+ type: "integer",
1235
+ description: "How many, of a pile; all when left out."
1236
+ },
1237
+ position: {
1238
+ type: "string",
1239
+ description: "Where, in words, for drop and put."
1240
+ },
1241
+ feature: {
1242
+ type: "string",
1243
+ description: "For drop: the feature of the place it is left at."
1244
+ },
1245
+ with: {
1246
+ type: "string",
1247
+ description: "For lock and unlock: the key item used. It has to be in hand and fit the lock."
1248
+ },
1249
+ exit: {
1250
+ type: "string",
1251
+ description: "For lock and unlock of a way instead of an item: the key of the place it leads to."
1252
+ },
1253
+ forced: {
1254
+ type: "boolean",
1255
+ description: "Only when the story breaks the lock (picked, smashed): no key is needed."
1256
+ }
1257
+ }
1258
+ }
1259
+ },
1260
+ variable_changes: {
1261
+ type: "array",
1262
+ 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).",
1263
+ items: {
1264
+ type: "object",
1265
+ additionalProperties: false,
1266
+ properties: {
1267
+ variable: {
1268
+ type: "string",
1269
+ required: true,
1270
+ description: "The key of the variable."
1271
+ },
1272
+ subject: {
1273
+ type: "string",
1274
+ required: true,
1275
+ description: "The key of the character, item or place it is about; world for the whole story."
1276
+ },
1277
+ to: {
1278
+ oneOf: [
1279
+ { type: "number" },
1280
+ { type: "boolean" },
1281
+ { type: "string" }
1282
+ ],
1283
+ description: "The new value."
1284
+ },
1285
+ by: {
1286
+ type: "number",
1287
+ description: "How much a number goes up (positive) or down (negative)."
1288
+ },
1289
+ baseline: {
1290
+ oneOf: [
1291
+ { type: "number" },
1292
+ { type: "boolean" },
1293
+ { type: "string" }
1294
+ ],
1295
+ description: "For a variable with a temperament (feelings): the new baseline, when what happened changes it lastingly."
1296
+ }
1297
+ }
1298
+ }
1299
+ },
1300
+ moves_to: {
1301
+ type: "object",
1302
+ additionalProperties: false,
1303
+ 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.",
1304
+ properties: {
1305
+ location: {
1306
+ type: "string",
1307
+ required: true,
1308
+ description: "The key of the place, as the scene lists it."
1309
+ },
1310
+ position: {
1311
+ type: "string",
1312
+ description: "Where in the place, in words: \"by the window\"."
1313
+ },
1314
+ feature: {
1315
+ type: "string",
1316
+ description: "The key of a feature of that place it is at."
1317
+ },
1318
+ ignore_exits: {
1319
+ type: "boolean",
1320
+ description: "Only when the story itself carries it (carried off, teleported, falls): the exits do not matter."
1321
+ }
1322
+ }
1323
+ }
1324
+ }
1325
+ }
1326
+ },
1327
+ elapsed_seconds: {
1328
+ type: "integer",
1329
+ 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."
1330
+ }
1331
+ },
1332
+ output: {
1333
+ schema: { type: "json" },
1334
+ render: (_args, value) => [{
1335
+ type: "text",
1336
+ text: renderResolution(value)
1337
+ }]
1338
+ },
1339
+ isConcurrencySafe: () => false,
1340
+ async execute(args, exec) {
1341
+ const { agent, owner } = ownerOf(exec.agent);
1342
+ await deps.engine.settle(owner.chat, owner.turn);
1343
+ const run = characterRunner({
1344
+ parent: agent,
1345
+ boundaries: deps.boundaries,
1346
+ store: storeOf(owner.chat)
1347
+ });
1348
+ const outcomes = args.outcomes.map((outcome) => ({
1349
+ character: outcome.character,
1350
+ result: outcome.result,
1351
+ summary: outcome.summary,
1352
+ ...outcome.public_state === void 0 ? {} : { publicState: outcome.public_state },
1353
+ ...outcome.spoken === void 0 ? {} : { spoken: outcome.spoken },
1354
+ ...outcome.roll === void 0 ? {} : { roll: outcome.roll },
1355
+ ...outcome.item_changes === void 0 || outcome.item_changes.length === 0 ? {} : { itemChanges: outcome.item_changes.map((change) => ({
1356
+ item: change.item,
1357
+ action: change.action,
1358
+ ...change.to === void 0 ? {} : { to: change.to },
1359
+ ...change.quantity === void 0 ? {} : { quantity: change.quantity },
1360
+ ...change.position === void 0 ? {} : { position: change.position },
1361
+ ...change.feature === void 0 ? {} : { feature: change.feature },
1362
+ ...change.with === void 0 ? {} : { with: change.with },
1363
+ ...change.exit === void 0 ? {} : { exit: change.exit },
1364
+ ...change.forced === true ? { forced: true } : {}
1365
+ })) },
1366
+ ...outcome.variable_changes === void 0 || outcome.variable_changes.length === 0 ? {} : { variableChanges: outcome.variable_changes.map((change) => ({
1367
+ variable: change.variable,
1368
+ subject: change.subject,
1369
+ ...change.to === void 0 ? {} : { to: change.to },
1370
+ ...change.by === void 0 ? {} : { by: change.by },
1371
+ ...change.baseline === void 0 ? {} : { baseline: change.baseline }
1372
+ })) },
1373
+ ...outcome.moves_to === void 0 ? {} : { moveTo: {
1374
+ location: outcome.moves_to.location,
1375
+ ...outcome.moves_to.position === void 0 ? {} : { position: outcome.moves_to.position },
1376
+ ...outcome.moves_to.feature === void 0 ? {} : { feature: outcome.moves_to.feature },
1377
+ ...outcome.moves_to.ignore_exits === true ? { ignoreExits: true } : {}
1378
+ } }
1379
+ }));
1380
+ return record(await deps.engine.resolve(owner, outcomes, run, exec.signal, args.elapsed_seconds));
1381
+ }
1382
+ });
1383
+ const narrate = defineTool({
1384
+ name: NARRATE_TOOL,
1385
+ 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.",
1386
+ parameters: {
1387
+ segments: {
1388
+ type: "array",
1389
+ description: "The output in order. Leave out only when a narrator other than you writes the output.",
1390
+ items: {
1391
+ type: "object",
1392
+ additionalProperties: false,
1393
+ properties: {
1394
+ type: {
1395
+ type: "string",
1396
+ required: true,
1397
+ enum: ["utterance", "narration"]
1398
+ },
1399
+ character: {
1400
+ type: "string",
1401
+ description: "For an utterance: the key of the character who says it."
1402
+ },
1403
+ text: {
1404
+ type: "string",
1405
+ required: true,
1406
+ description: "For an utterance: the words exactly as the character gave them, without quotation marks. For narration: what the player reads."
1407
+ }
1408
+ }
1409
+ }
1410
+ },
1411
+ addressed: {
1412
+ type: "array",
1413
+ items: { type: "integer" },
1414
+ 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."
1415
+ }
1416
+ },
1417
+ output: {
1418
+ schema: { type: "json" },
1419
+ render: (_args, value) => {
1420
+ const output = value;
1421
+ return [{
1422
+ type: "text",
1423
+ 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)}`
1424
+ }];
1425
+ }
1426
+ },
1427
+ isConcurrencySafe: () => false,
1428
+ async execute(args, exec) {
1429
+ const { agent, owner } = ownerOf(exec.agent);
1430
+ await deps.engine.settle(owner.chat, owner.turn);
1431
+ const segments = (args.segments ?? []).map((segment) => ({
1432
+ type: segment.type,
1433
+ text: segment.text,
1434
+ ...segment.character === void 0 ? {} : { character: segment.character }
1435
+ }));
1436
+ const output = await deps.engine.narrate(owner, segments, characterRunner({
1437
+ parent: agent,
1438
+ boundaries: deps.boundaries,
1439
+ store: storeOf(owner.chat)
1440
+ }), args.addressed ?? []);
1441
+ const timelineNode = deps.delivered?.(owner.chat, output);
1442
+ const delivered = timelineNode === void 0 ? output : {
1443
+ ...output,
1444
+ timelineNode
1445
+ };
1446
+ exec.concludeTurn();
1447
+ return record(delivered);
1448
+ }
1449
+ });
1450
+ const remember = defineTool({
1451
+ name: RECORD_TOOL,
1452
+ 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.",
1453
+ parameters: { focus: {
1454
+ type: "string",
1455
+ 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."
1456
+ } },
1457
+ output: {
1458
+ schema: { type: "json" },
1459
+ render: (_args, value) => [{
1460
+ type: "text",
1461
+ text: `The memory keeper is writing ${value.rounds} round${value.rounds === 1 ? "" : "s"} into the story's memory.`
1462
+ }]
1463
+ },
1464
+ isConcurrencySafe: () => false,
1465
+ execute(args, exec) {
1466
+ const { owner } = ownerOf(exec.agent);
1467
+ return Promise.resolve(record({ rounds: deps.engine.record(owner, args.focus) }));
1468
+ }
1469
+ });
1470
+ const plot = defineTool({
1471
+ name: PLOT_TOOL,
1472
+ 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.",
1473
+ parameters: {
1474
+ plot: {
1475
+ type: "string",
1476
+ required: true,
1477
+ description: "The plot id from the pacing opportunity."
1478
+ },
1479
+ development: {
1480
+ type: "string",
1481
+ description: "The development id; required for introduced or rejected."
1482
+ },
1483
+ action: {
1484
+ type: "string",
1485
+ required: true,
1486
+ enum: [
1487
+ "introduced",
1488
+ "rejected",
1489
+ "resolved",
1490
+ "abandoned"
1491
+ ]
1492
+ }
1493
+ },
1494
+ output: {
1495
+ schema: { type: "json" },
1496
+ render: (_args, value) => [{
1497
+ type: "text",
1498
+ text: `Plot pacing recorded: ${value.plot.name} is ${value.status}.`
1499
+ }]
1500
+ },
1501
+ isConcurrencySafe: () => false,
1502
+ execute(args, exec) {
1503
+ const { owner } = ownerOf(exec.agent);
1504
+ return Promise.resolve(record(updatePlotProgress(storeOf(owner.chat), args.plot, args.development, args.action)));
1505
+ }
1506
+ });
1507
+ const makePlot = defineTool({
1508
+ name: AUTHOR_PLOT_TOOL,
1509
+ 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.",
1510
+ parameters: {},
1511
+ output: {
1512
+ schema: { type: "json" },
1513
+ render: (_args, value) => {
1514
+ const made = value;
1515
+ return [{
1516
+ type: "text",
1517
+ 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.`
1518
+ }];
1519
+ }
1520
+ },
1521
+ isConcurrencySafe: () => false,
1522
+ async execute(_args, exec) {
1523
+ const { agent, owner } = ownerOf(exec.agent);
1524
+ const store = storeOf(owner.chat);
1525
+ 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");
1526
+ return record(await authorPlot(agent, store, owner.turn, exec.signal));
1527
+ }
1528
+ });
1529
+ const expand = defineTool({
1530
+ name: EXPAND_TOOL,
1531
+ 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.",
1532
+ parameters: {
1533
+ need: {
1534
+ type: "string",
1535
+ required: true,
1536
+ enum: AUTHORING_NEEDS,
1537
+ description: "Why: scene_change, arrival, introduction, object, variable or trigger."
1538
+ },
1539
+ what: {
1540
+ type: "string",
1541
+ required: true,
1542
+ 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."
1543
+ }
1544
+ },
1545
+ output: {
1546
+ schema: { type: "json" },
1547
+ render: (_args, value) => [{
1548
+ type: "text",
1549
+ text: renderExpansion(value)
1550
+ }]
1551
+ },
1552
+ isConcurrencySafe: () => false,
1553
+ async execute(args, exec) {
1554
+ const { owner } = ownerOf(exec.agent);
1555
+ await deps.engine.settle(owner.chat, owner.turn);
1556
+ return record(await deps.engine.expand(owner, {
1557
+ need: args.need,
1558
+ what: args.what
1559
+ }, exec.signal));
1560
+ }
1561
+ });
1562
+ const introduce = defineTool({
1563
+ name: INTRODUCE_TOOL,
1564
+ 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.",
1565
+ parameters: {
1566
+ name: {
1567
+ type: "string",
1568
+ required: true,
1569
+ description: "What it is called, as the story names it."
1570
+ },
1571
+ description: {
1572
+ type: "string",
1573
+ description: "One or two sentences: what it looks like, what it is made of, what state it is in."
1574
+ },
1575
+ quantity: {
1576
+ type: "integer",
1577
+ description: "How many, when it is a number of the same thing (default 1)."
1578
+ },
1579
+ quality: {
1580
+ type: "string",
1581
+ description: "Its condition in a word or two (rusty, new), when that matters."
1582
+ },
1583
+ notable: {
1584
+ type: "boolean",
1585
+ description: "Whether the characters present would notice it at once."
1586
+ },
1587
+ hidden: {
1588
+ type: "boolean",
1589
+ description: "Whether it starts out of sight (until a round reveals it)."
1590
+ },
1591
+ at: {
1592
+ type: "string",
1593
+ description: "The key of the place it lies in."
1594
+ },
1595
+ held_by: {
1596
+ type: "string",
1597
+ description: "The key of the character who holds it."
1598
+ },
1599
+ inside: {
1600
+ type: "string",
1601
+ description: "The key of the container it is in."
1602
+ }
1603
+ },
1604
+ output: {
1605
+ schema: { type: "json" },
1606
+ render: (_args, value) => {
1607
+ const made = value;
1608
+ return [{
1609
+ type: "text",
1610
+ text: `Introduced ${made.name} [${made.key}], ${made.where}. Use the key in item_changes; nobody has taken it up yet.`
1611
+ }];
1612
+ }
1613
+ },
1614
+ isConcurrencySafe: () => false,
1615
+ async execute(args, exec) {
1616
+ const { owner } = ownerOf(exec.agent);
1617
+ await deps.engine.settle(owner.chat, owner.turn);
1618
+ return record(deps.engine.introduce(owner, {
1619
+ name: args.name,
1620
+ ...args.description === void 0 ? {} : { description: args.description },
1621
+ ...args.quantity === void 0 ? {} : { quantity: args.quantity },
1622
+ ...args.quality === void 0 ? {} : { quality: args.quality },
1623
+ ...args.notable === void 0 ? {} : { notable: args.notable },
1624
+ ...args.hidden === void 0 ? {} : { hidden: args.hidden },
1625
+ ...args.at === void 0 ? {} : { at: args.at },
1626
+ ...args.held_by === void 0 ? {} : { heldBy: args.held_by },
1627
+ ...args.inside === void 0 ? {} : { inside: args.inside }
1628
+ }));
1629
+ }
1630
+ });
1631
+ const skip = defineTool({
1632
+ name: TIME_TOOL,
1633
+ 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.",
1634
+ parameters: {
1635
+ reason: {
1636
+ type: "string",
1637
+ required: true,
1638
+ description: "What happens in the time that passes, in a sentence (\"they sleep\", \"the ferry crosses\")."
1639
+ },
1640
+ by_minutes: {
1641
+ type: "integer",
1642
+ description: "How many minutes to skip."
1643
+ },
1644
+ until_time: {
1645
+ type: "string",
1646
+ 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."
1647
+ },
1648
+ days_later: {
1649
+ type: "integer",
1650
+ description: "With until_time: that many days after today (0 is later today, 1 is tomorrow)."
1651
+ }
1652
+ },
1653
+ output: {
1654
+ schema: { type: "json" },
1655
+ render: (_args, value) => {
1656
+ const done = value;
1657
+ return [{
1658
+ type: "text",
1659
+ text: `${describeDuration(done.to - done.from)} pass. It is now ${describeTime({
1660
+ now: done.to,
1661
+ zone: done.zone
1662
+ })}.${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")}`}`
1663
+ }];
1664
+ }
1665
+ },
1666
+ isConcurrencySafe: () => false,
1667
+ async execute(args, exec) {
1668
+ const { owner } = ownerOf(exec.agent);
1669
+ await deps.engine.settle(owner.chat, owner.turn);
1670
+ 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");
1671
+ if (args.days_later !== void 0 && args.until_time === void 0) throw new Error("days_later goes with until_time");
1672
+ const request = args.by_minutes !== void 0 ? {
1673
+ byMinutes: args.by_minutes,
1674
+ reason: args.reason
1675
+ } : {
1676
+ untilTime: args.until_time ?? "",
1677
+ ...args.days_later === void 0 ? {} : { daysLater: args.days_later },
1678
+ reason: args.reason
1679
+ };
1680
+ return record(deps.engine.advanceTime(owner, request));
1681
+ }
1682
+ });
1683
+ const preview = defineTool({
1684
+ name: PREVIEW_TOOL,
1685
+ 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.",
1686
+ parameters: { text: {
1687
+ type: "string",
1688
+ required: true,
1689
+ description: "The opening, plain prose in the narration voice."
1690
+ } },
1691
+ output: {
1692
+ schema: { type: "json" },
1693
+ render: (_args, value) => [{
1694
+ type: "text",
1695
+ text: `${encodePreview(value.text)}\nShown to the player. Now call activate_characters.`
1696
+ }]
1697
+ },
1698
+ isConcurrencySafe: () => false,
1699
+ execute(args, exec) {
1700
+ const { owner } = ownerOf(exec.agent);
1701
+ return Promise.resolve(record({ text: deps.engine.preview(owner, args.text) }));
1702
+ }
1703
+ });
1704
+ const ruling = defineTool({
1705
+ name: RULING_TOOL,
1706
+ 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.",
1707
+ parameters: {
1708
+ rule_check: {
1709
+ type: "string",
1710
+ required: true,
1711
+ 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."
1712
+ },
1713
+ legal: {
1714
+ type: "boolean",
1715
+ required: true,
1716
+ description: "Whether the command is allowed: false when any listed rule is broken."
1717
+ },
1718
+ reason: {
1719
+ type: "string",
1720
+ required: true,
1721
+ description: "To the player, in plain words and briefly: what you will do, or which rule it breaks."
1722
+ }
1723
+ },
1724
+ output: {
1725
+ schema: { type: "json" },
1726
+ render: (_args, value) => [{
1727
+ type: "text",
1728
+ 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.`
1729
+ }]
1730
+ },
1731
+ isConcurrencySafe: () => false,
1732
+ execute(args, exec) {
1733
+ const { owner } = ownerOf(exec.agent);
1734
+ return Promise.resolve(record(deps.engine.rule(owner, args.legal, args.reason)));
1735
+ }
1736
+ });
1737
+ const answer = defineTool({
1738
+ name: ANSWER_TOOL,
1739
+ 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.",
1740
+ parameters: {},
1741
+ output: {
1742
+ schema: { type: "json" },
1743
+ render: () => [{
1744
+ type: "text",
1745
+ text: `The player is shown the answer. Now call ${NARRATE_TOOL} with no segments.`
1746
+ }]
1747
+ },
1748
+ isConcurrencySafe: () => false,
1749
+ async execute(_args, exec) {
1750
+ const { agent, owner } = ownerOf(exec.agent);
1751
+ return record(await deps.engine.answer(owner, answerRunner({
1752
+ parent: agent,
1753
+ boundaries: deps.boundaries,
1754
+ store: storeOf(owner.chat)
1755
+ }), exec.signal));
1756
+ }
1757
+ });
1758
+ return [
1759
+ defineTool({
1760
+ name: JUDGE_TOOL,
1761
+ 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.",
1762
+ parameters: {
1763
+ rule_check: {
1764
+ type: "string",
1765
+ required: true,
1766
+ 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."
1767
+ },
1768
+ at: {
1769
+ type: "string",
1770
+ 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)."
1771
+ },
1772
+ allowed: {
1773
+ type: "boolean",
1774
+ required: true,
1775
+ description: "Whether what the character tries can work: false when any listed rule is broken or it is not viable."
1776
+ },
1777
+ uncertain: {
1778
+ type: "boolean",
1779
+ required: true,
1780
+ 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."
1781
+ },
1782
+ reason: {
1783
+ type: "string",
1784
+ required: true,
1785
+ description: "What the character tries, and the rule or the fact that decides it, in a sentence."
1786
+ }
1787
+ },
1788
+ output: {
1789
+ schema: { type: "json" },
1790
+ render: (_args, value) => [{
1791
+ type: "text",
1792
+ 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.`
1793
+ }]
1794
+ },
1795
+ isConcurrencySafe: () => false,
1796
+ execute(args, exec) {
1797
+ const { owner } = ownerOf(exec.agent);
1798
+ return Promise.resolve(record(deps.engine.judge(owner, args.allowed, args.reason, args.at, args.uncertain)));
1799
+ }
1800
+ }),
1801
+ preview,
1802
+ ruling,
1803
+ answer,
1804
+ activate,
1805
+ resolve,
1806
+ skip,
1807
+ remember,
1808
+ expand,
1809
+ introduce,
1810
+ makePlot,
1811
+ plot,
1812
+ narrate
1813
+ ];
1814
+ }
1815
+ //#endregion
1816
+ //#region src/host/tools/external.ts
1817
+ /** The reserved transport DSH presents tools through; it is never a tool of its own to switch. */
1818
+ const RESERVED = /* @__PURE__ */ new Set(["run_code"]);
1819
+ let own;
1820
+ /** The names of every tool this plugin and the state plugin register themselves: the story's own, which are not for switching here. */
1821
+ function ownToolNames() {
1822
+ own ??= /* @__PURE__ */ new Set([
1823
+ ...createTools(() => void 0, {
1824
+ write: true,
1825
+ authoring: true
1826
+ }).map((tool) => tool.name),
1827
+ ...createDiceTools(() => void 0).map((tool) => tool.name),
1828
+ ...createTools$1({}).map((tool) => tool.name)
1829
+ ]);
1830
+ return own;
1831
+ }
1832
+ /** 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. */
1833
+ function externalTools(registry) {
1834
+ const mine = ownToolNames();
1835
+ return registry.schemas().filter((tool) => !mine.has(tool.name) && !RESERVED.has(tool.name)).map((tool) => ({
1836
+ name: tool.name,
1837
+ description: tool.description
1838
+ })).sort((a, b) => a.name.localeCompare(b.name));
1839
+ }
1840
+ /** The external tools that are registered now and that an agent of this kind has been given. */
1841
+ function externalGiven(registry, board, agent) {
1842
+ return externalTools(registry).map((tool) => tool.name).filter((name) => externalEnabled(board, agent, name));
1843
+ }
1844
+ /** The external tools that are registered now and that an agent of this kind has not been given: they are taken away from it. */
1845
+ function externalWithheld(registry, board, agent) {
1846
+ return externalTools(registry).map((tool) => tool.name).filter((name) => !externalEnabled(board, agent, name));
1847
+ }
1848
+ //#endregion
1849
+ //#region src/host/sessions/activity.ts
1850
+ const KEY$1 = "activity";
1851
+ const isEntry = (value) => {
1852
+ if (typeof value !== "object" || value === null) return false;
1853
+ const entry = value;
1854
+ 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");
1855
+ };
1856
+ /** The recorded runs, oldest first. */
1857
+ function readActivity(session) {
1858
+ const stored = session.metadata.getValue(KEY$1);
1859
+ return Array.isArray(stored) ? stored.filter(isEntry) : [];
1860
+ }
1861
+ /** Files the run and returns the runs that fell off the end of the record to make room. */
1862
+ function recordActivity(session, entry) {
1863
+ const all = [...readActivity(session), entry];
1864
+ session.metadata.setValue(KEY$1, all.slice(-60));
1865
+ return all.slice(0, -60);
1866
+ }
1867
+ const RUN_FOLDER = "activity";
1868
+ const RUN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
1869
+ const runFile = (folder, run) => {
1870
+ if (!RUN_ID.test(run)) throw new RangeError(`"${run}" is not a run`);
1871
+ return join(folder, RUN_FOLDER, `${run}.json`);
1872
+ };
1873
+ /** 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. */
1874
+ function keepRunDetail(folder, run, detail) {
1875
+ const file = runFile(folder, run);
1876
+ mkdirSync(join(folder, RUN_FOLDER), { recursive: true });
1877
+ writeFileSync(`${file}.tmp`, JSON.stringify(detail));
1878
+ renameSync(`${file}.tmp`, file);
1879
+ }
1880
+ /** The stored detail of a run, or nothing when it was not kept or has been dropped. */
1881
+ function readRunDetail(folder, run) {
1882
+ try {
1883
+ return JSON.parse(readFileSync(runFile(folder, run), "utf8"));
1884
+ } catch (error) {
1885
+ if (error.code === "ENOENT") return void 0;
1886
+ throw error;
1887
+ }
1888
+ }
1889
+ function forgetRunDetails(folder, dropped) {
1890
+ for (const entry of dropped) if (entry.run !== void 0) rmSync(runFile(folder, entry.run), { force: true });
1891
+ }
1892
+ //#endregion
1893
+ //#region src/host/triggers/deliver.ts
1894
+ const KEY = "triggers.withdrawn";
1895
+ /** Why a note was withdrawn instead of told, by the number of the note. */
1896
+ function readWithdrawn(session) {
1897
+ const stored = session.metadata.getValue(KEY);
1898
+ if (!Array.isArray(stored)) return {};
1899
+ return Object.fromEntries(stored.flatMap((entry) => {
1900
+ const { note, reason } = entry ?? {};
1901
+ return typeof note === "number" && typeof reason === "string" ? [[note, reason]] : [];
1902
+ }));
1903
+ }
1904
+ /**
1905
+ * 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
1906
+ * reason kept (`readWithdrawn`). @returns what is to be told, with the number of its note.
1907
+ */
1908
+ function deliverNow(session, notes, clock) {
1909
+ const { shown, withdrawn } = session.deliverNotes(notes, clock);
1910
+ if (withdrawn.length > 0) session.transaction(() => {
1911
+ for (const { note } of withdrawn) session.triggers.resolveNote(note.id, "lapsed");
1912
+ const before = Object.entries(readWithdrawn(session)).map(([note, reason]) => ({
1913
+ note: Number(note),
1914
+ reason
1915
+ }));
1916
+ session.metadata.setValue(KEY, [...before, ...withdrawn.map(({ note, reason }) => ({
1917
+ note: note.id,
1918
+ reason
1919
+ }))].slice(-100));
1920
+ });
1921
+ return shown.map(({ note, text }) => ({
1922
+ id: note.id,
1923
+ text
1924
+ }));
1925
+ }
1926
+ //#endregion
1927
+ export { ClockError as A, languageOf as B, addToNote as C, readNotes as D, putNote as E, readTime as F, skipTime as I, zoneOf as L, describeTime as M, describeWhen as N, observeAsPlayer as O, endRound as P, RESULTS as R, toolEnabled as S, notesOfSession as T, translator as V, plotProgressOf as _, readActivity as a, MAX_OOC_ANSWER as b, externalGiven as c, PREVIEW_TOOL as d, createTools$1 as f, plotAuthorNeeded as g, pacingAdvice as h, keepRunDetail as i, beginTurn as j, observeSurroundings as k, externalTools as l, describePacingAdvice as m, readWithdrawn as n, readRunDetail as o, PLOTS_METADATA_KEY as p, forgetRunDetails as r, recordActivity as s, deliverNow as t, externalWithheld as u, populatePlots as v, clearNotes as w, parseOoc as x, AUTHORING_NEEDS as y, answerLimits as z };
1928
+
1929
+ //# sourceMappingURL=deliver-De62a8i9.js.map