@dsh-agentic-roleplay/core 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/lib/authoring.js +18 -223
  2. package/lib/client.js +1838 -489
  3. package/lib/client.js.map +1 -1
  4. package/lib/compaction.js +1 -1
  5. package/lib/deliver-BSsDtF6X.js +3443 -0
  6. package/lib/{documents-7GMc5NnW.js → documents-B5XAdfo2.js} +992 -14
  7. package/lib/{gallery-DUeBMHQX.js → gallery-DS5-qH9F.js} +2 -2
  8. package/lib/{generator-HPifO3Kk.js → generator-BzeepLd2.js} +3 -3
  9. package/lib/images.js +3 -3
  10. package/lib/index.js +351 -13
  11. package/lib/narration-DK2kiIjE.js +141 -0
  12. package/lib/orchestration.js +867 -1547
  13. package/lib/{packs-alJTiDM2.js → packs-BCGK9KZV.js} +51 -7
  14. package/lib/{presenter-agent-PX1WVaJB.js → presenter-agent-Cp-J0onD.js} +3 -3
  15. package/lib/{narration-CKZTk5UE.js → settings-CA6icLL_.js} +158 -142
  16. package/package.json +4 -4
  17. package/packs/scene/strip.js +1 -1
  18. package/prompts/en/roleplay/character-decide.md +1 -1
  19. package/prompts/en/roleplay/character-rules.md +1 -1
  20. package/prompts/en/roleplay/chronicler.md +1 -1
  21. package/prompts/en/roleplay/dice.md +7 -0
  22. package/prompts/en/roleplay/game-master.md +3 -1
  23. package/prompts/en/roleplay/reflection.md +4 -2
  24. package/prompts/en/roleplay/style.md +1 -1
  25. package/prompts/en/roleplay/suggester.md +1 -1
  26. package/prompts/en/translate/document.md +6 -0
  27. package/prompts/en/translate/glossary.md +5 -0
  28. package/prompts/en/translate/notice.md +2 -0
  29. package/prompts/zh/roleplay/character-decide.md +1 -1
  30. package/prompts/zh/roleplay/character-rules.md +1 -1
  31. package/prompts/zh/roleplay/chronicler.md +1 -1
  32. package/prompts/zh/roleplay/dice.md +7 -0
  33. package/prompts/zh/roleplay/game-master.md +3 -1
  34. package/prompts/zh/roleplay/reflection.md +4 -2
  35. package/prompts/zh/roleplay/style.md +1 -1
  36. package/prompts/zh/roleplay/suggester.md +1 -1
  37. package/prompts/zh/translate/document.md +6 -0
  38. package/prompts/zh/translate/glossary.md +5 -0
  39. package/prompts/zh/translate/notice.md +2 -0
  40. package/lib/deliver--uMhC6oO.js +0 -1878
  41. package/lib/src-CWTNeL6Y.js +0 -128
@@ -1,18 +1,41 @@
1
1
  import { n as chatSessionId, r as roleplaySessionOf, t as promptFor } from "./access-EbNdZFbk.js";
2
- import { F as shippedText, W as INTENT_STATUSES, _ as API_PREFIX, b as parsePlotsFile, z as ReflectionRefusedError } from "./packs-alJTiDM2.js";
3
- import { B as skipTime, D as observeSurroundings, E as observeAsPlayer, F as beginTurn, G as RESULTS, H as referent, I as describeTime, K as answerEstimate, L as describeWhen, N as sameWords, P as ClockError, R as endRound, S as clearNotes, T as readNotes, U as AWAY_ACTION_SCHEMA, V as zoneOf, W as CHARACTER_ACTION_SCHEMA, _ as plotAuthorNeeded, b as updatePlotProgress, c as dueReflection, f as whereabouts, g as pacingAdvice, h as describePacingAdvice, i as keepRunDetail, k as Timelines, l as memoryReflector, m as addSessionPlot, q as parseCharacterAction, r as forgetRunDetails, s as recordActivity, t as deliverNow, u as recordFailure, w as putNote, x as addToNote, z as readTime } from "./deliver--uMhC6oO.js";
4
- import { a as liveSettings, f as WORLD_RULES_KEY, n as encodeOutput, p as rulesOf, r as encodePreview } from "./narration-CKZTk5UE.js";
5
- import "./src-CWTNeL6Y.js";
6
- import { A as runChild, D as childSampling, E as childModel, T as uniqueKey, j as estimateAnswer, k as childTrace, o as addToLibrary, w as slug } from "./generator-HPifO3Kk.js";
7
- import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-DUeBMHQX.js";
8
- import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-PX1WVaJB.js";
2
+ import { B as shippedText, S as wrongLanguage, W as ReflectionRefusedError, Y as INTENT_STATUSES, _ as API_PREFIX } from "./packs-BCGK9KZV.js";
3
+ import { B as sameWords, D as parseOoc, E as MAX_OOC_ANSWER, G as readTime, H as beginTurn, I as Timelines, J as referent, K as skipTime, M as readNotes, N as observeAsPlayer, O as addToNote, P as observeSurroundings, S as plotAuthorNeeded, T as AUTHORING_NEEDS, U as describeWhen, V as ClockError, W as endRound, X as languageOf, Y as RESULTS, Z as translator, _ as PREVIEW_TOOL, b as describePacingAdvice, c as dueReflection, f as whereabouts, g as toolEnabled, h as externalWithheld, i as keepRunDetail, j as putNote, k as clearNotes, l as memoryReflector, p as externalGiven, q as zoneOf, r as forgetRunDetails, s as recordActivity, t as deliverNow, u as recordFailure, v as createTools$1, x as pacingAdvice } from "./deliver-BSsDtF6X.js";
4
+ import { a as WORLD_RULES_KEY, o as rulesOf } from "./settings-CA6icLL_.js";
5
+ import { a as liveSettings } from "./narration-DK2kiIjE.js";
6
+ import { A as runChild, D as childSampling, E as childModel, M as tokensOf, T as uniqueKey, j as estimateAnswer, k as childTrace, o as addToLibrary, w as slug } from "./generator-BzeepLd2.js";
7
+ import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-DS5-qH9F.js";
8
+ import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-Cp-J0onD.js";
9
9
  import { join } from "node:path";
10
10
  import { existsSync } from "node:fs";
11
11
  import { SessionId } from "@deepseek-ai/dsh-session";
12
12
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
13
- import { defineTool } from "@deepseek-ai/dsh-tools";
14
13
  import { readdir } from "node:fs/promises";
15
- import { ENGAGEMENT_GRACE, ITEM_ACTIONS, InvalidEditError, MINUTE, agendaAt, announcements, applyItemPlan, changeItem, changeVariable, characterKey, createCharacterTools, createTools, dayPart, describeDuration, describeHolder, describeInstant, describeValue, inAudience, itemKey, judgedStatements, lintWorld, localTime, locationKey, mentioned, nextOccurrence, occurrenceAt, parseInstant, parseRecordsEdit, planItemChange, planVariableChange, sessionDatabase, sessionFolder, shownVariables } from "@dsh-agentic-roleplay/state";
14
+ import { ENGAGEMENT_GRACE, InvalidEditError, MINUTE, agendaAt, announcements, applyItemPlan, changeItem, changeVariable, characterKey, createDiceTools, createTools, dayPart, describeDuration, describeHolder, describeInstant, describeValue, inAudience, itemKey, judgedStatements, lintWorld, localTime, locationKey, mentioned, nextOccurrence, occurrenceAt, parseInstant, parseRecordsEdit, planItemChange, planVariableChange, rollPlain, sessionDatabase, sessionFolder, shownVariables } from "@dsh-agentic-roleplay/state";
15
+ //#region src/host/tools/resource-hint.ts
16
+ /** The name DSH's MCP resource plugin gives the prompt paragraph it adds for every agent; a section of the same name in an agent's scope replaces it. */
17
+ const RESOURCE_HINT_SECTION = "mcp-resource-servers";
18
+ const RESOURCE_TOOLS = [
19
+ "list_mcp_resources",
20
+ "list_mcp_resource_templates",
21
+ "read_mcp_resource"
22
+ ];
23
+ const NAMESPACED = /^mcp__(.+?)__.+$/;
24
+ /**
25
+ * What an agent is told about MCP resources: nothing unless it can see a resource tool, since the plugin's own paragraph names the tools
26
+ * and servers to every agent whether or not it was given them, and an agent that is told of a tool it lacks goes looking for it. The servers are
27
+ * those with a tool registered for anyone, so that an agent given only the resource tools still learns their names.
28
+ */
29
+ function resourceHint(visible, registered, tr) {
30
+ const tools = RESOURCE_TOOLS.filter((name) => visible.includes(name));
31
+ if (tools.length === 0) return "";
32
+ const servers = [...new Set(registered.flatMap((name) => NAMESPACED.exec(name)?.[1] ?? []))].sort();
33
+ return servers.length === 0 ? tr("## MCP resource servers\n\nUse {tools} with the server argument naming an MCP server.", { tools: tools.join(", ") }) : tr("## MCP resource servers\n\nUse {tools} with one of these names as the server argument: {servers}.", {
34
+ tools: tools.join(", "),
35
+ servers: JSON.stringify(servers)
36
+ });
37
+ }
38
+ //#endregion
16
39
  //#region src/host/orchestration/committer.ts
17
40
  /** What the keeper reads back by default: the parts of the records its edits write. */
18
41
  const VERIFY_SECTIONS = [
@@ -34,11 +57,13 @@ function describeRound(round, known) {
34
57
  round.offstage === true ? `Off stage (away from the player's character; only the characters named here perceive it, and only those who were together perceive each other): ${round.situation}` : `The moment (includes what the player's character did or said): ${round.situation}`,
35
58
  ...round.place === void 0 ? [] : [`Place of the moment: ${round.place.name} (${round.place.key})`],
36
59
  ...round.time === void 0 ? [] : [`When: ${describeInstant(round.time.from, round.time.zone)} (${dayPart(localTime(round.time.from, round.time.zone).minuteOfDay)})${round.time.to > round.time.from ? `; the round took ${describeDuration(round.time.to - round.time.from)}` : ""}`],
60
+ ...round.rolls === void 0 ? [] : ["Dice rolled this round, which are facts (not interpreted by anyone):", ...round.rolls.map((line) => `- ${line}`)],
37
61
  "What each character did, and what became of it:",
38
62
  ...round.entries.map((entry) => [
39
63
  entry.forced === true ? `- ${entry.character} (${known.get(entry.character) ?? entry.name}): decreed, not chosen: ${entry.result}: ${entry.summary}` : entry.player === true ? `- ${entry.character} (${known.get(entry.character) ?? entry.name}, the player's character): ${entry.result}: ${entry.summary}` : `- ${entry.character} (${known.get(entry.character) ?? entry.name}): intended "${entry.intent}" [commitment: ${entry.commitment}]; ${entry.result}: ${entry.summary}`,
40
64
  entry.utterance === void 0 ? "" : ` said${entry.spoken ? "" : " (but was prevented from saying)"}: "${entry.utterance}"`,
41
65
  entry.publicState === void 0 ? "" : ` the game master says anyone present can now see: ${entry.publicState}`,
66
+ entry.rolled === void 0 ? "" : ` decided by the dice: ${entry.rolled}`,
42
67
  entry.variables === void 0 ? "" : ` the game master changed what is tracked: ${entry.variables.map((change) => `${change.subject}'s ${change.name} ${change.from} -> ${change.to}`).join("; ")}`,
43
68
  entry.items === void 0 ? "" : ` with things: ${entry.items.map((thing) => `${thing.name} (${thing.action}: ${thing.summary})`).join("; ")}`,
44
69
  entry.at === void 0 ? "" : ` was in ${entry.at.name} (${entry.at.key})${entry.moved === void 0 ? "" : ` and went to ${entry.moved.name} (${entry.moved.key})${entry.moved.position === void 0 ? "" : `, ${entry.moved.position}`}`}`
@@ -87,7 +112,7 @@ function describePrompt(job, memory) {
87
112
  ...records.open_threads.length === 0 ? ["- none"] : records.open_threads.map((thread) => `- id ${thread.id}: ${thread.text}`)
88
113
  ].join("\n");
89
114
  }
90
- const RESULT$4 = {
115
+ const RESULT$3 = {
91
116
  type: "object",
92
117
  properties: {
93
118
  complete: {
@@ -136,6 +161,16 @@ function keeperTools(job, memory, progress) {
136
161
  execute: async (args, exec) => {
137
162
  const outside = (parseRecordsEdit(args).events ?? []).filter((event) => !job.rounds.some((round) => round.turn === event.turn && round.round === event.round));
138
163
  if (outside.length > 0) throw new InvalidEditError(outside.map((event) => `an event has turn ${event.turn}, round ${event.round}, which is not one of the rounds given: ${job.rounds.map(label).join("; ")}`));
164
+ const edit = parseRecordsEdit(args);
165
+ const wording = wrongLanguage(job.store.settings().prompts.language, {
166
+ events: [...(edit.events ?? []).map((event) => event.text), ...(edit.eventEdits ?? []).map((event) => event.text)].join(" "),
167
+ perceptions: [
168
+ ...(edit.events ?? []).flatMap((event) => (event.perceivedBy ?? []).map((seen) => seen.content)),
169
+ ...(edit.perceptionEdits ?? []).map((seen) => seen.content),
170
+ ...(edit.perceptionsAdded ?? []).map((seen) => seen.content)
171
+ ].join(" ")
172
+ });
173
+ if (wording !== void 0) throw new InvalidEditError([wording]);
139
174
  const result = await tool.execute(args, exec);
140
175
  progress.edits += 1;
141
176
  progress.unchecked = true;
@@ -160,6 +195,9 @@ function keeperTools(job, memory, progress) {
160
195
  return tool;
161
196
  });
162
197
  }
198
+ /** What one request of the keeper may carry: the events and what each witness took in, for every round it was given, and the shape of the call. */
199
+ const KEEPER_CHARACTERS_PER_ROUND = 4e3;
200
+ const keeperEstimate = (rounds, language) => tokensOf(rounds * KEEPER_CHARACTERS_PER_ROUND, language) + 192;
163
201
  /**
164
202
  * Writes rounds into the story's records with a child agent of the game master that has the
165
203
  * record tools to itself (the game master and the characters never see them). It writes with
@@ -186,13 +224,14 @@ function recordKeeper(deps) {
186
224
  parent,
187
225
  signal,
188
226
  reasoningEffort: job.store.settings().reasoning.children,
189
- sampling: childSampling(job.store.settings(), "records"),
227
+ sampling: childSampling(job.store.settings(), "records", keeperEstimate(job.rounds.length, job.store.settings().prompts.language)),
190
228
  ...childModel(job.store.settings(), "records"),
191
229
  trace: childTrace(job.store, "records", "record keeper"),
192
230
  persona: promptFor(parent, "roleplay/record-keeper", job.store.settings().prompts.language),
193
231
  prompt: describePrompt(job, memory),
194
232
  tools: keeperTools(job, memory, progress),
195
- result: RESULT$4,
233
+ external: externalGiven(parent.ctx.tools, job.store.settings().tools, "records"),
234
+ result: RESULT$3,
196
235
  beforeSubmit: () => {
197
236
  if (progress.edits === 0 && !warned) {
198
237
  warned = true;
@@ -221,7 +260,7 @@ function suggestionProblems(lines, wanted) {
221
260
  const tidySuggestions = (lines) => lines.map((line) => line.trim().replace(/\s+/g, " "));
222
261
  //#endregion
223
262
  //#region src/host/orchestration/suggester.ts
224
- const RESULT$3 = {
263
+ const RESULT$2 = {
225
264
  type: "object",
226
265
  properties: { options: {
227
266
  type: "array",
@@ -260,7 +299,7 @@ function suggestionWriter(deps) {
260
299
  trace: childTrace(job.store, "suggestions", "suggestions"),
261
300
  persona: promptFor(parent, "roleplay/suggester", job.store.settings().prompts.language, { max: 200 }),
262
301
  prompt: promptOf(job),
263
- result: RESULT$3,
302
+ result: RESULT$2,
264
303
  beforeSubmit: (value) => {
265
304
  const problems = suggestionProblems(tidySuggestions(value.options), job.count);
266
305
  return problems.length === 0 ? void 0 : `not acceptable: ${problems.join("; ")}`;
@@ -296,7 +335,7 @@ const verdictReader = (session) => {
296
335
  };
297
336
  //#endregion
298
337
  //#region src/host/triggers/judge.ts
299
- const RESULT$2 = {
338
+ const RESULT$1 = {
300
339
  type: "object",
301
340
  properties: { verdicts: {
302
341
  type: "array",
@@ -358,12 +397,12 @@ function triggerJudge(deps) {
358
397
  parent,
359
398
  signal,
360
399
  reasoningEffort: store.settings().reasoning.children,
361
- sampling: childSampling(store.settings(), "records"),
400
+ sampling: childSampling(store.settings(), "records", statements.length * 2 * 8 + 8),
362
401
  ...childModel(store.settings(), "records"),
363
402
  trace: childTrace(store, "records", "trigger judge"),
364
403
  persona: promptFor(parent, "roleplay/trigger-judge", store.settings().prompts.language),
365
404
  prompt: brief$1(job, statements),
366
- result: RESULT$2,
405
+ result: RESULT$1,
367
406
  beforeSubmit: (value) => {
368
407
  const numbers = value.verdicts.map((verdict) => verdict.number);
369
408
  const missing = statements.flatMap((_, index) => numbers.includes(index + 1) ? [] : [index + 1]);
@@ -391,6 +430,16 @@ const DAY_MS = 864e5;
391
430
  const STRATEGY_ROUND = 200;
392
431
  const MAX_ACTIVE_GOALS = 8;
393
432
  const MAX_TEXT = 400;
433
+ /** What a decision may hold: the summary, both states, a new goal with its plan, and the status of each active goal. */
434
+ const DECISION_LIMITS = [
435
+ MAX_TEXT,
436
+ MAX_TEXT,
437
+ MAX_TEXT,
438
+ 120,
439
+ MAX_TEXT,
440
+ ...Array.from({ length: 6 }, () => 200),
441
+ ...Array.from({ length: MAX_ACTIVE_GOALS }, () => 10)
442
+ ];
394
443
  const keyOf$1 = (faction) => faction.sourceId ?? String(faction.id);
395
444
  function lastActed(session) {
396
445
  const stored = session.metadata.getValue(LAST_KEY);
@@ -425,7 +474,7 @@ function markActed(session, faction, now) {
425
474
  [keyOf$1(faction)]: now
426
475
  });
427
476
  }
428
- const RESULT$1 = {
477
+ const RESULT = {
429
478
  type: "object",
430
479
  properties: {
431
480
  summary: {
@@ -563,12 +612,12 @@ function factionStrategist(deps) {
563
612
  parent,
564
613
  signal,
565
614
  reasoningEffort: store.settings().reasoning.children,
566
- sampling: childSampling(store.settings(), "authoring"),
615
+ sampling: childSampling(store.settings(), "authoring", estimateAnswer(DECISION_LIMITS, store.settings().prompts.language)),
567
616
  ...childModel(store.settings(), "authoring"),
568
617
  trace: childTrace(store, "authoring", `faction ${faction.name}`),
569
618
  persona: promptFor(parent, "roleplay/faction-strategist", store.settings().prompts.language),
570
619
  prompt: brief(session, faction, now, zone, last[keyOf$1(faction)] ?? now),
571
- result: RESULT$1,
620
+ result: RESULT,
572
621
  maxCalls: 3
573
622
  });
574
623
  applyStrategy(job, session, faction, strategy, now);
@@ -582,6 +631,13 @@ function factionStrategist(deps) {
582
631
  }
583
632
  //#endregion
584
633
  //#region src/host/authoring/author-agent.ts
634
+ /** A made-up thing in one edit: its name, description and the handful of fields a character, place or item carries. */
635
+ const THING_TEXTS = 14;
636
+ const THING_TEXT_CHARS = 300;
637
+ /** What consolidating one waiting item writes: a way or a relationship with its descriptions. */
638
+ const FIT_TEXTS = 6;
639
+ const FIT_TEXT_CHARS = 200;
640
+ const editEstimate = (things, texts, chars, language) => estimateAnswer(Array.from({ length: Math.max(1, things) * texts }, () => chars), language);
585
641
  function authorTools(job, work, mode, limits) {
586
642
  const link = {
587
643
  session: job.store.story,
@@ -825,7 +881,7 @@ function worldAuthor(deps) {
825
881
  const work = { created: [] };
826
882
  const result = await runChild({
827
883
  reasoningEffort: job.store.settings().reasoning.children,
828
- sampling: childSampling(job.store.settings(), "authoring"),
884
+ sampling: childSampling(job.store.settings(), "authoring", editEstimate(authoring.perTurn, THING_TEXTS, THING_TEXT_CHARS, job.store.settings().prompts.language)),
829
885
  ...childModel(job.store.settings(), "authoring"),
830
886
  trace: childTrace(job.store, "authoring", "world author"),
831
887
  parent,
@@ -868,7 +924,7 @@ function worldAuthor(deps) {
868
924
  const work = { created: [] };
869
925
  const result = await runChild({
870
926
  reasoningEffort: job.store.settings().reasoning.children,
871
- sampling: childSampling(job.store.settings(), "authoring"),
927
+ sampling: childSampling(job.store.settings(), "authoring", editEstimate(pending.length, FIT_TEXTS, FIT_TEXT_CHARS, job.store.settings().prompts.language)),
872
928
  ...childModel(job.store.settings(), "authoring"),
873
929
  trace: childTrace(job.store, "authoring", "world consolidation"),
874
930
  parent,
@@ -1205,7 +1261,9 @@ function markHandled(session, keys) {
1205
1261
  * whose time has come with everyone to do with them away from the scene, and goals whose deadline has passed.
1206
1262
  * Oldest first.
1207
1263
  */
1208
- function dueOffScene(session, zone, now) {
1264
+ function dueOffScene(session, zone, now, language = "en") {
1265
+ const tr = translator(language);
1266
+ const when = (instant) => describeWhen(instant, now, zone, language);
1209
1267
  const handled = handledKeys(session);
1210
1268
  const characters = session.characters.list();
1211
1269
  const player = characters.find((character) => character.control === "player");
@@ -1228,7 +1286,19 @@ function dueOffScene(session, zone, now) {
1228
1286
  at: engagement.at,
1229
1287
  characters: everyone.map((id) => keyOf(agents.get(id))),
1230
1288
  ...place === void 0 ? {} : { place: place.sourceId ?? String(place.id) },
1231
- text: `You were to ${engagement.title}${place === void 0 ? "" : ` at ${place.name}`}, at ${describeWhen(engagement.at, now, zone)}${engagement.note === "" ? "" : ` (${engagement.note})`}. It is ${describeWhen(now, now, zone)} now${now > engagement.at + ENGAGEMENT_GRACE ? " and the time has passed" : ""}. It was with: ${everyone.map((id) => agents.get(id).name).join(", ")}. You are not with the player's character, and nothing of this happens in front of anyone: decide what you do about it.`
1289
+ text: [
1290
+ `${place === void 0 ? tr("You were to {title}, at {when}", {
1291
+ title: engagement.title,
1292
+ when: when(engagement.at)
1293
+ }) : tr("You were to {title} at {place}, at {when}", {
1294
+ title: engagement.title,
1295
+ place: place.name,
1296
+ when: when(engagement.at)
1297
+ })}${engagement.note === "" ? "" : tr(" ({note})", { note: engagement.note })}${tr(".")}`,
1298
+ now > engagement.at + ENGAGEMENT_GRACE ? tr("It is {now} now and the time has passed.", { now: when(now) }) : tr("It is {now} now.", { now: when(now) }),
1299
+ tr("It was with: {who}.", { who: everyone.map((id) => agents.get(id).name).join(tr(", ")) }),
1300
+ tr("You are not with the player's character, and nothing of this happens in front of anyone: decide what you do about it.")
1301
+ ].join(" ")
1232
1302
  });
1233
1303
  }
1234
1304
  for (const character of agents.values()) {
@@ -1247,7 +1317,11 @@ function dueOffScene(session, zone, now) {
1247
1317
  kind: "goal",
1248
1318
  at: deadline,
1249
1319
  characters: [keyOf(character)],
1250
- text: `The time you had for "${goal.name}" has passed (${describeWhen(deadline, now, zone)}; it is ${describeWhen(now, now, zone)} now)${goal.description === "" ? "" : `: ${goal.description}`} You are not with the player's character and nothing of this happens in front of anyone: decide what you do about it.`
1320
+ text: `${tr("The time you had for \"{goal}\" has passed ({when}; it is {now} now)", {
1321
+ goal: goal.name,
1322
+ when: when(deadline),
1323
+ now: when(now)
1324
+ })}${goal.description === "" ? "" : `${tr(": ")}${goal.description}`} ${tr("You are not with the player's character and nothing of this happens in front of anyone: decide what you do about it.")}`
1251
1325
  });
1252
1326
  }
1253
1327
  }
@@ -1552,7 +1626,7 @@ function storeOf(session, folder, problem, queryVector, wall, prompt) {
1552
1626
  changeVariables: (turn, changes) => session.transaction(() => changes.map((spec) => changeVariable(session, spec, turn))),
1553
1627
  trackedFor: (characterId, presentIds) => trackedFor(session, characterId, presentIds),
1554
1628
  tracked: () => trackedLines(session),
1555
- dueOffScene: (turn) => dueOffScene(session, zoneOf(settings().clock), readTime(session, settings().clock, turn, wall()).now),
1629
+ dueOffScene: (turn) => dueOffScene(session, zoneOf(settings().clock), readTime(session, settings().clock, turn, wall()).now, languageOf(settings().prompts.language)),
1556
1630
  markHandled: (keys) => {
1557
1631
  markHandled(session, keys);
1558
1632
  },
@@ -1630,19 +1704,17 @@ function storesOf(state, sessionsDir, problem = () => void 0, queryVector = () =
1630
1704
  };
1631
1705
  }
1632
1706
  //#endregion
1633
- //#region src/shared/ooc.ts
1634
- /** 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. */
1635
- const OOC_COMMAND = /^\s*\/(ooc|ask)(?=\s|$)\s*([\s\S]*)$/i;
1636
- /** The command or question in a player's message, or nothing when the message is an ordinary action. The request may be empty. */
1637
- function parseOoc(text) {
1638
- const match = OOC_COMMAND.exec(text);
1707
+ //#region src/shared/roll.ts
1708
+ /** The player rolls dice before acting: `/roll 2d6+1 pick the lock`. The dice are then part of what the game master judges. */
1709
+ const ROLL_COMMAND = /^\s*\/roll(?=\s|$)\s*(\S*)\s*([\s\S]*)$/i;
1710
+ /** The roll in a player's message, or nothing when the message does not start with `/roll`. The notation may be empty, and is then refused. */
1711
+ function parseRoll(text) {
1712
+ const match = ROLL_COMMAND.exec(text);
1639
1713
  return match === null ? void 0 : {
1640
- request: (match[2] ?? "").trim(),
1641
- question: match[1].toLowerCase() === "ask"
1714
+ expression: match[1] ?? "",
1715
+ reason: (match[2] ?? "").trim()
1642
1716
  };
1643
1717
  }
1644
- /** The longest answer to an out-of-character question. */
1645
- const MAX_OOC_ANSWER = 1200;
1646
1718
  //#endregion
1647
1719
  //#region src/host/orchestration/hooks.ts
1648
1720
  const notice = (text) => createUserMessage({
@@ -1679,6 +1751,46 @@ function previewToggle(tool) {
1679
1751
  }
1680
1752
  };
1681
1753
  }
1754
+ /** Where the withdrawals of an agent's optional tools are kept, by tool name: on the agent, so that a reloaded plugin still finds what its earlier self registered. */
1755
+ const OPTIONAL_SHOWN = Symbol.for("dsh-agentic-roleplay.optional-tools");
1756
+ /** Puts an agent's optional tools in line with the switches: registers the ones that are on and not yet there, withdraws the ones that are off. */
1757
+ function optionalToolSwitch(tools) {
1758
+ return (agent, enabled) => {
1759
+ const holder = agent;
1760
+ const shown = holder[OPTIONAL_SHOWN] ??= /* @__PURE__ */ new Map();
1761
+ for (const tool of tools) {
1762
+ const withdraw = shown.get(tool.name);
1763
+ if (enabled(tool.name) && withdraw === void 0) try {
1764
+ shown.set(tool.name, agent.ctx.tools.register(tool));
1765
+ } catch (error) {
1766
+ if (!(error instanceof Error) || !error.message.includes("already registered")) throw error;
1767
+ shown.set(tool.name, () => void 0);
1768
+ }
1769
+ else if (!enabled(tool.name) && withdraw !== void 0) {
1770
+ shown.delete(tool.name);
1771
+ withdraw();
1772
+ }
1773
+ }
1774
+ };
1775
+ }
1776
+ /** Where an agent's withdrawal of the external tools it was not given is kept: on the agent, so that a reloaded plugin still finds what its earlier self set. */
1777
+ const EXTERNAL_LIMIT = Symbol.for("dsh-agentic-roleplay.external-limit");
1778
+ /**
1779
+ * Takes away from an agent the tools other plugins registered for everyone that it was not given. A story gives the game master such tools (a file or
1780
+ * shell tool, an MCP server's) by switching them on; without it the agent has none of them. The limit follows the settings as they change.
1781
+ */
1782
+ function externalToolLimit(agent, withheld) {
1783
+ const holder = agent;
1784
+ const key = [...withheld].sort().join("\n");
1785
+ const current = holder[EXTERNAL_LIMIT];
1786
+ if (current?.key === key) return;
1787
+ current?.lift();
1788
+ delete holder[EXTERNAL_LIMIT];
1789
+ if (withheld.length > 0) holder[EXTERNAL_LIMIT] = {
1790
+ key,
1791
+ lift: agent.ctx.tools.restrict({ deny: [...withheld] })
1792
+ };
1793
+ }
1682
1794
  /**
1683
1795
  * The listeners of a roleplay preset. Preset listeners are shared by every chat
1684
1796
  * that uses the preset and also hear the agents that chat spawns, so each one
@@ -1687,6 +1799,18 @@ function previewToggle(tool) {
1687
1799
  function installHooks(ctx, deps) {
1688
1800
  const { engine, boundaries, stores, timelines, previewTool } = deps;
1689
1801
  const showPreviewTool = previewToggle(previewTool);
1802
+ const showOptionalTools = optionalToolSwitch(deps.optionalTools ?? []);
1803
+ /** The tools of the game master as the chat's settings say: its optional ones, and none of other plugins' that it was not given. */
1804
+ const applyTools = (agent, store) => {
1805
+ const { tools } = store.settings();
1806
+ showOptionalTools(agent, (tool) => toolEnabled(tools, "gameMaster", tool));
1807
+ externalToolLimit(agent, externalWithheld(agent.ctx.tools, tools, "gameMaster"));
1808
+ };
1809
+ ctx.on("agent/created", ({ agent }) => {
1810
+ const owner = ownerOf(agent, 0);
1811
+ const store = owner === void 0 ? void 0 : stores(owner.chat);
1812
+ if (store !== void 0) applyTools(agent, store);
1813
+ });
1690
1814
  ctx.on("session/event", (session, event) => {
1691
1815
  if (event.type !== "turn/end" || session.header.origin === "subagent" || roleplaySessionOf(session.id) === void 0) return;
1692
1816
  timelines.ended(session.id, session, event.seq);
@@ -1712,7 +1836,10 @@ function installHooks(ctx, deps) {
1712
1836
  const decision = await next();
1713
1837
  const owner = ownerOf(payload.agent, payload.turn);
1714
1838
  const store = owner === void 0 ? void 0 : stores(owner.chat);
1715
- if (owner !== void 0 && store !== void 0) showPreviewTool(payload.agent, store.settings().preview.enabled);
1839
+ if (owner !== void 0 && store !== void 0) {
1840
+ showPreviewTool(payload.agent, store.settings().preview.enabled);
1841
+ applyTools(payload.agent, store);
1842
+ }
1716
1843
  if (decision.kind !== "enter" || payload.step !== 1) return decision;
1717
1844
  if (owner === void 0 || store === void 0) return decision;
1718
1845
  const text = payload.messages.filter((message) => message.source.kind === "user").flatMap((message) => message.content.flatMap((block) => block.type === "text" ? [block.text] : [])).join("\n");
@@ -1730,9 +1857,16 @@ function installHooks(ctx, deps) {
1730
1857
  store.clearNotes();
1731
1858
  store.lapseNotes(payload.turn);
1732
1859
  const { time, away, agenda } = store.beginTurn(payload.turn);
1733
- if (store.settings().offstage.summary) store.addNote("away", payload.turn, agenda.moved.map((move) => `${move.name} went to ${move.to}.`));
1860
+ const tr = translator(languageOf(store.settings().prompts.language));
1861
+ if (store.settings().offstage.summary) store.addNote("away", payload.turn, agenda.moved.map((move) => tr("{name} went to {place}.", {
1862
+ name: move.name,
1863
+ place: move.to
1864
+ })));
1734
1865
  const world = {
1735
- happened: engine.fireAtStart(owner).flatMap((entry) => [...entry.events.map((text) => `${entry.name}: ${text}`), ...entry.cues.map((cue) => `${cue.names.join(" and ")} noticed: ${cue.text}`)]),
1866
+ happened: engine.fireAtStart(owner).flatMap((entry) => [...entry.events.map((text) => `${entry.name}: ${text}`), ...entry.cues.map((cue) => tr("{names} noticed: {text}", {
1867
+ names: cue.names.join(tr(" and ")),
1868
+ text: cue.text
1869
+ }))]),
1736
1870
  beats: store.pendingBeats(),
1737
1871
  upcoming: store.upcoming(payload.turn)
1738
1872
  };
@@ -1753,6 +1887,7 @@ function installHooks(ctx, deps) {
1753
1887
  at: (locationId) => store.itemsAt(locationId, true),
1754
1888
  carried: (characterId) => store.carried(characterId)
1755
1889
  },
1890
+ language: store.settings().prompts.language,
1756
1891
  ...queryVector === void 0 ? {} : { queryVector }
1757
1892
  })];
1758
1893
  const pacing = ooc === void 0 ? pacingAdvice(store, payload.turn) : void 0;
@@ -1760,6 +1895,30 @@ function installHooks(ctx, deps) {
1760
1895
  else if (ooc === void 0 && plotAuthorNeeded(store, payload.turn)) lines.push(store.text("roleplay/plot-hint"));
1761
1896
  const rules = store.rules();
1762
1897
  if (rules.length > 0) lines.push(store.text("roleplay/rules", { rules: rules.map((rule) => `- ${rule}`).join("\n") }));
1898
+ const wanted = ooc === void 0 ? parseRoll(text) : void 0;
1899
+ if (wanted !== void 0) try {
1900
+ const made = rollPlain(wanted.expression);
1901
+ const roll = store.story.dice.record({
1902
+ turn: payload.turn,
1903
+ expression: made.expression,
1904
+ faces: made.faces,
1905
+ kept: made.kept,
1906
+ modifier: made.modifier,
1907
+ total: made.total,
1908
+ value: made.total,
1909
+ reason: wanted.reason === "" ? tr("the player's roll") : wanted.reason,
1910
+ by: "player"
1911
+ });
1912
+ lines.push(tr("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.", {
1913
+ dice: roll.expression,
1914
+ reason: roll.reason,
1915
+ total: roll.total,
1916
+ faces: `[${roll.faces.join(", ")}]`
1917
+ }));
1918
+ } catch (error) {
1919
+ engine.skip(owner);
1920
+ lines.push(store.text("roleplay/input-refused", { reason: error instanceof Error ? error.message : String(error) }));
1921
+ }
1763
1922
  if (ooc !== void 0 && ooc.request !== "") lines.push(store.text(ooc.question ? "roleplay/ask-question" : "roleplay/ooc-command", { request: ooc.request }));
1764
1923
  if (ooc !== void 0 && ooc.request === "") {
1765
1924
  engine.skip(owner);
@@ -1780,6 +1939,26 @@ function installHooks(ctx, deps) {
1780
1939
  const PROTOCOL_SECTION = "roleplay:protocol";
1781
1940
  const PERSONA_SECTION = "roleplay:persona";
1782
1941
  //#endregion
1942
+ //#region src/host/dice/describe.ts
1943
+ /** The checks of a story as the game master is told of them: when each is used, what it rolls and what it needs. The result's bands are told by the roll itself. */
1944
+ function describeChecks(checks, tr) {
1945
+ if (checks.length === 0) return tr("No checks are defined: use roll_dice only.");
1946
+ const lines = checks.map((check) => {
1947
+ const needs = [
1948
+ tr("Rolls {dice}.", { dice: check.dice }),
1949
+ ...check.reading === "successes" ? [tr("Counts the dice that show {hit} or more.", { hit: check.hit ?? 0 })] : [],
1950
+ ...check.compare === "over" ? [tr("Give a target: the difficulty, the number to meet or beat; set it by how hard the attempt is.")] : check.compare === "under" ? [tr("Give a target: the number to stay under; set it by how hard the attempt is.")] : [],
1951
+ ...check.modifier === void 0 ? [] : [tr("It adds the character's {variable}.", { variable: check.modifier })]
1952
+ ];
1953
+ return `${tr("- {key} ({name}): {use}", {
1954
+ key: check.key,
1955
+ name: check.name,
1956
+ use: check.use.replace(/[.\s]+$/, "")
1957
+ })}. ${needs.join(" ")}`;
1958
+ });
1959
+ return [tr("The checks of this story:"), ...lines].join("\n");
1960
+ }
1961
+ //#endregion
1783
1962
  //#region src/host/orchestration/current-turn.ts
1784
1963
  /** The last turn the session started. */
1785
1964
  function currentTurn(agent) {
@@ -1791,1006 +1970,6 @@ function currentTurn(agent) {
1791
1970
  return 0;
1792
1971
  }
1793
1972
  //#endregion
1794
- //#region src/host/orchestration/character-runner.ts
1795
- /**
1796
- * Runs each character as a one-shot child of the game master. It is the character and nothing
1797
- * else: it knows what its brief gives it, and its only tool (when the chat allows it) reaches
1798
- * the memory of that character alone, so characters acting at the same time cannot see each
1799
- * other's memories.
1800
- */
1801
- function characterRunner(deps) {
1802
- return async (request, signal) => {
1803
- const brief = deps.boundaries().characterContext.brief(request);
1804
- const tools = request.lookup ? createCharacterTools(() => ({
1805
- session: deps.store.story,
1806
- turn: request.turn,
1807
- policy: deps.store.settings().memory,
1808
- queryVector: deps.store.queryVector
1809
- }), request.member.character.id) : [];
1810
- const settings = deps.store.settings();
1811
- const named = request.member.character.tier === "background" && settings.models.background.trim() !== "" ? settings.models.background : settings.models.characters;
1812
- const result = await runChild({
1813
- parent: deps.parent,
1814
- signal,
1815
- sampling: childSampling(settings, "characters", answerEstimate(settings.prompts.language, request.away === true)),
1816
- ...childModel(settings, "characters", named),
1817
- trace: childTrace(deps.store, "characters", request.member.character.name, recalledOf(request), named),
1818
- reasoningEffort: deps.store.settings().reasoning.children,
1819
- persona: brief.persona,
1820
- prompt: brief.prompt,
1821
- tools,
1822
- maxCalls: deps.store.settings().memory.lookupCalls,
1823
- result: request.away === true ? AWAY_ACTION_SCHEMA : CHARACTER_ACTION_SCHEMA,
1824
- unenforced: ["thought"]
1825
- });
1826
- return parseCharacterAction(result);
1827
- };
1828
- }
1829
- /** What the character was reminded of and why, for the run's record, when the recall said why. */
1830
- function recalledOf(request) {
1831
- const explained = (request.memories ?? []).filter((memory) => memory.why !== void 0);
1832
- return explained.length === 0 ? {} : { recalled: explained.slice(0, 30).map(({ clarity, turn, text, why }) => ({
1833
- clarity,
1834
- turn,
1835
- text,
1836
- why
1837
- })) };
1838
- }
1839
- const ANSWER_SCHEMA = {
1840
- type: "object",
1841
- properties: { answer: {
1842
- type: "string",
1843
- description: "The answer to the player, in plain words, in a few sentences."
1844
- } },
1845
- required: ["answer"],
1846
- additionalProperties: false
1847
- };
1848
- /**
1849
- * 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
1850
- * game master alone knows is in the prompt, so the answer cannot give away what the character could not know.
1851
- */
1852
- function answerRunner(deps) {
1853
- return async (request, signal) => {
1854
- const brief = deps.boundaries().characterContext.brief(request);
1855
- return (await runChild({
1856
- parent: deps.parent,
1857
- signal,
1858
- sampling: childSampling(deps.store.settings(), "records", estimateAnswer([MAX_OOC_ANSWER], deps.store.settings().prompts.language)),
1859
- ...childModel(deps.store.settings(), "records"),
1860
- trace: childTrace(deps.store, "records", "answer to the player"),
1861
- reasoningEffort: deps.store.settings().reasoning.children,
1862
- persona: request.text("roleplay/ask-answerer", { name: request.member.character.name }),
1863
- prompt: brief.prompt,
1864
- tools: [],
1865
- maxCalls: 3,
1866
- result: ANSWER_SCHEMA
1867
- })).answer;
1868
- };
1869
- }
1870
- //#endregion
1871
- //#region src/host/orchestration/boundaries.ts
1872
- /** Why the game master may ask for something to be made up: the story genuinely needs it. */
1873
- const AUTHORING_NEEDS = [
1874
- "scene_change",
1875
- "arrival",
1876
- "introduction",
1877
- "object",
1878
- "variable",
1879
- "trigger"
1880
- ];
1881
- //#endregion
1882
- //#region src/host/pacing/author.ts
1883
- const RESULT = {
1884
- type: "object",
1885
- required: [
1886
- "id",
1887
- "name",
1888
- "premise",
1889
- "themes",
1890
- "hook",
1891
- "developments",
1892
- "stakes",
1893
- "resolutions",
1894
- "participants"
1895
- ],
1896
- additionalProperties: false,
1897
- properties: {
1898
- id: { type: "string" },
1899
- name: { type: "string" },
1900
- premise: { type: "string" },
1901
- themes: {
1902
- type: "array",
1903
- items: { type: "string" }
1904
- },
1905
- hook: {
1906
- type: "object",
1907
- required: [
1908
- "id",
1909
- "text",
1910
- "guidance",
1911
- "avoid"
1912
- ],
1913
- additionalProperties: false,
1914
- properties: {
1915
- id: { type: "string" },
1916
- text: { type: "string" },
1917
- guidance: { type: "string" },
1918
- avoid: {
1919
- type: "array",
1920
- items: { type: "string" }
1921
- }
1922
- }
1923
- },
1924
- developments: {
1925
- type: "array",
1926
- items: {
1927
- type: "object",
1928
- required: [
1929
- "id",
1930
- "text",
1931
- "mode",
1932
- "prerequisites",
1933
- "guidance",
1934
- "avoid"
1935
- ],
1936
- additionalProperties: false,
1937
- properties: {
1938
- id: { type: "string" },
1939
- text: { type: "string" },
1940
- mode: {
1941
- type: "string",
1942
- enum: [
1943
- "opportunity",
1944
- "reminder",
1945
- "character",
1946
- "consequence",
1947
- "escalation",
1948
- "breathing_room"
1949
- ]
1950
- },
1951
- prerequisites: {
1952
- type: "array",
1953
- items: { type: "string" }
1954
- },
1955
- guidance: { type: "string" },
1956
- avoid: {
1957
- type: "array",
1958
- items: { type: "string" }
1959
- }
1960
- }
1961
- }
1962
- },
1963
- stakes: {
1964
- type: "array",
1965
- items: { type: "string" }
1966
- },
1967
- resolutions: {
1968
- type: "array",
1969
- items: { type: "string" }
1970
- },
1971
- participants: {
1972
- type: "array",
1973
- items: { type: "string" }
1974
- }
1975
- }
1976
- };
1977
- async function authorPlot(parent, store, turn, signal) {
1978
- const cast = store.cast().map((member) => `${member.character.name} (${member.key}): ${member.character.summary}`).join("\n");
1979
- const factions = store.story.factions.list().map((faction) => `${faction.name} (${faction.sourceId ?? faction.id}): ${faction.summary}`).join("\n");
1980
- const places = store.story.locations.list().map((place) => `${place.name} (${place.sourceId ?? place.id})`).join(", ");
1981
- const events = store.story.events.list().slice(-12).map((event) => `- ${event.text}`).join("\n");
1982
- let checked;
1983
- const result = await runChild({
1984
- parent,
1985
- signal,
1986
- sampling: childSampling(store.settings(), "authoring"),
1987
- ...childModel(store.settings(), "authoring"),
1988
- trace: childTrace(store, "authoring", "plot author"),
1989
- persona: promptFor(parent, "roleplay/plot-author", store.settings().prompts.language),
1990
- reasoningEffort: store.settings().reasoning.children,
1991
- result: RESULT,
1992
- maxCalls: 3,
1993
- 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"}`,
1994
- beforeSubmit(value) {
1995
- const authored = value;
1996
- const candidate = {
1997
- ...authored,
1998
- hooks: [{
1999
- ...authored.hook,
2000
- mode: "opportunity",
2001
- prerequisites: []
2002
- }],
2003
- start: "available",
2004
- pacing: {
2005
- quietTurns: 3,
2006
- cooldownTurns: 4,
2007
- cooldownDays: 1
2008
- }
2009
- };
2010
- const parsed = parsePlotsFile(JSON.stringify([candidate]));
2011
- if (!parsed.ok) return parsed.issues.map((issue) => `${issue.path}: ${issue.message}`).join("\n");
2012
- checked = parsed.value[0];
2013
- }
2014
- });
2015
- if (checked === void 0) throw new Error(`the plot author returned an invalid plot: ${result.name}`);
2016
- addSessionPlot(store, checked);
2017
- return checked;
2018
- }
2019
- //#endregion
2020
- //#region src/host/orchestration/tools.ts
2021
- const ACTIVATE_TOOL = "activate_characters";
2022
- const RESOLVE_TOOL = "resolve_round";
2023
- const NARRATE_TOOL = "narrate";
2024
- const RECORD_TOOL = "record_memory";
2025
- const EXPAND_TOOL = "expand_world";
2026
- const INTRODUCE_TOOL = "introduce_thing";
2027
- const TIME_TOOL = "advance_time";
2028
- const PREVIEW_TOOL = "preview_scene";
2029
- const RULING_TOOL = "ooc_ruling";
2030
- const ANSWER_TOOL = "ooc_answer";
2031
- const JUDGE_TOOL = "judge_action";
2032
- const PLOT_TOOL = "record_plot_progress";
2033
- const AUTHOR_PLOT_TOOL = "author_plot";
2034
- /** The JSON value the tool records; the model reads the rendered text. */
2035
- function record(value) {
2036
- return JSON.parse(JSON.stringify(value));
2037
- }
2038
- function failures(list) {
2039
- return list.length === 0 ? [] : [
2040
- "",
2041
- "Could not act:",
2042
- ...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}`)
2043
- ];
2044
- }
2045
- function renderAttempt(attempt) {
2046
- 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.";
2047
- 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}]`);
2048
- 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.`];
2049
- return [
2050
- heading,
2051
- ...lines,
2052
- ...failures(attempt.failures),
2053
- ...next
2054
- ].join("\n");
2055
- }
2056
- /** Who went where because their day says so. */
2057
- const routineLine = (move) => `By their routine, ${move.name} is now at ${move.to} (${move.activity}).`;
2058
- 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.";
2059
- const listed = (utterances) => utterances.map((utterance) => `- ${utterance.character} (${utterance.name}), round ${utterance.round}: "${utterance.text}"`).join("\n");
2060
- /** What the world did by itself, as the game master is told: what happened, what characters notice, and what it is to weave in. */
2061
- function renderWorld(world) {
2062
- return world.flatMap((entry) => [
2063
- ...entry.events.map((text) => `The world acted (${entry.name}): ${text}`),
2064
- ...entry.cues.map((cue) => `${cue.names.join(" and ")} will notice: ${cue.text}`),
2065
- ...entry.beats.map((beat) => `Weave this into the story, then say you did with addressed: [${beat.id}] in narrate (${beat.text})`)
2066
- ]);
2067
- }
2068
- function renderResolution(report) {
2069
- if (report.next !== void 0) return renderAttempt(report.next);
2070
- const done = report.done;
2071
- if (done === void 0) return "";
2072
- const left = done.limit - done.round;
2073
- const passed = done.time.to - done.time.from;
2074
- const lines = [
2075
- `Round ${done.round} is recorded (${done.updated.join(", ")}).`,
2076
- `It is now ${describeTime({
2077
- now: done.time.to,
2078
- zone: done.time.zone
2079
- })}${passed > 0 ? `; ${describeDuration(passed)} passed` : ""}.`,
2080
- ...done.moved.map(routineLine),
2081
- ...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"})` : ""}.`),
2082
- ...done.things.map((thing) => `${thing.name}: ${thing.summary}.`),
2083
- ...done.variables.map((line) => `${line}.`),
2084
- ...renderWorld(done.world),
2085
- ...failures(done.retryFailures)
2086
- ];
2087
- 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)}`);
2088
- 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.");
2089
- 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.`);
2090
- lines.push(OUTPUT_RULES);
2091
- lines.push("Narrate only what the player's character can perceive.");
2092
- return lines.join("\n");
2093
- }
2094
- function renderExpansion(report) {
2095
- 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.`;
2096
- const lines = report.created.map((entry) => `- ${entry.kind} ${entry.key} (${entry.name})`);
2097
- const characters = report.created.filter((entry) => entry.kind === "character");
2098
- return [
2099
- "Made up and fitted into the world:",
2100
- ...lines,
2101
- ...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.`],
2102
- ...report.declined === void 0 ? [] : [`Not made: ${report.declined}`]
2103
- ].join("\n");
2104
- }
2105
- /** The tools the game master plays a turn with. */
2106
- function createTools$1(deps) {
2107
- const ownerOf = (agent) => {
2108
- if (agent === void 0) throw new Error("the roleplay tools can only be called by an agent");
2109
- return {
2110
- agent,
2111
- owner: {
2112
- chat: agent.session.id,
2113
- turn: deps.turnOf(agent)
2114
- }
2115
- };
2116
- };
2117
- const storeOf = (chat) => {
2118
- const store = deps.stores(chat);
2119
- if (store === void 0) throw new Error("this chat is not a roleplay session");
2120
- return store;
2121
- };
2122
- const activate = defineTool({
2123
- name: ACTIVATE_TOOL,
2124
- 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.",
2125
- parameters: {
2126
- characters: {
2127
- type: "array",
2128
- required: true,
2129
- items: { type: "string" },
2130
- 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."
2131
- },
2132
- situation: {
2133
- type: "string",
2134
- required: true,
2135
- 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."
2136
- }
2137
- },
2138
- output: {
2139
- schema: { type: "json" },
2140
- render: (_args, value) => [{
2141
- type: "text",
2142
- text: renderAttempt(value)
2143
- }]
2144
- },
2145
- isConcurrencySafe: () => false,
2146
- async execute(args, exec) {
2147
- const { agent, owner } = ownerOf(exec.agent);
2148
- await deps.engine.settle(owner.chat, owner.turn);
2149
- const run = characterRunner({
2150
- parent: agent,
2151
- boundaries: deps.boundaries,
2152
- store: storeOf(owner.chat)
2153
- });
2154
- return record(await deps.engine.activate(owner, {
2155
- situation: args.situation,
2156
- characters: args.characters
2157
- }, run, exec.signal));
2158
- }
2159
- });
2160
- const resolve = defineTool({
2161
- name: RESOLVE_TOOL,
2162
- 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.",
2163
- parameters: {
2164
- outcomes: {
2165
- type: "array",
2166
- required: true,
2167
- items: {
2168
- type: "object",
2169
- additionalProperties: false,
2170
- properties: {
2171
- character: {
2172
- type: "string",
2173
- required: true,
2174
- 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."
2175
- },
2176
- result: {
2177
- type: "string",
2178
- required: true,
2179
- enum: RESULTS,
2180
- description: "Whether the character's intent went through."
2181
- },
2182
- summary: {
2183
- type: "string",
2184
- required: true,
2185
- description: "What concretely happens to the character, in a sentence. It becomes what the character is doing."
2186
- },
2187
- spoken: {
2188
- type: "boolean",
2189
- description: "Whether the character gets to say its utterance. It does unless something prevents it, such as being silenced or knocked out first."
2190
- },
2191
- public_state: {
2192
- type: "string",
2193
- description: "What anyone present can now see or infer about the character, when that changed."
2194
- },
2195
- item_changes: {
2196
- type: "array",
2197
- 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.",
2198
- items: {
2199
- type: "object",
2200
- additionalProperties: false,
2201
- properties: {
2202
- item: {
2203
- type: "string",
2204
- required: true,
2205
- description: "The key of the item, as the scene lists it. Leave a way's lock to exit."
2206
- },
2207
- action: {
2208
- type: "string",
2209
- required: true,
2210
- enum: ITEM_ACTIONS,
2211
- 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)."
2212
- },
2213
- to: {
2214
- type: "string",
2215
- description: "For give: who gets it. For put: the container."
2216
- },
2217
- quantity: {
2218
- type: "integer",
2219
- description: "How many, of a pile; all when left out."
2220
- },
2221
- position: {
2222
- type: "string",
2223
- description: "Where, in words, for drop and put."
2224
- },
2225
- feature: {
2226
- type: "string",
2227
- description: "For drop: the feature of the place it is left at."
2228
- },
2229
- with: {
2230
- type: "string",
2231
- description: "For lock and unlock: the key item used. It has to be in hand and fit the lock."
2232
- },
2233
- exit: {
2234
- type: "string",
2235
- description: "For lock and unlock of a way instead of an item: the key of the place it leads to."
2236
- },
2237
- forced: {
2238
- type: "boolean",
2239
- description: "Only when the story breaks the lock (picked, smashed): no key is needed."
2240
- }
2241
- }
2242
- }
2243
- },
2244
- variable_changes: {
2245
- type: "array",
2246
- 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).",
2247
- items: {
2248
- type: "object",
2249
- additionalProperties: false,
2250
- properties: {
2251
- variable: {
2252
- type: "string",
2253
- required: true,
2254
- description: "The key of the variable."
2255
- },
2256
- subject: {
2257
- type: "string",
2258
- required: true,
2259
- description: "The key of the character, item or place it is about; world for the whole story."
2260
- },
2261
- to: {
2262
- oneOf: [
2263
- { type: "number" },
2264
- { type: "boolean" },
2265
- { type: "string" }
2266
- ],
2267
- description: "The new value."
2268
- },
2269
- by: {
2270
- type: "number",
2271
- description: "How much a number goes up (positive) or down (negative)."
2272
- },
2273
- baseline: {
2274
- oneOf: [
2275
- { type: "number" },
2276
- { type: "boolean" },
2277
- { type: "string" }
2278
- ],
2279
- description: "For a variable with a temperament (feelings): the new baseline, when what happened changes it lastingly."
2280
- }
2281
- }
2282
- }
2283
- },
2284
- moves_to: {
2285
- type: "object",
2286
- additionalProperties: false,
2287
- 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.",
2288
- properties: {
2289
- location: {
2290
- type: "string",
2291
- required: true,
2292
- description: "The key of the place, as the scene lists it."
2293
- },
2294
- position: {
2295
- type: "string",
2296
- description: "Where in the place, in words: \"by the window\"."
2297
- },
2298
- feature: {
2299
- type: "string",
2300
- description: "The key of a feature of that place it is at."
2301
- },
2302
- ignore_exits: {
2303
- type: "boolean",
2304
- description: "Only when the story itself carries it (carried off, teleported, falls): the exits do not matter."
2305
- }
2306
- }
2307
- }
2308
- }
2309
- }
2310
- },
2311
- elapsed_seconds: {
2312
- type: "integer",
2313
- 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."
2314
- }
2315
- },
2316
- output: {
2317
- schema: { type: "json" },
2318
- render: (_args, value) => [{
2319
- type: "text",
2320
- text: renderResolution(value)
2321
- }]
2322
- },
2323
- isConcurrencySafe: () => false,
2324
- async execute(args, exec) {
2325
- const { agent, owner } = ownerOf(exec.agent);
2326
- await deps.engine.settle(owner.chat, owner.turn);
2327
- const run = characterRunner({
2328
- parent: agent,
2329
- boundaries: deps.boundaries,
2330
- store: storeOf(owner.chat)
2331
- });
2332
- const outcomes = args.outcomes.map((outcome) => ({
2333
- character: outcome.character,
2334
- result: outcome.result,
2335
- summary: outcome.summary,
2336
- ...outcome.public_state === void 0 ? {} : { publicState: outcome.public_state },
2337
- ...outcome.spoken === void 0 ? {} : { spoken: outcome.spoken },
2338
- ...outcome.item_changes === void 0 || outcome.item_changes.length === 0 ? {} : { itemChanges: outcome.item_changes.map((change) => ({
2339
- item: change.item,
2340
- action: change.action,
2341
- ...change.to === void 0 ? {} : { to: change.to },
2342
- ...change.quantity === void 0 ? {} : { quantity: change.quantity },
2343
- ...change.position === void 0 ? {} : { position: change.position },
2344
- ...change.feature === void 0 ? {} : { feature: change.feature },
2345
- ...change.with === void 0 ? {} : { with: change.with },
2346
- ...change.exit === void 0 ? {} : { exit: change.exit },
2347
- ...change.forced === true ? { forced: true } : {}
2348
- })) },
2349
- ...outcome.variable_changes === void 0 || outcome.variable_changes.length === 0 ? {} : { variableChanges: outcome.variable_changes.map((change) => ({
2350
- variable: change.variable,
2351
- subject: change.subject,
2352
- ...change.to === void 0 ? {} : { to: change.to },
2353
- ...change.by === void 0 ? {} : { by: change.by },
2354
- ...change.baseline === void 0 ? {} : { baseline: change.baseline }
2355
- })) },
2356
- ...outcome.moves_to === void 0 ? {} : { moveTo: {
2357
- location: outcome.moves_to.location,
2358
- ...outcome.moves_to.position === void 0 ? {} : { position: outcome.moves_to.position },
2359
- ...outcome.moves_to.feature === void 0 ? {} : { feature: outcome.moves_to.feature },
2360
- ...outcome.moves_to.ignore_exits === true ? { ignoreExits: true } : {}
2361
- } }
2362
- }));
2363
- return record(await deps.engine.resolve(owner, outcomes, run, exec.signal, args.elapsed_seconds));
2364
- }
2365
- });
2366
- const narrate = defineTool({
2367
- name: NARRATE_TOOL,
2368
- 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.",
2369
- parameters: {
2370
- segments: {
2371
- type: "array",
2372
- description: "The output in order. Leave out only when a narrator other than you writes the output.",
2373
- items: {
2374
- type: "object",
2375
- additionalProperties: false,
2376
- properties: {
2377
- type: {
2378
- type: "string",
2379
- required: true,
2380
- enum: ["utterance", "narration"]
2381
- },
2382
- character: {
2383
- type: "string",
2384
- description: "For an utterance: the key of the character who says it."
2385
- },
2386
- text: {
2387
- type: "string",
2388
- required: true,
2389
- description: "For an utterance: the words exactly as the character gave them, without quotation marks. For narration: what the player reads."
2390
- }
2391
- }
2392
- }
2393
- },
2394
- addressed: {
2395
- type: "array",
2396
- items: { type: "integer" },
2397
- 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."
2398
- }
2399
- },
2400
- output: {
2401
- schema: { type: "json" },
2402
- render: (_args, value) => {
2403
- const output = value;
2404
- return [{
2405
- type: "text",
2406
- 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)}`
2407
- }];
2408
- }
2409
- },
2410
- isConcurrencySafe: () => false,
2411
- async execute(args, exec) {
2412
- const { agent, owner } = ownerOf(exec.agent);
2413
- await deps.engine.settle(owner.chat, owner.turn);
2414
- const segments = (args.segments ?? []).map((segment) => ({
2415
- type: segment.type,
2416
- text: segment.text,
2417
- ...segment.character === void 0 ? {} : { character: segment.character }
2418
- }));
2419
- const output = await deps.engine.narrate(owner, segments, characterRunner({
2420
- parent: agent,
2421
- boundaries: deps.boundaries,
2422
- store: storeOf(owner.chat)
2423
- }), args.addressed ?? []);
2424
- const timelineNode = deps.delivered?.(owner.chat, output);
2425
- const delivered = timelineNode === void 0 ? output : {
2426
- ...output,
2427
- timelineNode
2428
- };
2429
- exec.concludeTurn();
2430
- return record(delivered);
2431
- }
2432
- });
2433
- const remember = defineTool({
2434
- name: RECORD_TOOL,
2435
- 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.",
2436
- parameters: { focus: {
2437
- type: "string",
2438
- 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."
2439
- } },
2440
- output: {
2441
- schema: { type: "json" },
2442
- render: (_args, value) => [{
2443
- type: "text",
2444
- text: `The memory keeper is writing ${value.rounds} round${value.rounds === 1 ? "" : "s"} into the story's memory.`
2445
- }]
2446
- },
2447
- isConcurrencySafe: () => false,
2448
- execute(args, exec) {
2449
- const { owner } = ownerOf(exec.agent);
2450
- return Promise.resolve(record({ rounds: deps.engine.record(owner, args.focus) }));
2451
- }
2452
- });
2453
- const plot = defineTool({
2454
- name: PLOT_TOOL,
2455
- 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.",
2456
- parameters: {
2457
- plot: {
2458
- type: "string",
2459
- required: true,
2460
- description: "The plot id from the pacing opportunity."
2461
- },
2462
- development: {
2463
- type: "string",
2464
- description: "The development id; required for introduced or rejected."
2465
- },
2466
- action: {
2467
- type: "string",
2468
- required: true,
2469
- enum: [
2470
- "introduced",
2471
- "rejected",
2472
- "resolved",
2473
- "abandoned"
2474
- ]
2475
- }
2476
- },
2477
- output: {
2478
- schema: { type: "json" },
2479
- render: (_args, value) => [{
2480
- type: "text",
2481
- text: `Plot pacing recorded: ${value.plot.name} is ${value.status}.`
2482
- }]
2483
- },
2484
- isConcurrencySafe: () => false,
2485
- execute(args, exec) {
2486
- const { owner } = ownerOf(exec.agent);
2487
- return Promise.resolve(record(updatePlotProgress(storeOf(owner.chat), args.plot, args.development, args.action)));
2488
- }
2489
- });
2490
- const makePlot = defineTool({
2491
- name: AUTHOR_PLOT_TOOL,
2492
- 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.",
2493
- parameters: {},
2494
- output: {
2495
- schema: { type: "json" },
2496
- render: (_args, value) => {
2497
- const made = value;
2498
- return [{
2499
- type: "text",
2500
- 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.`
2501
- }];
2502
- }
2503
- },
2504
- isConcurrencySafe: () => false,
2505
- async execute(_args, exec) {
2506
- const { agent, owner } = ownerOf(exec.agent);
2507
- const store = storeOf(owner.chat);
2508
- 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");
2509
- return record(await authorPlot(agent, store, owner.turn, exec.signal));
2510
- }
2511
- });
2512
- const expand = defineTool({
2513
- name: EXPAND_TOOL,
2514
- 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.",
2515
- parameters: {
2516
- need: {
2517
- type: "string",
2518
- required: true,
2519
- enum: AUTHORING_NEEDS,
2520
- description: "Why: scene_change, arrival, introduction, object, variable or trigger."
2521
- },
2522
- what: {
2523
- type: "string",
2524
- required: true,
2525
- 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."
2526
- }
2527
- },
2528
- output: {
2529
- schema: { type: "json" },
2530
- render: (_args, value) => [{
2531
- type: "text",
2532
- text: renderExpansion(value)
2533
- }]
2534
- },
2535
- isConcurrencySafe: () => false,
2536
- async execute(args, exec) {
2537
- const { owner } = ownerOf(exec.agent);
2538
- await deps.engine.settle(owner.chat, owner.turn);
2539
- return record(await deps.engine.expand(owner, {
2540
- need: args.need,
2541
- what: args.what
2542
- }, exec.signal));
2543
- }
2544
- });
2545
- const introduce = defineTool({
2546
- name: INTRODUCE_TOOL,
2547
- 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.",
2548
- parameters: {
2549
- name: {
2550
- type: "string",
2551
- required: true,
2552
- description: "What it is called, as the story names it."
2553
- },
2554
- description: {
2555
- type: "string",
2556
- description: "One or two sentences: what it looks like, what it is made of, what state it is in."
2557
- },
2558
- quantity: {
2559
- type: "integer",
2560
- description: "How many, when it is a number of the same thing (default 1)."
2561
- },
2562
- quality: {
2563
- type: "string",
2564
- description: "Its condition in a word or two (rusty, new), when that matters."
2565
- },
2566
- notable: {
2567
- type: "boolean",
2568
- description: "Whether the characters present would notice it at once."
2569
- },
2570
- hidden: {
2571
- type: "boolean",
2572
- description: "Whether it starts out of sight (until a round reveals it)."
2573
- },
2574
- at: {
2575
- type: "string",
2576
- description: "The key of the place it lies in."
2577
- },
2578
- held_by: {
2579
- type: "string",
2580
- description: "The key of the character who holds it."
2581
- },
2582
- inside: {
2583
- type: "string",
2584
- description: "The key of the container it is in."
2585
- }
2586
- },
2587
- output: {
2588
- schema: { type: "json" },
2589
- render: (_args, value) => {
2590
- const made = value;
2591
- return [{
2592
- type: "text",
2593
- text: `Introduced ${made.name} [${made.key}], ${made.where}. Use the key in item_changes; nobody has taken it up yet.`
2594
- }];
2595
- }
2596
- },
2597
- isConcurrencySafe: () => false,
2598
- async execute(args, exec) {
2599
- const { owner } = ownerOf(exec.agent);
2600
- await deps.engine.settle(owner.chat, owner.turn);
2601
- return record(deps.engine.introduce(owner, {
2602
- name: args.name,
2603
- ...args.description === void 0 ? {} : { description: args.description },
2604
- ...args.quantity === void 0 ? {} : { quantity: args.quantity },
2605
- ...args.quality === void 0 ? {} : { quality: args.quality },
2606
- ...args.notable === void 0 ? {} : { notable: args.notable },
2607
- ...args.hidden === void 0 ? {} : { hidden: args.hidden },
2608
- ...args.at === void 0 ? {} : { at: args.at },
2609
- ...args.held_by === void 0 ? {} : { heldBy: args.held_by },
2610
- ...args.inside === void 0 ? {} : { inside: args.inside }
2611
- }));
2612
- }
2613
- });
2614
- const skip = defineTool({
2615
- name: TIME_TOOL,
2616
- 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.",
2617
- parameters: {
2618
- reason: {
2619
- type: "string",
2620
- required: true,
2621
- description: "What happens in the time that passes, in a sentence (\"they sleep\", \"the ferry crosses\")."
2622
- },
2623
- by_minutes: {
2624
- type: "integer",
2625
- description: "How many minutes to skip."
2626
- },
2627
- until_time: {
2628
- type: "string",
2629
- 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."
2630
- },
2631
- days_later: {
2632
- type: "integer",
2633
- description: "With until_time: that many days after today (0 is later today, 1 is tomorrow)."
2634
- }
2635
- },
2636
- output: {
2637
- schema: { type: "json" },
2638
- render: (_args, value) => {
2639
- const done = value;
2640
- return [{
2641
- type: "text",
2642
- text: `${describeDuration(done.to - done.from)} pass. It is now ${describeTime({
2643
- now: done.to,
2644
- zone: done.zone
2645
- })}.${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")}`}`
2646
- }];
2647
- }
2648
- },
2649
- isConcurrencySafe: () => false,
2650
- async execute(args, exec) {
2651
- const { owner } = ownerOf(exec.agent);
2652
- await deps.engine.settle(owner.chat, owner.turn);
2653
- 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");
2654
- if (args.days_later !== void 0 && args.until_time === void 0) throw new Error("days_later goes with until_time");
2655
- const request = args.by_minutes !== void 0 ? {
2656
- byMinutes: args.by_minutes,
2657
- reason: args.reason
2658
- } : {
2659
- untilTime: args.until_time ?? "",
2660
- ...args.days_later === void 0 ? {} : { daysLater: args.days_later },
2661
- reason: args.reason
2662
- };
2663
- return record(deps.engine.advanceTime(owner, request));
2664
- }
2665
- });
2666
- const preview = defineTool({
2667
- name: PREVIEW_TOOL,
2668
- 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.",
2669
- parameters: { text: {
2670
- type: "string",
2671
- required: true,
2672
- description: "The opening, plain prose in the narration voice."
2673
- } },
2674
- output: {
2675
- schema: { type: "json" },
2676
- render: (_args, value) => [{
2677
- type: "text",
2678
- text: `${encodePreview(value.text)}\nShown to the player. Now call activate_characters.`
2679
- }]
2680
- },
2681
- isConcurrencySafe: () => false,
2682
- execute(args, exec) {
2683
- const { owner } = ownerOf(exec.agent);
2684
- return Promise.resolve(record({ text: deps.engine.preview(owner, args.text) }));
2685
- }
2686
- });
2687
- const ruling = defineTool({
2688
- name: RULING_TOOL,
2689
- 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.",
2690
- parameters: {
2691
- rule_check: {
2692
- type: "string",
2693
- required: true,
2694
- 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."
2695
- },
2696
- legal: {
2697
- type: "boolean",
2698
- required: true,
2699
- description: "Whether the command is allowed: false when any listed rule is broken."
2700
- },
2701
- reason: {
2702
- type: "string",
2703
- required: true,
2704
- description: "To the player, in plain words and briefly: what you will do, or which rule it breaks."
2705
- }
2706
- },
2707
- output: {
2708
- schema: { type: "json" },
2709
- render: (_args, value) => [{
2710
- type: "text",
2711
- 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.`
2712
- }]
2713
- },
2714
- isConcurrencySafe: () => false,
2715
- execute(args, exec) {
2716
- const { owner } = ownerOf(exec.agent);
2717
- return Promise.resolve(record(deps.engine.rule(owner, args.legal, args.reason)));
2718
- }
2719
- });
2720
- const answer = defineTool({
2721
- name: ANSWER_TOOL,
2722
- 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.",
2723
- parameters: {},
2724
- output: {
2725
- schema: { type: "json" },
2726
- render: () => [{
2727
- type: "text",
2728
- text: `The player is shown the answer. Now call ${NARRATE_TOOL} with no segments.`
2729
- }]
2730
- },
2731
- isConcurrencySafe: () => false,
2732
- async execute(_args, exec) {
2733
- const { agent, owner } = ownerOf(exec.agent);
2734
- return record(await deps.engine.answer(owner, answerRunner({
2735
- parent: agent,
2736
- boundaries: deps.boundaries,
2737
- store: storeOf(owner.chat)
2738
- }), exec.signal));
2739
- }
2740
- });
2741
- return [
2742
- defineTool({
2743
- name: JUDGE_TOOL,
2744
- 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.",
2745
- parameters: {
2746
- rule_check: {
2747
- type: "string",
2748
- required: true,
2749
- 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."
2750
- },
2751
- at: {
2752
- type: "string",
2753
- 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)."
2754
- },
2755
- allowed: {
2756
- type: "boolean",
2757
- required: true,
2758
- description: "Whether what the character tries can work: false when any listed rule is broken or it is not viable."
2759
- },
2760
- reason: {
2761
- type: "string",
2762
- required: true,
2763
- description: "What the character tries, and the rule or the fact that decides it, in a sentence."
2764
- }
2765
- },
2766
- output: {
2767
- schema: { type: "json" },
2768
- render: (_args, value) => [{
2769
- type: "text",
2770
- text: value.allowed ? `Judged: it can work. 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.`
2771
- }]
2772
- },
2773
- isConcurrencySafe: () => false,
2774
- execute(args, exec) {
2775
- const { owner } = ownerOf(exec.agent);
2776
- return Promise.resolve(record(deps.engine.judge(owner, args.allowed, args.reason, args.at)));
2777
- }
2778
- }),
2779
- preview,
2780
- ruling,
2781
- answer,
2782
- activate,
2783
- resolve,
2784
- skip,
2785
- remember,
2786
- expand,
2787
- introduce,
2788
- makePlot,
2789
- plot,
2790
- narrate
2791
- ];
2792
- }
2793
- //#endregion
2794
1973
  //#region src/host/memory/embedding-index.ts
2795
1974
  const BATCH = 32;
2796
1975
  /**
@@ -3027,10 +2206,415 @@ var AfterTurnJobs = class {
3027
2206
  }
3028
2207
  };
3029
2208
  //#endregion
3030
- //#region src/host/orchestration/turn-engine.ts
3031
- const MAX_OBJECTIONS = 3;
3032
- /** The most a single round may be said to take: a day. A longer time passing is skipped with `advanceTime`. */
3033
- const MAX_ROUND_SECONDS = 86400;
2209
+ //#region src/host/orchestration/turn-rules.ts
2210
+ /** Whether the game master still has to judge the player's action. */
2211
+ function judgeDue(state) {
2212
+ return state.judgeWanted === true && state.phase === "idle" && state.ooc === void 0 && state.judgement === void 0;
2213
+ }
2214
+ /** Why an out-of-character command may not change anything yet, when it may not. */
2215
+ function oocBlock(state) {
2216
+ if (state.ooc === void 0) return void 0;
2217
+ if (state.ooc.question === true) return state.ooc.ruling === void 0 ? "this turn is an out-of-character question: answer it first with ooc_answer" : "a question changes nothing: call narrate with no segments";
2218
+ if (state.ooc.ruling === void 0) return "this turn is an out-of-character command: rule on it first with ooc_ruling";
2219
+ return state.ooc.ruling.legal ? void 0 : "the command was refused: nothing changes; call narrate with no segments to tell the player";
2220
+ }
2221
+ /** Whether the chat wants a preview of the scene and the game master has not shown it yet. */
2222
+ function previewDue(state) {
2223
+ return state.phase === "idle" && state.previewWanted && !state.previewed && state.judgement?.allowed !== false;
2224
+ }
2225
+ /** Whether the game master still has to roll for an attempt it judged uncertain: nobody is asked to act before the dice are rolled. */
2226
+ function rollDue(state, store) {
2227
+ return state.rollWanted === true && state.phase === "idle" && state.judgement?.allowed !== false && store.story.dice.rolls({ turn: state.turn }).every((roll) => roll.by !== "agent");
2228
+ }
2229
+ const ROLL_FIRST = "the attempt is uncertain and matters, so roll for it before anyone is asked to act: call roll_check with the check that fits (list_checks shows them), naming the character it is for; roll_dice only when no check fits";
2230
+ function explainPhase(state, attempted) {
2231
+ if (state.ooc?.question === true && (state.phase === "idle" || state.phase === "between")) return state.ooc.ruling === void 0 ? "this turn is an out-of-character question: answer it first with ooc_answer" : "a question changes nothing: call narrate with no segments";
2232
+ if (state.ooc !== void 0 && (state.phase === "idle" || state.phase === "between")) return state.ooc.ruling === void 0 ? "this turn is an out-of-character command: rule on it first with ooc_ruling" : state.ooc.ruling.legal ? "make the command happen with resolve_round, expand_world or advance_time, then call narrate with what the player perceives (narration only)" : "the command was refused: call narrate with no segments";
2233
+ const waiting = (attempt) => (attempt?.reports ?? []).map((report) => report.character).join(", ");
2234
+ switch (state.phase) {
2235
+ case "idle": return judgeDue(state) ? "call judge_action first: does what the player's character tries work? It does not when it is not viable or it breaks a rule of the world or of the player" : previewDue(state) ? "call preview_scene first: two or three sentences that show the player how the scene opens, before the characters are asked" : state.judgement?.allowed === false && attempted !== "activate_characters" ? `the attempt does not work (${state.judgement.reason}): call resolve_round with one outcome, for the player's character only (result failed, a sentence on what it does and why nothing comes of it)${attempted === "narrate" ? ", then narrate" : ""}` : attempted === "activate_characters" || attempted === void 0 ? "call activate_characters to let the characters act" : attempted === "narrate" ? "nothing to deliver yet: call activate_characters to let the characters act, or, when nobody else needs to react, call resolve_round with an outcome for the player's character alone, and then narrate" : "nothing to resolve yet: call activate_characters first";
2236
+ case "resolving": return attempted === "activate_characters" ? "the characters already acted in this round: call resolve_round" : attempted === "narrate" ? `resolve the round first: call resolve_round with one outcome for each of: ${waiting(state.first)}` : `call resolve_round with one outcome for each of: ${waiting(state.first)}`;
2237
+ case "retrying": return attempted === "activate_characters" ? "the characters already acted in this round: call resolve_round" : attempted === "narrate" ? `resolve the round first: call resolve_round once more, with one outcome for each of: ${waiting(state.second)}` : `call resolve_round once more, with one outcome for each of: ${waiting(state.second)}`;
2238
+ case "between": return attempted === "resolve_round" ? "the round is already recorded: call activate_characters again if the story needs it, or narrate" : `call narrate with the output of the turn${mustSay(state)}${canContinue(state)}`;
2239
+ case "done": return "this turn is already recorded";
2240
+ case "skipped": return "this turn needs no round";
2241
+ }
2242
+ }
2243
+ function canContinue(state) {
2244
+ const left = (state.limit ?? 0) - state.rounds;
2245
+ return left > 0 ? `, or call activate_characters if the story genuinely needs them again (${left} round(s) left)` : "";
2246
+ }
2247
+ function mustSay(state) {
2248
+ return state.utterances.length === 0 ? "" : `; it must carry these utterances exactly, in this order: ${state.utterances.map((utterance) => `${utterance.name}: "${utterance.text}"`).join(" | ")}`;
2249
+ }
2250
+ /** `player` is the key of the player's character when an outcome for it is acceptable: it is not asked to act, but what it did can move it or have it handle things. */
2251
+ function checkOutcomes(attempt, outcomes, store, player, decreed, state) {
2252
+ const expected = decreed === void 0 ? attempt.reports.map((report) => report.character) : [...new Set(outcomes.map((outcome) => outcome.character))];
2253
+ const unknown = decreed === void 0 ? [] : [...new Set(outcomes.map((outcome) => outcome.character))].filter((key) => !decreed.some((member) => member.key === key)).map((key) => `${key} is not a character of the story`);
2254
+ const given = outcomes.filter((outcome) => outcome.character !== player).map((outcome) => outcome.character);
2255
+ const problems = [
2256
+ ...unknown,
2257
+ ...outcomes.filter((outcome) => outcome.character === player).length > 1 ? [`more than one outcome for ${player}`] : [],
2258
+ ...expected.filter((key) => !given.includes(key)).map((key) => `missing an outcome for ${key}`),
2259
+ ...[...new Set(given.filter((key) => !expected.includes(key)))].map((key) => `${key} is not waiting for an outcome`),
2260
+ ...[...new Set(given.filter((key, index) => given.indexOf(key) !== index))].map((key) => `more than one outcome for ${key}`),
2261
+ ...outcomes.filter((outcome) => !RESULTS.includes(outcome.result)).map((outcome) => `${outcome.character}: unknown result "${outcome.result}"`),
2262
+ ...outcomes.filter((outcome) => outcome.summary.trim() === "").map((outcome) => `${outcome.character}: say what happens`),
2263
+ ...outcomes.flatMap((outcome) => moveProblems(outcome, store)),
2264
+ ...itemProblems(outcomes, store),
2265
+ ...outcomes.flatMap((outcome) => store.checkVariableChanges(outcome.variableChanges ?? []).map((problem) => `${outcome.character}: ${problem}`)),
2266
+ ...state === void 0 ? [] : rollProblems(outcomes, store, state)
2267
+ ];
2268
+ if (problems.length > 0) throw new Error(`the outcomes are not acceptable: ${problems.join("; ")} (expected exactly: ${expected.join(", ")})`);
2269
+ for (const outcome of outcomes) if (outcome.roll !== void 0) state?.cited.add(outcome.roll);
2270
+ }
2271
+ /**
2272
+ * Why an outcome does not follow the dice, if it does not. A roll decides what it was rolled for: the result of the outcome is the roll's own, a roll serves one outcome,
2273
+ * and a character a check was rolled for cannot be given an outcome without it.
2274
+ */
2275
+ function rollProblems(outcomes, store, state) {
2276
+ const rolls = store.story.dice.rolls({ turn: state.turn });
2277
+ const problems = [];
2278
+ const taken = /* @__PURE__ */ new Set();
2279
+ for (const outcome of outcomes) {
2280
+ if (outcome.roll === void 0) continue;
2281
+ const roll = rolls.find((candidate) => candidate.id === outcome.roll);
2282
+ if (roll === void 0) problems.push(`${outcome.character}: there is no roll ${outcome.roll} in this turn: use the id the roll tool gave`);
2283
+ else if (roll.readout === void 0) problems.push(`${outcome.character}: roll ${roll.id} was a plain roll with no result to take: leave roll out and decide it yourself`);
2284
+ else if (state.cited.has(roll.id) || taken.has(roll.id)) problems.push(`${outcome.character}: roll ${roll.id} already decided another outcome: roll again for this one`);
2285
+ else if (roll.character !== void 0 && roll.character !== outcome.character) problems.push(`${outcome.character}: roll ${roll.id} was for ${roll.character}`);
2286
+ else if (roll.readout.result !== outcome.result) problems.push(`${outcome.character}: roll ${roll.id} gave ${roll.readout.result} (${roll.readout.label}), so the outcome's result is ${roll.readout.result}, not ${outcome.result}: the dice decide it`);
2287
+ taken.add(outcome.roll);
2288
+ }
2289
+ for (const roll of rolls) {
2290
+ if (roll.readout === void 0 || roll.character === void 0 || state.cited.has(roll.id) || taken.has(roll.id)) continue;
2291
+ if (outcomes.some((outcome) => outcome.character === roll.character && outcome.roll === void 0)) problems.push(`${roll.character}: you rolled for this character (roll ${roll.id}: ${roll.readout.label}, ${roll.readout.result}): give the outcome the result ${roll.readout.result} and cite the roll by adding "roll": ${roll.id} to that outcome`);
2292
+ }
2293
+ return problems;
2294
+ }
2295
+ /** Why a character cannot go where the outcome sends it, if it cannot: the game master hears it before the round is recorded. */
2296
+ function moveProblems(outcome, store) {
2297
+ if (outcome.moveTo === void 0) return [];
2298
+ if (outcome.result === "failed") return [`${outcome.character}: its intent failed, so it does not go anywhere: leave moves_to out`];
2299
+ const checked = store.checkMove(outcome.character, outcome.moveTo);
2300
+ return checked.ok ? [] : checked.problems.map((problem) => `${outcome.character}: cannot go to ${outcome.moveTo?.location}: ${problem}`);
2301
+ }
2302
+ /** Why what the outcomes do with things cannot be done, if it cannot: tried in order, each seeing what the one before did. */
2303
+ function itemProblems(outcomes, store) {
2304
+ const entries = outcomes.flatMap((outcome) => outcome.itemChanges === void 0 || outcome.itemChanges.length === 0 || outcome.result === "failed" ? [] : [{
2305
+ character: outcome.character,
2306
+ changes: outcome.itemChanges
2307
+ }]);
2308
+ const failed = outcomes.filter((outcome) => outcome.result === "failed" && (outcome.itemChanges?.length ?? 0) > 0).map((outcome) => `${outcome.character}: its intent failed, so it does nothing with things: leave item_changes out`);
2309
+ if (entries.length === 0) return failed;
2310
+ const checked = store.checkItemChanges(entries);
2311
+ return checked.ok ? failed : [...failed, ...checked.problems];
2312
+ }
2313
+ /** What the world made a character notice: taken up in the first attempt of a round, and told the same again on the retry. */
2314
+ function cuesOf(state, key, member, store, attempt) {
2315
+ if (attempt === 2 || store === void 0) return state.cues.get(key) ?? [];
2316
+ const pending = store.cuesFor(member.character.id);
2317
+ if (pending.length === 0) return [];
2318
+ store.doneCues(pending.map((cue) => cue.id));
2319
+ const texts = pending.map((cue) => cue.text);
2320
+ state.cues.set(key, texts);
2321
+ return texts;
2322
+ }
2323
+ /** How a character sees people present or explicitly in the moment, for those it has a profile of. */
2324
+ function knownRelationships(member, company, situation, cast, store) {
2325
+ const present = new Set(company.map((candidate) => candidate.character.id));
2326
+ const relevant = mentioned(situation, cast.map((candidate) => candidate.character));
2327
+ return store.story.relationships.from(member.character.id).flatMap((relation) => {
2328
+ if (!present.has(relation.toId) && !relevant.has(relation.toId)) return [];
2329
+ const other = cast.find((candidate) => candidate.character.id === relation.toId);
2330
+ return other === void 0 || other.key === member.key ? [] : [{
2331
+ name: referent(other.character),
2332
+ label: relation.label,
2333
+ summary: relation.summary,
2334
+ present: present.has(relation.toId),
2335
+ familiarity: relation.familiarity,
2336
+ trust: relation.trust,
2337
+ affinity: relation.affinity,
2338
+ tension: relation.tension
2339
+ }];
2340
+ });
2341
+ }
2342
+ function reactions(state) {
2343
+ const first = state.first;
2344
+ return (first?.outcomes ?? []).flatMap((outcome) => {
2345
+ const report = first?.reports.find((candidate) => candidate.character === outcome.character);
2346
+ return report === void 0 ? [] : [{
2347
+ character: report.character,
2348
+ name: report.name,
2349
+ intent: report.intent,
2350
+ ...report.utterance === void 0 ? {} : { utterance: report.utterance },
2351
+ result: outcome.result,
2352
+ summary: outcome.summary
2353
+ }];
2354
+ });
2355
+ }
2356
+ /** The final decision for each character of the round: the retry's replaces the first attempt's. */
2357
+ /** The player's character is never asked to act, so what the game master decided it did stands in for its report. */
2358
+ function playerReport(state, outcome) {
2359
+ const member = state.cast.find((candidate) => candidate.key === outcome.character && candidate.character.control === "player");
2360
+ return member === void 0 ? void 0 : {
2361
+ character: member.key,
2362
+ name: member.character.name,
2363
+ intent: outcome.summary,
2364
+ commitment: "high"
2365
+ };
2366
+ }
2367
+ function decisions(state) {
2368
+ const decided = /* @__PURE__ */ new Map();
2369
+ for (const attempt of [state.first, state.second]) for (const outcome of attempt?.outcomes ?? []) {
2370
+ const report = attempt?.reports.find((candidate) => candidate.character === outcome.character) ?? playerReport(state, outcome);
2371
+ if (report !== void 0) decided.set(outcome.character, {
2372
+ outcome,
2373
+ report
2374
+ });
2375
+ }
2376
+ return decided;
2377
+ }
2378
+ //#endregion
2379
+ //#region src/host/orchestration/character-attempt.ts
2380
+ /** Every character acts at the same time; one that fails or answers badly is reported, not fatal. */
2381
+ async function askCharacters(deps, owner, number, keys, cast, state, run, signal, away = false) {
2382
+ const { store, boundaries } = deps;
2383
+ const { outputValidator } = boundaries;
2384
+ const reaction = number === 2 ? reactions(state) : void 0;
2385
+ const queryVector = number === 1 && store !== void 0 ? await store.queryVector(state.situation, signal) : void 0;
2386
+ const time = store?.time(owner.turn);
2387
+ const answers = await Promise.all(keys.map(async (key) => {
2388
+ const member = cast.find((candidate) => candidate.key === key);
2389
+ if (member === void 0) return {
2390
+ character: key,
2391
+ name: key,
2392
+ reason: "no such character"
2393
+ };
2394
+ const previous = number === 2 ? state.first?.reports.find((report) => report.character === key) : void 0;
2395
+ const memories = number === 1 && store !== void 0 ? await boundaries.recaller.recall({
2396
+ member,
2397
+ situation: state.situation,
2398
+ turn: owner.turn,
2399
+ policy: store.settings().memory,
2400
+ ...store.settings().diagnostics.keepRuns ? { explain: true } : {},
2401
+ ...queryVector === void 0 ? {} : { queryVector }
2402
+ }, store.story, signal) : state.recalled.get(key) ?? [];
2403
+ if (number === 1 && memories.length > 0) state.recalled.set(key, memories);
2404
+ const place = member.place === void 0 ? void 0 : store?.place(member.place.location.id);
2405
+ const relationships = store === void 0 ? [] : knownRelationships(member, place === void 0 ? cast : place.here, state.situation, cast, store);
2406
+ const carrying = store === void 0 ? [] : store.carried(member.character.id);
2407
+ const knowledge = store?.knowledge(member.character.id, owner.turn, (place === void 0 ? cast : place.here).map((entry) => entry.character.id));
2408
+ const affiliations = store?.affiliations(member.character.id) ?? [];
2409
+ const agenda = store?.agenda(owner.turn, member.character.id);
2410
+ const cues = cuesOf(state, key, member, store, number);
2411
+ const upcoming = store?.upcomingFor(member.character.id, owner.turn) ?? [];
2412
+ const tracked = store?.trackedFor(member.character.id, (place === void 0 ? cast : place.here).map((entry) => entry.character.id));
2413
+ const request = {
2414
+ member,
2415
+ cast,
2416
+ situation: state.situation,
2417
+ attempt: number,
2418
+ language: store?.settings().prompts.language ?? "en",
2419
+ turn: owner.turn,
2420
+ ...away ? { away: true } : {},
2421
+ lookup: store?.settings().memory.lookup ?? false,
2422
+ text: (id, variables) => deps.storeOf(owner).text(id, variables),
2423
+ ...time === void 0 ? {} : { time },
2424
+ ...agenda === void 0 ? {} : { agenda },
2425
+ ...cues.length === 0 ? {} : { cues },
2426
+ ...upcoming.length === 0 ? {} : { upcoming },
2427
+ ...tracked === void 0 || tracked.self === "" && tracked.others.length === 0 ? {} : { tracked },
2428
+ ...place === void 0 ? {} : { place },
2429
+ ...relationships.length === 0 ? {} : { relationships },
2430
+ ...carrying.length === 0 ? {} : { carrying },
2431
+ ...knowledge === void 0 ? {} : { knowledge },
2432
+ ...affiliations.length === 0 ? {} : { affiliations },
2433
+ ...memories.length === 0 ? {} : { memories },
2434
+ ...state.history.length === 0 ? {} : { earlier: [...state.history] },
2435
+ ...reaction === void 0 ? {} : { reaction },
2436
+ ...previous === void 0 ? {} : { previous: {
2437
+ intent: previous.intent,
2438
+ commitment: previous.commitment
2439
+ } }
2440
+ };
2441
+ try {
2442
+ const action = await run(request, signal);
2443
+ const verdict = outputValidator.validate(action, request);
2444
+ if (!verdict.ok) return {
2445
+ character: key,
2446
+ name: member.character.name,
2447
+ reason: verdict.reason
2448
+ };
2449
+ return {
2450
+ character: key,
2451
+ name: member.character.name,
2452
+ ...action
2453
+ };
2454
+ } catch (error) {
2455
+ if (signal.aborted) throw error;
2456
+ const reason = error instanceof Error ? error.message : String(error);
2457
+ deps.problem(`${member.character.name} could not act: ${reason}`);
2458
+ return {
2459
+ character: key,
2460
+ name: member.character.name,
2461
+ reason,
2462
+ technical: true
2463
+ };
2464
+ }
2465
+ }));
2466
+ return {
2467
+ reports: answers.filter((answer) => "intent" in answer),
2468
+ failures: answers.filter((answer) => "reason" in answer)
2469
+ };
2470
+ }
2471
+ //#endregion
2472
+ //#region src/host/orchestration/round-record.ts
2473
+ /** Records the game master's decisions as a finished round: what the characters did and said, what changed in the story, and the round queued for the keeper. `fire` runs the triggers the round may have made true. */
2474
+ function recordRound(store, owner, state, fire) {
2475
+ const decided = decisions(state);
2476
+ const limit = store.settings().maxRounds;
2477
+ const round = state.rounds + 1;
2478
+ const checked = new Map([...decided.values()].flatMap(({ outcome }) => outcome.moveTo === void 0 ? [] : [[outcome.character, store.checkMove(outcome.character, outcome.moveTo)]]));
2479
+ const refused = [...checked].flatMap(([character, check]) => check.ok ? [] : [`${character}: ${check.problems.join("; ")}`]);
2480
+ if (refused.length > 0) throw new Error(`a move is no longer possible: ${refused.join("; ")}`);
2481
+ const spoken = [...decided.values()].flatMap(({ outcome, report }) => report.utterance === void 0 || outcome.spoken === false || state.utterances.some((said) => said.character === report.character && sameWords(said.text, report.utterance)) ? [] : [{
2482
+ character: report.character,
2483
+ name: report.name,
2484
+ text: report.utterance,
2485
+ round
2486
+ }]);
2487
+ state.rounds = round;
2488
+ state.situations.push(state.situation);
2489
+ state.utterances.push(...spoken);
2490
+ for (const { outcome, report } of decided.values()) {
2491
+ state.reports.push(report);
2492
+ state.outcomes.push(outcome);
2493
+ state.history.push({
2494
+ round,
2495
+ character: report.character,
2496
+ name: report.name,
2497
+ intent: report.intent,
2498
+ ...report.utterance === void 0 ? {} : { utterance: report.utterance },
2499
+ result: outcome.result,
2500
+ summary: outcome.summary
2501
+ });
2502
+ }
2503
+ state.limit = limit;
2504
+ state.phase = "between";
2505
+ const playerPlace = state.cast.find((member) => member.character.control === "player")?.place?.location;
2506
+ const updates = [...decided.values()].flatMap(({ outcome, report }) => {
2507
+ const member = state.cast.find((candidate) => candidate.key === report.character);
2508
+ if (member === void 0) return [];
2509
+ const check = checked.get(outcome.character);
2510
+ return [{
2511
+ key: report.character,
2512
+ update: {
2513
+ character: member.character.id,
2514
+ patch: {
2515
+ activity: outcome.summary,
2516
+ ...outcome.publicState === void 0 || outcome.publicState.trim() === "" ? {} : { publicState: outcome.publicState.trim() }
2517
+ },
2518
+ ...check?.ok === true ? { move: check.move } : {},
2519
+ ...outcome.itemChanges === void 0 || outcome.itemChanges.length === 0 ? {} : { items: outcome.itemChanges }
2520
+ }
2521
+ }];
2522
+ });
2523
+ const effects = /* @__PURE__ */ new Map();
2524
+ const done = store.commit(updates.map((entry) => entry.update));
2525
+ updates.forEach(({ key }, index) => {
2526
+ effects.set(key, done[index] ?? []);
2527
+ });
2528
+ const tracked = new Map(updates.map(({ key }) => [key, store.changeVariables(owner.turn, decided.get(key)?.outcome.variableChanges ?? []).map((effect) => ({
2529
+ subject: effect.subjectName,
2530
+ name: effect.variable.name,
2531
+ from: describeValue(effect.variable, effect.from),
2532
+ to: describeValue(effect.variable, effect.to)
2533
+ }))]));
2534
+ const journey = [...checked].flatMap(([character, check]) => check.ok && state.cast.find((candidate) => candidate.key === character)?.character.control === "player" ? [check.plan.travelSeconds ?? 0] : [])[0];
2535
+ const time = store.endRound(owner.turn, round, state.elapsed, journey);
2536
+ delete state.elapsed;
2537
+ const world = fire(round);
2538
+ const loose = store.story.dice.rolls({ turn: owner.turn }).filter((roll) => !state.cited.has(roll.id) && !state.reported.has(roll.id));
2539
+ for (const roll of loose) state.reported.add(roll.id);
2540
+ store.queueCommit({
2541
+ turn: owner.turn,
2542
+ round,
2543
+ situation: state.situation,
2544
+ ...loose.length === 0 ? {} : { rolls: loose.map((roll) => `${roll.reason}: ${roll.expression} came to ${roll.total}${roll.readout === void 0 ? "" : `: ${roll.readout.label}${roll.readout.critical ? " (critical)" : ""} (${roll.readout.result})`}${roll.by === "player" ? " (rolled by the player)" : ""}`) },
2545
+ ...playerPlace === void 0 ? {} : { place: {
2546
+ key: locationKey(playerPlace),
2547
+ name: playerPlace.name
2548
+ } },
2549
+ time: {
2550
+ from: time.from,
2551
+ to: time.to,
2552
+ zone: time.zone
2553
+ },
2554
+ entries: [...decided.values()].map(({ outcome, report }) => {
2555
+ const at = state.cast.find((candidate) => candidate.key === report.character)?.place?.location;
2556
+ const check = checked.get(outcome.character);
2557
+ return {
2558
+ character: report.character,
2559
+ name: report.name,
2560
+ intent: report.intent,
2561
+ commitment: report.commitment,
2562
+ ...report.utterance === void 0 ? {} : { utterance: report.utterance },
2563
+ result: outcome.result,
2564
+ summary: outcome.summary,
2565
+ ...outcome.publicState === void 0 || outcome.publicState.trim() === "" ? {} : { publicState: outcome.publicState.trim() },
2566
+ spoken: outcome.spoken !== false,
2567
+ ...(tracked.get(report.character) ?? []).length === 0 ? {} : { variables: tracked.get(report.character) },
2568
+ ...state.cast.find((candidate) => candidate.key === report.character)?.character.control === "player" ? { player: true } : {},
2569
+ ...report.forced === true ? { forced: true } : {},
2570
+ ...(effects.get(report.character) ?? []).length === 0 ? {} : { items: (effects.get(report.character) ?? []).map((effect) => ({
2571
+ name: effect.item.name,
2572
+ action: effect.action,
2573
+ summary: effect.summary
2574
+ })) },
2575
+ ...at === void 0 ? {} : { at: {
2576
+ key: locationKey(at),
2577
+ name: at.name
2578
+ } },
2579
+ ...check?.ok === true && check.plan.from !== check.move.to ? { moved: {
2580
+ ...check.to,
2581
+ ...check.position === void 0 ? {} : { position: check.position }
2582
+ } } : {}
2583
+ };
2584
+ })
2585
+ });
2586
+ return {
2587
+ round,
2588
+ limit,
2589
+ updated: [...decided.keys()],
2590
+ retryFailures: state.second?.failures ?? [],
2591
+ utterances: spoken,
2592
+ spoken: [...state.utterances],
2593
+ waiting: store.pendingCommits().length,
2594
+ variables: [...tracked.values()].flat().map((change) => `${change.subject}'s ${change.name} is now ${change.to} (it was ${change.from})`),
2595
+ time: {
2596
+ from: time.from,
2597
+ to: time.to,
2598
+ zone: time.zone
2599
+ },
2600
+ moved: time.moved,
2601
+ world,
2602
+ things: [...effects].flatMap(([character, list]) => list.map((effect) => ({
2603
+ character,
2604
+ name: effect.item.name,
2605
+ action: effect.action,
2606
+ summary: effect.summary
2607
+ }))),
2608
+ moves: [...checked].flatMap(([character, check]) => check.ok && check.plan.from !== check.move.to ? [{
2609
+ character,
2610
+ name: decided.get(character)?.report.name ?? character,
2611
+ to: check.to.name,
2612
+ via: Math.max(0, check.plan.via.length - 1)
2613
+ }] : [])
2614
+ };
2615
+ }
2616
+ //#endregion
2617
+ //#region src/host/orchestration/turn-text.ts
3034
2618
  /**
3035
2619
  * A model sometimes sends who speaks as a segment of its own (an utterance with no character whose text is the character's key or name) followed by the words with no
3036
2620
  * character either. When the label is exactly a character of the scene, the label is folded into the words that follow it.
@@ -3079,8 +2663,145 @@ function repeatsEarlier(signature, asked) {
3079
2663
  return union === 0 || shared / union >= SAME_SITUATION;
3080
2664
  });
3081
2665
  }
3082
- /** The game master is asked to correct its output this many times before it is corrected for it. */
3083
- const MAX_REFUSALS = 2;
2666
+ /** The words as the character said them, whatever quotes the game master put around them. */
2667
+ function asSpoken(segments, spoken) {
2668
+ const left = [...spoken];
2669
+ return segments.map((segment) => {
2670
+ if (segment.type !== "utterance") return segment;
2671
+ const at = left.findIndex((said) => said.character === segment.character && sameWords(said.text, segment.text));
2672
+ return at === -1 ? segment : {
2673
+ ...segment,
2674
+ text: left.splice(at, 1)[0].text
2675
+ };
2676
+ });
2677
+ }
2678
+ /**
2679
+ * The output the game master delivered, once it is acceptable: every utterance exactly once and in order, and the narration in the chat's language.
2680
+ * A refusal is thrown for the game master to correct; past `MAX_REFUSALS`, or when `silent`, the output is repaired instead.
2681
+ */
2682
+ function checkedOutput(narrationChecker, language, state, segments, silent) {
2683
+ const problems = [...segments.flatMap((segment, index) => segment.type === "utterance" && segment.character === "" ? [`segment ${index + 1}: an utterance needs the character who says it`] : []), ...narrationChecker.check(segments, state.utterances)];
2684
+ const wording = wrongLanguage(language, { narration: segments.flatMap((segment) => segment.type === "narration" ? [segment.text] : []).join(" ") });
2685
+ if (problems.length === 0 && wording !== void 0 && !silent && state.refused < 2) {
2686
+ state.refused += 1;
2687
+ throw new Error(`the output is not acceptable: ${wording}. Deliver it again with the narration corrected; utterances may not be touched`);
2688
+ }
2689
+ if (problems.length === 0) return {
2690
+ segments: asSpoken(segments, state.utterances),
2691
+ repaired: false
2692
+ };
2693
+ state.refused += 1;
2694
+ if (!silent && state.refused <= 2) throw new Error(`the output is not acceptable: ${problems.join("; ")}. Deliver it again with these corrected; narration may be written freely, utterances may not be touched`);
2695
+ return {
2696
+ segments: narrationChecker.repair(segments.filter((segment) => segment.type !== "utterance" || segment.character !== ""), state.utterances),
2697
+ repaired: true
2698
+ };
2699
+ }
2700
+ //#endregion
2701
+ //#region src/host/dice/view.ts
2702
+ const sign = (value) => value >= 0 ? `+${value}` : String(value);
2703
+ /** A roll as the player reads it: what it was for, what fell, what it came to and what the world's check made of it. */
2704
+ function rollView(roll) {
2705
+ const kept = roll.kept.length < roll.faces.length ? ` (${roll.kept.join(", ")})` : "";
2706
+ const against = roll.target === void 0 ? "" : ` / ${roll.target}`;
2707
+ const outcome = roll.readout === void 0 ? "" : ` - ${roll.readout.label}${roll.readout.critical ? "!" : ""}`;
2708
+ return {
2709
+ id: roll.id,
2710
+ by: roll.by,
2711
+ text: `${roll.reason}: ${roll.expression} [${roll.faces.join(", ")}]${kept}${roll.modifier === 0 ? "" : ` ${sign(roll.modifier)}`} = ${roll.total}${against}${outcome}`
2712
+ };
2713
+ }
2714
+ /**
2715
+ * What the characters away from the player decide about what fell due, one commitment after another: their activity, and a move to where the commitment was when they
2716
+ * mean to keep it. It is recorded as a round only they perceive, and the keeper writes it.
2717
+ */
2718
+ async function runOffScene(deps, owner, state, store, due, limit) {
2719
+ const { summary, perCharacter, joint } = store.settings().offstage;
2720
+ let budget = limit;
2721
+ const acted = /* @__PURE__ */ new Map();
2722
+ for (const item of due) {
2723
+ if (budget <= 0) break;
2724
+ const cast = store.cast();
2725
+ const keys = item.characters.filter((key) => cast.some((member) => member.key === key) && (acted.get(key) ?? 0) < perCharacter).slice(0, budget);
2726
+ if (keys.length === 0) continue;
2727
+ budget -= keys.length;
2728
+ for (const key of keys) acted.set(key, (acted.get(key) ?? 0) + 1);
2729
+ const reports = [];
2730
+ for (const group of joint ? keys.map((key) => [key]) : [keys]) {
2731
+ const attending = reports.filter((report) => report.commitment !== "low").map((report) => `${report.name} has decided: ${report.intent}${report.utterance === void 0 ? "" : `, saying "${report.utterance}"`}.`);
2732
+ const asked = {
2733
+ ...state,
2734
+ situation: attending.length === 0 ? item.text : `${item.text}\n${attending.join("\n")}`,
2735
+ history: [],
2736
+ recalled: /* @__PURE__ */ new Map()
2737
+ };
2738
+ delete asked.first;
2739
+ delete asked.second;
2740
+ reports.push(...(await deps.ask(group, cast, asked, summary)).reports);
2741
+ }
2742
+ if (reports.length === 0) continue;
2743
+ const where = item.place;
2744
+ const moves = new Map(reports.flatMap((report) => {
2745
+ if (report.commitment === "low" || where === void 0) return [];
2746
+ const check = store.checkMove(report.character, {
2747
+ location: where,
2748
+ ignoreExits: true
2749
+ });
2750
+ return check.ok ? [[report.character, check]] : [];
2751
+ }));
2752
+ store.commit(reports.flatMap((report) => {
2753
+ const member = cast.find((candidate) => candidate.key === report.character);
2754
+ const move = moves.get(report.character);
2755
+ return member === void 0 ? [] : [{
2756
+ character: member.character.id,
2757
+ patch: { activity: report.intent },
2758
+ ...move?.ok === true ? { move: move.move } : {}
2759
+ }];
2760
+ }));
2761
+ state.offstage += 1;
2762
+ const time = store.time(owner.turn);
2763
+ store.queueCommit({
2764
+ turn: owner.turn,
2765
+ round: 100 + state.offstage,
2766
+ situation: item.text,
2767
+ offstage: true,
2768
+ time: {
2769
+ from: time.now,
2770
+ to: time.now,
2771
+ zone: time.zone
2772
+ },
2773
+ entries: reports.map((report) => {
2774
+ const at = cast.find((candidate) => candidate.key === report.character)?.place?.location;
2775
+ const move = moves.get(report.character);
2776
+ return {
2777
+ character: report.character,
2778
+ name: report.name,
2779
+ intent: report.intent,
2780
+ commitment: report.commitment,
2781
+ result: "succeeded",
2782
+ summary: report.intent,
2783
+ spoken: false,
2784
+ ...at === void 0 ? {} : { at: {
2785
+ key: locationKey(at),
2786
+ name: at.name
2787
+ } },
2788
+ ...move?.ok === true && move.plan.from !== move.move.to ? { moved: { ...move.to } } : {}
2789
+ };
2790
+ })
2791
+ });
2792
+ store.markHandled([item.key]);
2793
+ deps.write();
2794
+ if (summary && deps.stillThis()) {
2795
+ const lines = reports.flatMap((report) => report.account === void 0 ? [] : [report.account]);
2796
+ store.addNote("away", owner.turn, lines);
2797
+ }
2798
+ }
2799
+ }
2800
+ //#endregion
2801
+ //#region src/host/orchestration/turn-engine.ts
2802
+ const MAX_OBJECTIONS = 3;
2803
+ /** The most a single round may be said to take: a day. A longer time passing is skipped with `advanceTime`. */
2804
+ const MAX_ROUND_SECONDS = 86400;
3084
2805
  /** The runs of the record keeper that may fail one after another before the rounds waiting for it are given up, so that they cannot pile up for ever. */
3085
2806
  const MAX_FAILED_RUNS = 3;
3086
2807
  /**
@@ -3156,7 +2877,7 @@ var TurnEngine = class {
3156
2877
  if (state.ooc.ruling !== void 0) throw new Error("this question was already answered");
3157
2878
  state.ooc.ruling = {
3158
2879
  legal: true,
3159
- note: text.length > 1200 ? `${text.slice(0, 1199)}…` : text,
2880
+ note: text.length > 1200 ? `${text.slice(0, MAX_OOC_ANSWER - 1)}…` : text,
3160
2881
  question: true
3161
2882
  };
3162
2883
  state.phase = "between";
@@ -3178,7 +2899,7 @@ var TurnEngine = class {
3178
2899
  }, store.story, signal);
3179
2900
  const place = member.place === void 0 ? void 0 : store.place(member.place.location.id);
3180
2901
  const company = place === void 0 ? cast : place.here;
3181
- const relationships = this.knownRelationships(member, company, question, cast, store);
2902
+ const relationships = knownRelationships(member, company, question, cast, store);
3182
2903
  const carrying = store.carried(member.character.id);
3183
2904
  const affiliations = store.affiliations(member.character.id);
3184
2905
  const tracked = store.trackedFor(member.character.id, company.map((entry) => entry.character.id));
@@ -3227,7 +2948,7 @@ var TurnEngine = class {
3227
2948
  * When the action is said to happen at a place (`at`, a place key) and the character is somewhere else, it does not work whatever was judged: the character has to get there first.
3228
2949
  * @throws {Error} when the turn is not an ordinary one, was already judged, the reason is empty, or `at` is not a place.
3229
2950
  */
3230
- judge(owner, allowed, reason, at) {
2951
+ judge(owner, allowed, reason, at, uncertain) {
3231
2952
  const state = this.stateFor(owner);
3232
2953
  if (state.ooc !== void 0) throw new Error("this turn is an out-of-character " + (state.ooc.question === true ? "question: answer it with ooc_answer" : "command: rule on it with ooc_ruling"));
3233
2954
  if (state.phase !== "idle") throw new Error("the action is judged first, before anything else");
@@ -3256,23 +2977,20 @@ var TurnEngine = class {
3256
2977
  allowed,
3257
2978
  reason: why
3258
2979
  };
2980
+ const { tools } = this.storeOf(owner).settings();
2981
+ if (allowed && uncertain === true && (toolEnabled(tools, "gameMaster", "roll_check") || toolEnabled(tools, "gameMaster", "roll_dice"))) {
2982
+ state.rollWanted = true;
2983
+ return {
2984
+ ...state.judgement,
2985
+ roll: true
2986
+ };
2987
+ }
3259
2988
  return state.judgement;
3260
2989
  }
3261
2990
  /** The turn is an ordinary one: the game master judges the player's action before anything else. */
3262
2991
  expectJudgement(owner) {
3263
2992
  this.stateFor(owner).judgeWanted = true;
3264
2993
  }
3265
- /** Whether the game master still has to judge the player's action. */
3266
- judgeDue(state) {
3267
- return state.judgeWanted === true && state.phase === "idle" && state.ooc === void 0 && state.judgement === void 0;
3268
- }
3269
- /** Why an out-of-character command may not change anything yet, when it may not. */
3270
- oocBlock(state) {
3271
- if (state.ooc === void 0) return void 0;
3272
- if (state.ooc.question === true) return state.ooc.ruling === void 0 ? "this turn is an out-of-character question: answer it first with ooc_answer" : "a question changes nothing: call narrate with no segments";
3273
- if (state.ooc.ruling === void 0) return "this turn is an out-of-character command: rule on it first with ooc_ruling";
3274
- return state.ooc.ruling.legal ? void 0 : "the command was refused: nothing changes; call narrate with no segments to tell the player";
3275
- }
3276
2994
  /** Mark a turn as one that needs no round, for example because the player's input was refused. */
3277
2995
  skip(owner) {
3278
2996
  this.stateFor(owner).phase = "skipped";
@@ -3284,10 +3002,11 @@ var TurnEngine = class {
3284
3002
  async activate(owner, input, run, signal) {
3285
3003
  const state = this.stateFor(owner);
3286
3004
  if (state.ooc !== void 0) throw new Error(state.ooc.question === true ? "a question asks nobody to act and changes nothing: answer it with ooc_answer" : "an out-of-character command asks nobody to act: decree what happens with resolve_round, or narrate");
3287
- if (state.phase !== "idle" && state.phase !== "between") throw new Error(this.explain(state, "activate_characters"));
3288
- if (this.judgeDue(state)) throw new Error(this.explain(state, "activate_characters"));
3005
+ if (state.phase !== "idle" && state.phase !== "between") throw new Error(explainPhase(state, "activate_characters"));
3006
+ if (judgeDue(state)) throw new Error(explainPhase(state, "activate_characters"));
3289
3007
  if (state.judgement?.allowed === false && state.rounds === 0) throw new Error(`the action cannot work (${state.judgement.reason}): nobody is asked to act on it. Play the failed attempt with resolve_round: one outcome for the player's character, result failed`);
3290
- if (this.previewDue(state)) throw new Error(this.explain(state, "activate_characters"));
3008
+ if (previewDue(state)) throw new Error(explainPhase(state, "activate_characters"));
3009
+ if (rollDue(state, this.storeOf(owner))) throw new Error(ROLL_FIRST);
3291
3010
  const store = this.storeOf(owner);
3292
3011
  const limit = store.settings().maxRounds;
3293
3012
  if (state.rounds >= limit) throw new Error(`${state.rounds} round${state.rounds === 1 ? "" : "s"} of characters were already played for this message, which is the most this chat allows: deliver the output with narrate`);
@@ -3309,7 +3028,7 @@ var TurnEngine = class {
3309
3028
  state.cues.clear();
3310
3029
  delete state.first;
3311
3030
  delete state.second;
3312
- const attempt = await this.runAttempt(owner, 1, keys, cast, state, run, signal);
3031
+ const attempt = await this.ask(owner, 1, keys, cast, state, run, signal);
3313
3032
  if (attempt.reports.length === 0) return {
3314
3033
  attempt: 1,
3315
3034
  reports: [],
@@ -3334,14 +3053,15 @@ var TurnEngine = class {
3334
3053
  const store = this.storeOf(owner);
3335
3054
  if (state.ooc !== void 0) return { done: this.decree(owner, state, outcomes, elapsedSeconds) };
3336
3055
  if (state.phase === "idle" || state.phase === "between") {
3337
- if (this.judgeDue(state) || this.previewDue(state)) throw new Error(this.explain(state, "resolve_round"));
3056
+ if (judgeDue(state) || previewDue(state)) throw new Error(explainPhase(state, "resolve_round"));
3057
+ if (rollDue(state, this.storeOf(owner))) throw new Error(ROLL_FIRST);
3338
3058
  const player = store.cast().find((member) => member.character.control === "player");
3339
3059
  if (player !== void 0 && outcomes.length === 1 && outcomes[0]?.character === player.key) return { done: this.resolvePlayer(owner, state, outcomes[0], elapsedSeconds) };
3340
3060
  }
3341
- if (state.phase !== "resolving" && state.phase !== "retrying") throw new Error(this.explain(state, "resolve_round"));
3061
+ if (state.phase !== "resolving" && state.phase !== "retrying") throw new Error(explainPhase(state, "resolve_round"));
3342
3062
  const attempt = state.phase === "resolving" ? state.first : state.second;
3343
3063
  if (attempt === void 0) throw new Error("internal: no round to resolve");
3344
- this.check(attempt, outcomes, store, state.phase === "resolving" ? this.playerKey(state) : void 0);
3064
+ checkOutcomes(attempt, outcomes, store, state.phase === "resolving" ? this.playerKey(state) : void 0, void 0, state);
3345
3065
  if (elapsedSeconds !== void 0) state.elapsed = this.elapsedChecked(owner, elapsedSeconds);
3346
3066
  attempt.outcomes = [...outcomes];
3347
3067
  if (state.phase === "resolving") {
@@ -3350,7 +3070,7 @@ var TurnEngine = class {
3350
3070
  outcomes: attempt.outcomes
3351
3071
  }).filter((key) => attempt.reports.some((report) => report.character === key));
3352
3072
  if (retrying.length > 0) {
3353
- const second = await this.runAttempt(owner, 2, retrying, state.cast, state, run, signal);
3073
+ const second = await this.ask(owner, 2, retrying, state.cast, state, run, signal);
3354
3074
  state.second = second;
3355
3075
  if (second.reports.length > 0) {
3356
3076
  state.phase = "retrying";
@@ -3362,7 +3082,7 @@ var TurnEngine = class {
3362
3082
  }
3363
3083
  }
3364
3084
  }
3365
- return { done: this.finishRound(owner, state) };
3085
+ return { done: recordRound(this.storeOf(owner), owner, state, (round) => this.fire(owner, round)) };
3366
3086
  }
3367
3087
  /**
3368
3088
  * What an out-of-character command decrees, as one round of its own: outcomes for any characters, asked or not, each checked like any other
@@ -3371,17 +3091,17 @@ var TurnEngine = class {
3371
3091
  * @throws {Error} when the command was not ruled legal, the limit of rounds is reached, or an outcome is not acceptable.
3372
3092
  */
3373
3093
  decree(owner, state, outcomes, elapsedSeconds) {
3374
- const blocked = this.oocBlock(state);
3094
+ const blocked = oocBlock(state);
3375
3095
  if (blocked !== void 0) throw new Error(blocked);
3376
3096
  const store = this.storeOf(owner);
3377
3097
  const limit = store.settings().maxRounds;
3378
3098
  if (state.rounds >= limit) throw new Error(`${state.rounds} round${state.rounds === 1 ? "" : "s"} were already decreed for this command, which is the most this chat allows: deliver the output with narrate`);
3379
3099
  state.cast = store.cast();
3380
3100
  if (outcomes.length === 0) throw new Error("decree at least one outcome");
3381
- this.check({
3101
+ checkOutcomes({
3382
3102
  reports: [],
3383
3103
  failures: []
3384
- }, outcomes, store, void 0, state.cast);
3104
+ }, outcomes, store, void 0, state.cast, state);
3385
3105
  if (elapsedSeconds !== void 0) state.elapsed = this.elapsedChecked(owner, elapsedSeconds);
3386
3106
  state.situation = `By the player's out-of-character command (${state.ooc?.request ?? ""}), the game master decreed:`;
3387
3107
  state.recalled.clear();
@@ -3400,7 +3120,7 @@ var TurnEngine = class {
3400
3120
  failures: [],
3401
3121
  outcomes: [...outcomes]
3402
3122
  };
3403
- return this.finishRound(owner, state);
3123
+ return recordRound(this.storeOf(owner), owner, state, (round) => this.fire(owner, round));
3404
3124
  }
3405
3125
  /** The key of the player's character. */
3406
3126
  playerKey(state) {
@@ -3417,10 +3137,10 @@ var TurnEngine = class {
3417
3137
  if (state.rounds >= limit) throw new Error(`${state.rounds} round${state.rounds === 1 ? "" : "s"} were already played for this message, which is the most this chat allows: deliver the output with narrate`);
3418
3138
  state.cast = store.cast();
3419
3139
  const player = state.cast.find((member) => member.key === outcome.character);
3420
- this.check({
3140
+ checkOutcomes({
3421
3141
  reports: [],
3422
3142
  failures: []
3423
- }, [outcome], store, outcome.character);
3143
+ }, [outcome], store, outcome.character, void 0, state);
3424
3144
  if (elapsedSeconds !== void 0) state.elapsed = this.elapsedChecked(owner, elapsedSeconds);
3425
3145
  state.situation = `${player?.character.name ?? outcome.character}: ${outcome.summary}`;
3426
3146
  state.recalled.clear();
@@ -3430,7 +3150,7 @@ var TurnEngine = class {
3430
3150
  failures: [],
3431
3151
  outcomes: [outcome]
3432
3152
  };
3433
- return this.finishRound(owner, state);
3153
+ return recordRound(this.storeOf(owner), owner, state, (round) => this.fire(owner, round));
3434
3154
  }
3435
3155
  /**
3436
3156
  * The game master shows the player how the scene opens, before anyone is asked: something to read while the rest of the turn is worked out.
@@ -3440,7 +3160,7 @@ var TurnEngine = class {
3440
3160
  preview(owner, text) {
3441
3161
  const state = this.stateFor(owner);
3442
3162
  if (state.ooc !== void 0) throw new Error("an out-of-character turn shows no preview: go on with " + (state.ooc.question === true ? "ooc_answer" : "ooc_ruling"));
3443
- if (this.judgeDue(state)) throw new Error("judge the action first with judge_action");
3163
+ if (judgeDue(state)) throw new Error("judge the action first with judge_action");
3444
3164
  if (!this.storeOf(owner).settings().preview.enabled) throw new Error("this chat shows no preview: go on with activate_characters");
3445
3165
  if (state.previewed) throw new Error("a preview was already shown for this message: go on with activate_characters");
3446
3166
  if (state.phase !== "idle") throw new Error("the preview comes first, before the characters are asked");
@@ -3476,8 +3196,8 @@ var TurnEngine = class {
3476
3196
  advanceTime(owner, request) {
3477
3197
  const state = this.stateFor(owner);
3478
3198
  if (state.phase === "resolving" || state.phase === "retrying") throw new Error("resolve the round first: time is skipped between rounds, not in the middle of one");
3479
- if (state.phase === "done" || state.phase === "skipped") throw new Error(this.explain(state, void 0));
3480
- const blocked = this.oocBlock(state);
3199
+ if (state.phase === "done" || state.phase === "skipped") throw new Error(explainPhase(state, void 0));
3200
+ const blocked = oocBlock(state);
3481
3201
  if (blocked !== void 0) throw new Error(blocked);
3482
3202
  try {
3483
3203
  return {
@@ -3497,7 +3217,7 @@ var TurnEngine = class {
3497
3217
  */
3498
3218
  async narrate(owner, segments, run, addressed = []) {
3499
3219
  const state = this.stateFor(owner);
3500
- if (state.phase !== "between") throw new Error(this.explain(state, "narrate"));
3220
+ if (state.phase !== "between") throw new Error(explainPhase(state, "narrate"));
3501
3221
  const pending = new Set(this.storeOf(owner).pendingBeats().map((beat) => beat.id));
3502
3222
  const unknown = addressed.filter((id) => !pending.has(id));
3503
3223
  if (unknown.length > 0) throw new Error(`addressed: ${unknown.join(", ")} ${unknown.length === 1 ? "is" : "are"} not ${unknown.length === 1 ? "a beat" : "beats"} still to weave in (the scene lists them)`);
@@ -3541,7 +3261,7 @@ var TurnEngine = class {
3541
3261
  async expand(owner, input, signal) {
3542
3262
  const state = this.stateFor(owner);
3543
3263
  if (state.phase === "resolving" || state.phase === "retrying") throw new Error("resolve the round first: the world is extended between rounds, not in the middle of one");
3544
- const blocked = this.oocBlock(state);
3264
+ const blocked = oocBlock(state);
3545
3265
  if (blocked !== void 0) throw new Error(blocked);
3546
3266
  const need = AUTHORING_NEEDS.find((candidate) => candidate === input.need);
3547
3267
  if (need === void 0) throw new Error(`"${input.need}" is not a reason to make something up; the reasons are: ${AUTHORING_NEEDS.join(", ")}`);
@@ -3568,7 +3288,7 @@ var TurnEngine = class {
3568
3288
  introduce(owner, input) {
3569
3289
  const state = this.stateFor(owner);
3570
3290
  if (state.phase === "resolving" || state.phase === "retrying") throw new Error("resolve the round first: things are introduced between rounds, not in the middle of one");
3571
- const blocked = this.oocBlock(state);
3291
+ const blocked = oocBlock(state);
3572
3292
  if (blocked !== void 0) throw new Error(blocked);
3573
3293
  const name = input.name.trim();
3574
3294
  if (name === "") throw new Error("name the thing");
@@ -3630,93 +3350,20 @@ var TurnEngine = class {
3630
3350
  this.offstage.delete(owner.chat);
3631
3351
  }));
3632
3352
  }
3633
- async runOffScene(owner, state, store, due, limit, run) {
3634
- const { summary, perCharacter, joint } = store.settings().offstage;
3635
- let budget = limit;
3636
- const acted = /* @__PURE__ */ new Map();
3637
- for (const item of due) {
3638
- if (budget <= 0) break;
3639
- const cast = store.cast();
3640
- const keys = item.characters.filter((key) => cast.some((member) => member.key === key) && (acted.get(key) ?? 0) < perCharacter).slice(0, budget);
3641
- if (keys.length === 0) continue;
3642
- budget -= keys.length;
3643
- for (const key of keys) acted.set(key, (acted.get(key) ?? 0) + 1);
3644
- const reports = [];
3645
- for (const group of joint ? keys.map((key) => [key]) : [keys]) {
3646
- const attending = reports.filter((report) => report.commitment !== "low").map((report) => `${report.name} has decided: ${report.intent}${report.utterance === void 0 ? "" : `, saying "${report.utterance}"`}.`);
3647
- const asked = {
3648
- ...state,
3649
- situation: attending.length === 0 ? item.text : `${item.text}\n${attending.join("\n")}`,
3650
- history: [],
3651
- recalled: /* @__PURE__ */ new Map()
3652
- };
3653
- delete asked.first;
3654
- delete asked.second;
3655
- reports.push(...(await this.runAttempt(owner, 1, group, cast, asked, run, state.cancel.signal, summary)).reports);
3656
- }
3657
- if (reports.length === 0) continue;
3658
- const where = item.place;
3659
- const moves = new Map(reports.flatMap((report) => {
3660
- if (report.commitment === "low" || where === void 0) return [];
3661
- const check = store.checkMove(report.character, {
3662
- location: where,
3663
- ignoreExits: true
3664
- });
3665
- return check.ok ? [[report.character, check]] : [];
3666
- }));
3667
- store.commit(reports.flatMap((report) => {
3668
- const member = cast.find((candidate) => candidate.key === report.character);
3669
- const move = moves.get(report.character);
3670
- return member === void 0 ? [] : [{
3671
- character: member.character.id,
3672
- patch: { activity: report.intent },
3673
- ...move?.ok === true ? { move: move.move } : {}
3674
- }];
3675
- }));
3676
- state.offstage += 1;
3677
- const time = store.time(owner.turn);
3678
- store.queueCommit({
3679
- turn: owner.turn,
3680
- round: 100 + state.offstage,
3681
- situation: item.text,
3682
- offstage: true,
3683
- time: {
3684
- from: time.now,
3685
- to: time.now,
3686
- zone: time.zone
3687
- },
3688
- entries: reports.map((report) => {
3689
- const at = cast.find((candidate) => candidate.key === report.character)?.place?.location;
3690
- const move = moves.get(report.character);
3691
- return {
3692
- character: report.character,
3693
- name: report.name,
3694
- intent: report.intent,
3695
- commitment: report.commitment,
3696
- result: "succeeded",
3697
- summary: report.intent,
3698
- spoken: false,
3699
- ...at === void 0 ? {} : { at: {
3700
- key: locationKey(at),
3701
- name: at.name
3702
- } },
3703
- ...move?.ok === true && move.plan.from !== move.move.to ? { moved: { ...move.to } } : {}
3704
- };
3705
- })
3706
- });
3707
- store.markHandled([item.key]);
3708
- this.write(owner, state);
3709
- if (summary && this.states.get(owner.chat) === state) {
3710
- const lines = reports.flatMap((report) => report.account === void 0 ? [] : [report.account]);
3711
- store.addNote("away", owner.turn, lines);
3712
- }
3713
- }
3353
+ runOffScene(owner, state, store, due, limit, run) {
3354
+ return runOffScene({
3355
+ ask: (group, cast, asked, summary) => this.ask(owner, 1, group, cast, asked, run, state.cancel.signal, summary),
3356
+ write: () => {
3357
+ this.write(owner, state);
3358
+ },
3359
+ stillThis: () => this.states.get(owner.chat) === state
3360
+ }, owner, state, store, due, limit);
3714
3361
  }
3715
3362
  /** What still has to happen before the turn may end, or nothing when it may. */
3716
3363
  missing(owner) {
3717
3364
  const state = this.stateFor(owner);
3718
3365
  if (state.phase === "done" || state.phase === "skipped") return void 0;
3719
- return this.explain(state, void 0);
3366
+ return explainPhase(state, void 0);
3720
3367
  }
3721
3368
  /** Wait until the records being written are written or have failed. */
3722
3369
  async flush(owner) {
@@ -3835,6 +3482,8 @@ var TurnEngine = class {
3835
3482
  reports: [],
3836
3483
  outcomes: [],
3837
3484
  utterances: [],
3485
+ cited: /* @__PURE__ */ new Set(),
3486
+ reported: /* @__PURE__ */ new Set(),
3838
3487
  refused: 0,
3839
3488
  previewed: false,
3840
3489
  previewWanted: this.stores(chat)?.settings().preview.enabled ?? false,
@@ -3854,362 +3503,15 @@ var TurnEngine = class {
3854
3503
  if (store === void 0) throw new Error("this chat is not a roleplay session");
3855
3504
  return store;
3856
3505
  }
3857
- /** Whether the chat wants a preview of the scene and the game master has not shown it yet. */
3858
- previewDue(state) {
3859
- return state.phase === "idle" && state.previewWanted && !state.previewed && state.judgement?.allowed !== false;
3860
- }
3861
- explain(state, attempted) {
3862
- if (state.ooc?.question === true && (state.phase === "idle" || state.phase === "between")) return state.ooc.ruling === void 0 ? "this turn is an out-of-character question: answer it first with ooc_answer" : "a question changes nothing: call narrate with no segments";
3863
- if (state.ooc !== void 0 && (state.phase === "idle" || state.phase === "between")) return state.ooc.ruling === void 0 ? "this turn is an out-of-character command: rule on it first with ooc_ruling" : state.ooc.ruling.legal ? "make the command happen with resolve_round, expand_world or advance_time, then call narrate with what the player perceives (narration only)" : "the command was refused: call narrate with no segments";
3864
- const waiting = (attempt) => (attempt?.reports ?? []).map((report) => report.character).join(", ");
3865
- switch (state.phase) {
3866
- case "idle": return this.judgeDue(state) ? "call judge_action first: does what the player's character tries work? It does not when it is not viable or it breaks a rule of the world or of the player" : this.previewDue(state) ? "call preview_scene first: two or three sentences that show the player how the scene opens, before the characters are asked" : state.judgement?.allowed === false && attempted !== "activate_characters" ? `the attempt does not work (${state.judgement.reason}): call resolve_round with one outcome, for the player's character only (result failed, a sentence on what it does and why nothing comes of it)${attempted === "narrate" ? ", then narrate" : ""}` : attempted === "activate_characters" || attempted === void 0 ? "call activate_characters to let the characters act" : attempted === "narrate" ? "nothing to deliver yet: call activate_characters to let the characters act, or, when nobody else needs to react, call resolve_round with an outcome for the player's character alone, and then narrate" : "nothing to resolve yet: call activate_characters first";
3867
- case "resolving": return attempted === "activate_characters" ? "the characters already acted in this round: call resolve_round" : attempted === "narrate" ? `resolve the round first: call resolve_round with one outcome for each of: ${waiting(state.first)}` : `call resolve_round with one outcome for each of: ${waiting(state.first)}`;
3868
- case "retrying": return attempted === "activate_characters" ? "the characters already acted in this round: call resolve_round" : attempted === "narrate" ? `resolve the round first: call resolve_round once more, with one outcome for each of: ${waiting(state.second)}` : `call resolve_round once more, with one outcome for each of: ${waiting(state.second)}`;
3869
- case "between": return attempted === "resolve_round" ? "the round is already recorded: call activate_characters again if the story needs it, or narrate" : `call narrate with the output of the turn${this.mustSay(state)}${this.canContinue(state)}`;
3870
- case "done": return "this turn is already recorded";
3871
- case "skipped": return "this turn needs no round";
3872
- }
3873
- }
3874
- canContinue(state) {
3875
- const left = (state.limit ?? 0) - state.rounds;
3876
- return left > 0 ? `, or call activate_characters if the story genuinely needs them again (${left} round(s) left)` : "";
3877
- }
3878
- mustSay(state) {
3879
- return state.utterances.length === 0 ? "" : `; it must carry these utterances exactly, in this order: ${state.utterances.map((utterance) => `${utterance.name}: "${utterance.text}"`).join(" | ")}`;
3880
- }
3881
- /** `player` is the key of the player's character when an outcome for it is acceptable: it is not asked to act, but what it did can move it or have it handle things. */
3882
- check(attempt, outcomes, store, player, decreed) {
3883
- const expected = decreed === void 0 ? attempt.reports.map((report) => report.character) : [...new Set(outcomes.map((outcome) => outcome.character))];
3884
- const unknown = decreed === void 0 ? [] : [...new Set(outcomes.map((outcome) => outcome.character))].filter((key) => !decreed.some((member) => member.key === key)).map((key) => `${key} is not a character of the story`);
3885
- const given = outcomes.filter((outcome) => outcome.character !== player).map((outcome) => outcome.character);
3886
- const problems = [
3887
- ...unknown,
3888
- ...outcomes.filter((outcome) => outcome.character === player).length > 1 ? [`more than one outcome for ${player}`] : [],
3889
- ...expected.filter((key) => !given.includes(key)).map((key) => `missing an outcome for ${key}`),
3890
- ...[...new Set(given.filter((key) => !expected.includes(key)))].map((key) => `${key} is not waiting for an outcome`),
3891
- ...[...new Set(given.filter((key, index) => given.indexOf(key) !== index))].map((key) => `more than one outcome for ${key}`),
3892
- ...outcomes.filter((outcome) => !RESULTS.includes(outcome.result)).map((outcome) => `${outcome.character}: unknown result "${outcome.result}"`),
3893
- ...outcomes.filter((outcome) => outcome.summary.trim() === "").map((outcome) => `${outcome.character}: say what happens`),
3894
- ...outcomes.flatMap((outcome) => this.moveProblems(outcome, store)),
3895
- ...this.itemProblems(outcomes, store),
3896
- ...outcomes.flatMap((outcome) => store.checkVariableChanges(outcome.variableChanges ?? []).map((problem) => `${outcome.character}: ${problem}`))
3897
- ];
3898
- if (problems.length > 0) throw new Error(`the outcomes are not acceptable: ${problems.join("; ")} (expected exactly: ${expected.join(", ")})`);
3899
- }
3900
- /** Why a character cannot go where the outcome sends it, if it cannot: the game master hears it before the round is recorded. */
3901
- moveProblems(outcome, store) {
3902
- if (outcome.moveTo === void 0) return [];
3903
- if (outcome.result === "failed") return [`${outcome.character}: its intent failed, so it does not go anywhere: leave moves_to out`];
3904
- const checked = store.checkMove(outcome.character, outcome.moveTo);
3905
- return checked.ok ? [] : checked.problems.map((problem) => `${outcome.character}: cannot go to ${outcome.moveTo?.location}: ${problem}`);
3906
- }
3907
- /** Why what the outcomes do with things cannot be done, if it cannot: tried in order, each seeing what the one before did. */
3908
- itemProblems(outcomes, store) {
3909
- const entries = outcomes.flatMap((outcome) => outcome.itemChanges === void 0 || outcome.itemChanges.length === 0 || outcome.result === "failed" ? [] : [{
3910
- character: outcome.character,
3911
- changes: outcome.itemChanges
3912
- }]);
3913
- const failed = outcomes.filter((outcome) => outcome.result === "failed" && (outcome.itemChanges?.length ?? 0) > 0).map((outcome) => `${outcome.character}: its intent failed, so it does nothing with things: leave item_changes out`);
3914
- if (entries.length === 0) return failed;
3915
- const checked = store.checkItemChanges(entries);
3916
- return checked.ok ? failed : [...failed, ...checked.problems];
3917
- }
3918
- /** Every character acts at the same time; one that fails or answers badly is reported, not fatal. */
3919
- async runAttempt(owner, number, keys, cast, state, run, signal, away = false) {
3920
- const store = this.stores(owner.chat);
3921
- const { outputValidator } = this.boundaries();
3922
- const reaction = number === 2 ? this.reactions(state) : void 0;
3923
- const queryVector = number === 1 && store !== void 0 ? await store.queryVector(state.situation, signal) : void 0;
3924
- const time = store?.time(owner.turn);
3925
- const answers = await Promise.all(keys.map(async (key) => {
3926
- const member = cast.find((candidate) => candidate.key === key);
3927
- if (member === void 0) return {
3928
- character: key,
3929
- name: key,
3930
- reason: "no such character"
3931
- };
3932
- const previous = number === 2 ? state.first?.reports.find((report) => report.character === key) : void 0;
3933
- const memories = number === 1 && store !== void 0 ? await this.boundaries().recaller.recall({
3934
- member,
3935
- situation: state.situation,
3936
- turn: owner.turn,
3937
- policy: store.settings().memory,
3938
- ...store.settings().diagnostics.keepRuns ? { explain: true } : {},
3939
- ...queryVector === void 0 ? {} : { queryVector }
3940
- }, store.story, signal) : state.recalled.get(key) ?? [];
3941
- if (number === 1 && memories.length > 0) state.recalled.set(key, memories);
3942
- const place = member.place === void 0 ? void 0 : store?.place(member.place.location.id);
3943
- const relationships = store === void 0 ? [] : this.knownRelationships(member, place === void 0 ? cast : place.here, state.situation, cast, store);
3944
- const carrying = store === void 0 ? [] : store.carried(member.character.id);
3945
- const knowledge = store?.knowledge(member.character.id, owner.turn, (place === void 0 ? cast : place.here).map((entry) => entry.character.id));
3946
- const affiliations = store?.affiliations(member.character.id) ?? [];
3947
- const agenda = store?.agenda(owner.turn, member.character.id);
3948
- const cues = this.cuesOf(state, key, member, store, number);
3949
- const upcoming = store?.upcomingFor(member.character.id, owner.turn) ?? [];
3950
- const tracked = store?.trackedFor(member.character.id, (place === void 0 ? cast : place.here).map((entry) => entry.character.id));
3951
- const request = {
3952
- member,
3953
- cast,
3954
- situation: state.situation,
3955
- attempt: number,
3956
- language: store?.settings().prompts.language ?? "en",
3957
- turn: owner.turn,
3958
- ...away ? { away: true } : {},
3959
- lookup: store?.settings().memory.lookup ?? false,
3960
- text: (id, variables) => this.storeOf(owner).text(id, variables),
3961
- ...time === void 0 ? {} : { time },
3962
- ...agenda === void 0 ? {} : { agenda },
3963
- ...cues.length === 0 ? {} : { cues },
3964
- ...upcoming.length === 0 ? {} : { upcoming },
3965
- ...tracked === void 0 || tracked.self === "" && tracked.others.length === 0 ? {} : { tracked },
3966
- ...place === void 0 ? {} : { place },
3967
- ...relationships.length === 0 ? {} : { relationships },
3968
- ...carrying.length === 0 ? {} : { carrying },
3969
- ...knowledge === void 0 ? {} : { knowledge },
3970
- ...affiliations.length === 0 ? {} : { affiliations },
3971
- ...memories.length === 0 ? {} : { memories },
3972
- ...state.history.length === 0 ? {} : { earlier: [...state.history] },
3973
- ...reaction === void 0 ? {} : { reaction },
3974
- ...previous === void 0 ? {} : { previous: {
3975
- intent: previous.intent,
3976
- commitment: previous.commitment
3977
- } }
3978
- };
3979
- try {
3980
- const action = await run(request, signal);
3981
- const verdict = outputValidator.validate(action, request);
3982
- if (!verdict.ok) return {
3983
- character: key,
3984
- name: member.character.name,
3985
- reason: verdict.reason
3986
- };
3987
- return {
3988
- character: key,
3989
- name: member.character.name,
3990
- ...action
3991
- };
3992
- } catch (error) {
3993
- if (signal.aborted) throw error;
3994
- const reason = error instanceof Error ? error.message : String(error);
3995
- this.problem(`${member.character.name} could not act: ${reason}`);
3996
- return {
3997
- character: key,
3998
- name: member.character.name,
3999
- reason,
4000
- technical: true
4001
- };
3506
+ ask(owner, number, keys, cast, state, run, signal, away = false) {
3507
+ return askCharacters({
3508
+ boundaries: this.boundaries(),
3509
+ store: this.stores(owner.chat),
3510
+ storeOf: (o) => this.storeOf(o),
3511
+ problem: (message) => {
3512
+ this.problem(message);
4002
3513
  }
4003
- }));
4004
- return {
4005
- reports: answers.filter((answer) => "intent" in answer),
4006
- failures: answers.filter((answer) => "reason" in answer)
4007
- };
4008
- }
4009
- /** What the world made a character notice: taken up in the first attempt of a round, and told the same again on the retry. */
4010
- cuesOf(state, key, member, store, attempt) {
4011
- if (attempt === 2 || store === void 0) return state.cues.get(key) ?? [];
4012
- const pending = store.cuesFor(member.character.id);
4013
- if (pending.length === 0) return [];
4014
- store.doneCues(pending.map((cue) => cue.id));
4015
- const texts = pending.map((cue) => cue.text);
4016
- state.cues.set(key, texts);
4017
- return texts;
4018
- }
4019
- /** How a character sees people present or explicitly in the moment, for those it has a profile of. */
4020
- knownRelationships(member, company, situation, cast, store) {
4021
- const present = new Set(company.map((candidate) => candidate.character.id));
4022
- const relevant = mentioned(situation, cast.map((candidate) => candidate.character));
4023
- return store.story.relationships.from(member.character.id).flatMap((relation) => {
4024
- if (!present.has(relation.toId) && !relevant.has(relation.toId)) return [];
4025
- const other = cast.find((candidate) => candidate.character.id === relation.toId);
4026
- return other === void 0 || other.key === member.key ? [] : [{
4027
- name: referent(other.character),
4028
- label: relation.label,
4029
- summary: relation.summary,
4030
- present: present.has(relation.toId),
4031
- familiarity: relation.familiarity,
4032
- trust: relation.trust,
4033
- affinity: relation.affinity,
4034
- tension: relation.tension
4035
- }];
4036
- });
4037
- }
4038
- reactions(state) {
4039
- const first = state.first;
4040
- return (first?.outcomes ?? []).flatMap((outcome) => {
4041
- const report = first?.reports.find((candidate) => candidate.character === outcome.character);
4042
- return report === void 0 ? [] : [{
4043
- character: report.character,
4044
- name: report.name,
4045
- intent: report.intent,
4046
- ...report.utterance === void 0 ? {} : { utterance: report.utterance },
4047
- result: outcome.result,
4048
- summary: outcome.summary
4049
- }];
4050
- });
4051
- }
4052
- /** The final decision for each character of the round: the retry's replaces the first attempt's. */
4053
- /** The player's character is never asked to act, so what the game master decided it did stands in for its report. */
4054
- playerReport(state, outcome) {
4055
- const member = state.cast.find((candidate) => candidate.key === outcome.character && candidate.character.control === "player");
4056
- return member === void 0 ? void 0 : {
4057
- character: member.key,
4058
- name: member.character.name,
4059
- intent: outcome.summary,
4060
- commitment: "high"
4061
- };
4062
- }
4063
- decisions(state) {
4064
- const decided = /* @__PURE__ */ new Map();
4065
- for (const attempt of [state.first, state.second]) for (const outcome of attempt?.outcomes ?? []) {
4066
- const report = attempt?.reports.find((candidate) => candidate.character === outcome.character) ?? this.playerReport(state, outcome);
4067
- if (report !== void 0) decided.set(outcome.character, {
4068
- outcome,
4069
- report
4070
- });
4071
- }
4072
- return decided;
4073
- }
4074
- finishRound(owner, state) {
4075
- const store = this.storeOf(owner);
4076
- const decided = this.decisions(state);
4077
- const limit = store.settings().maxRounds;
4078
- const round = state.rounds + 1;
4079
- const checked = new Map([...decided.values()].flatMap(({ outcome }) => outcome.moveTo === void 0 ? [] : [[outcome.character, store.checkMove(outcome.character, outcome.moveTo)]]));
4080
- const refused = [...checked].flatMap(([character, check]) => check.ok ? [] : [`${character}: ${check.problems.join("; ")}`]);
4081
- if (refused.length > 0) throw new Error(`a move is no longer possible: ${refused.join("; ")}`);
4082
- const spoken = [...decided.values()].flatMap(({ outcome, report }) => report.utterance === void 0 || outcome.spoken === false || state.utterances.some((said) => said.character === report.character && sameWords(said.text, report.utterance)) ? [] : [{
4083
- character: report.character,
4084
- name: report.name,
4085
- text: report.utterance,
4086
- round
4087
- }]);
4088
- state.rounds = round;
4089
- state.situations.push(state.situation);
4090
- state.utterances.push(...spoken);
4091
- for (const { outcome, report } of decided.values()) {
4092
- state.reports.push(report);
4093
- state.outcomes.push(outcome);
4094
- state.history.push({
4095
- round,
4096
- character: report.character,
4097
- name: report.name,
4098
- intent: report.intent,
4099
- ...report.utterance === void 0 ? {} : { utterance: report.utterance },
4100
- result: outcome.result,
4101
- summary: outcome.summary
4102
- });
4103
- }
4104
- state.limit = limit;
4105
- state.phase = "between";
4106
- const playerPlace = state.cast.find((member) => member.character.control === "player")?.place?.location;
4107
- const updates = [...decided.values()].flatMap(({ outcome, report }) => {
4108
- const member = state.cast.find((candidate) => candidate.key === report.character);
4109
- if (member === void 0) return [];
4110
- const check = checked.get(outcome.character);
4111
- return [{
4112
- key: report.character,
4113
- update: {
4114
- character: member.character.id,
4115
- patch: {
4116
- activity: outcome.summary,
4117
- ...outcome.publicState === void 0 || outcome.publicState.trim() === "" ? {} : { publicState: outcome.publicState.trim() }
4118
- },
4119
- ...check?.ok === true ? { move: check.move } : {},
4120
- ...outcome.itemChanges === void 0 || outcome.itemChanges.length === 0 ? {} : { items: outcome.itemChanges }
4121
- }
4122
- }];
4123
- });
4124
- const effects = /* @__PURE__ */ new Map();
4125
- const done = store.commit(updates.map((entry) => entry.update));
4126
- updates.forEach(({ key }, index) => {
4127
- effects.set(key, done[index] ?? []);
4128
- });
4129
- const tracked = new Map(updates.map(({ key }) => [key, store.changeVariables(owner.turn, decided.get(key)?.outcome.variableChanges ?? []).map((effect) => ({
4130
- subject: effect.subjectName,
4131
- name: effect.variable.name,
4132
- from: describeValue(effect.variable, effect.from),
4133
- to: describeValue(effect.variable, effect.to)
4134
- }))]));
4135
- const journey = [...checked].flatMap(([character, check]) => check.ok && state.cast.find((candidate) => candidate.key === character)?.character.control === "player" ? [check.plan.travelSeconds ?? 0] : [])[0];
4136
- const time = store.endRound(owner.turn, round, state.elapsed, journey);
4137
- delete state.elapsed;
4138
- const world = this.fire(owner, round);
4139
- store.queueCommit({
4140
- turn: owner.turn,
4141
- round,
4142
- situation: state.situation,
4143
- ...playerPlace === void 0 ? {} : { place: {
4144
- key: locationKey(playerPlace),
4145
- name: playerPlace.name
4146
- } },
4147
- time: {
4148
- from: time.from,
4149
- to: time.to,
4150
- zone: time.zone
4151
- },
4152
- entries: [...decided.values()].map(({ outcome, report }) => {
4153
- const at = state.cast.find((candidate) => candidate.key === report.character)?.place?.location;
4154
- const check = checked.get(outcome.character);
4155
- return {
4156
- character: report.character,
4157
- name: report.name,
4158
- intent: report.intent,
4159
- commitment: report.commitment,
4160
- ...report.utterance === void 0 ? {} : { utterance: report.utterance },
4161
- result: outcome.result,
4162
- summary: outcome.summary,
4163
- ...outcome.publicState === void 0 || outcome.publicState.trim() === "" ? {} : { publicState: outcome.publicState.trim() },
4164
- spoken: outcome.spoken !== false,
4165
- ...(tracked.get(report.character) ?? []).length === 0 ? {} : { variables: tracked.get(report.character) },
4166
- ...state.cast.find((candidate) => candidate.key === report.character)?.character.control === "player" ? { player: true } : {},
4167
- ...report.forced === true ? { forced: true } : {},
4168
- ...(effects.get(report.character) ?? []).length === 0 ? {} : { items: (effects.get(report.character) ?? []).map((effect) => ({
4169
- name: effect.item.name,
4170
- action: effect.action,
4171
- summary: effect.summary
4172
- })) },
4173
- ...at === void 0 ? {} : { at: {
4174
- key: locationKey(at),
4175
- name: at.name
4176
- } },
4177
- ...check?.ok === true && check.plan.from !== check.move.to ? { moved: {
4178
- ...check.to,
4179
- ...check.position === void 0 ? {} : { position: check.position }
4180
- } } : {}
4181
- };
4182
- })
4183
- });
4184
- return {
4185
- round,
4186
- limit,
4187
- updated: [...decided.keys()],
4188
- retryFailures: state.second?.failures ?? [],
4189
- utterances: spoken,
4190
- spoken: [...state.utterances],
4191
- waiting: store.pendingCommits().length,
4192
- variables: [...tracked.values()].flat().map((change) => `${change.subject}'s ${change.name} is now ${change.to} (it was ${change.from})`),
4193
- time: {
4194
- from: time.from,
4195
- to: time.to,
4196
- zone: time.zone
4197
- },
4198
- moved: time.moved,
4199
- world,
4200
- things: [...effects].flatMap(([character, list]) => list.map((effect) => ({
4201
- character,
4202
- name: effect.item.name,
4203
- action: effect.action,
4204
- summary: effect.summary
4205
- }))),
4206
- moves: [...checked].flatMap(([character, check]) => check.ok && check.plan.from !== check.move.to ? [{
4207
- character,
4208
- name: decided.get(character)?.report.name ?? character,
4209
- to: check.to.name,
4210
- via: Math.max(0, check.plan.via.length - 1)
4211
- }] : [])
4212
- };
3514
+ }, owner, number, keys, cast, state, run, signal, away);
4213
3515
  }
4214
3516
  /**
4215
3517
  * The game master asks for what happened to be written into the story's lasting records. The memory
@@ -4299,25 +3601,17 @@ var TurnEngine = class {
4299
3601
  if ((this.runs.get(owner.chat) ?? 0) === 0 && store !== void 0 && waiting > 0 && (state.requested || waiting >= store.settings().memory.backlogRounds)) this.write(owner, state);
4300
3602
  }
4301
3603
  async deliver(owner, state, segments, silent, run) {
4302
- const { narrationChecker } = this.boundaries();
4303
- const problems = [...segments.flatMap((segment, index) => segment.type === "utterance" && segment.character === "" ? [`segment ${index + 1}: an utterance needs the character who says it`] : []), ...narrationChecker.check(segments, state.utterances)];
4304
- let output;
4305
- if (problems.length === 0) output = {
4306
- segments: asSpoken(segments, state.utterances),
4307
- repaired: false
4308
- };
4309
- else {
4310
- state.refused += 1;
4311
- if (!silent && state.refused <= MAX_REFUSALS) throw new Error(`the output is not acceptable: ${problems.join("; ")}. Deliver it again with these corrected; narration may be written freely, utterances may not be touched`);
4312
- output = {
4313
- segments: narrationChecker.repair(segments.filter((segment) => segment.type !== "utterance" || segment.character !== ""), state.utterances),
4314
- repaired: true
4315
- };
4316
- }
3604
+ let output = checkedOutput(this.boundaries().narrationChecker, this.storeOf(owner).settings().prompts.language, state, segments, silent);
4317
3605
  if (state.ooc?.ruling !== void 0) output = {
4318
3606
  ...output,
4319
3607
  ooc: state.ooc.ruling
4320
3608
  };
3609
+ const store = this.storeOf(owner);
3610
+ const rolled = store.settings().dice.visibility === "card" ? store.story.dice.rolls({ turn: owner.turn }) : [];
3611
+ if (rolled.length > 0) output = {
3612
+ ...output,
3613
+ rolls: rolled.map(rollView)
3614
+ };
4321
3615
  this.storeOf(owner).completeTurn();
4322
3616
  this.storeOf(owner).resolveBeats(state.addressed);
4323
3617
  state.phase = "done";
@@ -4329,18 +3623,6 @@ var TurnEngine = class {
4329
3623
  return output;
4330
3624
  }
4331
3625
  };
4332
- /** The words as the character said them, whatever quotes the game master put around them. */
4333
- function asSpoken(segments, spoken) {
4334
- const left = [...spoken];
4335
- return segments.map((segment) => {
4336
- if (segment.type !== "utterance") return segment;
4337
- const at = left.findIndex((said) => said.character === segment.character && sameWords(said.text, segment.text));
4338
- return at === -1 ? segment : {
4339
- ...segment,
4340
- text: left.splice(at, 1)[0].text
4341
- };
4342
- });
4343
- }
4344
3626
  //#endregion
4345
3627
  //#region src/host/images/jobs.ts
4346
3628
  /** The same service, whose requests stand where the job's do unless a call says otherwise. */
@@ -4632,6 +3914,23 @@ function apply(ctx) {
4632
3914
  settings: liveSettings(sessionFolder(sessionsDir(), session), problem)
4633
3915
  };
4634
3916
  };
3917
+ /** What the game master is told of the dice, when it has a dice tool; nothing when it has none. */
3918
+ const diceSection = (context, chat, language) => {
3919
+ const chatId = context.agent?.session.id;
3920
+ const store = chatId === void 0 ? void 0 : stores(chatId);
3921
+ if (chat === void 0 || store === void 0) return "";
3922
+ const on = [
3923
+ "roll_check",
3924
+ "roll_dice",
3925
+ "list_checks"
3926
+ ].filter((tool) => toolEnabled(chat.settings.tools, "gameMaster", tool));
3927
+ if (on.length === 0) return "";
3928
+ const checks = on.includes("roll_check") ? describeChecks(store.story.dice.checks(), translator(languageOf(language))) : "";
3929
+ return ctx.roleplayPrompts.text("roleplay/dice", language, {
3930
+ tools: on.join(", "),
3931
+ checks
3932
+ }, chat.session);
3933
+ };
4635
3934
  for (const [name, order, id] of [[
4636
3935
  PERSONA_SECTION,
4637
3936
  ctx.systemPrompt.getSectionOrder("DEPLOYMENT_PERSONA_PREFIX"),
@@ -4648,10 +3947,22 @@ function apply(ctx) {
4648
3947
  const chat = settingsOf(context);
4649
3948
  const language = chat?.settings.prompts.language ?? "en";
4650
3949
  const part = (name) => ctx.roleplayPrompts.text(name, language, {}, chat?.session);
4651
- const variables = id === "roleplay/game-master" ? { preview: chat?.settings.preview.enabled === false ? "" : part("roleplay/preview") } : id === "roleplay/persona" ? { style: part("roleplay/style") } : {};
3950
+ const variables = id === "roleplay/game-master" ? {
3951
+ preview: chat?.settings.preview.enabled === false ? "" : part("roleplay/preview"),
3952
+ dice: diceSection(context, chat, language)
3953
+ } : id === "roleplay/persona" ? { style: part("roleplay/style") } : {};
4652
3954
  return ctx.roleplayPrompts.text(id, language, variables, chat?.session);
4653
3955
  }
4654
3956
  });
3957
+ ctx.systemPrompt.section({
3958
+ name: RESOURCE_HINT_SECTION,
3959
+ order: ctx.systemPrompt.getSectionOrder("MCP_SERVERS"),
3960
+ interpolate: false,
3961
+ text: (context) => {
3962
+ const chat = settingsOf(context);
3963
+ return resourceHint(ctx.tools.schemas(context.scope).map((tool) => tool.name), ctx.tools.schemas().map((tool) => tool.name), translator(languageOf(chat?.settings.prompts.language ?? "en")));
3964
+ }
3965
+ });
4655
3966
  const [previewTool, ...tools] = [...createTools$1({
4656
3967
  engine,
4657
3968
  boundaries,
@@ -4722,12 +4033,21 @@ function apply(ctx) {
4722
4033
  ctx.roleplayOrchestration.images = void 0;
4723
4034
  };
4724
4035
  }, "roleplay: images");
4036
+ const diceLink = (chat) => {
4037
+ const store = stores(chat);
4038
+ const agent = ctx.agents.get(SessionId(chat));
4039
+ return store === void 0 || agent === void 0 ? void 0 : {
4040
+ session: store.story,
4041
+ turn: currentTurn(agent)
4042
+ };
4043
+ };
4725
4044
  installHooks(ctx, {
4726
4045
  engine,
4727
4046
  boundaries,
4728
4047
  stores,
4729
4048
  timelines,
4730
- previewTool
4049
+ previewTool,
4050
+ optionalTools: createDiceTools(diceLink)
4731
4051
  });
4732
4052
  }
4733
4053
  //#endregion